Repository navigation
perf(vmpool): poll finely for the API socket instead of a fixed 20ms sleep (#304) - #315
Conversation
…sleep (rossoctl#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 (rossoctl#255, fixed in rossoctl#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]>
| @@ -607,8 +607,36 @@ func fcJailOccupied(path string) bool { | |||
| // waitForUnixSocket polls until a listener answers at path, or ctx ends, or timeout | |||
There was a problem hiding this comment.
Severity: low — Finding 1/6: the old function doc now documents the const block.
The pre-existing three-line waitForUnixSocket doc comment was left here and the new pacing comment was appended to it with no blank line, so the whole block binds to the const group rather than to the function.
Evidence — go doc -all -u ./internal/vmpool renders the constants as:
const (
socketPollMin = 250 * time.Microsecond
socketPollMax = 5 * time.Millisecond
socketPollGrowthNum = 3
socketPollGrowthDen = 2
)
waitForUnixSocket polls until a listener answers at path, or ctx ends,
or timeout elapses. File existence alone is not enough: Firecracker creates
the socket file before it is actually accept()ing on it. Retry pacing for
waitForUnixSocket (#304). ...
The function's real doc at line 631 then restates "creates the socket file before it accept()s", so the same fact lives in two places that can drift apart.
Suggested change: delete lines 607-609 (the new doc at 631-636 already covers them), leaving the pacing rationale as the const block's own comment.
There was a problem hiding this comment.
Confirmed — go doc rendered the whole block against the const group, and the accept() fact was duplicated at line 631 where it could drift. Deleted the old three lines in 3179732; the function's own doc carries it, and the pacing rationale is now the const block's comment as you suggest.
| // waitForUnixSocket polls until a listener answers at path, or ctx ends, or timeout | ||
| // elapses. File existence alone is not enough: Firecracker creates the socket file | ||
| // before it is actually accept()ing on it. | ||
| // Retry pacing for waitForUnixSocket (#304). A FIXED 20 ms sleep made every restore pay at |
There was a problem hiding this comment.
Severity: medium — Finding 2/6: the committed rationale asserts what the PR description retracts.
This comment states the fixed sleep "set the replenishment rate, and with it an aggregate throughput ceiling, not merely per-restore latency" — the exact inference the PR description withdraws:
the mean only moved 24.92 -> 22.24 ms, and the restore 27.73 -> 25.09 ms — about 11% […] That inference was wrong […] it is no longer something a poll change can recover.
The same claim is repeated in the test at socket_wait_unix_test.go:36-37 ("so this sets the replenishment rate and therefore an aggregate throughput ceiling").
The code comment is the durable artifact; the PR description is not. Concrete scenario: the next engineer chasing the replenishment ceiling reads this, concludes the poll was the ceiling and that #304 removed it, and stops looking at Firecracker's ~21 ms socket bind — the cost that actually dominates.
Suggested change: carry the retraction into the comment. State that the fixed quantum was a measurement floor that is now gone, that the measured throughput effect was ~11%, and that sockwait remains ~89% of a restore for reasons a poll change cannot reach.
There was a problem hiding this comment.
Confirmed, and this is the one I most needed pointed out. You are right about which artifact is durable — the PR description is not what the next engineer reads.
The comment now carries the retraction: the quantum was a measurement floor, removing it was worth ~11% (24.92 → 22.24 ms), the ~5x reasoning was an inference the old data could not support (at 20 ms granularity "appears at 2 ms" and "appears at 19 ms" are the same reading), and sockwait remains ~89% of a restore for reasons no poll change reaches. It ends with an explicit "do NOT read this block as having removed a throughput ceiling."
Same correction applied to the test comment at socket_wait_unix_test.go:36.
| // restore (89.9%) against 2.80 ms of real work, and quantized with no tail below the quantum | ||
| // at all -- min 20.06 ms, ZERO under 20 ms, 78.2% in [20,40), 21.8% in [40,60). | ||
| // | ||
| // Starts fine and grows, rather than simply polling fast forever: a 250 us fixed poll across |
There was a problem hiding this comment.
Severity: medium — Finding 3/6: the pacing arithmetic is wrong, and the residual grid still quantizes the result.
I replayed this exact schedule (same constants, same post-sleep growth). Probes land at:
attempt 1: dial at t=0s then sleep 250µs
attempt 2: dial at t=250µs then sleep 375µs
attempt 3: dial at t=625µs then sleep 562.5µs
attempt 4: dial at t=1.1875ms then sleep 843.75µs
attempt 5: dial at t=2.03125ms then sleep 1.265625ms
attempt 6: dial at t=3.296875ms then sleep 1.898437ms
attempt 7: dial at t=5.195312ms then sleep 2.847655ms
attempt 8: dial at t=8.042967ms then sleep 4.271482ms
attempt 9: dial at t=12.314449ms then sleep 5ms <- cap first applies here
attempt 10: dial at t=17.314449ms then sleep 5ms
attempt 11: dial at t=22.314449ms then sleep 5ms
So two claims in this comment do not hold:
- "reaches the cap in 8 attempts having spent ~5 ms" — eight sleeps total 8.04 ms, and the cap does not apply until t = 12.31 ms.
- "a socket that appears in the low milliseconds is caught within a few hundred microseconds of doing so" — true only below ~2 ms. At 5 ms the next probe is 2.85 ms later; at the measured p50 of ~21 ms the grid is a full 5 ms.
That second point bears directly on the PR's conclusion. The "after" distribution is described as "continuous: modes at [10,12), [14,16), [20,22), [26,28)" — but those modes are spaced 4-6 ms, which is the residual poll comb above t = 12.31 ms, not a continuous distribution. The 22.24 ms mean therefore still carries up to 5 ms (~2.5 ms mean) of our own sleep, so "that is now a measurement of Firecracker's startup, not of our sleep" is overstated by roughly the size of the remaining improvement.
Falsifiable prediction: drop socketPollMax to 1 ms and the mean should fall another ~2 ms. Until that is checked, the "~89% is Firecracker" figure is still instrument-inflated.
Suggested change: fix the two numbers (8.04 ms of sleeping, cap at 12.31 ms), and state the residual resolution explicitly — sockwait is now measured to ±5 ms rather than ±20 ms, which is what bounds any attribution drawn from it.
There was a problem hiding this comment.
Finding 3 — confirmed, including your falsifiable prediction
I replayed the schedule and got your numbers exactly: eight sleeps total 12.31 ms, cap first applies at attempt 9, not "the cap in 8 attempts having spent ~5 ms". Both numbers in that comment were wrong.
The consequence was the more important half, and you were right there too. I tested the prediction on metal — same host, c=4, 400 iters/slot, 1,625 restores each, only socketPollMax differing:
| cap | sockwait mean | p50 | min | below 20 ms | restore total |
|---|---|---|---|---|---|
| 5 ms | 22.24 ms | 21.02 ms | 9.37 ms | 46.3% | 25.09 ms |
| 1 ms | 20.34 ms | 18.50 ms | 9.19 ms | 52.6% | 23.20 ms |
The mean fell 1.90 ms — you predicted ~2 ms. So the 22.24 ms figure did carry ~2 ms of our own sleep, and my "that is now a measurement of Firecracker's startup, not of our sleep" was overstated by roughly the size of the remaining improvement, exactly as you said. The reported "continuous modes at [10,12), [14,16), [20,22), [26,28)" being 4–6 ms apart was the comb, not a distribution.
Changes in 3179732:
socketPollMax5 ms → 1 ms, so the comb is finer than the thing being measured.- The comment now states the residual resolution as the thing that bounds attribution: sockwait is accurate to about ±1 ms rather than ±20 ms (or ±5 ms), at ~27 probes to reach 25 ms, and raising the cap re-inflates every sockwait figure by up to the new cap.
- The schedule is written out as a table with the corrected figures (attempt 8 at t=8.04 ms, cap from attempt 9 at t=12.31 ms).
TestWaitForUnixSocketBackoffGrowsAndIsCappednow fails if the cap exceeds 2 ms, so this cannot silently regress.
Net for #304 with the corrected cap: sockwait 24.92 → 20.34 ms and restore 27.73 → 23.20 ms, about 18% rather than the 11% I reported — and still nothing like the 5x the issue predicted. Throughput at c=4 is unchanged (57.00 vs 57.10), which is consistent with Destroy, not sockwait, being the bound at that slot count (#258).
| if elapsed < 80*time.Millisecond { | ||
| t.Fatalf("returned after %v, before its own %v budget", elapsed, 80*time.Millisecond) | ||
| } | ||
| // Finer polling must not overshoot either: the backoff cap bounds how late the last |
There was a problem hiding this comment.
Severity: medium — Finding 4/6: this assertion cannot detect a coarse cap, and nothing pins the backoff at all.
The comment says the 400 ms ceiling pins that "the backoff cap is too coarse" would be caught. It cannot be:
- I set
socketPollMax = 2 * time.Second(400x coarser) and ran this test at-count=3: all three passed, in 0.11 s each. With 1.5x growth from 250 µs the last sleep is at most ~0.5x the elapsed time, so total elapsed is bounded at ~1.5x the 80 ms budget (~120 ms) regardless of the cap — the 400 ms ceiling is unreachable for any cap value.
Worse, the backoff mechanism as a whole is untested. I replaced the entire growth block
if wait < socketPollMax {
if wait = wait * socketPollGrowthNum / socketPollGrowthDen; wait > socketPollMax {
wait = socketPollMax
}
}with nothing — a flat 250 µs poll, no growth, no cap — and all four tests in this file passed at -count=2. So a future edit that deletes the cap and burns ~4,000 probes/s per waiter (the very cost the rationale at launcher_firecracker.go:619-623 argues the growth exists to prevent) ships green.
Suggested change: pin the pacing directly rather than through wall-clock slack. Count probe attempts over a known window — e.g. wait ~200 ms against a socket that never appears and assert the attempt count lands in the range the schedule predicts (~50, not ~800) — which fails both for a removed cap and for a removed growth term. Alternatively make the sleep injectable, as clock_fake_test.go already does elsewhere in this package.
There was a problem hiding this comment.
Confirmed on both counts, fixed in 3179732.
The bind error now comes back over a channel and fails as FIXTURE failed to bind %s: %v (not a failure of waitForUnixSocket). You identified the real cost precisely: the old shape turned a fixture break into a 5 s timeout that then accused the production poll, with the assertion message compounding it.
Close moved inside the goroutine with a done channel, for the reason you give — waitForUnixSocket returns the instant the bind is visible, so a t.Cleanup registered after tRunner drained the list never runs.
Noted on the 10 ms assertion itself being robust (80/80, and 40x under -race with CPU hogs) — I have left that bound as it is rather than tightening it.
There was a problem hiding this comment.
(That reply landed on the wrong thread — finding 5's response is below; this thread is finding 4.)
There was a problem hiding this comment.
Finding 4 — confirmed, and the new test is mutation-tested
I reproduced both of your mutations before changing anything:
- entire growth block deleted (flat 250 µs poll, no growth, no cap) → all four tests green at
-count=2 socketPollMax = 2s→ timeout test green
So the backoff was genuinely unpinned, and the 400 ms ceiling cannot detect a coarse cap. That bound no longer claims to — its comment now states why (with 1.5× growth the last sleep is ≤ ~0.5× elapsed, so elapsed stays within ~1.5× the budget for any cap) and points at the new test.
Took your first suggestion: socketProbe is now a package var (same reasoning as phaseLog — "a variable rather than a bool so tests can capture"), and TestWaitForUnixSocketBackoffGrowsAndIsCapped waits 200 ms against a probe that never answers, asserting 120..400 probes.
Mutation-tested, every variant caught:
| mutation | probes over 200 ms | result |
|---|---|---|
| growth removed | 687 | caught (upper bound) |
| cap → 5 ms | 40 | caught (lower bound) |
| cap → 10 ms | 26 | caught |
| cap → 2 s | 16 | caught |
| cap removed | 16 | caught |
Worth recording a trap from building it: my first mutation script patched socketPollMax with a sed pattern whose spacing did not match gofmt's const alignment, so two mutations silently changed nothing and reported as MISSED. A mutation that fails to apply is indistinguishable from a test that catches nothing — the assertion in the script that the substitution actually altered the file is what caught it.
|
|
||
| // Stands in for Firecracker binding its API socket a couple of ms after the jailer | ||
| // execs it -- which is what the 2.80 ms of real work above actually is. | ||
| go func() { |
There was a problem hiding this comment.
Severity: low — Finding 5/6: the fixture swallows its own failure, and registers cleanup from a goroutine that can outlive the test.
Two problems in this goroutine:
-
net.Listen's error is discarded (if err != nil { return }). If the bind fails —/tmpnot writable,sun_pathoverflow (the very hazardsockBase's comment exists to avoid), a stale path — the test does not report a fixture failure. It sits for the full 5 s and fails withwaitForUnixSocket: timed out after 5s waiting for /tmp/..., i.e. it accuses the production poll of the bug. That is the confusing-diagnosis trap the assertion message at line 60 then compounds ("the fixed 20ms poll is still the floor"). -
t.Cleanupis called from a non-test goroutine and races the test's return.waitForUnixSocketreturns the momentbindbecomes visible, which can precede this goroutine reaching line 49; a cleanup registered aftertRunnerhas drained the list is never invoked, so thenet.Listenerfd leaks for the life of the test binary.
Suggested change: bind in the test goroutine and delay only the bind, or keep the goroutine but hand the error back over a channel and defer l.Close() inside the goroutine after the wait completes:
errc := make(chan error, 1)
go func() {
time.Sleep(2 * time.Millisecond)
l, err := net.Listen("unix", path)
errc <- err
if err == nil {
defer l.Close()
<-done
}
}()so a fixture break reads as a fixture break.
(Note: I could not make the 10 ms assertion itself flake — 80/80 green on an idle box, and 40x green under -race with 24 CPU hogs at -cpu=1. The schedule gives it until t = 8.04 ms to observe a bind nominally at 2 ms, which is ample slack. This finding is only about the failure diagnosis and the leak.)
There was a problem hiding this comment.
Finding 5 — confirmed on both counts, fixed in 3179732
(My reply to this went onto the finding-4 thread by mistake; it belongs here.)
The swallowed bind error. Now returned over a channel and asserted as FIXTURE failed to bind %s: %v (not a failure of waitForUnixSocket). You identified the real cost precisely: the old shape turned a fixture break into a 5 s timeout that then accused the production poll, with the assertion message at line 60 compounding it.
The off-goroutine t.Cleanup. Moved Close inside the goroutine behind a done channel, for exactly the reason you give — waitForUnixSocket returns the instant the bind becomes visible, which can precede the goroutine reaching the t.Cleanup call, and a cleanup registered after tRunner has drained the list never runs.
Noted on the 10 ms assertion itself being robust (80/80 on an idle box, 40× under -race with 24 CPU hogs at -cpu=1) — I have left that bound alone rather than tightening it, since the schedule gives it until t = 8.04 ms to observe a bind nominally at 2 ms.
|
|
||
| // waitForUnixSocket returns once something ANSWERS at path, or on timeout/cancellation. | ||
| // | ||
| // It DIALS rather than stats, and that is load-bearing in both directions: Firecracker |
There was a problem hiding this comment.
Severity: medium — Finding 6/6: "it DIALS rather than stats" is now a pinned invariant, but one caller cannot tolerate a probe dial. PRE-EXISTING — not introduced by this PR.
This comment, plus TestWaitForUnixSocketDialsRatherThanStats, elevates connect-and-close probing to a documented, test-enforced property of waitForUnixSocket for every caller. One caller cannot take it.
launcher_chv.go:918 waits on virtiofsd's vhost-user socket, and virtiofsdArgv (launcher_chv.go:356) starts it with only:
"--socket-path=" + sock,
"--shared-dir=" + dir,
"--sandbox=namespace",
"--cache=never",
"--inode-file-handles=prefer",In that mode the rust-vmm vhost-user backend accepts exactly one connection and the daemon exits when it drops. The probe's net.DialTimeout + immediate conn.Close() can therefore consume virtiofsd's single accept, leaving cloud-hypervisor with nothing to connect to when it starts at line 984. That matches the failure already recorded in this tree at launcher_chv.go:966-968 — "guessing at the vhost-user disconnect that provoked it", explicitly left unaddressed.
To be clear: this behaviour predates this PR — the dial-probe on fsSock is unchanged, and finer polling does not alter how many connections are accepted (still exactly one). What changes here is that the probe becomes an asserted invariant, which is the moment to record the exception.
Suggested change: either carve the vhost-user path out (for fsSock, wait on os.Stat + ModeSocket, or drop the wait and let cloud-hypervisor's own connect be the synchronisation point), or note the exception in this comment so the next reader does not take "dial, never stat" as universal. Worth confirming against the virtiofsd version actually deployed before changing behaviour — but the invariant as written should not claim to cover that caller.
There was a problem hiding this comment.
Confirmed, and filed as #316 rather than fixed here.
I verified the mechanism you describe: launcher_chv.go:918 dial-probes fsSock, virtiofsdArgv passes no flag that survives a dropped connection, and the tree already documents the symptom at launcher_chv.go:966-968 — "guessing at the vhost-user disconnect that provoked it ... that disconnect itself is NOT addressed by this change". A probe consuming the single accept is a concrete candidate for exactly that.
Not changing behaviour here, for the reason this file states about itself: there is no systemd + KVM host to verify the CHV arm, and the failure is intermittent, so a fix made on inference could look like it worked. Your framing is the part I took — elevating dial-not-stat to a test-enforced invariant is the moment to record the exception. waitForUnixSocket's doc now says the rule is about the Firecracker sockets and names this caller as the exception, pointing at the documented disconnect.
#316 carries your three options (drop the wait, stat for ModeSocket on that path only, or a flag that survives the disconnect) and the note to confirm against the deployed virtiofsd version first.
… schedule (rossoctl#315 review) Six findings, all reproduced before changing anything. **The committed rationale asserted what the PR description retracts.** The comment said the fixed sleep "set the replenishment rate, and with it an aggregate throughput ceiling" -- the exact inference the measurement falsified. The code comment is the durable artifact, so the retraction now lives there: the quantum was a measurement FLOOR, removing it was worth ~11% (24.92 -> 22.24 ms), and sockwait remains ~89% of a restore for reasons no poll change reaches. The same claim is corrected in the test. **The pacing arithmetic was wrong, and the residual grid still quantized the result.** Replayed: eight sleeps total **12.31 ms**, and the cap first applies at attempt 9, not "reaches the cap in 8 attempts having spent ~5 ms". The consequence matters more than the numbers -- above 12.31 ms the comb was the cap, so the "continuous" modes reported at [10,12), [14,16), [20,22), [26,28) were 4-6 ms apart because they WERE that comb. At a 5 ms cap the p50 of ~21 ms still carried up to 5 ms of our own sleep. So socketPollMax drops 5 ms -> **1 ms**: the comb is now finer than the thing being measured, sockwait is accurate to about +-1 ms, and reaching 25 ms costs ~27 probes. The comment states that resolution explicitly, because it bounds every attribution drawn from sockwait -- including the "~89% is Firecracker" figure. **Nothing pinned the backoff.** Confirmed both of the reviewer's mutations: deleting the growth and cap outright (a flat 250 us poll) left all four tests green at -count=2, and socketPollMax = 2s left the timeout test green at -count=3. The 400 ms ceiling cannot detect a coarse cap and no longer claims to -- with 1.5x growth the last sleep is at most ~0.5x the elapsed time, so elapsed stays within ~1.5x the budget for ANY cap. `socketProbe` is now a var (same reasoning as phaseLog) so a test can COUNT probes. TestWaitForUnixSocketBackoffGrowsAndIsCapped waits 200 ms against a probe that never answers and asserts 120..400. Mutation-tested -- every variant is caught: growth removed 687 probes cap 5 ms 40 probes cap removed 16 probes cap 10 ms 26 probes cap 2 s 16 probes (The first attempt at this check missed two mutations because the sed pattern's spacing did not match gofmt's alignment, so it silently changed nothing. Worth recording: a mutation that fails to apply is indistinguishable from a test that catches nothing.) **The fixture swallowed its own bind error and registered cleanup off-goroutine.** A failed bind surfaced as a 5 s timeout and read as "the production poll is broken" -- the wrong diagnosis, compounded by the assertion message. The error now comes back over a channel and reads as a FIXTURE failure. Close moved inside the goroutine: t.Cleanup from a non-test goroutine races the test's return, and waitForUnixSocket can return the instant the bind is visible, so the listener fd could leak for the life of the test binary. **"It DIALS rather than stats" is now documented as NOT universal.** launcher_chv.go waits here on virtiofsd's vhost-user socket, and virtiofsdArgv passes no flag that survives a dropped connection -- the rust-vmm backend accepts exactly one connection and exits when it drops, so this probe's connect-and-close can consume the accept cloud-hypervisor then needs. That predates this change and finer polling does not alter how many connections are accepted, but elevating the dial to a test-enforced invariant is the moment to record the exception rather than imply it covers every caller. No behaviour changed on that path: this tree records having no systemd + KVM host to verify that arm, and it already documents the vhost-user disconnect as unexplained and unfixed. Filed separately rather than fixed on inference. **The old three-line doc bound to the const block.** Deleted; the function's own doc covers it, so the accept() fact no longer lives in two places that can drift. Verified: `go test ./...` 9 packages exit 0, timing tests 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]>
…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]>
Closes #304.
waitForUnixSocketretried on a fixedtime.After(20 * time.Millisecond), so no restore couldobserve its socket sooner than one full quantum. Replaced with backoff from 250 us growing 1.5x
to a 5 ms cap, applied after the sleep so the first retry is always the fine one.
It works — and it buys much less than this issue predicted
The floor is gone. Restore
sockwaitdistribution at 4 slots onsrv-r16b14s16, 1,625restores either side:
But the mean only moved 24.92 -> 20.34 ms, and the restore 27.73 -> 23.20 ms — about 18%.
(First measured at 22.24 ms with a 5 ms cap. Review finding 3 showed that still carried ~2 ms of
our own sleep — the "modes" 4-6 ms apart were the residual comb, not a distribution. The cap is
now 1 ms, which confirmed the prediction: the mean fell a further 1.90 ms. sockwait is therefore
measured to about +-1 ms, and that bound is what limits any attribution drawn from it.)
This issue (and my own earlier comment on it) argued the win would be ~5x, reasoning that
sockwaitwas 90% of a restore over 2.80 ms of real work, so the socket must be appearing insingle-digit milliseconds and the caller merely sleeping past it. That inference was wrong, and
the old data could not have supported it: at 20 ms granularity, "appears at 2 ms" and "appears
at 19 ms" are the same measurement. With fine polling the true distribution is visible, and on
this host the socket genuinely takes ~9-35 ms to appear, centred near 18.5 ms. The quantum was
coincidentally close to the real cost.
So
sockwaitis still ~88% of a restore at 4 slots. That is now a measurement of Firecracker'sstartup, not of our sleep, and it is no longer something a poll change can recover.
Why it is still worth merging
bounded 100% of them, and the fastest observed halved (20.06 -> 9.37 ms).
socket from a slow one, which is precisely how the 5x estimate survived as long as it did.
sockwaitat 64 slots is 299 ms against 1722 ms before,though that comparison is contaminated by microVM: two empty dirs leak per VM id, and a sudo-glob hazard when probing jail internals #255 and should not be read as this change's work.
Verification
Four tests; the first fails at 21.41 ms before the change:
Restore'scleanup()depends on it to unwind promptlyThe dial-vs-stat test matters in both directions: Firecracker creates the socket file before it
accept()s, so a stat would report ready early and race the snapshot PUT, andfcJailOccupied'sid-collision guard rests on the same distinction.
go test ./...9 packages exit 0, timing-sensitive tests pass at-count=5;go vet,gofmt,make lintclean. Local pacing check (15 samples per point, listener bound at a known delay):a socket appearing at 2 ms is observed at 2.29 ms, at 5 ms at 5.94 ms — tracking within ~0.3-0.9 ms.
The 5 s overall ceiling is deliberately unchanged: the 396 timeouts seen at c=64 came from
#255's cgroup leak (fixed in #314), and the re-run below took zero timeouts at any slot count,
so the pressure that made 5 s look tight is gone.
🤖 Generated with Claude Code