Repository navigation
feat(sbx): lease mode plan 3 — the wire (proto, control plane, relay, worker wiring) - #802
Conversation
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Thanks — a big, carefully staged PR. The relay and control-plane trust boundaries check out: mode/epoch always come from token claims on the sandbox path and are cleared on the harness path; moca-sandbox+jwt and moca-sandbox-mode+jwt are typ-pinned so neither passes as the other; set_mode's sbx/wrk/wsk binding, the in-flight cap (released in finally on every path), waiter teardown on worker disconnect, and request-id rewriting for lease events all look right. The proto change is additive (Exec 7-10, new oneof arms, 0 = UNSPECIFIED enums), and the Redis SET_MODE Lua reads fromMode atomically.
Requesting changes for one worker bug: frameSink.Lease can report a lease event as queued after the connection has ended (enqueue takes buffer room before it checks connCtx), so AckLeaseEvent clears an event the sender then discards. This is the opposite of spec §5's "stays pending" promise, on the most common lease-disconnect path. Details inline.
Suggestions: add mode/epoch to the dedup fingerprint; fix the proto keepalive wording (it never resets idle); decide whether narrowing SH_SANDBOX_MODES_ALLOWED should affect existing sandboxes. A few doc nits as well.
CI: trivy-scan is red, but not because of this PR. The PR changes no dependency manifest, and the Trivy code-scanning check reports no new alerts in changed code. The cause is the new hono / @hono/node-server CVEs in the existing lockfile, which #803 fixes. Every other check is green.
Reviewed by the AI review assistant; posted after maintainer approval.
| func (f *frameSink) Lease(ev *pb.LeaseEvent) error { | ||
| out := proto.Clone(ev).(*pb.LeaseEvent) | ||
| out.ReqId = f.reqID | ||
| if !f.send(&pb.WorkerFrame{Msg: &pb.WorkerFrame_Lease{Lease: out}}) { |
There was a problem hiding this comment.
must-fix: a lease event can be acked after its connection has already ended, so it is lost. frameSink.Lease takes f.send (the session's enqueue) returning true as "queued". But enqueue (loop.go:416-) tries non-blocking sends on chunkSlots/outbound before it looks at connCtx.Done(), so it returns true after the connection is cancelled whenever the buffer has room. That is exactly the common lease-disconnect path: cancelConn() aborts the in-flight lease Exec, Runner.Run still calls deliverLeaseEvents, the event fits in the buffer, AckLeaseEvent clears it, and the sender goroutine (failed drain, or dead st.Send) discards it. Spec §5 and the errLeaseNotQueued comment both promise the opposite: "An event that could not be queued (the connection had ended) stays pending, and the next lease Exec carries it."
Fix: have the lease path refuse once the connection is done. For example, give frameSink the conn's done channel and check select { case <-done: return errLeaseNotQueued; default: } before f.send, or add an enqueue variant that checks connCtx.Err() first. Please add a session-level test that disconnects during a lease Exec and asserts the event stays pending. The runner_test "not queued" case only fakes the sink error.
There was a problem hiding this comment.
Fixed in e650350. frameSink now holds the connection's connCtx.Done() (passed through runOne) and Lease checks it before f.send, returning errLeaseNotQueued once the connection is done, so the event is not acked and stays pending for the next lease Exec. It checks the connection, not the Exec's ctx, so after an Abort on a live connection the event is still queued. The chunk path is unchanged.
The remaining check-then-send window (the connection ending just after the check) is the same as the connection ending just after a frame was queued or sent, which no worker-side check can see. It is documented in lease.go, and spec §5 already calls the event best-effort for that window.
Tests in internal/session/lease_test.go:
TestLeaseEventAfterDisconnectIsNotQueued: the stream closes during a lease Exec, then the runner calls the sink, which must returnerrLeaseNotQueued. This failed on the old code.TestLeaseEventAfterAbortIsQueued: after anAbort, the event still goes out under the req_id.
| TimeoutS: e.GetTimeoutS(), | ||
| Streaming: e.GetStreaming(), | ||
| WorkspaceKey: e.GetWorkspaceKey(), | ||
| Mode: specMode(e.GetMode()), |
There was a problem hiding this comment.
suggestion: the dedup cache's Fingerprint(command, stdin, timeout_s, streaming) (cache.go:30; Put/lookup sites are outside the hunk) doesn't include the new mode/mode_epoch (or idle_timeout_s/keepalive). cache.go's own rule is that anything that changes what the exec means belongs in the fingerprint. A req_id collision between a per-exec and a lease Exec, or across two epochs, would be answered from the other's cached End and skip the stale_mode check and the lease-event delivery. A genuine redelivery carries identical values, so adding mode + fixed-width mode_epoch costs nothing.
There was a problem hiding this comment.
Done, in e650350, a1a13b6 and 11263f9. Fingerprint now takes the *pb.Exec. Besides command, stdin, timeout_s and streaming, it covers:
modeand fixed-widthmode_epoch, so a req_id reused across modes or epochs runs fresh and gets itsstale_modecheck and lease-event delivery;workspace_key, length-prefixed. One worker serves many sandboxes, so without it a reused req_id with an identical command on another sandbox could be answered from the other's cache. That gap predates this PR.
idle_timeout_s and keepalive are deliberately left out. Neither changes an Exec's result. idle_timeout_s comes from the token, so it can differ between a genuine retry and its original after a re-mint: a lowered idle ceiling would otherwise rerun a non-idempotent command. keepalive is the client's opt-in, and it doesn't change the result either.
Tests:
TestReqIDReusedAcrossLeaseFieldsRunsFresh, at session level. It failed on the old code.TestFingerprintSeparatesLeaseFields.TestFingerprintSeparatesWorkspaceKey.- A retry that differs only in
idle_timeout_sorkeepaliveis answered from the cache.
| // Lease mode (SBX0.3). Both act on the sandbox's lease, not on one Exec, and both | ||
| // are relayed to the worker as a ServerFrame. LeaseControl reads the lease status, | ||
| // ends the lease (reset) or changes the mode (set_mode, which needs a signed | ||
| // set_mode_token); LeaseKeepalive pushes back the idle timeout of a live lease. |
There was a problem hiding this comment.
suggestion: "LeaseKeepalive pushes back the idle timeout of a live lease" contradicts the code and the spec. pool.Keepalive (vmpool/lease.go:1040-1042) never resets idle, spec §2 says "A keepalive never resets it", and sandbox-v1-direct-client.md agrees. This proto is the file handed to direct clients, so please make it something like "LeaseKeepalive records harness liveness for a live lease (the keepalive-loss rule); it never resets idle".
There was a problem hiding this comment.
Fixed in 19cc9a3. The service comment now reads: "LeaseKeepalive records harness liveness for a live lease (the keepalive-loss rule); it never resets idle, and the worker gives no answer". LeaseKeepaliveFrame got the same correction. The stubs are regenerated; the Go and both TS outputs changed in comments only.
| Exec exec = 1; // run one command | ||
| Abort abort = 2; // cancel an in-flight exec | ||
| LeaseControlFrame lease_control = 3; // status | reset | set_mode; answered by lease_result | ||
| LeaseKeepaliveFrame keepalive = 4; // push back a live lease's idle timeout; no answer |
There was a problem hiding this comment.
suggestion: same wording issue as line 20, "push back a live lease's idle timeout". Suggest "keepalive-loss heartbeat for a live lease; never resets idle; no answer".
There was a problem hiding this comment.
Fixed in 19cc9a3: "keepalive-loss heartbeat for a live lease; never resets idle; no answer".
| sbx: rec.id, | ||
| wrk: rec.worker, | ||
| wsk: rec.wsk, | ||
| mode: rec.mode, |
There was a problem hiding this comment.
suggestion: SH_SANDBOX_MODES_ALLOWED / SH_SANDBOX_IDLE_CEILING_S are enforced only on create and PUT. mintSandboxToken (here) and mintSandboxModeToken → setModeTokenFor re-sign rec.mode / rec.idleTimeoutS unchecked. So if an operator removes lease/lease+processes, or lowers the ceiling, existing sandboxes keep getting lease tokens for their whole life. Spec §8.1 calls this list "the switch", which matters for rolling back level 2. Either clamp at mint time (downgrade through store.setMode so the epoch is raised, not re-issued at the same epoch, which the worker treats as a retry), or document plainly that narrowing the policy affects only new changes, and add a test.
There was a problem hiding this comment.
Clamped at mint, in bf3750f. The new underPolicy runs in mintSandboxToken and mintSandboxModeToken, after requireLive:
- If the record's mode is not
per-execand the currentSH_SANDBOX_MODES_ALLOWEDno longer lists it, the record is first downgraded through the atomicstore.setModetoper-exec, which raises the epoch. The next Exec therefore ends the live lease; it is not a same-epoch re-issue. - The downgrade is audited as
sandbox_mode_changedwithreason: 'mode_not_allowed', and the token is minted from the updated record. idleClaimclamps theidle_timeout_sclaim to the currentSH_SANDBOX_IDLE_CEILING_Sin both token kinds. The record and the epoch are unchanged, because the idle timeout travels on every Exec.
Two races are accepted and documented in underPolicy:
- concurrent mints can raise the epoch twice, which is harmless;
- an owner's PUT to a still-allowed mode that lands between the read and the downgrade is overwritten, and the owner sends it again. The store has no conditional
setMode.
Docs: spec §8.1, CHANGELOG 1.6.0, deploy/sbx/README.md and the two routes' openapi descriptions now say that narrowing the policy downgrades existing sandboxes at their next token mint.
Tests: "a narrowed policy, at the next mint" in sandbox-handlers.test.ts.
- With either token minted first, both come back
per-execat epoch 2, and there is exactly one audit line. - Allowed modes are left alone.
- A lowered ceiling clamps both claims and leaves the record as it was.
- All of these failed on the old code.
| // which HINCRBY reads as 0. The record is read back in the same script, so the caller sees the epoch | ||
| // it raised and no later one. | ||
| const SET_MODE = ` | ||
| if redis.call('EXISTS', KEYS[1]) == 0 then return false end |
There was a problem hiding this comment.
nit: the SET_MODE script refuses a missing or deleted record but doesn't check expiresAt (DELETE in this file does). A PUT that crosses the expiry second raises the epoch and writes a sandbox_mode_changed audit, then setModeTokenFor throws sandbox_terminated, so the client sees a 409 for a change that was stored and audited. Low impact because no usable token comes out. Passing now and checking it in the script (and in MemorySandboxStore.setMode) makes the check atomic.
There was a problem hiding this comment.
Fixed in bf3750f. SandboxStore.setMode takes nowS. The Redis SET_MODE script refuses now >= expiresAt, the same check DELETE makes, and MemorySandboxStore.setMode uses isLive. A PUT that crosses expiry now stores and audits nothing. A new store-contract case, "gives undefined from setMode for an expired sandbox, and changes nothing", runs against both stores. It failed on the old code for both.
| default) and `modeEpoch`. A sandbox created `per-exec` starts at epoch 0, one created in a lease | ||
| mode at 1. | ||
| - POST /v1/sandboxes accepts `mode` (default `per-exec`) and `idleTimeoutS` (30 to | ||
| `SH_SANDBOX_IDLE_CEILING_S`, default 1800; omitted means the worker's default, an explicit 0 is |
There was a problem hiding this comment.
nit: "idleTimeoutS (30 to SH_SANDBOX_IDLE_CEILING_S, default 1800; …)" reads as if idleTimeoutS defaults to 1800. 1800 is the ceiling's default. An omitted idleTimeoutS is stored as 0, which means the worker's default of 300 s. Suggest "(30 to SH_SANDBOX_IDLE_CEILING_S, whose default is 1800; omitted, the worker's default of 300 s; …)".
There was a problem hiding this comment.
Fixed in 5ebd5a5: "(30 to SH_SANDBOX_IDLE_CEILING_S, whose default is 1800; omitted, the worker's default of 300 s; an explicit 0 is 400 invalid_request)". Checked: DefaultLeaseIdle = 300 * time.Second in vmpool/config.go.
| | Variable | Default | Rule | | ||
| | --------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| | `SH_SANDBOX_MODES_ALLOWED` | `per-exec` | the modes a user may pick, a comma list of `per-exec`, `lease` and `lease+processes`. `per-exec` is always allowed, listed or not. Keep the default until the lease gate below is passed | | ||
| | `SH_SANDBOX_IDLE_CEILING_S` | 1800 | the longest lease idle timeout an owner may set, in seconds; at least 30, or the control plane refuses to boot. An owner who sets none gets the worker's default, 300 s | |
There was a problem hiding this comment.
nit: the worker also clamps the idle timeout with its own SH_LEASE_IDLE_CEILING_S (default 1800, microvm-worker main.go / vmpool/config.go). An operator who raises only SH_SANDBOX_IDLE_CEILING_S gets silently clamped. One sentence would help: "raise the worker's SH_LEASE_IDLE_CEILING_S with it".
There was a problem hiding this comment.
Added in 5ebd5a5: "The worker also clamps with its own SH_LEASE_IDLE_CEILING_S (default 1800), so raise it together with this one".
| `mode_epoch` and `idle_timeout_s`, and the relay writes them into every `Exec` it routes, over | ||
| whatever the client sent. Leave `Exec.mode`, `mode_epoch` and `idle_timeout_s` unset. After a mode | ||
| change, mint a fresh token: the old one still carries the old epoch. A token from before the | ||
| sandbox's first mode change carries epoch 0, and it is not refused: the worker serves an epoch-0 |
There was a problem hiding this comment.
nit: "A token from before the sandbox's first mode change carries epoch 0" holds only for a sandbox created per-exec. A lease create starts at epoch 1, as this page says a few lines further down. Also, the LeaseControl status table's PERMISSION_DENIED row could mention the harness token, and a CANCELLED row is missing (spec §8.3 lists both).
There was a problem hiding this comment.
Fixed in 5ebd5a5:
- The epoch-0 sentence now covers only a sandbox created
per-exec; a lease create starts at 1. - The
PERMISSION_DENIEDrow leads with the harness exec token. - New
CANCELLEDrow: the relay rejects a cancelled call withstatus.CANCELLEDand frees its place at once. A reset or set_mode that was already sent keeps running at the worker, so read the outcome withstatus.
| } | ||
| // A client that goes away withdraws its call: the relay drops the waiter and frees the slot. | ||
| const cancelled = new AbortController(); | ||
| call.on('cancelled', () => cancelled.abort()); |
There was a problem hiding this comment.
nit: call.on('cancelled', () => cancelled.abort()) is never removed after the call settles. It's harmless, since settle() already detaches from the signal, but removing it in the .then handlers would be tidier.
There was a problem hiding this comment.
Done in b2f101f. A named onCancelled listener is removed with call.off in both .then handlers. A transport test checks that each call's 'cancelled' listener count is back to its entry value after the call settles, both on OK and on UNAVAILABLE.
…aseKeepalive (additive)
Plan 3 Task 1 of SBX0.3 lease mode: the wire only; nothing sets or reads the new
fields yet.
- Exec gains mode (SandboxMode) = 7, mode_epoch = 8, idle_timeout_s = 9 and
keepalive = 10. An Exec without them is per-exec, epoch 0.
- New LeaseEvent, LeaseControlFrame, LeaseKeepaliveFrame, LeaseStatus,
LeaseControlResult and the SandboxMode and LeaseOp enums. New oneof members:
ExecEvent.lease = 4, WorkerFrame.lease = 6 and lease_result = 7,
ServerFrame.lease_control = 3 and keepalive = 4.
- SandboxExec gains LeaseControl and LeaseKeepalive. The relay answers both
UNIMPLEMENTED (the grpc-js default for an omitted method) until Task 5.
- Stubs regenerated (Go, and the two identical ts-proto copies);
@moca/k8s-sandbox re-exports the new types.
- Under useOptionals=none, the new Exec scalars are required in TS, and an Exec
literal without them throws in encode ("invalid int32: undefined"). Every
hand-built Exec now goes through Exec.fromPartial: the harness transport, the
sandbox-client exec conn, and the relay and harness tests, including the
ones that cast the client to unknown and so were never typechecked. The Go
SandboxExecClient fakes in cmd/sbx gain the two new methods.
- Contract tests pin the new numbers, a round-trip of each new message and
oneof member, and the decoding of pre-change Exec bytes (all four lease
fields zero) in Go and TS.
buf breaking against upstream/main is clean.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…rd; SH_SANDBOX_MODES_ALLOWED SandboxRecord gains mode (per-exec | lease | lease+processes), idleTimeoutS (0 = the worker's default) and modeEpoch. SandboxStore.setMode sets mode and idle timeout and raises the epoch by 1 on every call, atomically: one Lua script (HSET + HINCRBY + HGETALL) in Redis. It returns undefined for a missing or deleted sandbox. A hash written before these fields reads back as per-exec/0/0, and an unknown stored mode reads as per-exec. SandboxConfig gains modesAllowed (SH_SANDBOX_MODES_ALLOWED, default per-exec,lease; an unknown name refuses boot) and idleCeilingS (SH_SANDBOX_IDLE_CEILING_S, default 1800). Create still stores per-exec/0/0; the routes that use these land next. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…de claims, audit
- POST /v1/sandboxes takes optional mode and idleTimeoutS; PUT
/v1/sandboxes/{id}/mode (owner, user API token) raises the epoch, audits
sandbox_mode_changed (fromMode, toMode, modeEpoch) and returns the sandbox
and a set-mode token; POST /v1/sandboxes/{id}/mode-token re-mints one for
the current epoch.
- Policy: a lease mode not in SH_SANDBOX_MODES_ALLOWED is 403
mode_not_allowed (per-exec always allowed); idleTimeoutS is 30..ceiling
or omitted (0); SH_SANDBOX_IDLE_CEILING_S below 30 refuses boot.
- Sandbox tokens carry mode, mode_epoch, idle_timeout_s (absent = per-exec,
0, 0; malformed refused). The set-mode token is typ
moca-sandbox-mode+jwt, aud moca-sandbox, 300 s, under the sandbox key;
verifySetModeToken is exported for the relay.
- The Sandbox wire shape and openapi.yaml gain mode, idleTimeoutS and
modeEpoch.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…atomic setMode
- R8: createSandbox stores modeEpoch 1 for a lease mode (per-exec stays
0): the worker serves every epoch-0 Exec as unversioned per-Exec.
- R9: SandboxStore.setMode returns { record, previousMode }, read in the
same atomic step (memory; Redis SET_MODE HGETs mode before the HSET);
the sandbox_mode_changed audit takes fromMode from it.
- openapi.yaml: the owner-only wording of the /token route on both mode
routes; omit idleTimeoutS for the worker default (explicit 0 is a 400).
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…events through
On the sandbox-token path the relay overwrites Exec.mode, mode_epoch and
idle_timeout_s from the verified claims (claimsToExecMode), so a client
cannot raise its own lease mode; keepalive stays the client's opt-in. The
harness path zeroes all four. A WorkerFrame.lease is routed to its Exec's
sink as ExecEvent{lease}, and withReqId maps its req_id back to the
caller's.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…oken checks
The relay now serves the two SBX0.3 lease calls in place of the UNIMPLEMENTED
stubs (lease-mode spec §8.2):
- Relay.routeLeaseControl sends ServerFrame{leaseControl} under a fresh
relay-wide ctl_id and resolves on the matching WorkerFrame{leaseResult}. It
rejects DEADLINE_EXCEEDED at the per-op timeout (an old worker ignores the
frame) and UNAVAILABLE with no live worker or on disconnect.
Relay.routeKeepalive is fire-and-forget.
- Only sandbox-token callers: the harness gets PERMISSION_DENIED. sandbox_id
must equal the token's wrk, and the workspace is the token's wsk.
- set_mode needs a moca-sandbox-mode+jwt (same keys, issuer and leeway as
the sandbox token) whose sbx, wrk and wsk equal the caller's. The frame's
mode and epoch come from it, via claimsToExecMode. Anything else is
PERMISSION_DENIED and the worker sees nothing.
- Timeouts: status 15 s; reset and set_mode 31 min (LeaseGraceLimit + 60 s).
RelayServerDeps.leaseTimeoutsMs overrides them for tests (ruling R4).
- A worker error maps to FAILED_PRECONDITION with its message.
- One sandbox_lease_control audit line per call, with op and outcome, plus
mode and modeEpoch for a verified set_mode. Keepalives are not audited.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… message Task 5 review, fix round 1: - Every set_mode token refusal now ends with the same PERMISSION_DENIED message, including a verified token for another sandbox. The specific reason goes only to the sandbox_lease_control audit line (ruling R11). - At most LEASE_CONTROL_MAX_INFLIGHT = 4 LeaseControl calls in flight per sbx. The next one gets RESOURCE_EXHAUSTED, audited as `busy` (ruling R13). - A client cancel withdraws the call at once. The handler aborts a signal that routeLeaseControl takes, which drops the waiter, clears the timer and frees the slot. The worker's later answer for that ctl_id is dropped. Audited as `cancelled`. - A write of the leaseControl frame that throws now rejects UNAVAILABLE at once and removes the waiter and timer; it no longer waits for the timeout. - New tests: a late or duplicate leaseResult is dropped, and a keepalive with no worker connected answers OK. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
The worker session now answers the relay's LeaseControl and Keepalive
frames, and carries the lease fields into wexec.Spec.
- wexec.Spec gains Mode ("" for per-exec, "lease", "lease+processes";
an unknown enum value is "unknown(<n>)" so a runner refuses it),
ModeEpoch, IdleTimeoutS and Keepalive, copied from pb.Exec in runOne.
- wexec.LeaseSink: the session's per-Exec sink writes WorkerFrame{lease}
under the Exec's req_id, and returns an error when the connection
ended before the event was queued, so the runner does not ack it.
- session.LeaseController: a runner that implements it gets each
LeaseControl on its own goroutine, at most 16 at once across the
Session (a call blocked past a disconnect keeps its place), answered
through enqueue. Without it: lease_unsupported. At the cap: busy.
Keepalive is called inline and ignored without the interface.
- Serve does not wait for lease goroutines (a set_mode can block for
the lease grace limit); a gate keeps a late reply off the closed
outbound channel and drops it instead.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
- Tests wait on a positive signal, the count of lease calls holding a cap slot (export_test.go), instead of racing the slot release (TestLeaseControlCap) or sleeping (TestLateLeaseReply...). A slot is freed only after its reply was queued or dropped, so zero proves every lease goroutine finished. - The reconnect and late-reply tests release and drain their blocked calls before returning, so no "dropping its result" line lands after the test; every blocking test closes release on cleanup. - reqIDOf becomes frameRef: a wedged lease refusal logs its ctl_id rather than "req_id 0". - LeaseController documents that ctx is the connection's, and that a controller may ignore it (vmpool does): the op completes and its result is dropped if the connection has ended. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ents, maps lease errors vmpool.Runner fills Exec.Mode (ParseMode; an unknown "unknown(<n>)" is refused lease_unsupported), ModeEpoch, IdleTimeout and Keepalive from the Spec. After ExecPhased returns, for a non-per-exec Exec, it emits the pending lease event through wexec.LeaseSink, acknowledging it only when the sink queued it, and an "expiring" notice while the lease is past its maximum duration -- ahead of the result or the error. Lease errors take their wire strings: lease_ended(<reason>), stale_mode: <detail>, lease_unsupported: <detail>; timeout and abort are unchanged. Runner implements session.LeaseController: STATUS, RESET (EndLease reset) and SET_MODE (SetMode) return the status after the op; LeaseKeepalive calls Pool.Keepalive. Mode.Proto and ModeFromProto map the wire enum. relaytest gains SendLeaseControl, LeaseResult and ExecFrames for the attach round-trip over the real session. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
… End); cross-component test Spec v0.3 records plan 3's wire: a lease event rides on a lease Exec's response before its End (and before an error), delivered at least once (clients dedupe on at_unix_ms), and a downgrade's mode_change end comes back in the set_mode result's status (R16); the mode routes, the epoch a create starts at (R8), the idle-timeout bounds and policy (R6, R7); the third claim and the set-mode token (R2, R11, R12); the relay's limits, timeouts and status codes for LeaseControl and LeaseKeepalive (R10, R13), with the audit outcomes. The sandbox/v1 page gains a Lease mode section; the control-plane API goes to 1.4.0 with a changelog entry; deploy/sbx documents SH_SANDBOX_MODES_ALLOWED and SH_SANDBOX_IDLE_CEILING_S. Two comments stale since R8 now say a per-exec sandbox starts at epoch 0 and a lease create at 1. lease-wire.transport.test.ts drives the control plane's own sandbox handlers (create, mint, PUT mode, mode-token) into the relay and a fake worker: a lease create's claims reach the Exec at epoch 1, a mode change raises the epoch, set_mode carries the new one, and a token minted before the change reaches the worker at its old epoch. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…rding Review fix round 1 for Task 8. - Spec §5 and the sandbox/v1 page: a lease event is acknowledged when the worker queues it, not when the client reads it, so it is a best-effort notice delivered once and lost if the stream breaks in between (LeaseControl status still shows the state). The rare duplicate (an acknowledgement that could not be written, or the next Exec finishing first) is why clients dedupe on at_unix_ms. The "two overlapping Execs" example is gone. - Spec §8.3: the sandbox_lease_control line covers refusals too, a call with no bearer token included; only a relay with no sandbox keyset answers UNAUTHENTICATED without one; sub and sbx appear once the token verified. - sandbox.proto: LeaseStatus.pending is the last undelivered lease event (a start or an end), not only an end; generated Go and TS regenerated (comment line only). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…workspace One sandbox could fill the worker's 16 lease-call slots (blocked reset or set_mode calls whose relay call was cancelled) and deny every other sandbox's LeaseControl, status included, for up to the grace limit. A status now runs on its own goroutine without a slot (vmpool's only takes the pool lock briefly). Reset and set_mode take one of the 16 worker-wide slots and one of 2 per workspace key; a third on the same key answers busy at once while other keys still get a slot. Spec section 8.3 says so. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ode verify; keepalive write caught - routeLeaseControl and routeKeepalive refuse a workload sandbox with PERMISSION_DENIED, as routeExec refuses an Exec that names no workload (SBX0 3.3); the refusal is audited `refused`. - The per-sbx LeaseControl cap is checked before the set-mode token, so a saturated sandbox answers busy alike whatever the token, and no verify work is spent. - routeKeepalive catches a failed write to the worker stream and logs it; the caller is still answered OK (fire-and-forget). Spec 8.3 says so. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ase doc corrections Ruling R20: a microVM worker serves lease mode on its own once its snapshot advertises lease-v1, so the control plane's list is the only switch, and spec section 11 gates level 1 on the security review's lease section. The default is now `per-exec` until plan 4's live smoke and that section; operators opt in with `per-exec,lease`. Spec 8.1, the deploy README, openapi.yaml and the API changelog say so. Doc corrections on the direct-client page and spec 8.2: - lease_unsupported on an Exec comes from a microVM worker without a lease-v1 snapshot (or an unknown mode); the container tier and older workers serve a lease-mode Exec per-Exec, silently; - an epoch-0 token from before the first mode change is not refused stale_mode: it runs per-Exec and ends a live lease; - the worker's per-sandbox and worker-wide lease-call caps, and the workload-sandbox PERMISSION_DENIED. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…wait - runner.go: the pool's refusals are counted in Stats, but the unknown-mode lease_unsupported refusal Runner builds (specMode) never reaches the pool and is not; the comment said all were. - TestLeaseEndedWireString waits for the guest with recvWithin (5 s, then t.Fatal) instead of a bare receive that would hang on a regression. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
The cross-component test boots a control plane from env; with the per-exec default (R20) it must list `per-exec,lease` to create a lease sandbox, as an operator would. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…fields The template-create quota test (from the self-serve create work on main) builds SandboxRecord literals by hand; since the lease wire made mode, idleTimeoutS and modeEpoch required on the record, they need the per-exec defaults. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
41dd7ef to
a405e31
Compare
…rint the lease fields frameSink.Lease took enqueue's true as "queued", but enqueue tries its non-blocking sends before it looks at the connection, so after cancelConn it still queued into a buffer with room. The common lease-disconnect path (the connection's end aborts the lease Exec, the runner then reports its event) therefore had the pool acknowledge an event that was discarded. The sink now checks the connection's done channel first and answers errLeaseNotQueued, so the event stays pending (spec §5). The chunk path is unchanged. The remaining check-then-send race is documented as the best-effort window spec §5 already names. The dedup fingerprint now covers mode, a fixed-width mode_epoch, idle_timeout_s and keepalive, so a req_id reused across modes or epochs runs fresh instead of being answered from the other Exec's cached End. Fingerprint takes the Exec. Review: #4559538346, #4559538351. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
… idle The service comment and the ServerFrame.keepalive field said a keepalive pushes back a live lease's idle timeout. It does not: vmpool's Keepalive records harness liveness for the keepalive-loss rule and never touches idle (spec §2), as the direct-client page already says. This proto is the file handed to direct clients, so say what the call does. Stubs regenerated (comments only). Review: #4559538355, #4559538360. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…time; setMode refuses expired SH_SANDBOX_MODES_ALLOWED and SH_SANDBOX_IDLE_CEILING_S were checked on create and PUT only, so narrowing either left existing sandboxes minting lease tokens for their whole life, and the list was not the switch spec §8.1 calls it. Both mints (the sandbox token and mode-token) now take the record through underPolicy first: a lease mode the policy no longer lists is set to per-exec through the store's atomic setMode, which raises the epoch (the next Exec ends the live lease; a same-epoch re-issue would be a retry to the worker), audited as sandbox_mode_changed with reason mode_not_allowed. The idle_timeout_s claim is clamped to the current ceiling with the record and epoch unchanged (ruling R12). Documented in spec §8.1, the 1.6.0 changelog, openapi.yaml and deploy/sbx/README.md. setMode takes now and refuses an expired record, in the SET_MODE script and in MemorySandboxStore, as DELETE does, so a PUT that crosses expiry stores and audits nothing. Review: #4559538363, #4559538369. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ase epochs and status codes - CHANGELOG 1.6.0: 1800 is the ceiling's default; an omitted idleTimeoutS means the worker's default of 300 s (vmpool DefaultLeaseIdle). - deploy/sbx/README.md: the worker clamps with its own SH_LEASE_IDLE_CEILING_S (default 1800), so raise it together with SH_SANDBOX_IDLE_CEILING_S. - sandbox-v1-direct-client.md: an epoch-0 token exists only for a sandbox created per-exec (a lease create starts at 1); the LeaseControl PERMISSION_DENIED row names the harness token, and a CANCELLED row is added, as spec §8.3 lists (the relay rejects a cancelled call with CANCELLED and frees its place; a reset or set_mode already sent runs on at the worker). Review: #4559538377, #4559538384, #4559538389. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…he call settles The 'cancelled' listener was left on the server call after it settled. Harmless, since settle() already detaches from the signal, but both .then handlers now remove it. Review: #4559538392. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
This PR wires lease mode through the proto, the control plane, the sandbox relay and the worker. The trust boundaries hold:
- Mode, epoch and idle timeout: the relay overwrites them from the verified token claims on the sandbox path, and zeroes them on the harness path.
- Set-mode token: it has its own typ, and is bound to the sandbox, the worker and the workspace key (sbx/wrk/wsk). It is checked after the busy cap.
- Mode routes: owner-only.
- Epoch: raised atomically in a Redis Lua script, and the worker refuses an epoch below the one it holds.
- Caps: 4 lease calls in flight per sandbox at the relay; 16 in total and 2 per workspace at the worker; a status call takes no slot.
- Proto: the change is purely additive.
Must-fix:
- A lease event can be acked after the connection has ended (remote-worker/internal/session/lease.go:83). This was raised in the earlier review at 41dd7ef and is still open at head.
enqueue(loop.go:416-451) checksconnCtxonly when it would block. SoframeSink.Leasereturns nil aftercancelConn(), andRunner.deliverLeaseEventscallsAckLeaseEventon an event that is never sent. That breaks spec §5's "stays pending" promise. A throwaway probe gotnilin 5 of 5 runs.
The rest are a suggestion and a nit, inline:
- Narrowing
SH_SANDBOX_MODES_ALLOWEDdoes not reach existing lease sandboxes. Token minting copiesrec.modewithout checking the list. This needs a decision either way, and docs to match. - The proto comments say a keepalive pushes back idle. The code and the spec say it never resets idle.
One more point, from the earlier review: mode and epoch are still not part of the dedup Fingerprint (session/cache.go, not in this diff). The impact is low. req_id is unique per sandbox, and stale_mode replies are not cached, so only a same-req_id retry of a finished Exec across a mode change replays the old answer.
- Author: pdettori (MEMBER — maintainer)
- Areas reviewed:
- proto (sandbox/v1)
- TypeScript: the control plane (mode, set-mode tokens, epoch, Redis Lua) and the sandbox relay (LeaseControl, keepalive, waiters, caps)
- Go: remote-worker session (lease frames, the enqueue path) and vmpool Runner
- deploy/sbx README, docs and spec
- Agent/IDE config (.claude/.vscode): none
- Commits: 18 commits, all signed-off: yes
- CI status: passing (17/17)
Verified by:
go test ./...in remote-worker: every package this PR touches passes, and the lease tests also pass under-race. Two tests this PR does not touch fail here, and fail the same way on base d4babb8: one needs a non-root uid, the other needs cloud-hypervisor.- vitest:
- control-plane: 1390 pass
- sandbox-relay: 266 pass
- k8s-sandbox: 133 pass
- sandbox-client: 148 pass
- A throwaway session probe test: after the connection closes,
Leasereturns nil (5 of 5 runs). The probe has been deleted.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
| func (f *frameSink) Lease(ev *pb.LeaseEvent) error { | ||
| out := proto.Clone(ev).(*pb.LeaseEvent) | ||
| out.ReqId = f.reqID | ||
| if !f.send(&pb.WorkerFrame{Msg: &pb.WorkerFrame_Lease{Lease: out}}) { |
There was a problem hiding this comment.
must-fix Still open from the previous review: Lease can return nil after the connection has ended, so vmpool.Runner.deliverLeaseEvents (runner.go:125-126) calls AckLeaseEvent for an event that is never sent. Spec §5 says such an event "stays pending, and the next lease Exec carries it", and the LeaseSink doc in exec/runner.go makes the same promise.
Cause: enqueue (loop.go:416-451) tries the non-blocking chunkSlots and outbound sends first and returns true (loop.go:439) whenever there is buffer room. It checks connCtx only when it would block. After cancelConn() the buffer usually has room, so the frame is "queued" into an outbound that the sender only drains into a dead stream, or the frame is discarded.
Probe: a throwaway session test with a runner whose Run waits on <-ctx.Done() (the exec ctx derives from connCtx), after st.close(), and then calls sink.(wexec.LeaseSink).Lease(...). It got nil in 5/5 runs (-count=5). No existing test covers the errLeaseNotQueued path: there is no reference to it in any _test.go.
Fix: in Lease, return errLeaseNotQueued when the connection is already done before enqueuing, e.g. give frameSink the conn ctx (or a connDone func() bool) and check ctx.Err() first. Alternatively have enqueue check connCtx.Err() before its fast path. Then add a test of the shape above that asserts a non-nil error and that AckLeaseEvent is not called.
| sbx: rec.id, | ||
| wrk: rec.worker, | ||
| wsk: rec.wsk, | ||
| mode: rec.mode, |
There was a problem hiding this comment.
suggestion mintSandboxToken copies rec.mode into the token without checking cfg.modesAllowed, and setModeTokenFor (mode-token route) does the same. So an operator who removes lease from SH_SANDBOX_MODES_ALLOWED, for example after the security review finds a problem, stops only new creates and PUTs. Every existing lease sandbox keeps minting mode: lease sandbox tokens and set-mode tokens, and the worker serves them, because LeaseSupported is its only gate. That contradicts deploy/sbx/README.md:66 ("the control plane's list is the only switch") and spec §8.1 ("so this list is the switch"). The previous review raised this too, and it is still neither decided nor documented.
Fix: either clamp at mint time (mode: cfg.modesAllowed.has(rec.mode) || rec.mode === 'per-exec' ? rec.mode : 'per-exec', noting that a lower mode at the same epoch is served as the lower one, effectiveModeLocked), or state plainly in the README/spec that narrowing the list does not affect existing sandboxes and describe how to turn them off.
| // Lease mode (SBX0.3). Both act on the sandbox's lease, not on one Exec, and both | ||
| // are relayed to the worker as a ServerFrame. LeaseControl reads the lease status, | ||
| // ends the lease (reset) or changes the mode (set_mode, which needs a signed | ||
| // set_mode_token); LeaseKeepalive pushes back the idle timeout of a live lease. |
There was a problem hiding this comment.
nit "LeaseKeepalive pushes back the idle timeout of a live lease" is wrong, and so is line 44 ("push back a live lease's idle timeout"). vmpool Keepalive (lease.go:1043-1046) says "It never resets idle", leaseEndDueLocked measures idle from lastEnd only, and docs/api/sandbox-v1-direct-client.md:192-193 and spec §4 agree. Generated-client users read this comment. The previous review raised it, and it is still unfixed. Suggest: "LeaseKeepalive reports that the client still runs; it turns on the keepalive-loss rule and restarts its clock, and never resets idle" (and regenerate).
One worker serves many sandboxes and the dedup cache is per Session, not per workspace, so a req_id reused across two workspaces with an otherwise identical Exec was answered from the other sandbox's cached terminal frame: one sandbox's result handed to another. workspace_key is now part of the fingerprint, length-prefixed like command and stdin. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…gerprint; neutral collision text idle_timeout_s and keepalive do not change an Exec's result, and both can differ between a genuine retry and its original after a re-mint: the relay stamps idle_timeout_s from the token, and a lowered idle ceiling clamps it. Hashing them turned such a retry into a second run of a possibly non-idempotent command. The fingerprint keeps mode, mode_epoch and workspace_key, and its doc comment says why exactly those. The session test for them is inverted: a retry differing only in idle_timeout_s or keepalive is answered from the cache. A req_id collision can now be a different mode, epoch or workspace, so the collision log lines and the refusal say "a different Exec (command, mode, epoch or workspace)"; the "req_id collision:" prefix clients match on is kept. The workspace-key aliasing test now says what it pins (stdin's prefix; the key's own cannot be observed while only fixed-width fields follow it). Re-review: N1, N2, N5. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…downgrade An owner's PUT to a mode still allowed, landing between a mint's read and its downgrade, can be overwritten with per-exec; the owner sends it again. The underPolicy comment said so; now the spec does too. Re-review: N3. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
|
Review 1 addressed in
CI on the rebased head was all green, Assisted-By: Claude Code |
clawgenti
left a comment
There was a problem hiding this comment.
Re-review at c705435, covering the 8 commits since a405e31. All checks pass. Ready for human review.
Every finding from the two earlier reviews is fixed, and I checked each fix on head:
-
Lease event acked after the connection ended (the earlier must-fix):
frameSink.Leasenow checksconnDonebefore it sends and returnserrLeaseNotQueued, so the runner no longer acks an event that is never sent. It checks the connection, not the Exec's ctx, so an event from an aborted Exec on a live connection is still queued. The check-then-send window that remains is documented, and it matches spec §5's best-effort wording. -
Dedup fingerprint:
Fingerprint(*pb.Exec)now also coversworkspace_key(length-prefixed),modeand a fixed-widthmode_epoch.idle_timeout_sandkeepaliveare left out on purpose, because a token re-minted under a lowered ceiling would otherwise turn a genuine retry into a second run. The collision log and error text now say "different Exec". -
Policy narrowing: the new
underPolicyin both mint handlers downgrades a mode that is no longer allowed toper-execthrough the atomicsetMode. That raises the epoch, and the downgrade is audited withreason: mode_not_allowed.idleClaimclamps the idle claim on both token kinds. The two accepted races are written down in spec §8.1 and the README. -
SET_MODEacross expiry: the Lua script andMemorySandboxStore.setModenow refusenow >= expiresAt. There is a store-contract case for both stores. -
Proto keepalive wording, CHANGELOG/README/direct-client nits,
cancelledlistener: all fixed as suggested. The generated stubs changed in comments only. -
Author: pdettori (MEMBER — maintainer)
-
Areas reviewed:
- Go: remote-worker session (lease.go, loop.go, cache.go)
- TypeScript: control-plane (sandbox-handlers, sandbox-redis, sandbox-store) and sandbox-relay main.ts
- proto comments and regenerated stubs
- docs: the spec §8.1, the API CHANGELOG,
deploy/sbxREADME and sandbox-v1-direct-client
-
Agent/IDE config (.claude/.vscode): none
-
Commits: 26 commits, all signed-off: yes
-
CI status: passing (17/17)
Verified by:
- remote-worker:
go vetandgofmt -lare clean.go test -race -count=3 ./internal/session/passes. Ingo test ./...every package this PR touches passes. Two tests fail here because of this environment, and both are outside the PR:TestNormaliseWorkspaceOwnsGroupWritesAndStaysInsideneeds a non-root uid, andTestRestoreFoldsCloudHypervisorsOwnLogIntoTimeoutErrorhits a fake-virtiofsd exec permission error. - Mutation tests (restored afterwards, worktree clean):
- Removing the
connDonecheck inframeSink.LeasemakesTestLeaseEventAfterDisconnectIsNotQueuedfail. With the check back, it passes. - Dropping
mode_epochfromFingerprintmakesTestFingerprintSeparatesModeAndEpochandTestReqIDReusedAcrossLeaseFieldsRunsFresh/mode_epochfail.
- Removing the
- vitest: control-plane has 1396 passed and 3 skipped, against Redis. sandbox-relay, k8s-sandbox and sandbox-client were not run here, because they need the
pi-forksubmodule build. CI covers them.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Re-review at c705435: every item from the previous review is resolved.
- must-fix (lease event acked after the connection ended): fixed in e650350.
frameSink.Leasechecks the connection's done channel before queueing, so an Abort still delivers and a disconnect leaves the event pending. Both cases are tested. The remaining check-then-send window is correctly documented as the spec §5 best-effort case. - Dedup fingerprint:
Fingerprint(*pb.Exec)now covers workspace_key, mode and mode_epoch. Leaving idle_timeout_s and keepalive out is the right call, because the relay re-stamps them from the token. It also closes the cross-workspace cache answer that existed before this PR. - Policy narrowing:
underPolicyandidleClaimat mint time makeSH_SANDBOX_MODES_ALLOWEDand the idle ceiling apply to existing sandboxes. The accepted races (a double downgrade, an overwritten owner PUT) are documented in spec §8.1. - Nits: all addressed. That includes
SET_MODErefusing an expired record atomically in both stores, the doc wording fixes and the relay's cancel-listener cleanup.
DCO is signed off and CI is green. No .claude/ or .vscode/ changes.
Upstream main (634781a) adds the sandbox lease wire (rossoctl#802) as API 1.6.0, which this branch also claimed; its section moves to 1.7.0. Conflicted: - docs/api/CHANGELOG.md: main's 1.6.0 (sandbox modes) kept as main has it; this branch's session-templates section is now 1.7.0, above it. Also changed in the merge: - docs/api/openapi.yaml: info.version 1.7.0 (both sides said 1.6.0, so it merged without a conflict). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Rong Chang <[email protected]>
Upstream main (634781a) adds the sandbox lease wire (rossoctl#802) as API 1.6.0, which this branch also claimed; its section moves to 1.7.0. Conflicted: - deploy/sbx/RUNBOOK.md: this branch's enrollment-through-the-API text kept, followed by main's §5 heading "Adding, updating and removing a template" and its body. - docs/api/CHANGELOG.md: main's 1.6.0 (sandbox modes) kept as main has it; this branch's enrollment section is now 1.7.0, above it. - docs/api/openapi.yaml: error codes are the union (main's mode_not_allowed, then bootstrap_subject, self_revoke, admin_granted); info.version 1.7.0. - packages/control-plane/src/errors.ts: both code lists and both status entries kept (mode_not_allowed 403; the three 409s). - packages/control-plane/test/errors.test.ts: the expected table holds all four codes. Also changed in the merge: - docs/reference/http-api.md: the subjects routes say API 1.7.0. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Rong Chang <[email protected]>
Upstream main (634781a) adds the sandbox lease wire (rossoctl#802) as API 1.6.0, which this branch also claimed; its section moves to 1.7.0. Conflicted: - docs/api/CHANGELOG.md: main's 1.6.0 (sandbox modes) kept as main has it; this branch's section is now 1.7.0, above it. - docs/api/openapi.yaml: error codes are the union (main's mode_not_allowed, then self_attested); info.version 1.7.0. - packages/control-plane/src/errors.ts: both codes and both status entries kept (mode_not_allowed 403, self_attested 409). - packages/control-plane/src/sandbox-config.ts: main's SH_SANDBOX_IDLE_CEILING_S check kept, then this branch's SH_GATE_RECORD_SCHEMA check; the config carries both. - packages/control-plane/test/errors.test.ts: the expected table holds both codes. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Rong Chang <[email protected]>
Upstream main (f60db30) adds the sandbox lease wire (rossoctl#802) as API 1.6.0, which this branch also claimed, and session grants (rossoctl#807) as API 1.7.0; this branch's section moves to 1.8.0. Conflicted: - docs/api/CHANGELOG.md: main's 1.7.0 (grants) and 1.6.0 (sandbox modes) kept as main has them; this branch's template-admin section is now 1.8.0, above them. - docs/api/openapi.yaml: info.version 1.8.0 (this branch said 1.6.0, main 1.7.0). - packages/control-plane/src/sandbox-handlers.ts: the imports are the union (this branch's provenance, identity and isEnrolled imports, and main's MIN_IDLE_TIMEOUT_S). - packages/control-plane/test/openapi-contract.test.ts: the enrollable route count is 24: the base's 18, this branch's four template admin routes and main's two sandbox mode routes. Also changed in the merge: - docs/reference/http-api.md: the template admin routes say API 1.8.0. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Rong Chang <[email protected]>
…te lifecycle stack Upstream main 0dc3d01 (API 1.21.0) carries the reviewed, final form of the features this branch held in early, integrated versions, through the PRs filed from this fork (rossoctl#755-rossoctl#776, rossoctl#781, rossoctl#782, rossoctl#784-rossoctl#786, rossoctl#789-rossoctl#794, rossoctl#798-rossoctl#800) and the maintainer's lease mode, grants and lease clients (rossoctl#763, rossoctl#802, rossoctl#807, rossoctl#808, rossoctl#810, rossoctl#812, rossoctl#814). Where upstream has a feature, upstream's version wins: its code, tests, openapi, CHANGELOG (byte identical), docs and specs. The fork was 736 commits behind and 390 ahead (merge base dd0ce71). Conflict resolution (148 files, 82 both-modified, 66 both-added): every conflicted file is upstream's side as is (byte identical to 0dc3d01). No conflicted file differs from 0dc3d01 in this commit. One file merged without a conflict and was set back to upstream's: - packages/mocactl/src/sbx/push.ts: the auto-merge added the fork's baselineAtHead a second time beside upstream's own (fb28e06's function, already upstream); upstream's file as is. With that, this commit's tree is 0dc3d01's plus the 18 files only the fork has (below). Every other file the fork changed is upstream's. Conflicted files, all resolved to upstream's side (0dc3d01): - deploy/k8s/overlays/ocp-combined/kustomization.yaml (AA) - deploy/k8s/overlays/ocp-combined/patch-addressing.yaml (AA) - deploy/k8s/overlays/ocp-combined/patch-relay.yaml (AA) - deploy/microvm/P4-ON-P6.md (UU) - deploy/microvm/build-rootfs.sh (UU) - deploy/microvm/build-snapshot.sh (UU) - deploy/microvm/setup-microvm.sh (UU) - deploy/microvm/tests/build-rootfs.test.sh (UU) - deploy/microvm/tests/build-snapshot.test.sh (UU) - deploy/microvm/tests/setup-microvm.test.sh (UU) - deploy/sbx/README.md (UU) - deploy/sbx/RUNBOOK.md (UU) - deploy/sbx/host-agent.sh (AA) - deploy/sbx/install-host.sh (UU) - deploy/sbx/sbx-host-agent-wanted.service (AA) - deploy/sbx/sbx-host-agent-wanted.timer (AA) - deploy/sbx/sbx-host-agent.service (AA) - deploy/sbx/[email protected] (UU) - deploy/sbx/setup.sh (UU) - deploy/sbx/template-onboarding/GUIDE.md (AA) - deploy/sbx/template-onboarding/ONBOARDING.md (AA) - deploy/sbx/template-onboarding/README.md (AA) - deploy/sbx/template-onboarding/examples/django__django-11133.gate-record.json (AA) - deploy/sbx/template-onboarding/examples/django__django-11133.json (AA) - deploy/sbx/template-onboarding/governance/GATING-RULES.md (AA) - deploy/sbx/template-onboarding/governance/PROCESS.md (AA) - deploy/sbx/template-onboarding/governance/README.md (AA) - deploy/sbx/template-onboarding/template-build.sh (AA) - deploy/sbx/template-onboarding/template-register.sh (AA) - deploy/sbx/template-onboarding/tests/examples.test.sh (AA) - deploy/sbx/template-onboarding/tests/template-build.test.sh (AA) - deploy/sbx/template-onboarding/tests/template-register.test.sh (AA) - deploy/sbx/template-onboarding/verify-provenance.py (AA) - deploy/sbx/templates-check.sh (AA) - deploy/sbx/tests/host-agent.test.sh (AA) - deploy/sbx/tests/install-host.test.sh (UU) - deploy/sbx/tests/overlay-combined.test.sh (AA) - deploy/sbx/tests/setup.test.sh (UU) - deploy/sbx/tests/templates-check.test.sh (AA) - deploy/vm/tests/setup-vm.test.sh (UU) - docs/api/CHANGELOG.md (UU) - docs/api/harness-openapi.yaml (UU) - docs/api/openapi.yaml (UU) - docs/concepts/sandboxes-and-tiers.md (UU) - docs/reference/change-policy.md (UU) - docs/reference/cli-mocactl.md (UU) - docs/reference/configuration.md (UU) - docs/reference/http-api.md (UU) - docs/sbx/user-guide.md (UU) - docs/specs/2026-10-15-sbx0-internal-sandbox-service-design.md (UU) - docs/specs/2026-10-30-session-sandbox-templates-design.md (AA) - docs/specs/2026-11-03-template-lifecycle-and-provenance-design.md (AA) - docs/specs/2026-11-05-combined-control-plane-design.md (AA) - docs/specs/2026-11-08-enrollment-and-roles-api-design.md (AA) - docs/specs/2026-11-08-sandbox-egress-records-design.md (AA) - docs/specs/2026-11-08-subject-trust-gate-records-design.md (AA) - docs/specs/README.md (UU) - harness/src/run-turn.ts (UU) - harness/src/sandbox-affinity.ts (UU) - harness/src/select-sandbox.ts (UU) - harness/test/select-sandbox-templates.test.ts (AA) - harness/test/turn-seed.test.ts (AA) - harness/test/turn-stream.test.ts (UU) - packages/control-plane/src/activation-lock.ts (AA) - packages/control-plane/src/activation.ts (AA) - packages/control-plane/src/egress-handlers.ts (UU) - packages/control-plane/src/egress-log.ts (AA) - packages/control-plane/src/errors.ts (UU) - packages/control-plane/src/exchange.ts (UU) - packages/control-plane/src/handler-util.ts (UU) - packages/control-plane/src/handlers.ts (UU) - packages/control-plane/src/host-handlers.ts (AA) - packages/control-plane/src/identity.ts (UU) - packages/control-plane/src/index.ts (UU) - packages/control-plane/src/main.ts (UU) - packages/control-plane/src/member-handlers.ts (AA) - packages/control-plane/src/members.ts (AA) - packages/control-plane/src/ownership.ts (UU) - packages/control-plane/src/provenance.ts (AA) - packages/control-plane/src/routes.ts (UU) - packages/control-plane/src/sandbox-config.ts (UU) - packages/control-plane/src/sandbox-handlers.ts (UU) - packages/control-plane/src/server.ts (UU) - packages/control-plane/src/template-catalog.ts (AA) - packages/control-plane/src/template-policy.ts (AA) - packages/control-plane/src/token.ts (UU) - packages/control-plane/test/activation.test.ts (AA) - packages/control-plane/test/egress-redis.test.ts (AA) - packages/control-plane/test/errors.test.ts (UU) - packages/control-plane/test/host-flow.test.ts (AA) - packages/control-plane/test/members.test.ts (AA) - packages/control-plane/test/openapi-contract.test.ts (UU) - packages/control-plane/test/provenance.test.ts (AA) - packages/control-plane/test/repository-allowlist.test.ts (AA) - packages/control-plane/test/route-authz-enumeration.test.ts (UU) - packages/control-plane/test/route-profile.test.ts (UU) - packages/control-plane/test/routes.test.ts (UU) - packages/control-plane/test/sandbox-egress.test.ts (AA) - packages/control-plane/test/sandbox-handlers.test.ts (UU) - packages/control-plane/test/session-templates.test.ts (AA) - packages/control-plane/test/subject-trust.test.ts (AA) - packages/control-plane/test/template-admin.test.ts (AA) - packages/control-plane/test/template-catalog.test.ts (AA) - packages/control-plane/test/template-create.test.ts (AA) - packages/knative-server/src/server.ts (UU) - packages/knative-server/src/turn-auth.ts (UU) - packages/knative-server/test/turn-auth.test.ts (UU) - packages/mocactl/src/api/errors.ts (UU) - packages/mocactl/src/api/frames.ts (UU) - packages/mocactl/src/cli.ts (UU) - packages/mocactl/src/core/session-manager.ts (UU) - packages/mocactl/src/core/session-options.ts (UU) - packages/mocactl/src/headless.ts (UU) - packages/mocactl/src/sbx/api.ts (UU) - packages/mocactl/src/sbx/call-record.ts (AA) - packages/mocactl/src/sbx/cli.ts (UU) - packages/mocactl/src/sbx/commands.ts (UU) - packages/mocactl/src/sbx/dry-run.ts (AA) - packages/mocactl/src/sbx/exec.ts (UU) - packages/mocactl/src/sbx/run.ts (UU) - packages/mocactl/src/sbx/templates.ts (AA) - packages/mocactl/test/contract.test.ts (UU) - packages/mocactl/test/harness.test.ts (UU) - packages/mocactl/test/headless.test.ts (UU) - packages/mocactl/test/helpers/sbx.ts (UU) - packages/mocactl/test/run-record.test.ts (AA) - packages/mocactl/test/sbx-admin-subjects.test.ts (AA) - packages/mocactl/test/sbx-cli.test.ts (UU) - packages/mocactl/test/sbx-egress.test.ts (AA) - packages/mocactl/test/sbx-exec.test.ts (UU) - packages/mocactl/test/sbx-templates.test.ts (AA) - packages/mocactl/test/session-manager.test.ts (UU) - packages/mocactl/test/session-options.test.ts (UU) - remote-worker/cmd/microvm-worker/main.go (UU) - remote-worker/cmd/microvm-worker/template_record.go (AA) - remote-worker/cmd/microvm-worker/template_record_test.go (AA) - remote-worker/cmd/microvm-worker/verify_cache.go (AA) - remote-worker/cmd/microvm-worker/verify_cache_test.go (AA) - remote-worker/internal/egress/audit_test.go (UU) - remote-worker/internal/session/labels.go (UU) - remote-worker/internal/vmpool/errors.go (UU) - remote-worker/internal/vmpool/guestconn.go (UU) - remote-worker/internal/vmpool/guestconn_test.go (UU) - remote-worker/internal/vmpool/launcher_firecracker.go (UU) - remote-worker/internal/vmpool/launcher_firecracker_egress_unix_test.go (UU) - remote-worker/internal/vmpool/snapshot.go (UU) - remote-worker/internal/vmpool/snapshot_test.go (UU) - remote-worker/internal/vmpool/verifycache.go (AA) Fork-only files, kept as they are (upstream has no such file): - deploy/sbx/mint-login.sh, deploy/sbx/tests/mint-login.test.sh: a test login minted with the deployment's signing key. Checked against upstream: makeSigner/mint, SANDBOX_API_ISSUER, the moca-mu1 Secret and its label, the env keys it reads and mocactl's sbx-auth.json shape are all still upstream's. - deploy/sbx/template-onboarding/deck/ (README, requirements, the two generators, deck_kit.py, the two PDFs, .gitignore): the fork's decks. - deploy/sbx/template-onboarding/GUIDE.pdf: regenerated from upstream's GUIDE.md in a later commit. - deploy/sbx/template-onboarding/governance/GAPS-AND-ASSUMPTIONS.md and INVENTORY-2026-11-02.md: the fork's register and inventory. - docs/specs/2026-11-09-cold-start-pacing-design.md, 2026-11-09-memory-aware-placement-design.md and 2026-11-10-mocactl-template-commands-design.md: the fork's design notes; upstream folded their content into its lifecycle spec (§6.4 memory, §6.5 pacing) and the user guide (mocactl). - docs/tools/gen_pdf.py, docs/tools/gen_toc.py: the PDF and TOC tools. Fork-only behaviour, decided one by one (from git log 0dc3d01..f125c02 --no-merges, checked against 0dc3d01): Ported onto upstream's code, each in its own commit after this one: - The pinned-session retire guard (c571226): a retire is refused (409 build_in_use) while an active Moca Pi session is pinned to the build. Upstream's buildsInUse checks live sandboxes only and its comment says pinned sessions are still to be checked. - Reuse only while a host holds the snapshot (G29, 521efe5): upstream reuses any registered build with the same inputs; its own lifecycle spec (§4, Reuse) says a registered build is reused only while a host reports holding its snapshot. - install-host.sh --uninstall-shared and the mounted legacy jail guard (5e66397): upstream has neither. - GUIDE §4b.4's base example without skip_git_identity_check (f125c02): upstream applies X12 under every profile, so its example create would be refused. - Links from upstream's READMEs to the fork-only files above. Dropped, because upstream's design replaces them on purpose: - Removal of admin-rejected builds: upstream stops them and never removes them (the user's decision in rossoctl#786). - The harness-profile catalog's fallback to SH_SESSION_TEMPLATES (902255b): upstream serves the harness profile the store's templates only (its test was renamed so); a combined plane is unaffected. - The fork's register ids (G-numbers), window dates and results pointers inside the documents upstream now has (RUNBOOK, README, GUIDE, ONBOARDING, PROCESS, GATING-RULES, P4-ON-P6, the specs): upstream's text wins; the fork's own documents above keep them. - The fork's image-builder-specific wording in GATING-RULES.md: upstream's generic wording (the image builder) is taken as is. Dropped, could be re-proposed (no upstream equivalent, but the port is an API change or its intent upstream is unclear): - TurnPlacement.template, a turn result naming the session's sandbox template (9d6004d): a harness API field; upstream's CHANGELOG is kept byte identical. - An imported build's catalog entry and create record carrying the declared seed (20d0995): sessions are seeded the same (upstream falls back to the declared seed); only the field in the catalog API goes. - mocactl: sbx create --seed checking the seeded HEAD against the spec's baseline_commit; activate --wait stopping at once on not_held or memfile_mismatch; ApiError's readiness, readinessReason and queuePosition in refusals; an admin write refused when the control plane URL came only from the login; the admin-write issuer check for the combined profile; the dry run's X1.offline check and its guest_mb and git-less advice; the quota, policy and build lines' extra fields (quotaSource, selfAttest, allowedRepositories, heldBy, attestation). Upstream's reviewed client (rossoctl#767, rossoctl#768) left them out; the server still enforces every rule. Already upstream (not lost): build reuse (G21), the verify cache, the host agent's --keep-shared removals, read-ahead, the hash_version 2 check in the microVM worker, M7, G39, G42, G43, G48, G49, G50, mocactl --record, --version, the minted login's own control plane, activate --wait sizing, and every other fork feature listed in the task. The relay's per-client tokens: not on this branch (the fork's sandbox-relay main.ts is older upstream code), so nothing to resolve. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Rong Chang <[email protected]>
Sixteen ADRs still said Proposed although their decisions are in code on main. Each status line now names the merged PRs that implemented it and the date the core landed (format of ADR-0042), and notes what is still owed where only part is built: - 0028 (rossoctl#170, rossoctl#201, rossoctl#340; its KEDA transport removed by ADR-0041) - 0029 (rossoctl#171), 0030 (rossoctl#214), 0031 (rossoctl#214, rossoctl#225) - 0032 (rossoctl#249, rossoctl#350, as amended by MI1) - 0035 (rossoctl#251; ADR-0048 adds lease mode beside it) - 0036 (rossoctl#347), 0038 (rossoctl#458), 0039 (rossoctl#467), 0040 (rossoctl#481) - 0043 (rossoctl#560, rossoctl#588, rossoctl#600, rossoctl#615), 0044 (rossoctl#563), 0045 (rossoctl#620) - 0046 (phase 1: rossoctl#630, rossoctl#641, rossoctl#646; phase 2 owed) - 0047 (M1 and M3: rossoctl#704, rossoctl#713, rossoctl#717, rossoctl#765; M2 owed) - 0048 (rossoctl#706, rossoctl#763, rossoctl#802, rossoctl#808, rossoctl#814; off by default until the security review's lease sections are signed off) The README index follows, and its 0033 row, which still said Proposed after rossoctl#249 accepted the ADR, is corrected. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Summary
SBX0.3 lease mode, plan 3 of 5: the wire. This PR carries lease mode from the control plane through the relay to the worker. Plan 2 (#763) built the worker's lease lifecycle behind
Poolmethods; this PR fills the newsandbox/v1fields, adds theLeaseControlandLeaseKeepalivecalls, and wiresvmpool.Runnerto plan 2'sPoolAPI. Per-Execbehaviour is unchanged for every existing client, token and worker.Spec:
docs/specs/2026-11-08-sbx-lease-mode-design.mdv0.2 (#718), §4, §5 and §8; this PR updates §5 and §8.1–§8.3 to match what was built. Plan 2: #763.What it adds
Proto (
sandbox/v1, additive):Exec.mode(enumSandboxMode),mode_epoch,idle_timeout_sandkeepalive;LeaseEventmessage,ExecEvent.lease,WorkerFrame.leaseandlease_result,ServerFrame.lease_controlandkeepalive;LeaseControl(status / reset / set_mode) andLeaseKeepalivecalls.buf breakingpasses againstmain, and the generated Go and both TypeScript outputs match the proto.Control plane:
mode,idleTimeoutSandmodeEpochon the sandbox record. A per-exec sandbox starts at epoch 0 and a lease sandbox at epoch 1; each mode change raises the epoch atomically.PUT /v1/sandboxes/{id}/mode, andPOST /v1/sandboxes/{id}/mode-token. The mode-token route issues a signed set-mode token:typmoca-sandbox-mode+jwt, valid 300 s and never past the sandbox's own expiry.SH_SANDBOX_MODES_ALLOWEDandSH_SANDBOX_IDLE_CEILING_S, and an audit record for every mode change. The audit's old mode is read inside the same atomic change.SH_SANDBOX_MODES_ALLOWEDno longer lists is downgraded toper-execat its next mint (epoch raised, audited), and a loweredSH_SANDBOX_IDLE_CEILING_Sclamps the idle claim.Relay:
Exec's mode fields from the token's claims, so a client can't raise its own mode or epoch. Requests that don't come from a sandbox token (the harness path) have all four fields cleared.LeaseControlandLeaseKeepaliveaccept only sandbox-token callers.set_modetakes its mode and epoch only from a verified set-mode token, and that token's sandbox, worker and workspace must all match the caller's.sandbox_lease_controlaudit line;Execalready applies.Worker:
busy: too many lease calls in flight;vmpool.Runnerpasses the lease fields to the pool.Exec's response, before its result or error, and acknowledged only once it is queued.lease_ended(<reason>),stale_mode: …andlease_unsupported: …. Timeout and abort errors are unchanged.Docs and a test across components:
docs/api/openapi.yaml, thesandbox-v1-direct-clientpage and thedeploy/sbxREADME;lease-wire.transport.test.tsruns the real control-plane handlers through the real relay to a fake worker.Behaviour worth knowing
at_unix_ms.mode_changeis reported in theset_moderesult.set_mode. That follows plan 2's fail-closed state file (spec §8.2); plan 4'smocactlsendsset_moderight after create.Tests
go test ./...(remote-worker)go test -raceoninternal/sessionandinternal/vmpoolmake typecheckmake lintmake check-linksmake testas a whole hits the known supervisor shutdown-grace flake under full parallelism; every package passes on its own. The KVM gates aren't touched by this PR. The live end-to-end run on SBX0 is in plan 4.Left for plan 4
mocactl sbx mode,resetandget(sendingset_modeafter create, and again when the epoch is unknown), the MCP keepalive and the notice line;SH_SANDBOX_MODES_ALLOWEDandSH_SANDBOX_IDLE_CEILING_Sthroughdeploy/sbx/setup.shand the ocp-sbx overlay (today they have to be set by hand);expiringevent should carry the lease's age and mode;sandbox_deleted;Checklist
git commit -s).make lintand the tests for the touched packages pass.docs/api/anddeploy/sbx/README.md.make check-linkspasses.Assisted-By: Claude Code