Skip to content

feat(vmpool): surface Exec/restore phases and add opt-in pprof - #308

Merged
pdettori merged 3 commits into
rossoctl:mainfrom
pdettori:diag/expose-exec-phases-and-pprof
Sep 21, 2026
Merged

pdettori merged 3 commits into
rossoctl:mainfrom
pdettori:diag/expose-exec-phases-and-pprof

Conversation

@pdettori

Copy link
Copy Markdown
Member

Summary

Makes the worker's hot path measurable. Phases and ExecPhased already decompose an Exec into
Acquire/Resume/Run/Destroy, and vmpoolctl already drives them — but vmpool.Runner,
the path microvm-worker actually serves, called Pool.Exec with a throwaway Phases. So
nothing 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:

finding issue
session.DefaultConcurrency = 4 caps a worker at 4 concurrent Execs and set every E11 throughput number; raising it took one worker 62.99 -> 172.88 Exec/s #305
Destroy is 55% of an Exec (33.7ms of 61.4ms); the command itself is 6.6% #307
90% of a restore is waitForUnixSocket's fixed 20ms sleep — and the restore path does not serialize at all #304, #303

This PR makes that decomposition available without a custom build. It is instrumentation only:
no scheduling, admission, teardown or refusal behaviour changes.

Changes

  • Runner.Run uses ExecPhased instead of Exec. Free: Exec delegates to ExecPhased
    with a throwaway Phases, so this is the same code path with the output kept rather than
    discarded.
  • SH_DIAG_PHASES=1 emits one line per Exec, and one per restore with its five phases. The
    hook is a nil function pointer, so the cost when off is one nil check per Exec.
  • SH_DIAG_PPROF=<addr> enables net/http/pprof plus block and mutex profiling.
  • Two tests: the default-off contract, and that all four phases are named.

Security note on the pprof endpoint

Off unless SH_DIAG_PPROF is set. pprof serves goroutine dumps, heap contents and command lines
to anyone who can reach the address, so the code comment says to bind loopback
(127.0.0.1:6060) and reach it over ssh, never 0.0.0.0. Flagging it explicitly because this is
the one part of the diff that could widen an attack surface if misconfigured.

Design notes worth a reviewer's attention

  • Why the restore timing is unconditional. Five time.Now() calls (~100ns) against a restore
    measured 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.
  • Why a func and not a bool. It lets the test capture lines instead of asserting against a
    logger'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.
  • TestRunnerEmitsAllFourPhases asserts the field set, not durations. Asserting on values
    would make it a clock test. What it catches is someone swapping ExecPhased back to Exec,
    after which the phases silently become zero rather than failing.
  • phaseLog is package state, so capturePhaseLog must not be used from a parallel test that
    Execs. Noted in its doc comment.

Verification

  • go build ./..., go vet, and the full remote-worker suite: 9 packages, exit 0, on
    linux/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.
  • No change to deploy/microvm/predictions.json or EXPERIMENTS.md.

Not in scope

The fixes the instrumentation points at are deliberately separate, since each is a design decision
rather than a measurement: the MaxConcurrent default (#305), the 20ms poll (#304, wants TDD),
Destroy's cost (#307), and replacing coldAcquireRate with the real Phases.Cold (#306 — the
proxy reported 0.76 where the truth was 0.056).

Refs #303, #304, #305, rossoctl/moca-experiments#8, #307

🤖 Generated with Claude Code

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 mrsabath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ExecPhased swap really is free. pool.Exec is a one-line delegation to ExecPhased(…, nil) (pool.go:200-202), and ExecPhased nil-guards every write behind if ph != nil. Same code path, output kept rather than discarded — exactly as described.
  • The pprof surface is tight. The blank net/http/pprof import registers on DefaultServeMux, so the thing worth checking is whether any other listener serves that mux. It does not: the only ListenAndServe in the worker is the SH_DIAG_PPROF-gated one, and the worker's real traffic is gRPC (sess.Serve). Elsewhere in main.go net/http is client-only. Default-off, and the loopback warning sits where someone setting the variable will actually read it. runtime was 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, and total_us is measured independently rather than summed, so the individual terms cannot silently drift away from the whole.
  • Cost-when-off is what is claimed. phaseLog is a nil func pointer and logPhases returns on the nil check. On the unconditional time.Now() calls in Restore — 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="} {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed 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]>
@pdettori

Copy link
Copy Markdown
Member Author

Heads-up on a commit that is outside this PR's stated scope, since the approval was for instrumentation only.

639d250 changes packages/config-bundle/test/preflight.test.ts. It is the blocking CI failure, pre-existing on main and unrelated to the instrumentation — check went red on checkMemoryLinks ReDoS resistance, which asserts a wall-clock ratio. I re-ran it first rather than touching it, and it failed again on a different shape:

run shape ratio limit
1 a run of '[[' 3.11 3
2 a run of '[' 5.64 3

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 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 locally under 2x CPU oversubscription:

true cost (idle) best of 9 under load
small input 10.6 ms 10.6 ms — clean floor reached 4/9
large input 20.3 ms 32.8 ms — floor never reached

The large window is too long to ever find an uncontended slot, so neither more samples nor a min estimator repairs it. Idle, every shape measures exactly 2.00x — the signal is real, the instrument was not.

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 [^\]]+ / [^)]+ and cannot be matched by {1,300} / {1,500}. That is the ReDoS regression itself.

Verified both directions: 3 tests fail in 4 ms with the regexes unbounded in src/preflight.ts, 34/34 pass on the real code, and 5/5 runs pass under the same oversubscription that produced ratios of 3.09–8.33. Side effect: config-bundle's suite goes 8.6 s -> 0.6 s, since the old form burned ~7 s of contended CPU per run — some of which was itself the contention.

Two things worth a reviewer's eye:

  • The retained 30 s anti-hang assertion does not catch the unbounded regression on its own (measured 24.7 s, under the ceiling). That is deliberate — it is a backstop against a true hang, not the primary assertion, and the comment says so. The deterministic tests are what catch the regression.
  • Pinning "an over-cap link is not reported" pins a real cost of the ReDoS fix: a pathological link is silently skipped. That was already the intended behaviour (src/preflight.ts says real links are far inside the bounds); it is now asserted rather than implicit.

Separately, proto failed once on TestAnExecThatNamesNoTimeoutIsStillBounded (timeout_test.go:79, "2 VMs live after the default bound fired") and passed on re-run with no change. I did not assume a flake, since this branch does touch internal/vmpool: proto passed on the preceding commit 80a65d0, and the only change since was the TypeScript file above, which cannot alter Go behaviour. timeout_test.go is untouched by the branch, and the instrumentation is not on its path — logPhases is reached only from Runner.Run, while that test calls p.Exec directly. It would not reproduce locally (30 runs under load, 8 full-suite runs at GOMAXPROCS=2 under load, and a deliberately widened race window all clean), so its root cause is unknown rather than diagnosed — flagging it as a latent flake in the package rather than claiming it fixed.

All 13 checks are green on 639d250.

@pdettori
pdettori merged commit 00e277e into rossoctl:main Sep 21, 2026
17 of 18 checks passed
@pdettori
pdettori deleted the diag/expose-exec-phases-and-pprof branch September 21, 2026 16:21
pdettori added a commit to pdettori/moca that referenced this pull request Sep 22, 2026
… 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]>
moonlight16 pushed a commit to moonlight16/moca that referenced this pull request Sep 25, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants