Repository navigation
fix(vmpool): rmdir the per-VM cgroup on the normal destroy path (#255) - #314
Conversation
…octl#255) The per-VM cgroup is created by jailer (`--cgroup`) and was removed ONLY by `SweepOrphans`, which runs at startup. `Destroy` killed the process group, reaped it and `RemoveAll`'d the jail, but left the cgroup directory behind -- so one leaked per Exec for the whole life of the worker process, and only a restart reclaimed them. Nothing bounded it. rossoctl#255 files this as hygiene: "Neither affected a measurement, and neither is a data or process leak -- both are hygiene/guidance items." Both claims turn out to be false. It is a progressive throughput collapse, and it invalidated a measurement campaign (rossoctl#305). Measured on srv-r16b14s16, one worker at 16 slots, 400 iters/slot, identical configuration either side: ~41,000 stale directories 25.84 Exec/s mean restore sockwait 1008 ms directories removed 136.51 Exec/s mean restore sockwait 98 ms 5.3x, from `rmdir` alone. Peak observed on the box was 47,940 directories. Mechanism: cgroup create/destroy is kernel-serialised and degrades with how many exist. A jailer cgroup that is slow to set up delays Firecracker binding its API socket, so the cost lands in `waitForUnixSocket` -- already ~90% of a restore (rossoctl#304) -- and restores are how the standby pool replenishes, which makes it an aggregate throughput ceiling. Worth recording for whoever meets this next: throughput collapses while the host goes IDLE (88% idle at the worst point). Nothing is computing; everything waits on cgroup operations, so a CPU-based diagnosis looks clean and finds nothing. - `cgroupDir` is recorded on the VM at restore, from `vmCgroupDirFor`, rather than re-derived in `Destroy`: a removal that targets a path other than the one jailer created silently does nothing. - `vmCgroupDirFor` is gated on exactly the condition `firecrackerCgroupArgs` uses, so the two cannot disagree about whether a cgroup exists. With `ParentCgroup` unset it returns "" -- load-bearing, because a path built anyway would resolve to `Cgroup2Root` and try to rmdir the cgroup root. - Removal reuses `removeCgroupDir`, the helper `SweepOrphans` already calls, so the startup and steady-state paths cannot drift on what removal means. rmdir, never `rm -rf` (D5): these are kernel-backed pseudo-files. - A failure is appended to the existing error set, which the caller logs and counts as `destroyFailed` rather than failing the Exec. That is the right weight: a leaked directory must be visible, and must not break a command that already ran. Not changed: the Cloud Hypervisor arm, whose per-VM cgroup is a systemd transient scope (`systemd-run --scope`) that systemd removes when the unit stops. Its names stay recognised by `SweepOrphans` for crash recovery. This file records that it has no host with systemd + KVM to verify that arm end to end, so it is left alone rather than changed on inference. Also not changed: part 1 of rossoctl#255, the empty `<ChrootBase>/firecracker/<id>` parent directory. Real, but it is ~4 KB of inode with no measured throughput cost, so it does not belong in a fix whose justification is a 5.3x regression. Verified: 4 new tests (removal, the no-cgroup case, idempotency, and that the recorded path is the one jailer was told to use) fail to compile before the change and pass after; `go test ./...` 9 packages exit 0; `go vet`, `gofmt` and `make lint` all clean. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
pdettori
left a comment
There was a problem hiding this comment.
Automated review of f1c98d9 (2 files, +140/-2). Verified the change compiles, gofmt/go vet are clean, and the full remote-worker suite passes (9 packages, exit 0).
The core fix is sound: cgroupDir is recorded at restore from the same derivation jailer is given, and removal reuses removeCgroupDir so it cannot drift from SweepOrphans.
5 findings: 3 inline below, plus two that fall outside the diff hunks -- including the most severe one.
remote-worker/internal/vmpool/launcher_firecracker.go:274 -- Restore's cleanup() closure still leaks the per-VM cgroup. (Outside the diff hunks.)
The closure kills the pgroup and RemoveAlls the jail, but never rmdirs the cgroup jailer already created. A sockwait timeout or a LoadSnapshot failure after cmd.Start() therefore leaks one directory per attempt -- and since each replenish retry draws a fresh id from nextIDLocked(), it is unbounded.
This is the same leak the PR closes on the happy path, on a path the degradation itself provokes. Given #255's finding that leaked VM cgroups cost ~5.3x throughput, the failure path is arguably where it matters most: a host that starts timing out on sockwait is exactly the host that then accumulates leaked directories fastest. vmCgroupDirFor(opts, id) is already available at that point, so the fix is a removeCgroupDir call in the closure.
remote-worker/internal/vmpool/replenish.go:130 -- _ = vm.Destroy() on the closed-pool branch discards the new cgroup-removal error. (File not in this PR.)
Unlike all six other Destroy call sites, this one neither logs nor counts destroyFailed, so a leak taken on that branch is invisible. That contradicts this PR's own stated principle that "a leaked directory must be visible" -- before the change Destroy had nothing to report there, and now it does.
| // and returning a path anyway would resolve to Cgroup2Root itself and try to rmdir the | ||
| // cgroup ROOT. Gated on exactly the same condition as firecrackerCgroupArgs so the two | ||
| // cannot disagree about whether a cgroup was created. | ||
| func vmCgroupDirFor(opts FirecrackerOptions, id string) string { |
There was a problem hiding this comment.
vmCgroupDirFor guards empty ParentCgroup but not empty id.
The doc comment correctly explains why an unset ParentCgroup must return "" -- otherwise the path resolves to Cgroup2Root and Destroy would rmdir the cgroup ROOT. But an empty id has the same shape of consequence one level down: vmCgroupPath(parent, "") resolves to the shared parent slice itself, so Destroy would rmdir the systemd slice that every jailer --parent-cgroup and the next start's SweepOrphans depend on.
Unreachable from production today only because nextIDLocked() is the sole id source and never yields "". Since the function's whole purpose is to be the one place that cannot disagree with firecrackerCgroupArgs about what is safe to remove, guarding id == "" here is cheap and keeps the invariant local rather than resting on a caller two packages away.
There was a problem hiding this comment.
Confirmed and guarded in f418c1d. vmCgroupPath(parent, "") resolves to the parent slice itself, so Destroy would rmdir the slice every jailer --parent-cgroup and the next start's SweepOrphans depend on — the same shape as the Cgroup2Root case, one level down.
Agreed on where it belongs: the function exists to be the one place that cannot disagree with firecrackerCgroupArgs about what is safe to remove, so resting the invariant on nextIDLocked never yielding "" would put it in the wrong file. Both guards are now in the one condition, and the test pins the empty-id case alongside the empty-ParentCgroup one.
| // --parent-cgroup alone only relocates the process into the shared parent). Split out | ||
| // of Restore's argv construction so a test can assert the memory bound agrees with | ||
| // PerVMBytes(cfg) without spawning jailer. | ||
| // vmCgroupDirFor returns the cgroupfs path jailer will create for this VM, or "" when no |
There was a problem hiding this comment.
Nit, but it costs the rationale: the new function was inserted between firecrackerCgroupArgs's doc comment and its declaration.
Lines 143-145 are the tail of the doc comment for firecrackerCgroupArgs (".. Split out of Restore's argv construction so a test can assert the memory bound agrees with PerVMBytes(cfg) without spawning jailer"). With vmCgroupDirFor now sitting between that comment and its declaration at line 159:
- godoc attributes the comment to
vmCgroupDirFor, where it makes no sense. firecrackerCgroupArgsloses the D1/D2 rationale -- which is the reasoning this entire change rests on, since the whole point is that--parent-cgroupalone only relocates the process and the per-VM directory is ours to remove.
Moving vmCgroupDirFor (with its own doc) above the firecrackerCgroupArgs comment block, or below its declaration, restores both.
There was a problem hiding this comment.
Confirmed — I inserted it between the doc comment and its declaration, so godoc attributed the D1/D2 rationale to vmCgroupDirFor. That rationale is exactly what this change rests on (--parent-cgroup alone only relocates the process; the per-VM directory is ours to remove), so losing it from firecrackerCgroupArgs would have been the more expensive half of the mistake.
Moved above the comment block in f418c1d, with its own doc.
|
|
||
| // Destroy is idempotent (it returns early on the second call), and that must not regress | ||
| // into a second rmdir attempt reporting failure for an already-removed directory. | ||
| func TestDestroyIsStillIdempotentWithCgroupRemoval(t *testing.T) { |
There was a problem hiding this comment.
This idempotency test is vacuous -- it never reaches the code it claims to guard.
Destroy returns early at the destroyed check, which sits before the cgroup branch. So the second call never attempts a second rmdir, and the test passes even if removeCgroupDir stopped tolerating ENOENT -- i.e. it cannot fail for the reason the comment gives ("must not regress into a second rmdir attempt reporting failure for an already-removed directory").
Two ways to make it bite, depending on which invariant you actually want pinned:
- If the intent is "the early return protects the cgroup branch": assert that directly -- remove the directory out from under the VM between the two calls and assert the second
Destroystill returns nil and that no rmdir was attempted (thefakeSliceharness can count). - If the intent is "
removeCgroupDirtolerates ENOENT": testremoveCgroupDiron a missing path directly, without routing throughDestroy.
Worth resolving because this is the one test standing behind the ENOENT tolerance that makes the SweepOrphans / Destroy overlap safe.
There was a problem hiding this comment.
Confirmed — the destroyed early-return sits before the cgroup branch, so the second call never reaches a second rmdir and the test could not fail for the ENOENT reason its comment claimed.
Took your option 2 plus the case that actually occurs, rather than option 1: a second Destroy short-circuits regardless of what happened to the directory, so removing it between calls would still pass trivially. Instead, in f418c1d:
TestDestroyToleratesAnAlreadySweptCgrouproutes a genuinely missing directory through the cgroup branch on a FIRSTDestroy— which is what a startup sweep, an operator clearing the slice, orRestore'scleanup()having already run actually produce. This one bites.TestRemoveCgroupDirToleratesAMissingDirectorypins the helper directly, since that tolerance is what makes the SweepOrphans/Destroy overlap safe.- The idempotency test stays as a cheap regression guard, with the false ENOENT claim removed from its comment.
…tl#314 review) Five review findings, all confirmed against the code before changing anything. **The severe one: `Restore`'s `cleanup()` closure leaked the cgroup.** It kills the pgroup and `RemoveAll`s the jail but never rmdir'd the cgroup jailer had already created. `cleanup()` runs after `cmd.Start()`, so a sockwait timeout or a failed `LoadSnapshot` leaked one directory per attempt -- and each replenish retry draws a FRESH id from `nextIDLocked`, so it was unbounded. This is the same leak the PR closes on the happy path, on the path the degradation itself provokes: a host that has started timing out on sockwait is exactly the host that then accumulates directories fastest. The c=64 run behind rossoctl#255 took 396 such timeouts. Tested through the REAL path, not structurally: the fake jailer exits 0 without ever creating the API socket, so `Restore` reaches `waitForUnixSocket`, and a cancelled context makes that return in ~20 ms rather than its 5 s timeout. Verified non-vacuous by removing only the new block -- the test then fails naming the leftover directory. That needed a seam. `Cgroup2Root` is a const naming the host's real cgroupfs, which a test cannot write to without root, so `FirecrackerOptions` gains an **unexported** `cgroupRoot` -- settable only from this package's own tests, empty everywhere else. **`vmCgroupDirFor` now guards an empty `id` as well.** An unset `ParentCgroup` would resolve to `Cgroup2Root`; an empty id resolves one level down, to the shared PARENT SLICE that every jailer `--parent-cgroup` and the next start's `SweepOrphans` depend on. Unreachable today (`nextIDLocked` never yields ""), but this function exists to be the one place that cannot disagree with `firecrackerCgroupArgs` about what is safe to remove, so the invariant belongs here rather than in a caller. **`replenish.go`'s closed-pool branch no longer discards the error.** Alone among the seven `Destroy` call sites it neither logged nor counted `destroyFailed`. Before this work `Destroy` had nothing to report there; now it can report a leak, and this PR's own principle is that a leaked directory must be visible. **`vmCgroupDirFor` was sitting between `firecrackerCgroupArgs`'s doc comment and its declaration**, so godoc attributed the D1/D2 rationale to the wrong function and `firecrackerCgroupArgs` lost it -- the very reasoning this change rests on, since `--parent-cgroup` alone only relocates the process and the per-VM directory is ours to remove. Moved above the comment block, with its own doc. **The idempotency test was vacuous.** `Destroy`'s `destroyed` early-return sits before the cgroup branch, so a second call never attempts a second rmdir and the test could not fail for the ENOENT reason its comment claimed. Replaced with two that can: `TestDestroyToleratesAnAlreadySweptCgroup` routes a genuinely missing directory through the cgroup branch (the case a startup sweep or `cleanup()` having already run actually produces), and `TestRemoveCgroupDirToleratesAMissingDirectory` pins the helper directly. The idempotency test stays as a cheap regression guard with its false ENOENT claim removed. 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]>
Review addressed in
|
| finding | disposition |
|---|---|
Restore's cleanup() leaks the cgroup |
fixed, with a test that fails without it |
replenish.go:130 discards the new error |
fixed — logs and counts destroyFailed like the other six sites |
vmCgroupDirFor unguarded empty id |
fixed — both guards in one condition, test pins the id case |
| doc comment placement | fixed — moved above firecrackerCgroupArgs's comment block |
| vacuous idempotency test | replaced with two that bite |
On the cleanup() leak
You were right that this is where it matters most, and the run behind #255 makes it concrete: the c=64 rung took 396 API socket never appeared timeouts, every one of them a leaked directory on the old code, each with a fresh id from nextIDLocked.
I drove it through the real path rather than asserting structurally. The fake jailer exits 0 without creating the API socket, so Restore reaches waitForUnixSocket, and a cancelled context returns in ~20 ms instead of its 5 s timeout. Verified non-vacuous by removing only the new block:
--- FAIL: TestRestoreCleanupRemovesThePerVMCgroupOnAFailedRestore
cleanup() left the per-VM cgroup .../microvm-vms.slice/vm-42 behind (err=<nil>)
-- one leaks per failed restore, with a fresh id each retry
That needed a seam: Cgroup2Root is a const naming the host's real cgroupfs, which a test cannot write to without root. FirecrackerOptions gains an unexported cgroupRoot, settable only from this package's own tests and empty on every production path. Flagging it explicitly in case you'd rather it were done another way — it is the one thing here that adds a field to a production struct for testability.
Verification
go test ./... 9 packages exit 0; go vet, gofmt and make lint clean. The metal verification in the PR body still stands — it was run against f1c98d9, and f418c1d only adds the failure path plus tests, so the 0-directories-after-6,497-restores result is unaffected.
…sleep (#304) `waitForUnixSocket` retried on a fixed `time.After(20 * time.Millisecond)`, so every restore paid at least one full quantum however fast Firecracker actually bound its socket. Restores are how the standby pool replenishes, so this set the replenishment rate and with it an aggregate throughput ceiling -- not merely per-restore latency. Measured over 1,625 restores on an idle srv-r16b14s16: sockwait 24.92 ms of a 27.73 ms restore (89.9%) against 2.80 ms of real work (prep 0.22 + wsimg 0.05 + jailer 0.39 + loadsnap 2.14). Quantized with no tail below the quantum at all: min 20.06 ms, ZERO of 1,625 under 20 ms, 78.2% in [20,40), 21.8% in [40,60) Every socket therefore appeared inside the first quantum and every restore slept through it. Replaced with backoff from 250 us growing 1.5x to a 5 ms cap. Fine-and-growing rather than a fast fixed poll: 250 us forever would burn three syscalls per attempt per concurrent restore for the whole wait, whereas this reaches the cap in 8 attempts having spent ~5 ms, so a socket appearing in the low milliseconds is caught within a few hundred microseconds of doing so while a genuinely absent one settles to ~200 polls/s instead of 50. Measured after (15 samples each, against a listener bound at a known delay): socket appears at 2 ms -> sockwait p50 2.29 ms (was >= 20 ms, always) socket appears at 5 ms -> sockwait p50 5.94 ms So it now tracks true appearance within ~0.3-0.9 ms. On the measured restore that should take 27.73 ms toward ~3-5 ms. The growth is applied AFTER the sleep, so the first retry is always the fine one -- which the distribution says is the case that matters. Four tests, the first of which fails at 21.41 ms before the change: - returns well inside one old quantum for a socket bound after ~2 ms; - still honours its overall timeout, naming the budget and the path, and does not overshoot it (the cap bounds how late the last sleep pushes the deadline check); - still honours ctx cancellation, which `Restore`'s `cleanup()` depends on to unwind promptly rather than sitting out the full timeout; - still DIALS rather than stats. Load-bearing both ways: Firecracker creates the socket file before it `accept()`s, so a stat would report ready too early and race the snapshot PUT, and `fcJailOccupied`'s id-collision guard rests on the same distinction. The test puts a plain FILE at the path -- stat succeeds, dial must not. The 5 s overall ceiling is deliberately unchanged. The 396 timeouts seen at c=64 came from cgroup-leak-induced slowness (#255, fixed in #314), so the pressure that made 5 s look tight is gone; re-sizing it now would be guessing ahead of the re-measurement. Verified: `go test ./...` 9 packages exit 0, and the timing-sensitive tests pass at `-count=5`; `go vet`, `gofmt`, `make lint` clean. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
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 #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` (#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 #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]>
Closes #255 (part 2 — the cgroup half).
The defect
The per-VM cgroup is created by jailer (
--cgroup) and was removed only bySweepOrphans,which runs at startup.
Destroykills the process group, reaps it andRemoveAlls the jail —but left the cgroup directory behind. So one directory leaked per Exec for the whole life of
the worker process, and only a restart reclaimed them. Nothing bounded it.
#255 files this as hygiene: "Neither affected a measurement, and neither is a data or process
leak — both are hygiene/guidance items." Both claims are false. It is a progressive throughput
collapse, and it invalidated a measurement campaign (#305).
Measured on metal, before and after
srv-r16b14s16, one microVM worker, 16 slots, 400 iters/slot (6,497 restores), D=2, 256 MiBguests — identical configuration on every row:
sockwaitmeanThree things worth separating out:
was 47,940.
as it proceeds — by the end, that run had built up 6,497 of its own.
And
sockwaitp50 is now 21.08 ms, back at the fixed 20 ms quantum. So the "restores getslower with concurrency" effect I reported on #305 was largely this leak, and #304 is cleanly the
next bottleneck rather than being tangled with it.
Mechanism
Cgroup create/destroy is kernel-serialised and degrades with how many exist. A jailer cgroup that
is slow to set up delays Firecracker binding its API socket, so the cost lands in
waitForUnixSocket— already ~90% of a restore (#304) — and restores are how the standby poolreplenishes, which is what turns it into an aggregate throughput ceiling.
The signature is worth knowing, because it misdirects: throughput collapses while the host
goes idle (88% idle at the worst point). Nothing is computing; everything waits on cgroup
operations, so a CPU-based diagnosis looks clean and finds nothing. If you see a large throughput
drop with falling
coresBusy, countfind /sys/fs/cgroup/microvm.slice -type d -name 'vm-*' | wc -lfirst.Design notes
cgroupDiris recorded on the VM at restore, fromvmCgroupDirFor, rather than re-derivedinside
Destroy. A removal that targets a path other than the one jailer created silently doesnothing, which is the failure mode this whole issue is made of.
vmCgroupDirForis gated on exactly the conditionfirecrackerCgroupArgsuses, so the twocannot disagree about whether a cgroup exists. With
ParentCgroupunset it returns""— thatis load-bearing: a path built anyway would resolve to
Cgroup2Rootand attempt to rmdir thecgroup root. A test pins that.
removeCgroupDir, the helperSweepOrphansalready calls, so the startup andsteady-state paths cannot drift on what removal means.
rmdir, neverrm -rf(D5) — these arekernel-backed pseudo-files.
destroyFailedrather than failing the Exec. That is the right weight: a leaked directory mustbe visible, and must not break a command that already ran correctly.
waitForCgroupEmptyis a short bounded guard, not an expected wait — the VMM is SIGKILLed andreaped by
cmd.Wait()before this point, so the kernel has already emptiedcgroup.procs.Deliberately not in this PR
(
systemd-run --scope), which systemd removes when the unit stops; its names stay recognised bySweepOrphansfor crash recovery. That file records having no host with systemd + KVM to verifythe arm end to end, so it is left alone rather than changed on inference.
<ChrootBase>/firecracker/<id>parent directory. Real, but ~4 KBof inode with no measured throughput cost — it does not belong in a change justified by a 5.3x
regression.
Verification
go test ./...go vet/gofmtmake lintThe tests cover removal, the no-cgroup case, idempotency of a second
Destroy, and that therecorded path is the one jailer was told to use. They need neither root nor KVM — a cgroup v2 tree
is a directory with a
cgroup.procsfile, and the suite already hasfakeSlicefor that.🤖 Generated with Claude Code