Repository navigation
feat(vmpool): surface Exec/restore phases and add opt-in pprof - #308
Conversation
The worker's hot path was unmeasurable. `Phases` and `ExecPhased` already decompose an
Exec into Acquire/Resume/Run/Destroy, and `vmpoolctl` already drives them — but
`vmpool.Runner`, which is the path microvm-worker actually serves, called `Pool.Exec`
with a throwaway `Phases`. So nothing about the relayed path could be attributed to a
phase without rebuilding the worker by hand.
Three findings came out of doing exactly that rebuild, and none were obtainable
otherwise:
- session.DefaultConcurrency = 4 caps a worker at 4 concurrent Execs, which is what
set every E11 throughput number. Raising it took one worker from 62.99 to 172.88
Exec/s (rossoctl#305).
- Destroy is 55% of an Exec (33.7ms of 61.4ms) and the command itself is 6.6% (rossoctl#307).
- 90% of a restore is waitForUnixSocket's fixed 20ms sleep (rossoctl#304), which also showed
the restore path does not serialize at all (rossoctl#303).
This makes that decomposition available without a custom build.
Runner.Run now calls ExecPhased instead of Exec. That costs nothing: Exec delegates to
ExecPhased with a throwaway Phases, so this is the same code path with the output kept
rather than discarded.
Phase lines are emitted only when SH_DIAG_PHASES=1. The hook is a nil function pointer,
so the cost when off is one nil check per Exec, and TestPhaseLogIsOffByDefault pins that
default-off contract — a diagnostic that defaulted on would put a log line on the hot
path of every Exec in production.
SH_DIAG_PPROF=<addr> enables net/http/pprof plus block and mutex profiling. Off unless
the address is set, and the comment says to bind loopback: pprof serves goroutine dumps,
heap contents and command lines to anyone who can reach it. Its absence is what forced
localising the hot path by SIGQUIT-ing the worker, which kills it.
The restore phase timing takes five time.Now() calls unconditionally and gates only the
log line. That is ~100ns against a restore measured in tens of milliseconds; branching
each one would be noise for no measurable gain.
TestRunnerEmitsAllFourPhases is the regression this package did not have: if someone
swaps ExecPhased back to Exec, the phases silently become zero rather than failing. It
asserts the field set rather than any duration, since asserting on values would make it
a clock test.
Verified on linux/amd64 (go 1.25) against this base as well as darwin/arm64: build, vet
and the full remote-worker suite pass, 9 packages, exit 0.
Refs rossoctl#303, rossoctl#304, rossoctl#305, #306, rossoctl#307
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
mrsabath
left a comment
There was a problem hiding this comment.
Instrumentation-only, correctly scoped, and the security-sensitive part is handled well. One suggestion on a test that does not hold the line its comment says it holds — non-blocking, since nothing in production behaviour depends on it.
Verified as correct.
- The
ExecPhasedswap really is free.pool.Execis a one-line delegation toExecPhased(…, nil)(pool.go:200-202), andExecPhasednil-guards every write behindif ph != nil. Same code path, output kept rather than discarded — exactly as described. - The pprof surface is tight. The blank
net/http/pprofimport registers onDefaultServeMux, so the thing worth checking is whether any other listener serves that mux. It does not: the onlyListenAndServein the worker is theSH_DIAG_PPROF-gated one, and the worker's real traffic is gRPC (sess.Serve). Elsewhere inmain.gonet/httpis client-only. Default-off, and the loopback warning sits where someone setting the variable will actually read it.runtimewas already imported, so no new dependency either. - The restore-phase arithmetic is right. The running-difference chain (
time.Since(phaseStart) - phPrep - …) is correct at each step, andtotal_usis measured independently rather than summed, so the individual terms cannot silently drift away from the whole. - Cost-when-off is what is claimed.
phaseLogis a nil func pointer andlogPhasesreturns on the nil check. On the unconditionaltime.Now()calls inRestore— you offered to gate them; I would leave them. Five calls at ~100ns against a restore in tens of milliseconds is not worth a branch, and the asymmetry you describe is the right read.
On the test counts. I see 2 failures locally (TestDialVsockCompletesTheConnectHandshake, TestDialVsockFailsOnARefusedConnect), both mkdir /tmp/...: operation not permitted from my sandbox, and both reproduce identically on origin/main. Not attributable to this PR — the stated 9-packages-exit-0 on linux/amd64 is consistent. go build ./... and go vet ./... are clean here.
Minor, and I would not change it: the os.Link / os.Chown of workspace.img sits between the phWsImg and phJailer markers, so its cost lands in jailer_us rather than wsimg_us. Since total_us is measured independently nothing is lost, and given the finding this exists to support is a 20ms sleep in sockwait_us, the mislabelling is immaterial.
Scope discipline is good: the five issues the instrumentation points at (#303–#307) are correctly left out, and predictions.json / EXPERIMENTS.md are untouched as claimed.
Areas reviewed: Go (vmpool, microvm-worker), Go tests, security (pprof exposure)
Commits: 1, all signed-off: yes
CI status: passing (13 checks)
| // Every phase must be NAMED. Asserting on values would be a clock test; asserting on | ||
| // the field set is what catches a dropped phase or a rename, which is the failure that | ||
| // makes an aggregated run silently miss a term. | ||
| for _, field := range []string{"acquire_us=", "resume_us=", "run_us=", "destroy_us=", "cold="} { |
There was a problem hiding this comment.
suggestion — this test does not catch the regression its doc comment claims, and the claim is the reason someone would trust it later.
Line 44 says: "If someone swaps ExecPhased back to Exec, the phases silently become zero and this fails." I made exactly that edit in runner.go — ExecPhased → Exec, dropping the &ph argument — and the test still passes. logPhases(&ph) is called unconditionally on a zero-valued Phases, so all five field names appear in the output whether or not anything populated them. What the loop pins is the log format, which is genuinely worth pinning since these fields get parsed when aggregating a run — it just does not pin the wiring.
The fix is not a duration assertion. testPool's clock does not advance, so all four durations are legitimately 0 even on correct code and asserting nonzero would be flaky — I checked. cold is the field that discriminates: ExecPhased sets ph.Cold = cause, and this test's first Exec yields cold="first-exec", against cold="" on the reverted path.
if strings.Contains(got, `cold=""`) {
t.Errorf("cold is empty: Phases was not populated (Exec, not ExecPhased): %s", got)
}I verified both directions: this passes on the real code and fails on the reverted code, deterministically and with no clock dependency.
Not blocking — the production change is correct either way, and the format assertion has independent value. But since the stated purpose of the test is catching that specific swap, it is worth closing the gap while the reasoning is fresh.
There was a problem hiding this comment.
Confirmed and fixed in 80a65d0. I reproduced your edit — ExecPhased → Exec, dropping &ph — and the test passed, exactly as you said. logPhases runs unconditionally on whatever it is handed, so the five field names appear against a zero-valued Phases; the loop pinned the format and nothing else.
Your diagnosis of cold as the discriminating field is right, and so is the reason a duration assertion is not the fix. I took the positive form rather than the negative one:
if want := fmt.Sprintf("cold=%q", string(ColdFirstExec)); !strings.Contains(got, want) {
t.Errorf("phase line has no %s -- Phases was not populated (Exec, not ExecPhased): %s", want, got)
}It fails everywhere cold="" would, and additionally catches the cause being plumbed through as the wrong value rather than merely as empty. ColdFirstExec as a constant instead of the literal keeps this test about the wiring — replenish_test.go already pins the constant's spelling.
On determinism: acquire reaches ColdFirstExec via fresh from runLocked, and this is a fresh pool's first Exec on an unseen key with no standbys pre-filled, so it cannot come out as parked or exhausted. Verified both directions — fails on the reverted code, passes on the real code — plus -count=20 -race clean, all 9 packages exit 0, go build and go vet clean.
The field-set loop stays, for the format-pinning value you noted. The doc comment's claim now holds.
… wiring TestRunnerEmitsAllFourPhases claimed to catch a revert of ExecPhased back to Exec, but it did not: logPhases runs unconditionally on whatever Phases it is handed, so all five field NAMES appear even when nothing populated them. The swap passed the test. Cold is the field that discriminates. ExecPhased sets ph.Cold from acquire's ColdCause; Exec leaves the throwaway Phases zero. This test's Exec is a fresh pool's first Exec on an unseen key, so the cause is deterministically first-exec, against "" on the reverted path -- no duration assertion, and so no dependence on the fake clock, which does not advance and legitimately leaves all four phases at 0 on correct code. Verified both directions: fails with ExecPhased swapped to Exec, passes on the real code, and 20x under -race. The field-set loop is kept: it pins the log format, which is parsed when aggregating a run. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ll clock The ReDoS scaling test failed CI on this PR twice in a row, on two different shapes, at ratios of 3.11 and 5.64 against a limit of 3. The 5.64 is the decisive number: it is ABOVE the ~4x that marks the quadratic form the limit exists to sit below, so on a two-core runner that measurement cannot tell a ReDoS regression from a busy neighbour at any threshold. The ratio was adopted (4fea73b) to replace a wall-clock budget, on the reasoning that contention slows both measurements and cancels. It does not: `make test` runs seven workspaces in parallel, and the interference is additive per unit of wall clock, so the longer measurement absorbs more of it. Measured under 2x CPU oversubscription, the nested shape's small input still reached its true 10.6ms floor in 4 of 9 samples while its large input never got below 32.8ms against a true 20.3ms -- ratios of 3.09 (min/min) to 8.33 (worst). More samples cannot help; there is no uncontended window of the longer length to find. Idle, every shape measures exactly 2.00x, so the signal is real and only the instrument was wrong. So pin the property where it comes from: the bound on each quantifier. An over-cap title or target, and a link spanning a newline, are matched by the unbounded `[^\]]+` / `[^)]+` and cannot be matched by `{1,300}` / `{1,500}`. That is the ReDoS regression itself, observable with no clock. Verified both directions: 3 tests fail in 4ms with the regexes unbounded, all 34 pass on the real code, and 5/5 runs pass under the same oversubscription that produced the ratios above. Also drops config-bundle's suite from 8.6s to 0.6s, since the old form burned ~7s of contended CPU on every run -- some of which was the contention. The one timing assertion kept is an anti-hang backstop at 30s against a real cost of ~130ms; a 200x margin no runner load reaches. Note this touches a package the rest of the PR does not. It is the blocking CI failure, pre-existing on main and unrelated to the instrumentation, so it could not be landed separately without leaving this PR red. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
|
Heads-up on a commit that is outside this PR's stated scope, since the approval was for instrumentation only.
The 5.64 is the decisive number: the limit exists to sit between linear (~2x) and quadratic (~4x), and observed noise above 4x means that on a two-core runner the measurement cannot separate a ReDoS regression from a busy neighbour at any threshold. So raising the limit was not an option and re-running was not either. The ratio was adopted in
The large window is too long to ever find an uncontended slot, so neither more samples nor a The fix drops the clock. The property comes from the bound on each quantifier, and that is directly observable: an over-cap title (>300) or target (>500), or a link spanning a newline, is matched by the unbounded Verified both directions: 3 tests fail in 4 ms with the regexes unbounded in Two things worth a reviewer's eye:
Separately, All 13 checks are green on |
… model fit and three ratios All ten findings from @huang195, @mrsabath and @aslom were checked against `main` and all were correct. The cold-rate finding resolves better than the reviews assumed. Both tables already used `coldAcquireRateTrue`, diffed from the worker's vmpool.Stats counters, not the `coldAcquireRate` latency proxy #306 discredits. The records show why that matters: across these rungs the proxy reads a saturated 1.000 everywhere, carrying no information, while the true metric tracks the ladder 0.142 -> 0.698. Now labelled, and #306 reconciled rather than hedged: its ">99% warm at c=16, the restore was never on the hot path" was measured under the 4-slot cap where demand was four slots' worth. Past 64 slots demand outruns replenishment and the true cold rate reaches 0.698, so the restore is on the hot path in this regime and was not in that one. Both readings are right about their own configuration. The "each then paying a full restore" phrasing is replaced with the measured share, and the note now says the argument stands on `Acquire` growing 65x regardless of how coldness is counted. Corrected arithmetic: - "within ~4%" was wrong and wrong at the peak: the model over-predicts by 6.4% at 64 slots, 4.2% at 128, 2.9% at 256. Stated with the table. - Two per-Exec totals were in use without the difference being named. The column is summed instrumented sub-phases (104.11 ms); wall-clock per slot is slots/throughput (110.81 ms). The 2.8-6.0% residual is uninstrumented time, and by this document's own rule about unexplained zeros it is now flagged as a lower bound rather than passed over. Resume+Destroy is given against both denominators: 90.0% of summed, 84.6% of wall-clock. - "roughly 90x" on memory did not follow from any figure present. Replaced with the divisions shown: 144x worst observed VM, 320x mean, 58x budget against host memory used. 144x is the one to quote. - The gains table explained its own non-composition with "each was measured against the tree that preceded it", which is the reason they *would* compose. Real cause named: each was measured at the slot count and configuration current when it landed. Composed they give 56x against an actual 9.2x. - 577.55 and 580.60 are now labelled as separate sessions, with the 0.5% spread placed inside the measured 2.9% drift. Also: the tier's shipped default is 16 (rossoctl#313), deliberately 4x below the measured peak, and reaching 64 needs WORKER_MAX_CONCURRENT set — the capacity section said "raised" without saying from what. The self-describing rung record is rossoctl#312's work; rossoctl#313 never touched the driver. `session.MaxConcurrent` is not a symbol; the constant is `session.DefaultConcurrency = 4`. In the dead-ends note: `microvm-worker` does have a pprof endpoint on `main` since rossoctl#308, so the "it had none" lesson is marked as acted on rather than left to be re-added; and the pointer into EXPERIMENTS.md section E11 now directs readers to rossoctl#305 and PR rossoctl#300, since the section still carries the pre-correction banner until rossoctl#300 merges. Refs rossoctl#305 #306 rossoctl#308 rossoctl#312 rossoctl#313 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…rs (#306) coldAcquireRate is a latency-classification proxy: the share of Execs slower than SH_E11_COLD_LATENCY_MS. Measured against vmpool.Phases.Cold on the same runs it was wrong by 13x at c=8 (0.76 reported vs 0.056 true) and by ~250x at c=16 (~1.0 vs 0.0039). It cannot be repaired by tuning the threshold: Acquire is 0.3% of an Exec, so no threshold on end-to-end latency separates a warm acquire from a cold one. vmpool has always maintained the real figures in Stats.WarmAcquires/.ColdAcquires. Nothing outside vmpoolctl could read them, because the worker never exposed Stats at all. This adds that transport -- chosen over parsing SH_DIAG_PHASES lines because the counters are already authoritative and a log format is not a contract. microvm-worker now serves them on SH_DIAG_STATS_ADDR, opt-in and separate from SH_DIAG_PPROF so that obtaining counters does not require exposing heap contents, goroutine dumps and command lines. The handler is on its OWN mux, never http.DefaultServeMux: this package imports _ "net/http/pprof", whose handlers register on the default mux at import time, so /stats there would have smuggled rossoctl#308's documented pprof exposure in behind a different variable. A test pins that, and it was verified to fail against the default mux (all three pprof paths returned 200). The driver diffs the counters across each rung's own timed window -- they are process-lifetime totals, so a rung reading them absolutely would report every earlier rung's acquires as its own -- and records coldAcquireRateTrue beside the proxy rather than replacing it, so the two can be compared on one run before the proxy is renamed and retired (#306 step 3, deliberately not in here: that wants the comparison first). -1, never 0, when the rate cannot be determined: no acquires in the window, counters that went backwards because the worker restarted, or an arm with no microvm-worker to ask. Zero cold out of zero acquires would read as "replenishment kept up perfectly", the optimistic direction this file refuses everywhere else; -1 is outside [0,1]. Also records maxConcurrent, reported BY THE WORKER rather than assumed by the driver. Every E11 microVM rung ever recorded swept c to 64 against a 4-slot cap the driver never set and never wrote down, and at every point measured so far it was that, not the pool, which set throughput (rossoctl#305). Two proxyLimitations disclosures became false the moment the endpoint existed and are corrected: coldAcquireRate's "no stats endpoint exists", and standbysResident's "no pool introspection endpoint exists" -- the latter now says the endpoint exists while the field is still the proxy, so it cannot be misread as a pool statistic. Found by the tests, worth recording: the first draft wired SH_DIAG_STATS_ADDR into start_container_stack (whose worker is cmd/worker and has no pool at all), and the record-shape check was passing vacuously by matching 'coldAcquireRate' against its proxyLimitations disclosure string instead of the field, because the extraction was anchored at the 'arm' field, which appears AFTER it in the template. 481 bash checks (470 before), 9/9 Go packages, gofmt/vet/shellcheck/prettier clean, and experiments' microvm-predictions still passes. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Summary
Makes the worker's hot path measurable.
PhasesandExecPhasedalready decompose an Exec intoAcquire/Resume/Run/Destroy, andvmpoolctlalready drives them — butvmpool.Runner,the path
microvm-workeractually serves, calledPool.Execwith a throwawayPhases. Sonothing on the relayed path could be attributed to a phase without rebuilding the worker by hand.
Doing that rebuild by hand produced three findings that were not obtainable otherwise:
session.DefaultConcurrency = 4caps a worker at 4 concurrent Execs and set every E11 throughput number; raising it took one worker 62.99 -> 172.88 Exec/sDestroyis 55% of an Exec (33.7ms of 61.4ms); the command itself is 6.6%waitForUnixSocket's fixed 20ms sleep — and the restore path does not serialize at allThis PR makes that decomposition available without a custom build. It is instrumentation only:
no scheduling, admission, teardown or refusal behaviour changes.
Changes
Runner.RunusesExecPhasedinstead ofExec. Free:Execdelegates toExecPhasedwith a throwaway
Phases, so this is the same code path with the output kept rather thandiscarded.
SH_DIAG_PHASES=1emits one line per Exec, and one per restore with its five phases. Thehook is a nil function pointer, so the cost when off is one nil check per Exec.
SH_DIAG_PPROF=<addr>enablesnet/http/pprofplus block and mutex profiling.Security note on the pprof endpoint
Off unless
SH_DIAG_PPROFis set. pprof serves goroutine dumps, heap contents and command linesto anyone who can reach the address, so the code comment says to bind loopback
(
127.0.0.1:6060) and reach it over ssh, never0.0.0.0. Flagging it explicitly because this isthe one part of the diff that could widen an attack surface if misconfigured.
Design notes worth a reviewer's attention
time.Now()calls (~100ns) against a restoremeasured in tens of milliseconds; only the log line is gated. Branching each would be noise for
no measurable gain. Happy to gate them if you would rather have zero added instructions.
funcand not abool. It lets the test capture lines instead of asserting against alogger's side effects, and keeps the field names in one place — they get parsed when aggregating
a run, and a silently renamed field reads as a missing phase rather than an error.
TestRunnerEmitsAllFourPhasesasserts the field set, not durations. Asserting on valueswould make it a clock test. What it catches is someone swapping
ExecPhasedback toExec,after which the phases silently become zero rather than failing.
phaseLogis package state, socapturePhaseLogmust not be used from a parallel test thatExecs. Noted in its doc comment.
Verification
go build ./...,go vet, and the fullremote-workersuite: 9 packages, exit 0, onlinux/amd64 (go 1.25) against this exact base, and on darwin/arm64.
make lint(pre-commit, all files): passes, including prettier, shellcheck and the secrets scan.deploy/microvm/predictions.jsonorEXPERIMENTS.md.Not in scope
The fixes the instrumentation points at are deliberately separate, since each is a design decision
rather than a measurement: the
MaxConcurrentdefault (#305), the 20ms poll (#304, wants TDD),Destroy's cost (#307), and replacingcoldAcquireRatewith the realPhases.Cold(#306 — theproxy reported 0.76 where the truth was 0.056).
Refs #303, #304, #305, rossoctl/moca-experiments#8, #307
🤖 Generated with Claude Code