Skip to content

feat(vmpool): charge paused standbys at dirty-page cost in admission control - #647

Merged
pdettori merged 3 commits into
rossoctl:mainfrom
pdettori:fix/644-standby-dirty-charge
Oct 28, 2026
Merged

pdettori merged 3 commits into
rossoctl:mainfrom
pdettori:fix/644-standby-dirty-charge

Conversation

@pdettori

Copy link
Copy Markdown
Member

Fixes #644.

Problem

vmpool's memory gate charged every VM at full PerVMBytes, running or paused, so each workspace booked (1+D)×PerVMBytes while unparked. On SBX0 (4 GiB guests, D=2, 172 GiB budget) that capped the host at ~14–22 concurrent sandboxes while nearly idle:

  • AM6: every microVM ladder stop was RefuseMemoryBudget with 150–178 GiB of 188 free.
  • E11: per-VM cgroup memory.current at 0.9 MiB mean / 2 MiB max vs a 288 MiB limit — 144× below the charge — because VMs COW-share one mlocked page-cache-resident memfile.

The full-RAM booking double-counted a hazard the slot count already bounds: only WORKER_MAX_CONCURRENT VMs can run at any moment.

Change

Split the admission charge by VM state (committedLocked = running + standby component):

  • Running (inFlight) and warming VMs: full PerVMBytes. Their total is bounded by the slot count; slotBudgetWarning now warns on that running-component arithmetic (slots × PerVMBytes vs budget) instead of the old slots × (1+D) worst case.
  • Paused (ready) standbys: dirty-page cost (standbyChargeLocked): per-VM cgroup memory.current × StandbyHeadroom, floored at VMOverheadBytes, capped at PerVMBytes. Knob: SH_STANDBY_HEADROOM (default 4; a number ≥ 1, or full to restore the pre-microvm-worker: charge paused standbys at dirty-page cost in admission control (SBX0 density) #644 full-RAM charge on the same binary). An unreadable footprint charges full price — fail-safe, the cgroupPool.release posture.
  • Promotion-time re-pricing (admitPromotionLocked): a warm acquire re-prices the popped standby at full PerVMBytes before the pop, as a pure check. This is the invariant that makes dirty charging safe — a host cannot promote more standbys to running than it could have admitted cold. Dead code when slots × PerVMBytes fits the budget; fires (correctly, as a failed exec) on a mis-sized host.
  • Eviction, not refusal, for the paused component: evictForBudgetLocked is now a loop — under dirty charge one standby frees only its dirty charge, so funding a full-price admission can take several evictions. Sheds standbys coldest-run-first until the triggering admission fits; bounded by reclaimQ capacity; degenerates to the old single eviction under headroom=full.
  • Host backstop: opt-in SH_HOST_MEM_FLOOR_MB refuses admission when host MemAvailable drops below it, with a distinct refusal reason RefuseHostMemory ("host-memory") so density ladders can distinguish budget-sizing refusals from genuine host exhaustion (spec §6). Fails closed on an unreadable /proc/meminfo.

Both real launchers implement the standbyFootprinter seam (StandbyBytes()) with a cached-once read — firecrackerVM from its pooled cgroup, chvVM from its systemd scope cgroup (built from the same naming authorities the orphan sweep uses).

Observability: Stats/diag gain StandbyCommittedBytes beside CommittedBytes; the worker banner prints standby_headroom and mem_floor; vmpoolctl's run record gains standby_headroom, budget_evictions, and standby_committed_bytes.

Deliberate deviation from the issue sketch

Warming VMs are charged full price, not dirty. A warming VM has no footprint to read at the moment admitLocked prices it (its cgroup exists and is empty), and rp.warming does not distinguish a replenishment that will park from a cold acquire that will run. Charging both at full is pessimistic only for the ~10–25 ms of the restore, self-limiting in the right direction, and keeps the warming → inFlight handoff charge-neutral.

Non-goals (per the issue)

Guest RAM right-sizing, #274 restore cost, any wire/proto change.

Verification

  • go vet + full remote-worker suite (go test -count=1 ./..., 16 packages) green; -race on internal/vmpool, cmd/microvm-worker, cmd/vmpoolctl.
  • New tests in standby_charge_test.go: dirty-cost charging, floor/ceiling clamps, unreadable-footprint fail-safe, headroom=full legacy restore, pop-time re-pricing (refusal leaves the standby in place), eviction shedding exactly as much dirty charge as an admission needs (non-vacuity verified by mutation: a single-eviction revert makes it fail), host-floor refusals distinct from budget refusals (incl. promotion and fail-closed), and StandbyHeadroom validation.
  • vmpoolctl's bulk-scale reachability test moved its assertion from the refusal counter to the eviction counter — a paused-side fan-out past the budget now sheds standbys rather than refusing, which is the intended microvm-worker: charge paused standbys at dirty-page cost in admission control (SBX0 density) #644 behavior; the gate still bites, measurably.

On-hardware follow-up (out of scope for this PR): re-run the AM6 density ladder on SBX0 to confirm the ceiling lifts from ~14–22 sandboxes toward the slot count, and to pin SH_STANDBY_HEADROOM empirically (the default of 4 is the conservative end of the issue's 2–4× range).

Assisted-By: Claude Code

…control (rossoctl#644)

vmpool's memory gate charged every VM at full PerVMBytes, running or
paused, so each workspace booked (1+D) x PerVMBytes while unparked. On
SBX0 (4 GiB guests, D=2, 172 GiB budget) that capped the host at
~14-22 concurrent sandboxes while nearly idle: AM6 stopped every
microVM ladder rung on RefuseMemoryBudget with 150-178 GiB of 188 free,
and E11 measured per-VM cgroup memory.current at 0.9 MiB mean / 2 MiB
max against a 288 MiB limit — 144x below the charge — because VMs
COW-share one mlocked page-cache-resident memfile.

Split the charge by VM state:

- Running (inFlight) and warming VMs are charged full PerVMBytes,
  bounded by the slot count; slotBudgetWarning now warns on that
  running-component arithmetic (slots x PerVMBytes vs budget).
- Paused (ready) standbys are charged their measured per-VM cgroup
  memory.current x StandbyHeadroom (SH_STANDBY_HEADROOM, default 4,
  "full" restores the pre-rossoctl#644 charge), floored at VMOverheadBytes and
  capped at PerVMBytes. An unreadable footprint charges full price.
- Warm acquire re-prices the popped standby at full PerVMBytes before
  the pop (admitPromotionLocked, a pure check), so a host cannot
  promote more VMs to running than it could have admitted cold.
- A paused component over budget now evicts instead of refusing:
  evictForBudgetLocked loops, shedding standbys coldest-run-first until
  the triggering admission fits (degenerates to the old single eviction
  under headroom=full).
- Opt-in host backstop: SH_HOST_MEM_FLOOR_MB refuses admission when
  host MemAvailable drops below it (RefuseHostMemory, distinct from
  RefuseMemoryBudget, fail-closed on an unreadable /proc/meminfo).

Both real launchers implement the standbyFootprinter seam with a
cached-once read (firecrackerVM: pooled cgroup; chvVM: systemd scope
cgroup). Stats/diag gain StandbyCommittedBytes beside CommittedBytes,
and vmpoolctl's run record gains standby_headroom, budget_evictions and
standby_committed_bytes.

Warming VMs are deliberately still charged full price: a warming VM has
no footprint to read yet, and charging it full keeps the warming ->
inFlight handoff charge-neutral.

Verification: go vet + full remote-worker suite (16 packages, -count=1)
and -race on vmpool, microvm-worker, vmpoolctl; eviction-loop
non-vacuity checked by mutation test. AM6 density-ladder re-run on SBX0
is the on-hardware validation follow-up.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review of 9034c12: dirty-page charging for paused standbys (#644).

The accounting design holds up. Every transition recomputes committedLocked from live state, and the cached-once StandbyBytes can't go stale, because a VM runs at most one exec (defer destroy()) and only fresh restores park. The eviction loop is a clear improvement. One must-fix and one CI blocker are below.

Must-fix

  1. admitPromotionLocked refuses and never evicts. On the standby-heavy hosts #644 targets, warm acquires are refused far below the slot ceiling (details inline at budget.go:251).
  2. lint is red. Prettier re-pads the docs/reference/configuration.md microVM-worker table, because the two new rows are longer than the column width. I confirmed this locally with the pinned prettier 3.9.10 (prettier --check fails, 18 lines change). Run pnpm exec prettier --write docs/reference/configuration.md.

Other

  • trivy-scan is red. This PR only touches Go and docs, and #646 @7c76de6 went red 4 minutes earlier while earlier heads were green. That points to a new advisory against an existing dependency, not to this change.
  • Missing tests: the promotion case below, eviction under RefuseHostMemory, eviction stopping at the reclaimQ cap, and parsing for readMemoryCurrent, readHostMemAvailable and chvScopeCgroupDir.
  • Not verified on hardware: pooled Firecracker cgroups are reused, so memory.current may include page-cache charged by an earlier VM. That errs toward overcharging, which is safe, but it may hide part of the density gain in the AM6 re-run.

// committedLocked already books vm at its dirty-page charge; replace that with
// the full price it is one Resume away from costing.
standby := p.standbyChargeLocked(vm)
if next := p.committedLocked() - standby + p.perVMBytes(); next > budget {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix: the promotion check is a pure refusal, and that makes warm acquires fail far below the slot ceiling on standby-heavy hosts.

replenishOne → admitLocked keeps adding standbys while committed + perVM <= budget. Under dirty charging, that fills the budget to within one PerVMBytes with cheap standbys from other, idle runs.

Example: the budget fits 10 VMs (2880 MiB), and 40 idle runs each hold 2 floor-charged standbys (32 MiB), so 2560 MiB is committed.

  • The 1st warm acquire reaches 2560 − 32 + 288 = 2816, which fits.
  • The 2nd reaches 3072 > 2880, which is refused with RefuseMemoryBudget while only 1 VM is running.

slotBudgetWarning stays silent, because slots × PerVMBytes fits. Before this PR a warm pop was charge-neutral, so this is a regression on exactly the shape #644 is meant to fix.

The comment at :230 says eviction can't fund a promotion. That doesn't hold: a promotion needs only perVM − standby of headroom, and evicting other runs' standbys provides it. Suggest calling evictForBudgetLocked with a target of committed − standby + perVM <= budget, excluding rp (it isn't busy yet and has a non-empty ready, so the loop could pick it). Re-check afterwards and add a test with many idle runs' standbys plus sequential warm acquires on one run.

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.

Fixed in 6c3e53c. The arithmetic held up as you described it — the comment's claim that eviction cannot fund a promotion was wrong: the incremental need is perVM − standby(vm), which other runs' dirty charges can cover. acquire now evicts for the promotion (evictForPromotionLocked → evictForAdmissionLocked with need = perVM − standby, exclude = the promoting run) and re-checks before the pop.

The exclusion is load-bearing only in the regime you flagged plus one twist: acquire bumps rp.lastExec to now before the check, so the promoting run is always the warmest candidate and the coldest-first loop reaches it last — it gets picked only when the shortfall exceeds every other run's evictable charge, at which point the loop would wrap around and hand the promoted standby itself to reclaimQ.

Tests: TestSequentialWarmAcquiresOnOneRunShedIdleStandbys is your scenario (budget 10 VMs, 40 idle runs × D2 at the floor, second warm acquire on one run funded by exactly six evictions, only 2 of 10 VMs running); TestPromotionEvictionSparesThePromotingRun pins the exclusion from the wrap-around side (shortfall 224 MiB vs 192 MiB elsewhere → refused, nothing shed, no run-y VM reaches reclaimQ). Non-vacuity checked by mutation both ways: dropping the exclusion admits the exec and destroys the standby under it; dropping the funding reverts to the refusal.

Comment thread remote-worker/internal/vmpool/budget.go Outdated
// the worst case (a full-price admission against a queue of floor-charged
// standbys) proportionate rather than a reclaim storm.
budget := p.cfg.MaxCommittedBytes - p.cfg.MemoryReserveBytes
if p.committedLocked()+p.perVMBytes() <= budget {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: there are two problems with this loop.

(a) The stop test only looks at the budget. When the refusal was RefuseHostMemory and the budget fits, it returns without evicting. When both fail, it evicts, but destroys run asynchronously through reclaimQ, so MemAvailable hasn't moved at the re-admit. The call is still refused and the standbys are gone. So the "pressure valve is the same in both directions" rationale (:66) doesn't hold: either skip eviction for RefuseHostMemory, or document that it only helps the next admission.

(b) Each victim goes out as its own one-VM reclaimBatch. On SBX0 (perVM ≈ 4128 MiB, 32 MiB floor), funding one admission can take about 129 evictions, but the queue holds 64. The loop can therefore park 64 standbys, still refuse, and fill the queue (sweep then destroys inline). Collect the victims into one batch per call, or check up front whether the evictable charge can cover the shortfall.

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.

Both parts fixed in 6c3e53c.

(a) Took the skip option: admitOrEvictLocked no longer evicts on RefuseHostMemory — since reclaimLoop destroys asynchronously, MemAvailable is unchanged at the re-admit and the standbys would be burned for a refusal the caller suffers either way. Documented at both call sites (including the promotion path) that relieving host pressure is not the admission path's job; a persistent host-memory refusal is an operator signal.

(b) evictForAdmissionLocked now gathers all victims of one call into a single reclaimBatch (one queue slot regardless of how many VMs it sheds — the SBX0 ~129-eviction funding no longer fills the 64-slot queue and forces inline destroys), and adds the up-front futility check you suggested: candidate runs' evictable charge is totaled first, and if it cannot cover the shortfall nothing is detached — the re-admit refuses identically, and burning the coldest runs' warm state for it is the reclaim-storm shape spec §6 names.

VMM: *vmm, Host: host, Key: *key, Command: command, Mode: *mode,
Iterations: *iterations, Concurrency: *concurrency, Keys: keysUsed(*mode, *keys),
StandbyDepth: cfg.StandbyDepth, GuestRAMMB: *guestMB,
StandbyHeadroom: cfg.StandbyHeadroom,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: cfg here is vmpoolctl's local copy. vmpool.New normalizes its own by-value copy, so the default run records standby_headroom: 0, not the resolved 4 that the comment at :59 promises. Call cfg.Normalize() first, or record pool.Stats()/the resolved value.

Also, --standby-headroom=inf gets through ParseFloat, but then json.Encoder fails on +Inf ("unsupported value") and the run record is lost. Map it to a sentinel or a string.

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.

Fixed in 6c3e53c. realMain now calls cfg.Normalize() on its local copy before building the record (Normalize is idempotent, so vmpool.New's own call is unaffected): the default run records standby_headroom: 4, --standby-headroom=2.5 records 2.5 — pinned by TestTheRecordCarriesTheResolvedStandbyHeadroom.

Non-finite values are refused at flag validation (inf, -inf, NaN), with the message pointing at 1e9+ for the legacy charge — exactly for the reason you gave: ParseFloat accepts them but json.Encoder cannot encode +Inf, so the whole record would have been lost. Pinned by TestNonFiniteStandbyHeadroomIsRefused.

Comment thread remote-worker/internal/vmpool/budget.go Outdated
if p.cfg.HostMemFloorBytes <= 0 {
return nil
}
avail, err := memAvailable()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: with the floor set, /proc/meminfo is read under the global p.mu on every admission and every warm acquire. It's cheap, but it is file I/O on the pool's hot lock. A ~100 ms cached value would remove it without weakening the backstop.

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.

Done in 6c3e53c: cachedMemAvailable caches the read — value and error both — for 100ms behind its own mutex, and hostFloorLocked reads the cache. The tests that pin the floor override the raw memAvailable seam and call invalidateMemAvailableCache() between phases, so the staleness is invisible to them.

…victions

Review rework of rossoctl#644 (PR rossoctl#647), four findings:

- must-fix: the promotion check was a pure refusal, which failed warm
  acquires far below the slot ceiling on standby-heavy hosts.
  replenishOne keeps booking standbys while committed + PerVMBytes fits
  the budget, so idle runs' floor-charged standbys fill it to within one
  warming of full; the second warm acquire on a run then hit
  RefuseMemoryBudget while one VM of a ten-VM budget was running. A
  promotion's incremental need is only PerVMBytes minus the popped
  standby's dirty charge, and other runs' standbys can cover exactly
  that: acquire now evicts for the promotion (evictForPromotionLocked,
  the promoting run excluded from the victim set so the popped standby
  can never be handed to reclaimQ) and re-checks. Pinned by
  TestSequentialWarmAcquiresOnOneRunShedIdleStandbys (the reviewer's
  scenario) and TestPromotionEvictionSparesThePromotingRun (the
  exclusion, load-bearing only when the shortfall exceeds every other
  run's evictable charge).

- evictForBudgetLocked reworked (evictForAdmissionLocked): victims are
  gathered coldest-run-first into ONE reclaimBatch per call (on SBX0
  funding an admission can take ~129 evictions against a 64-slot queue,
  which previously filled the queue and left the sweep destroying
  inline), and a futility check detaches nothing when the evictable
  charge cannot cover the shortfall — burning standbys for a refusal
  the caller suffers anyway is the reclaim-storm shape.

- RefuseHostMemory no longer triggers eviction: reclaimLoop destroys
  asynchronously, so MemAvailable is unchanged at the re-admit and the
  standbys would be burned for nothing. Relieving host pressure is not
  the admission path's job.

- hostFloorLocked reads a ~100ms cached MemAvailable instead of hitting
  /proc/meminfo under p.mu on every admission and warm acquire.

vmpoolctl: the run record now carries the RESOLVED StandbyHeadroom
(cfg.Normalize on the local copy; vmpool.New normalizes only its own),
and --standby-headroom=inf is refused at flag validation — ParseFloat
accepts it but json.Encoder cannot encode +Inf, so the run record would
be lost wholesale.

Also prettier-format docs/reference/configuration.md (CI lint failed on
the table rows added in the first push).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…7045

trivy-scan went red on this branch (and on rossoctl#646, which touches no
dependencies either): golang.org/x/net v0.61.0 in remote-worker and
v0.60.0 in gen/go are vulnerable to CVE-2026-78661 (quadratic
complexity coalescing text nodes in html) and CVE-2026-97045
(ancestor namespace transitions when rendering raw text), both fixed in
v0.62.0.

Both advisories are currently severity UNKNOWN, so the workflow's
severity: CRITICAL,HIGH input does not gate them: trivy-action drops
the severity filter when building the SARIF report ("with all
severities"), and exit-code 1 then fires on any finding — verified by
running the exact action invocation locally against this tree before
and after the bump (exit 1 -> 0).

gen/go additionally picks up x/sys v0.49.0 and x/text v0.43.0, the
versions x/net v0.62.0 requires.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Re-review at 1b76333 (6c3e53c + 1b76333 since 9034c12). All four threads are verified fixed:

  1. Promotion funding (must-fix): acquire evicts other runs' standbys for perVM − standby on RefuseMemoryBudget and re-checks before the pop. The promoting run is excluded, so the captured slice index stays valid. Both tests pin the scenario and the exclusion.
  2. Eviction loop: RefuseHostMemory no longer burns standbys on either path. Victims go out as one reclaimBatch (one queue slot), and the futility check detaches nothing when the evictable charge can't cover the shortfall.
  3. vmpoolctl record: the resolved headroom is recorded, and non-finite values are refused at flag validation.
  4. MemAvailable read under p.mu: now a 100 ms cached read.

lint and trivy-scan are green now (the x/net v0.62.0 bump also explains #646's red).

Non-blocking follow-ups:

  • Tests for "no eviction on RefuseHostMemory" (a BudgetEvictions delta of 0 in the host-floor tests), the single-batch property, and parsing for readMemoryCurrent / readHostMemAvailable / chvScopeCgroupDir.
  • proto went red twice on this head before passing. Running go test -race ./... in isolation at 1b76333, vmpool/vmpoolctl passed at all three commits with no races. The only failure was internal/egress TestCapRefusalsAreBoundedPerVM (proxy_test.go:530 "no refusal was ever in flight"), which flaked 1 in 3 under -race. It samples capRefusalsInFlight without waiting for the accept loop. This PR doesn't touch it, but it may deserve its own issue.

@pdettori

Copy link
Copy Markdown
Member Author

Non-blocking follow-ups from the review are now tracked in #649 (vmpool test coverage: host-memory no-eviction, single-batch eviction, parser seams) and #650 (the TestCapRefusalsAreBoundedPerVM -race flake).

@pdettori
pdettori merged commit 92e57ce into rossoctl:main Oct 28, 2026
25 of 27 checks passed
@pdettori
pdettori deleted the fix/644-standby-dirty-charge branch October 28, 2026 14:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

microvm-worker: charge paused standbys at dirty-page cost in admission control (SBX0 density)

2 participants