Repository navigation
Fix: answer 503 for a host capacity refusal instead of narrating it to the model (#452) - #597
Conversation
…udget A host at its `MICROVM_MAX_COMMITTED_MB` ceiling refused every exec, even when most of the memory it had committed belonged to standby VMs no session was using. The ceiling counts resident VMs, and what makes a VM resident is a distinct workspace_key — one per session — not a command in flight, so a host could sit at its budget with nothing actually running. `admitOrEvictLocked` now sheds the least-recently-used IDLE standby VM and retries the admission, at both call sites (`acquire` and `runLocked`). A refusal therefore means every resident VM belongs to a session with live work, which is the only case where "wait and retry" is honest advice. Only idle standby VMs are candidates: a VM serving an exec is never evicted, and the eviction is LRU so the session most likely to have gone away is the one that pays. `Stats.BudgetEvictions` counts them, surfaced on the worker's diagnostic stats so an operator can read evictions against `Refusals[RefuseMemoryBudget]` and tell "the budget is tight" from "the host is genuinely busy". This is half of rossoctl#452. The other half makes a refusal that does happen reach the caller as a 503 instead of being narrated to the model. Refs rossoctl#452 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…o the model A sandbox host that refused an exec on its memory or MaxRuns ceiling reported that refusal to the MODEL as the command's output, and the turn then answered HTTP 200 with the host's admission arithmetic quoted back as prose. The chain, which is broken at every point here: - The wire has no "busy" frame, so a refusal can only travel as ExecError. The relay forwarded it and `grpc-relay-transport` rejected with a plain Error, indistinguishable from "your command failed". - Pi's bash tool bare-rethrows anything that is not aborted/timeout, and the agent loop catches a tool throw, converts it to `isError: true` content and CONTINUES. So the throw was consumed two frames below the turn and `session.prompt()` returned `stopReason: 'end_turn'`. - Nothing above could see it, so nothing became `reason: 'saturated'` or a 503. What this adds: - `SandboxCapacityRefusedError`, classified at the transport — the last place the two meanings of an ExecError are still separable. It sets `name` in its own constructor because `name` is what the status mapper reads and `instanceof` is unsound across package instances. - `CapacityLatch`: a per-turn object that records a refusal on its way past the transport, lets the `tool_call` hook stop the loop spending more turns on a host that is refusing work, and is rethrown by the caller AFTER `prompt()` resolves — the first point in the stack where a throw propagates. Deliberately not module state: a replica serves many turns concurrently against different hosts. - `reason: 'saturated'` in all four leaf catches, alongside the lease-time `SandboxPoolSaturatedError`. They are not interchangeable (one is raised before any exec, one mid-turn) but the remedy is the same, and `reason: 'error'` spent the run permanently on a condition that clears by itself. - 503 + `Retry-After` + `sandbox_unavailable` in knative-server, which is what makes the SAME prompt retryable. `throwIfRefused()` placement differs per site by what each site's output means: after `backend.flush()` in `executeTurnCore` (persist, then fail — the session must stay resumable); before the diff capture on a solve leaf (a partial patch reported as `solved` is worse than the original error); last and only if nothing was captured on a verdict leaf (a captured verdict IS the result, and discarding it would retry finished work). The classification is a prose prefix match, because the wire cannot say "busy". `refusal-vocabulary-coupling.test.ts` reads the Go `RefusalReason` constants directly, so a rename fails the build rather than silently degrading to 500. The durable fix is a typed refusal on the wire. Every new test has a negative-direction half: an ordinary command failure must stay a plain Error, must not latch, and must not match the regex. Classifying too widely would turn a permanent failure into an unbounded 503 retry loop. P4-ON-P6.md now says to size the budget for DISTINCT SESSIONS rather than for concurrency (~10 at the verified settings), and records under "Not verified" that no run on the rig ever reached the ceiling — the eviction and the 503 are covered by unit tests, not by hardware. Fixes rossoctl#452 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…ration Signed-off-by: cwiklik <[email protected]> # Conflicts: # harness/src/run-leaf.ts
The two eviction tests added for rossoctl#452 read fakeLauncher.destroyedFor straight after Exec returned. evictForBudgetLocked hands the VM to p.reclaimQ and reclaimLoop calls Destroy off the hot path, so that read raced the reclaim: it won locally and lost on the CI runner, failing the proto job with "run-a destroys = 1, want 2" and "run-old lost 0 standbys, want 1". Use waitFor, the idiom the sweep and close tests already use for anything behind the queue. Stats().BudgetEvictions is unaffected and still read synchronously -- it is incremented under p.mu, which is why those assertions passed throughout. In the LRU test the positive half is waited on first so the negative half stays meaningful: once the victim's VM is destroyed the queue has drained past this eviction, so a zero for run-new means "not the victim" rather than "not yet". The workspace-on-disk test gets the same guard, for the same reason in reverse -- its os.Stat would otherwise assert "not deleted yet". No production code changes. Refs rossoctl#452 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Summary: two well-separated fixes for #452. (1) On a memory-budget refusal, the vmpool now sheds one LRU idle standby and re-admits. (2) A capacity refusal that does get through (memory-budget: / max-runs: / busy: queue full) becomes SandboxCapacityRefusedError at the gRPC relay transport. A per-turn CapacityLatch carries it past Pi's swallow-and-continue loop, and it surfaces as reason: 'saturated' on leaves and 503 + Retry-After sandbox_unavailable on /turn.
The code reads correct to me:
- Eviction never touches a busy run.
- Stopping the pending timers prevents a refill race.
- The send to reclaimQ can't block, because it's pre-checked under p.mu and all senders hold it.
- MaxRuns refusals don't evict.
- The anchored regex matches the unwrapped
RefusalError.Error()that loop.go:759 puts on the wire. - The latch is per turn, not module state.
The coupling test reading the Go constants and the negative-direction tests are good.
The blocker is the operator docs. They state that idle sessions hold their VMs until SH_WORKSPACE_IDLE, and they recommend lowering it as a fix for 503s. sweepOnce parks idle runs with zero VMs after StandbyIdle (90s), so that knob relieves nothing and only brings #338's silent workspace reset forward. The ~10-session figure also leaves out the 4 GiB reserve and the per-VM overhead (≈4–5 at the verified settings). Details inline.
Author: cwiklik (MEMBER, maintainer)
Areas reviewed: Go (vmpool, microvm-worker), TypeScript (k8s-sandbox, harness, knative-server), tests, Docs
Agent/IDE config (.claude/.vscode): none
Commits: 4 commits (incl. a merge of main), all signed-off: yes
CI status: passing (all 15 checks green)
|
|
||
| `MICROVM_MAX_COMMITTED_MB` bounds the memory of VMs _resident at once_, and what makes a VM resident | ||
| is a **distinct `workspace_key`** — one per session — not a command in flight. A session that ran one | ||
| tool call an hour ago still holds its VM, standby included, until `SH_WORKSPACE_IDLE` reclaims it. |
There was a problem hiding this comment.
must-fix (docs): the memory model this section is built on doesn't match the pool. sweepOnce (sweep.go:52) drops an idle run's standbys once idle >= StandbyIdle, which is 90s (DefaultStandbyIdle). microvm-worker has no env override for it. The run is then parked, and admitLocked's own comment says "a parked run holds ZERO VMs by construction". So a session that ran one tool call an hour ago holds no VM. It holds only its workspace on disk until SH_WORKSPACE_IDLE. The memory budget is consumed by sessions active in roughly the last StandbyIdle + ReclaimScanInterval (~2 min), not by sessions that are merely open.
That makes the second row of the knob table at L276 actively harmful. Lowering SH_WORKSPACE_IDLE frees no memory, because parked runs already hold none, and parked runs don't count toward MaxRuns either. It only makes #338's silent workspace reset hit sooner. Please rewrite the section around "sessions active within ~StandbyIdle" and drop or replace that row.
If the rig in #452 really did show idle sessions holding VMs past 90s, that would be a sweep bug worth its own issue, because the eviction added here would hide it rather than fix it.
| distinct sessions ≈ MICROVM_MAX_COMMITTED_MB / (guest MiB × (1 + standby depth)) | ||
| ``` | ||
|
|
||
| At the verified settings — `8192` MiB, `guest=256MiB`, `D=2` — that is roughly **10 sessions**, not |
There was a problem hiding this comment.
suggestion: the arithmetic leaves out two terms that the issue itself uses. The budget is MaxCommittedBytes - MemoryReserveBytes, and the shipped unit's SH_MEMORY_RESERVE_MB is 4096. Each VM is charged GuestRAMBytes + VMOverheadBytes = 256 + 32 = 288 MiB. At 8192 MiB that gives (8192 - 4096) / 288 ≈ 14 VMs, which is #452's own "about 14 VMs". At D=2 that's ≈ 4–5 warm sessions, not 10. The formula should be (MICROVM_MAX_COMMITTED_MB - SH_MEMORY_RESERVE_MB) / ((guest MiB + 32) × (1 + D)). The same figure appears in the Limits bullet at L600 ("About ten open sessions").
| // | ||
| // #452: a memory refusal reaching one of these is a failed exec in somebody's | ||
| // transcript, so try to make room before returning it. A session's idle-but-resident | ||
| // standbys hold memory for WorkspaceIdle (8h on the shipped P4-on-P6 unit) while |
There was a problem hiding this comment.
suggestion: the same premise as the doc comment. Standbys are dropped after StandbyIdle (90s), not WorkspaceIdle. Past that the run is parked with zero VMs (see admitLocked's "PARKED RUNS DO NOT COUNT" paragraph a few lines down, and sweepOnce). Eviction is still worth having for bursts inside that window, which is what the tests exercise (they never advance past StandbyIdle). But "stays there for hours" isn't what this code does, and the rationale should say what eviction actually relieves.
| // read as a hang rather than an error. | ||
| if (opts?.capacity) { | ||
| const latch = opts.capacity; | ||
| pi.on('tool_call', () => { |
There was a problem hiding this comment.
suggestion: this blocks every tool once the latch is set, including harness-side tools that never touch the sandbox: submit_verdict and request_approval in the verdict leaf. That works against run-leaf.ts:1017. The point there is that a verdict the model can reach is the leaf's result, but after a refusal on an early sandbox read, the model is blocked from submitting it. The leaf then falls through to throwIfRefused() and retries finished reasoning. Consider checking event.toolName against the tools this extension registers (read/write/edit/ls/find/bash/grep) and returning {} for everything else.
| cwd, | ||
| extensionFactories: [ | ||
| k8sSandboxExtension({ config: agentConfig }), | ||
| k8sSandboxExtension({ config: agentConfig, capacity }), |
There was a problem hiding this comment.
nit: this latch can't fire today. The solve leaf passes only config here (no transport), so the extension uses KubectlTransport, which never produces SandboxCapacityRefusedError. The class only comes from GrpcRelayTransport. The solve leaf's converge/diff path is kubectl-only too. That's harmless and future-proof, but the PR body's "solve leaf — before the diff capture" reads as covered behaviour, and the run-leaf.test.ts case covers it only through a mocked produceSolve. A one-line comment saying it's inert until the solve leaf uses the leased transport would keep this honest.
| 10 simultaneous commands. Four people with three abandoned chat tabs each will reach it while the | ||
| host looks idle. | ||
|
|
||
| Past that point the worker refuses an exec rather than overcommitting, and since v0.9 it first sheds |
There was a problem hiding this comment.
nit: "since v0.9". The latest tag is v0.7.0. Either name the release this will ship in or say "since #452".
Review follow-ups on rossoctl#597. The latch's `tool_call` block applied to EVERY tool in the session, because an extension's handler sees all of them and not only the ones it registered. On a verdict leaf that meant `submit_verdict` and `request_approval` were blocked too — tools that never cross the sandbox seam. Since `run-leaf.ts` calls `throwIfRefused()` only when nothing was captured, precisely so a verdict the model can still reach becomes the leaf's result, blocking the submit discarded finished reasoning and sent the run back to redo it. Scoped by name to the seven tools the extension registers, with a test that pins the set against the registrations rather than the list. The P4-ON-P6 sizing section had the memory model wrong: it said a session holds its VMs until `SH_WORKSPACE_IDLE`. What releases them is `StandbyIdle` (90s), after which the sweep parks the run — and a parked run holds zero VMs. So the budget tracks sessions active in roughly the last two minutes, not sessions merely open. The arithmetic now nets `SH_MEMORY_RESERVE_MB` and charges the per-VM overhead admission actually charges (`vmpool.PerVMBytes`), which moves the figure from 10 sessions to 4-5 — the number rossoctl#452 reports from the rig. The knob table's `SH_WORKSPACE_IDLE` row was actively harmful advice (it frees no memory and brings rossoctl#338's silent reset forward) and is replaced with `SH_STANDBY_DEPTH`. Also: `admitOrEvictLocked` now states what the eviction relieves and why it is a burst fix rather than a leak fix, the solve leaf's latch is marked INERT TODAY (no `transport` passed, so it gets a `KubectlTransport`, and only `GrpcRelayTransport` raises the refusal), and "since v0.9" is "since rossoctl#452". Refs rossoctl#452 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
|
Thanks — all six held up against the code, and two of them were real defects rather than wording. Addressed in 847efb7.
Gates on the new commit: One unrelated note while you have this open: the |
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Follow-up to our 6b7f9ea review: we checked all six items against 847efb7, and each one is closed.
- Memory model (was must-fix): the section now describes
StandbyIdle(90s,DefaultStandbyIdle), after whichsweepOnceparks the run with zero VMs. The harmfulSH_WORKSPACE_IDLErow has been replaced, and the text says why that knob frees no memory. - Arithmetic:
(budget − SH_MEMORY_RESERVE_MB) / ((guest + 32) × (1 + D))matchesPerVMBytesand the shipped unit (reserve 4096,SH_STANDBY_DEPTH=2). (8192 − 4096) / 864 ≈ 4.7. The Limits and Not-verified bullets were updated to match. - budget.go rationale: now framed as a burst fix rather than a leak fix, and it notes that it would mask a sweep bug.
- Latch scope:
tool_callis now gated onSANDBOX_TOOLS.toolNameis a real field on Pi'sToolCallEventat the pinned fork (2c28be5). The new test pins the set against the actual registrations and checks thatsubmit_verdict/request_approvalstill go through. - Solve-leaf latch: marked INERT TODAY at the call site.
- "since v0.9": changed to "since #452".
One non-blocking nit inline. The TestDeferredReapOpensTheGateAtTheBarrierNotAfterTheReap flake analysis sounds right (two ready select cases with a random pick). A separate issue for it would be welcome.
Author: cwiklik (MEMBER, maintainer)
Areas reviewed: incremental diff 6b7f9ea..847efb7 (Docs, Go comment, TypeScript extension + tests, run-leaf comment)
Agent/IDE config (.claude/.vscode): none
Commits: 1 new commit, signed-off: yes
CI status: 13 checks passing; check and k8s-kind-e2e still pending at drafting time
|
|
||
| | Symptom | Knob | | ||
| | ------------------------------------------- | ----------------------------------------------------------------------------- | | ||
| | 503s with few sessions active | raise `MICROVM_MAX_COMMITTED_MB`, or lower `SH_MEMORY_RESERVE_MB` | |
There was a problem hiding this comment.
nit: "or lower SH_MEMORY_RESERVE_MB" is a bit too casual for this table. The reserve is the host's headroom outside the VM budget. It's baked into the shipped microvm-worker.service (L162), so there's no installer knob for it: lowering it means a systemd drop-in. setup-microvm.sh also hard-codes SHIPPED_RESERVE_MB=4096 for its budget check. Suggest either dropping this alternative or adding "(via a drop-in; it is host headroom, so only if the host really has it)".
Summary
A sandbox host at its memory or
MaxRunsceiling refused an exec, and that refusal was reported to the model as the command's output. The turn then answered HTTP 200 with the host's admission arithmetic quoted back as prose.Two independent causes, fixed in two commits.
1. The host refused when it didn't have to (Go)
MICROVM_MAX_COMMITTED_MBbounds VMs resident at once, and what makes a VM resident is a distinctworkspace_key— one per session — not a command in flight. A host could sit at its budget with nothing running, most of the committed memory held by standby VMs no session was using.admitOrEvictLockednow sheds the least-recently-used idle standby VM and retries, at both call sites. A refusal therefore means every resident VM belongs to a session with live work — the only case where "wait and retry" is honest advice. A VM serving an exec is never a candidate. NewStats.BudgetEvictions, surfaced on the worker's diagnostic stats so an operator can read evictions againstRefusals[RefuseMemoryBudget]and tell "the budget is tight" from "the host is genuinely busy".2. A refusal that does happen never reached the caller (TypeScript)
The chain, broken at every point:
ExecErrorgrpc-relay-transportError— indistinguishable from "your command failed"bash.tsaborted/timeout:isError: truecontent, and continuessession.prompt()stopReason: 'end_turn'. Nothing above can see what happenedSo nothing became
reason: 'saturated'or a 503.What this adds:
SandboxCapacityRefusedError, classified at the transport — the last place the two meanings of anExecErrorare still separable. It setsnamein its own constructor becausenameis what the status mapper reads, andinstanceofis unsound across package instances.CapacityLatch— a per-turn object that records a refusal on its way past the transport, lets thetool_callhook stop the loop spending more turns on a host that is refusing work, and is rethrown by the caller afterprompt()resolves, the first point in the stack where a throw propagates. Deliberately not module state: a replica serves many turns concurrently against different hosts, and a shared flag would fail one session's turn because a different session's host filled up.reason: 'saturated'in all four leaf catches.SandboxPoolSaturatedError(lease time, before any exec) andSandboxCapacityRefusedError(mid-turn, on a sandbox that was leased) are not interchangeable, but the remedy is the same — andreason: 'error'spent the run permanently on a condition that clears by itself.Retry-After+sandbox_unavailablein knative-server, which is what makes the same prompt retryable.throwIfRefused()placement differs per site by what each site's output means:executeTurnCore— afterbackend.flush(). The turn really did happen; a session whose checkpoint is missing it cannot be resumed cleanly once the host has room. Persist, then fail.status: 'solved'hands the caller a partial patch with no indication it was cut short, which is worse than the error this issue is about. Inert today: this leaf passes notransport, so it gets aKubectlTransport, and onlyGrpcRelayTransportraises the refusal — the wiring is there so moving this leaf onto the leased transport cannot silently reintroduce P4: the worker advertises lease slots its memory budget can no longer admit, so turns get an in-turn tool error instead of a 503 #452. Therun-leaf.test.tscase covers it through a mockedproduceSolve.submit_verdictandrequest_approvalnever touch the sandbox, so a captured verdict is the leaf's result; discarding it would retry finished work.Testing
evict_test.go)go test ./...pass,go vetcleantsc --noEmitclean ink8s-sandbox,harness,knative-server. Prettier clean.Full suites match a stashed-clean baseline exactly — harness 18 fail / 685 pass and knative 3 files / 524 pass, all pre-existing Redis
ECONNREFUSED, re-confirmed against a clean tree in this session.Negative controls. Reverting each fix in source failed exactly the tests written for it and nothing else: the transport classification (2 of 4), the latch wrap (3 of 5), the leaf mapping (3 of 3), the
NO_CAPACITYentry (2 of 2 — the name-pin test correctly still passed, as it tests the class and not the mapper). All restored and re-verified green.Every new test has a negative-direction half: an ordinary command failure must stay a plain
Error, must not latch, and must not match the regex. Classifying too widely is the worse failure — it turns a permanent error into an unbounded 503 retry loop against a request that can never succeed.Two things worth flagging
The classification is a prose prefix match, because the wire cannot say "busy".
refusal-vocabulary-coupling.test.tsreads the GoRefusalReasonconstants directly, so a rename fails the build rather than silently degrading to 500. The durable fix is a typed refusal on the wire — worth its own issue.The ceiling is not verified end-to-end on hardware. Every verified P4 run stayed well inside the 8192 MiB budget (the largest used 4 Execs), so no run on the rig ever evicted a standby or produced a 503. That is now stated explicitly under "Not verified" in
P4-ON-P6.mdrather than left to imply coverage the rig doesn't have. Reaching it deliberately needs ~10 open sessions or a temporarily small budget.Docs
deploy/microvm/P4-ON-P6.mdnow says to sizeMICROVM_MAX_COMMITTED_MBfor distinct sessions, not concurrency — the startup banner counts slots, which reads like a concurrency limit and isn't one. Includes the arithmetic (~10 sessions at the verified settings), the two distinct knobs (MICROVM_MAX_COMMITTED_MBvsSH_WORKSPACE_IDLE) and what each symptom points at.Fixes #452
Assisted-By: Claude Code