Repository navigation
feat(sbx): lease mode plan 2 — worker lease lifecycle, accounting, reclaim - #763
Conversation
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Reviewed the 14 code commits (a9dfab7b..dcea0fdd, i.e. git diff 44b1968 dcea0fd). The 8 #718 docs commits were reviewed on #718.
The host-side lifecycle holds up on the risky axes. Gates are taken under p.mu only with non-blocking sends and released off the lock. Every path that ends a lease holds the gate or waits on l.gone, so a second concurrent end is a no-op, a cut's reason wins, and endLeaseLocked writes exactly one Pending. The lease VM is charged once and released once on every path. Lease cgroups are marked before memory.max is raised and retired at Reap, never pooled. The guest ownership walk uses WalkDir and Fchownat(AT_SYMLINK_NOFOLLOW), chmods only lstat'd regular files and directories, and skips other devices. checkKey blocks path traversal into .lease-state/, and the atomic write and fail-closed read are correct. The oom_score_adj reset happens as root before the capability drop, so uid 7000 can't restore -1000. With LeaseEnabled false, the per-Exec path is unchanged apart from the nit at pool.go:800.
No must-fix. The main suggestion is the guest cap gap: tmpfs charge reparents to an uncapped moca-execs, so caps that are only per-Exec don't prevent a global guest OOM across Execs.
Other non-blocking items, not inline:
saveLeaseState's two fsyncs run under the pool-widep.mufromrouteExec,SetMode, the sweep andsweepLeasesLocked, which has no cap on leases ended per tick. Already carried to plan 4. Capping the leases ended per tick (likeMaxReclaimsPerScan) would bound the worst case until then.AckLeaseEventmatchesPending.At.Equal(at)at nanosecond precision (already carried to plan 3). TruncatingAtto ms where it is created would also cover JSDateclients.effectiveModeLockedat an equal epoch serves the Exec's mode even when it differs from the stored one (lease_mode.go:157). That's only reachable through a control-plane bug, but servingmin(e.Mode, s.Mode)would be cheap defence-in-depth for a downgrade.SetModefor a key with no run leaves a.lease-state/<key>.jsonthat only a run's retire ever removes. The plan-4 janitor item should cover keys with no workspace too.
Author: pdettori (MEMBER — maintainer)
Areas reviewed: Go (vmpool, guestagent, microvm-worker), shell (build-snapshot.sh + test)
Agent/IDE config (.claude/.vscode): none
Commits: 22 (8 from #718 + 14), all signed-off: yes
CI status: all 17 checks green (incl. check, microvm-gates, proto, deploy-scripts, k8s-kind-e2e). Still a draft PR stacked on open #718.
Assisted-By: Claude Code
| return nil, fmt.Errorf("guest-agent: lease: cgroup: %w", err) | ||
| } | ||
| for _, w := range []struct{ file, val string }{ | ||
| {"memory.max", strconv.FormatInt(memMax, 10)}, |
There was a problem hiding this comment.
suggestion (strong): tmpfs charge escapes the per-Exec cap. memory.max is only set on each e<seq>, and moca-execs itself is uncapped. Pages an Exec writes into /tmp or /var (both unsized tmpfs, build-snapshot.sh:650-651) outlive it: the dead memcg's charge moves up to moca-execs, and the next e<seq+1> starts from zero. So Exec 1 can leave about 7/8 of MemTotal in /tmp, and Exec 2 gets a fresh 7/8 cap on top of that. The guest as a whole then OOMs globally instead of inside a cgroup, which is the failure lease_caps.go:10-14 says the caps prevent. Between Execs the only userspace process is PID 1 at -1000, so an allocation by the agent then finds nothing it can kill (no swap, tmpfs can't be reclaimed), and the guest panics and the lease ends. Suggest also writing memory.max = execCgroupMemoryMax(MemTotal) (and pids.max) on the cgroup root in enableExecControllers. The limit is hierarchical and includes the reparented charge, so a later Exec gets OOM-killed inside its cgroup. Alternatively, size the tmpfs mounts. Either way, a gate or unit test that fills /tmp in one Exec and allocates in the next would pin this down.
There was a problem hiding this comment.
Agreed, fixed in 0d85028. enableExecControllers now also writes memory.max = execCgroupMemoryMax(MemTotal) and pids.max = 4096 on moca-execs itself. The limit is hierarchical and counts the charge reparented from dead Exec cgroups, so a later Exec is OOM-killed inside its own cgroup rather than the guest OOMing globally.
TestLeasePrepareCapsTheCgroupRoot pins the root writes. TestGateLeaseExecCaps gained the case you describe: Exec 1 fills /tmp, Exec 2 allocates past what is left and is OOM-killed inside the cgroup tree, and Exec 3 still runs with the agent alive. That gate passes on KVM on the E15 metal rig (256 MiB guests).
| switch { | ||
| case res.TeardownFailed: | ||
| reason = LeaseEndTeardownFailed | ||
| case timedOut.Load(), runErr != nil: |
There was a problem hiding this comment.
suggestion: every timeout or abort ends the lease as agent_dead. The host timer is armed before routeExec, so it also covers the gate wait, a cold restore and Resume. Meanwhile the guest gets the full timeoutS (:466), so the host deadline always fires first: closeConn → ErrAborted, and the lease ends with agent_dead and the VM is destroyed. Example: a lease Exec with timeout_s=60 that waits 50 s behind another Exec is cut 10 s into Run, and the user sees "guest restarted (agent_dead)" and loses /tmp and their processes. Spec §3.1 has the guest kill the Exec's cgroup and send End on a timeout or abort, and §3.2 reserves agent_dead for the agent's dead latch. I see this is ruling "any Run error ends the lease as agent_dead", but for a common timeout it costs the user a lot. Suggest sending the guest the remaining budget (deadline − now, floored at 1 s), giving the host deadline a few seconds of slack in lease mode, and keeping the lease when the guest's timed-out End arrives. That could be plan 3's, but then the spec or the ruling should say so.
There was a problem hiding this comment.
Agreed: the ruling was too costly for the common case. Fixed in 8dff0f8, with the slack raised to 8 s in 5f44fc9.
- The guest gets the budget left,
max(1, ceil(deadline − now)), computed right before Run. So the gate wait, the restore and Resume are charged to it. - In lease mode the host deadline gets 8 s of slack, covering the guest's 1 s rounding plus its 5 s teardown bound. The guest's own timeout fires first: it kills the Exec's cgroup and reports a
timeout:<n>frame. - For that frame the lease is kept, and the caller gets the usual timeout error. A host-side deadline hit, a transport error,
TeardownFailedor the dead-agent marker still end it. - An abort (caller cancel) still ends the lease
agent_deadin v1. The host can't tell whether the guest's teardown finished before the next Exec's connection.
Spec §3.1/§4.1 now say both. TestGateLeaseTimeoutKeepsTheLease passes on KVM; per-Exec timeouts are unchanged.
| // and the epoch unknown until SetMode, exactly as for a deleted file, and RootWrote false, | ||
| // which unknown state already treats as true (ruling R7). With nothing pending it is | ||
| // deleted. | ||
| func retireLeaseState(root, key string, s leaseState) { |
There was a problem hiding this comment.
suggestion: an idle workspace reclaim drops the mode and epoch. retireLeaseState keeps only Pending (Known=false), or deletes the file, every time the workspace sweep removes an idle workspace (SH_WORKSPACE_IDLE, 30 min default). So a lease sandbox that sits unused over lunch quietly serves per-Exec afterwards, until something sends set_mode. The MCP path never does, and only mocactl sbx get re-sends it (§8.2). The epoch is control-plane state, not workspace data. Keeping {Mode, Epoch, Known} and resetting only RootWrote/Open can't weaken stale-mode, since epochs only go up. If dropping it is intended, please document it, and have plan 3 surface "epoch unknown" on the Exec result so clients re-send.
There was a problem hiding this comment.
Agreed, fixed in b3d29a7. A workspace removal (by the idle sweep or by Reclaim) now keeps {Mode, Epoch, Known} and resets only RootWrote (set to true, since the new tree's history is unknown) and Open. The pending event is kept as before. The file is deleted only when nothing is worth keeping. Epochs only go up, so stale-mode protection is unchanged. A test reclaims a lease key's workspace idle and checks that the same epoch still serves lease and an older one is still refused.
| // After the sweep, so that a lease due to end for its own clocks ends with that reason, | ||
| // and its charge has already left committedLocked. | ||
| over := p.committedLocked() - (p.cfg.MaxCommittedBytes - p.cfg.MemoryReserveBytes) | ||
| vs = append(vs, p.reclaimLeasesLocked(now, over)...) |
There was a problem hiding this comment.
suggestion: the tick reclaims leases before standbys. When measured lease charges have grown past the budget, reclaimLeasesLocked(now, over) ends the idle-longest lease, even if idle per-Exec runs still hold standbys. A standby costs its run one cold acquire, while a lease costs the user their processes, /tmp and a notice. evictForAdmissionLocked sheds standbys first, so the ticker breaks the ordering the admission path (and the PR body) describes. Suggest routing the over > 0 part through the same standbys-first path, and calling reclaimLeasesLocked directly only for the MemAvailable deficit.
There was a problem hiding this comment.
Agreed, fixed in b870392. On the lease tick, the over-budget part now goes through the same standbys-first path as admission (helpers factored out of evictForAdmissionLocked): idle standbys first, then idle leases, idle-longest first. Only the MemAvailable deficit reclaims leases directly. Test: over budget with an idle standby and an idle lease, the standby goes and the lease stays. The same commit also caps how many leases the sweep ends per tick at MaxReclaimsPerScan, which bounds the fsyncs under p.mu (your review-body item).
| err = e | ||
| } | ||
| } else { | ||
| *dst = time.Duration(v) * time.Second |
There was a problem hiding this comment.
nit: time.Duration(v) * time.Second overflows for v above about 9.2e9, and v << 20 at :276 overflows above 2^43. For example, SH_LEASE_GRACE_S=10000000000 wraps to a negative value, and normalizeLease's fill then silently puts back the 30 min default. That's contrary to "a malformed value is refused, never defaulted". Suggest refusing v > math.MaxInt64/int64(time.Second) (and > math.MaxInt64>>20 for MiB), or capping at a sane maximum.
There was a problem hiding this comment.
Fixed in d87a1cb. SH_LEASE_*_S values above math.MaxInt64/int64(time.Second) and *_MB values above math.MaxInt64>>20 are refused at start, never defaulted (main_test.go).
| fill(&c.LeaseMaxDuration, DefaultLeaseMaxDuration) | ||
| fill(&c.LeaseMaxDurationProcesses, DefaultLeaseMaxDurationProcesses) | ||
| fill(&c.LeaseGraceLimit, DefaultLeaseGraceLimit) | ||
| fill(&c.LeaseKeepaliveLoss, DefaultLeaseKeepaliveLoss) |
There was a problem hiding this comment.
nit: there's no cross-check between LeaseKeepaliveLoss and the 30 s MCP keepalive period (§8.3). With SH_LEASE_KEEPALIVE_LOSS_S=20, every opted-in lease ends keepalive_lost between two keepalives. Likewise LeaseScanInterval > LeaseIdleMin makes idle ends late. Consider refusing KeepaliveLoss < 2×30 s and ScanInterval > IdleMin/4.
There was a problem hiding this comment.
Fixed in d87a1cb. Normalize refuses LeaseKeepaliveLoss < 60 s (2 × the 30 s MCP keepalive period, §8.3) and LeaseScanInterval > LeaseIdleMin/4. The defaults satisfy both, and the fixtures that slowed the ticker were adjusted.
| if !busy { | ||
| if tomb, detachErr = detachWorkspace(rp.dir); detachErr == nil { | ||
| delete(p.runs, key) | ||
| retireLeaseState(p.cfg.WorkspaceRoot, key, p.leaseStateIfAnyLocked(rp)) // as the sweep does: see sweepOnce |
There was a problem hiding this comment.
nit: this retireLeaseState (and the one in sweepOnce, sweep.go:99) runs on every Reclaim and workspace sweep even when LeaseEnabled is false. That adds an os.Stat and possibly a read and os.Remove under p.mu on per-Exec-only workers, while the PR says per-Exec paths are unchanged. Guarding both with if p.cfg.LeaseEnabled (or doing the remove after the unlock, as the tombstone removal does) would keep that true.
There was a problem hiding this comment.
Fixed in 3c12cf9. Both retireLeaseState calls (in Reclaim and in the sweep) are guarded by p.cfg.LeaseEnabled, so a per-Exec-only worker does no lease-state I/O. A test plants a state file and checks a lease-disabled reclaim leaves it untouched.
memory.max sat only on each e<seq>. Pages an Exec writes to /tmp or /var (unsized tmpfs) outlive it, and once its cgroup is removed their charge reparents to moca-execs, so the next Exec started from zero on top of them and could drive the guest into a global OOM with only PID 1 left to kill. enableExecControllers now also writes the Exec memory.max and pids.max on the cgroup root. The limit is hierarchical and counts the reparented charge, so a later Exec is OOM-killed inside the cgroup tree. TestGateLeaseExecCaps gains the tmpfs case: one Exec fills ~60% of guest memory in /tmp and /var, the next allocates past what remains and ends non-zero, the root's oom count rises, and the agent is still PID 1. PR rossoctl#763 review, F1. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
… left Every lease Exec timeout ended the lease agent_dead: the host timer covers the gate wait, a cold restore and Resume, while the guest got the full timeout_s, so the host deadline always fired first and destroyed the VM. Ruling R8b. In lease mode the host deadline moves LeaseTimeoutSlack (5 s) past the budget, and the guest gets max(1, ceil(deadline - now)) computed right before Run, so its own timeout fires first: it kills the Exec's cgroup and answers with ga.TimeoutMessage. runLease recognises that answer (guestTimedOut, via a guestError that keeps the KindError message; its text is unchanged), keeps the lease and returns ErrTimeout as before. A guest that has not answered by budget + slack, a transport error, teardown_failed or an abort still ends the lease. Per-Exec timeouts are unchanged: no slack, the whole budget to the guest. The agent_dead KVM gate driver now aborts instead of timing out, and TestGateLeaseTimeoutKeepsTheLease checks the kept lease on a real guest. Spec §4.1 says a timeout keeps the lease and an abort ends it in v1. PR rossoctl#763 review, F2. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
retireLeaseState kept only a pending event, so a lease sandbox whose workspace the idle sweep or Reclaim removed (30 min by default) quietly served per-Exec afterwards, until something re-sent set_mode. The mode, epoch and Known are the control plane's, not the tree's, and epochs only go up, so keeping them cannot weaken stale-mode. Retiring now keeps them, sets root_wrote (the new tree's history is unknown, R7), clears Open and keeps a pending event (R9). The file is deleted only when nothing is worth keeping: no known epoch and nothing pending. PR rossoctl#763 review, F3. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
The lease tick called reclaimLeasesLocked for the whole overshoot once measured lease charges grew past the budget, so it ended the idle-longest lease even while idle per-Exec runs held standbys. An admission sheds standbys first; the tick now does the same. The donor ordering and the gather move out of evictForAdmissionLocked into standbyDonorsLocked and shedStandbysLocked, which both paths use; reclaimLeasesLocked gets what the standbys could not cover, and the MemAvailable deficit as before. Standbys the tick sheds count as BudgetEvictions. sweepLeasesLocked also ends at most MaxReclaimsPerScan leases per tick, bounding the state-file fsyncs it does under p.mu; the rest end at the next tick. Marking expiring and cutting at the grace limit are not capped. PR rossoctl#763 review, F4 and F8. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…imings leaseConfig converted SH_LEASE_*_S with time.Duration(v) * time.Second and SH_LEASE_*_MB with v << 20, both of which wrap: SH_LEASE_GRACE_S=10000000000 became a negative Duration that Normalize then replaced with the default, against "a malformed value is refused, never defaulted". Values above math.MaxInt64/int64(time.Second) seconds or math.MaxInt64>>20 MiB are now refused, naming the variable. Normalize also refuses two timings that cannot work: LeaseKeepaliveLoss under two of the MCP server's 30 s keepalive periods (spec §8.3), which would end every opted-in lease between keepalives, and LeaseScanInterval above LeaseIdleMin/4, which ends idle leases late. Two tests that slow the lease ticker raise the idle bounds with it, and the keepalive_lost KVM gate driver uses the 60 s minimum. PR rossoctl#763 review, F5 and F6. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Reclaim and the workspace sweep retired the key's lease state on every workspace removal, even with LeaseEnabled false: an os.Stat, and possibly a read, rewrite or remove, under p.mu on workers that never serve a lease. Both calls are now guarded by LeaseEnabled, so a per-Exec-only worker's reclaim paths do no lease-state work at all. PR rossoctl#763 review, F7. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…at an equal epoch A client acknowledges a lease event by its At, and a JS Date holds milliseconds, so an At with nanoseconds could never be acknowledged from one. Every event (start, end, the worker_restart end) is now minted at the millisecond (leaseEventAt). effectiveModeLocked served the Exec's mode at an equal epoch whatever was stored. It now serves the lower of the two (per-exec < lease < lease+processes) when they differ, as defence in depth for a downgrade: a token minted before a same-epoch SetMode cannot keep the higher mode, and the R18 re-level, which uses the served mode, cannot raise a lease back above it (ruling R19's same-epoch case). PR rossoctl#763 review, F9 and F10. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
|
Thanks for the review. The inline comments each have a reply; here are the four review-body items:
Re-verified on the E15 metal rig with the review-fix commits (snapshot
Assisted-By: Claude Code |
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Follow-up to our dcea0fd review. The 9 fix commits (0d85028..e187b4f) close all 7 items from that round, and I checked each one against the code. The moca-execs root now carries the same memory.max and pids.max, so reparented tmpfs charge OOMs inside the tree (TestGateLeaseExecCaps covers the /tmp-fill case). The guest gets the remaining budget at Run, and the host has 8 s of slack, so a guest timeout keeps the lease. Reclaim keeps mode, epoch and Known. The lease tick sheds standbys before leases and is capped per tick. Overflowing env values are refused. KeepaliveLoss and ScanInterval are cross-checked. retireLeaseState is guarded by LeaseEnabled. The equal-epoch min(e.Mode, s.Mode) rule and the recompute under the gate are safe: they can only lower the served mode, and stale epochs are still refused.
Two suggestions on the new timeout path and one nit, inline. None of them block.
Author: pdettori (MEMBER, maintainer)
Areas reviewed: Go (vmpool, guestagent, microvm-worker), spec. Incremental diff only, dcea0fd..e187b4f
Agent/IDE config (.claude/.vscode): none
Commits: 9 new, all signed off
CI status: all 17 checks green
Assisted-By: Claude Code
| // own timeout fires first and the lease survives it (LeaseTimeoutSlack). A timer | ||
| // that has already fired stays fired: the Exec is timed out either way. | ||
| if tm.Stop() { | ||
| tm = p.clk.AfterFunc(deadline.Add(LeaseTimeoutSlack).Sub(p.clk.Now()), fire) |
There was a problem hiding this comment.
suggestion: a lease Exec whose budget runs out while it is queued still runs for 1 s. The timer moves to deadline+LeaseTimeoutSlack here, before execLease waits on the gate, does the acquire and resumes. Example: timeout_s=10 queued 12 s behind another lease Exec reaches Run with the host timer still live (fires at 18 s). leaseGuestTimeoutS then floors to 1, so the command starts and runs 1 s past its budget. The per-Exec fallback a few lines below takes the opposite rule: a spent budget fires at once, and TestPerExecFallbackWithItsBudgetSpentTimesOutAtOnce pins that. Suggest one of two fixes. Either refuse with timeout:<n> (lease kept, nothing run) when !p.clk.Now().Before(deadline) once the gate is held and again just before vm.Run. Or keep the host timer at deadline until Run starts and add the slack only then. A unit test for the spent-while-queued lease case would pin it.
There was a problem hiding this comment.
Agreed, fixed in 9129a42. In lease mode the host timer now stays at the plain deadline through the gate wait, acquire, Resume and the normalise step. It gains the 8 s slack only right before vm.Run, with the gate held. If the budget is already spent at that point, nothing is sent to the guest: the Exec returns timeout:<n> and the lease is kept, the same rule as the per-Exec fallback. Tests cover your example (timeout_s=10 queued 12 s → timeout, the fake VM never gets the Run, the next Exec reuses the VM) and a 3 s remainder (guest gets 3 s; the host fires at 3 + 8 s if the guest never answers). A side effect: an abort that lands before Run now keeps the lease too, since nothing reached the guest.
| res, runErr := vm.Run(execCtx, Command{ | ||
| Command: e.Command, | ||
| Stdin: e.Stdin, | ||
| TimeoutS: leaseGuestTimeoutS(deadline, t0), |
There was a problem hiding this comment.
suggestion: the guest's budget doesn't count normalisation and first-request hardening. leaseGuestTimeoutS(deadline, t0) gives the guest everything that remains as of t0. But the guest arms its TimeoutS timer only after the fork (lease_linux.go runLease). So NormaliseWorkspace, plus the one-time leaseHarden/enableExecControllers, run on top of that budget. A normalise over a big tree that takes more than about 7 s (8 s slack minus up to 1 s of rounding) trips the host deadline, and the result is agent_dead. b3d29a7 now sets RootWrote=true on every retired workspace, so this path is more common than before. A failed Run also leaves RootWrote set (:554), so the next lease normalises again, and a short-timeout Exec can keep looping into agent_dead. Suggest arming the guest timer when the request arrives (before normalise), or having the host send an absolute deadline.
There was a problem hiding this comment.
Agreed, fixed host-side in a8cb2f4, with no protocol change. The ownership walk is now a lease-start step of its own, like the restore and Resume. When RootWrote is set, the host first sends a lease request running true with NormaliseWorkspace. It runs under its own 10 min bound (LeaseNormaliseTimeout), in a context the Exec's timeout can't cancel; an abort and the grace cut still can. The one-time hardening happens in that request.
RootWroteis cleared only when the step exits 0 cleanly.- A failed step fails the lease start, leaves
RootWroteset, and the next lease Exec retries. - The user's command never carries the flag, and the G1 rule applies after the walk: a budget spent during the walk gives
timeout:<n>without running and keeps the lease. So the short-timeoutagent_deadloop is gone.
One remaining edge: a client that aborts sooner than a very long walk (the SBX client gives up at timeout + 90 s) still cuts it, and the next lease walks again. That's noted as a follow-up.
| return err | ||
| } | ||
| for _, w := range execCgroupCapFiles(memMax) { | ||
| if err := os.WriteFile(filepath.Join(root, w.file), []byte(w.val), 0); err != nil { |
There was a problem hiding this comment.
nit: now that the root is capped, files an Exec leaves in /tmp or /var make every later Exec in the lease OOM (exit 137) until someone deletes them. The host sees only a non-zero exit. Consider reporting the root's memory.events oom delta (or memory.current) in End, or adding a stderr hint, so a user can tell "your /tmp is full" from "your command used too much memory".
There was a problem hiding this comment.
Taken, in e77e784. When a lease Exec's cgroup recorded an oom_kill and the lease's cgroup root still holds at least 25 % of its memory.max after the Exec is torn down, the agent appends one stderr line before End: guest-agent: this command was killed for memory; <N> MiB is still held in the lease (files in /tmp and /var count against its memory until deleted). The exit code and End are unchanged. TestGateLeaseExecCaps's /tmp-fill case asserts the hint. Follow-up noted: reading shmem from memory.stat would measure the tmpfs files exactly instead of the root's whole memory.current.
Lays the types and config the lease-mode worker builds on (plan 2, Task 1); nothing executes a lease Exec yet. - Mode (per-exec, lease, lease+processes), LeaseEndReason, LeaseEvent. - Exec gains Mode, ModeEpoch, IdleTimeout (clamped to [30 s, 1800 s], 0 = 300 s) and Keepalive. - Per-key state file <WorkspaceRoot>/.lease-state/<key>.json, written atomically (temp, fsync, rename, fsync dir); missing or malformed reads as an unknown epoch (spec §8.2, fail closed). - effectiveModeLocked: stale epoch refused, unknown epoch runs per-exec and stores nothing, newer epoch stored. Pool.SetMode restores a mode. - RefuseStaleMode, RefuseLeaseUnsupported. New sets LeaseEnabled only for Firecracker with the lease-v1 manifest feature; a lease Exec otherwise is refused before any acquire. - Config lease fields and defaults; LeaseReclaimFreeBytes derived from PerVMBytes. microvm-worker reads SH_LEASE_*, refusing malformed values, loads the manifest before New, and prints the lease fields in its banner. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…d fresh footprint A lease VM starts as a pooled standby, so at promotion its cgroup leaves the cgroup pool (spec §6, "Not from the cgroup pool"): LeaseCgroup raises memory.max to the lease bound and marks the cgroup so Reap retires it (rmdir after release's cgroup.procs guard, failures counted in leaks()) instead of returning it to the free list. LeaseBytes reads memory.current fresh on every call; StandbyBytes' cache is unchanged. Firecracker only; nothing calls these yet (Task 3). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ed admission) A lease Exec keeps its VM: later Execs of the same workspace_key run in it, one at a time, until the lease ends, and the VM is then destroyed, never returned to the standbys (spec §3, §4, §6, §8.4). - execLease pins the run and takes its execGate before it acquires (the E15 resident ordering). Without a live lease it acquires at LeaseStartBytes, raises the cgroup to PerVMBytes + LeasePageCacheBytes, resumes once and installs the lease; every Run carries Lease, and NormaliseWorkspace while root_wrote is set. TeardownFailed ends the lease teardown_failed; a Run error or a timeout ends it agent_dead; a closed pool detaches it and keeps the open record for the next process. The footprint is sampled into vmLease.charge before the gate is released. - A lease VM is the third accounting class: not in inFlight, charged LeaseStartBytes by leaseCommittedLocked (ruling R2). acquire, run creation, promotion and eviction take a price. - A per-Exec Exec ends a live lease (mode_change) under the gate before it acquires, with a backstop under its own gate before Resume, and records root_wrote on a key with known state. An epoch-0 Exec skips the state lookup and creates no state file (R6); SetMode on an unknown history sets root_wrote so the first lease normalises (R7). - No standbys beside a lease: leftovers go at lease start and replenishment stands down while a lease is alive. A leased or pinned run is busy(). - The fake launcher accepts repeat Runs only for Command.Lease. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
routeExec creates a new key's run before acquire, so acquire's runLocked found it existing and counted the first cold acquire as exhausted: every lease start on a new key, and every per-Exec Exec with a ModeEpoch on a new key. The run is now marked unacquired at creation and acquire treats that as fresh, clearing it on the first acquire. Epoch-0 per-Exec Execs never reach routeExec's creation and are unchanged. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
A lease-enabled pool arms a second ticker (LeaseScanInterval, 5 s) apart
from the per-Exec reclaim ticker, whose timing is unchanged. Each tick
marks leases past their maximum duration expiring (8 h; 4 h for
lease+processes) and ends a due lease only after a non-blocking send on
its run's gate: idle (from the last Exec end; a keepalive never resets
it), keepalive_lost (only once opted in), max_duration at the next idle
of an expiring lease, grace_limit. The run stays pinned and the gate
held until the VM is destroyed on the reclaim goroutine, so an Exec
arriving mid-destroy waits and starts a fresh lease.
grace_limit is the one end under a held gate: the sweep cancels the
running Exec, whose unwind ends the lease and returns
*LeaseEndedError{grace_limit} (errors.Is ErrLeaseEnded), not ErrAborted.
An Exec arriving past the grace deadline before a tick ends the lease
and runs in a fresh VM.
Later lease Execs apply their IdleTimeout (clamped) and Exec.Keepalive
turns the keepalive rule on for good; Pool.Keepalive records one.
Close destroys every lease VM whose gate is free and records no end, so
each state file keeps its open lease for worker_restart (Task 5). A
workspace reclaimed by the sweep or by Reclaim takes its
.lease-state/<key>.json with it.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
- LeaseStatus, AckLeaseEvent and EndLease (reset, sandbox_deleted) on Pool; EndLease and a SetMode downgrade to per-exec wait for the in-flight Exec, cutting it at LeaseGraceLimit with lease_ended(<reason>). - SetMode completes the downgrade: per-exec ends the lease (mode_change); lease+processes -> lease keeps it at level 1. A lease Exec queued on the gate behind a downgrade is refused stale-mode. - New reports every lease the previous process left open as a pending worker_restart end, once, before the pool serves. - A lease start is pending only when no end is pending. - A pending event survives workspace removal (ruling R9): the state file keeps only the event (epoch unknown) and is deleted once acknowledged. - Stats: LeaseVMs, LeaseExecuting, LeaseCommittedBytes, LeaseEnds by reason; /stats carries them omitempty. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…race limit After the grace cut, endLeaseWaiting re-queued on the gate at the back, so a lease Exec queued behind the cut Exec could start a fresh lease that the waiter then ended too (two reset ends), and EndLease returned only after that Exec. It now targets the lease live at the call: once cut, it waits for that lease's new gone channel rather than the gate, and under the gate it ends only that lease. The cut is sticky on a lease no Exec is running in: the next gate holder (execLease, runLease or the sweep) ends it with the cut's reason. Docs: Pool.SetMode and EndLease state that they block up to LeaseGraceLimit plus the cut Exec's unwind. Test for ruling R11: a lease+processes -> lease downgrade runs at mode lease (Open.Mode too) and expires at 8 h, not 4 h. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ds it Ruling R12. runLease called Run with an already-cancelled context when it found a pending cut, and on a real VM the request write races the close, so the command could reach the old guest a reset is meant to retire. A lease Exec that finds a cut before Run now ends the lease with the cut's reason and returns lease_ended(<reason>) without calling Run, both in execLease's check and in runLease's (a cut landed after it, or during startLease). It starts no fresh lease. endLeaseLocked ends a cut lease with the cut's reason whichever gate holder ends it, so a per-Exec Exec's mode_change no longer overwrites EndLease's reset. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
A lease VM is now charged LeaseStartBytes until its first sample, then its measured memory.current x LeaseHeadroom (floored at VMOverheadBytes), idle or busy, never re-priced to PerVMBytes. The lease ticker re-samples idle leases, so an idle lease's charge follows free-page reporting down. Idle leases are reclaimed for memory (memory_reclaim), idle-longest first, taken only on a non-blocking send on the run's gate: on the lease tick when MemAvailable is below LeaseReclaimFreeBytes or measured charges pass the budget, and in admission after standbys (spec §6 order: standbys, then idle leases, then refuse memory-budget). Per-Exec arithmetic is unchanged with no lease. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…_score_adj -1000 In a lease VM the agent is PID 1 and serves many Execs, so a guest OOM or a fork bomb in one Exec must cost that Exec, not panic the guest and take the lease with it (plan 1 review, rossoctl#706). - The first lease request enables +pids +memory in the cgroup root's parent and in the cgroup root. A failure refuses the request and leaves the latch unset, so lease service is refused rather than served uncapped; the next lease request retries. - Each e<seq> gets memory.max = MemTotal - max(64 MiB, MemTotal/8) (MemTotal from /proc/meminfo, read per Exec) and pids.max = 4096 before anything runs in it. An Exec whose caps cannot be written is refused. - The first lease request writes -1000 to the agent's oom_score_adj; a failure is logged, not fatal. The shim puts each Exec's back to 0 while still root, or every Exec process would inherit -1000 and an OOM would find nothing it may kill. The arithmetic and meminfo parsing are platform-neutral (lease_caps.go) and tested everywhere; the cgroupfs writes are Linux-only. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…-fpr-v1)
Firecracker builds now configure a virtio-balloon in free-page reporting
mode only (PUT /balloon {"amount_mib":0,"deflate_on_oom":false,
"free_page_reporting":true}) after /machine-config and before
InstanceStart, so one golden snapshot carries it for every mode and a
restored VM keeps reporting freed pages (spec §6, §16 item 5). The
manifest advertises balloon-fpr-v1 on the Firecracker arm only; the
Cloud Hypervisor arm is unchanged.
vmpool gains FeatureBalloonFPRV1. microvm-worker logs a start-up warning
when the snapshot has lease-v1 without balloon-fpr-v1: lease mode still
works, but measured lease charge then follows peaks.
The build-snapshot test runs the Firecracker build's own api_put/api_patch
statements against recording stubs and asserts the exact /balloon body sits
between /machine-config and InstanceStart.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…p, notice, reclaim, secrets, reporting, caps) Spec §9's worker gates, against the pool's lease path over the real Firecracker launcher: VMs in pooled cgroups under a gate-private parent (SH_LEASE_GATE_CGROUP_BASE, default the cgroup root), ManifestFeatures and guest RAM from the snapshot manifest as the worker sets them. Each gate skips as NOT RUN without SH_KVM=1 or without a lease-v1 snapshot; the free-page-reporting gate also needs balloon-fpr-v1. requireLeaseSnapshot is split out of leaseGateVM for them, and the inventory classifies all nine as manual-only. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…aseLocked Final-review cleanup, no behaviour change: - protectAgentFromOOM: -1000 is defence in depth (the kernel never OOM-kills global init); its real effect is inheritance, which the shim's per-Exec reset reverses and must keep reversing. - Reap: cgrouprmdir_us is a real rmdir for a retired lease cgroup. - endLeaseWaiting: after the cut it still competes for the gate, which is what guarantees a cut lease is ended. - MaxReclaimsPerScan / reclaimLeasesLocked: the cap is per call, not per sweep; a lease tick's due ends are uncapped. - runLease: a cut between the unlock and vm.Run is the in-flight case. - budget.go: delete admitLeaseLocked (no caller). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
An upgrade lease -> lease+processes, or a downgrade lease+processes -> lease whose SetMode never arrived, reached a live lease only through the Exec's newer epoch and was never applied: the lease kept its old level and maximum duration. Spec §8.2: an upgrade takes effect from the next Exec carrying the new epoch, and a lost downgrade lands at the next Exec. execLease's reuse branch now moves the lease to the Exec's level under the run's gate, before the grace check and before Run, and records it in the open lease on disk. The maximum duration follows the new level, counted from the lease's original start (R11): an upgrade past level 2's 4 h makes the lease expiring at once. SetMode's existing L2 -> L1 path shares the helper. A change to per-exec still ends the lease. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
memory.max sat only on each e<seq>. Pages an Exec writes to /tmp or /var (unsized tmpfs) outlive it, and once its cgroup is removed their charge reparents to moca-execs, so the next Exec started from zero on top of them and could drive the guest into a global OOM with only PID 1 left to kill. enableExecControllers now also writes the Exec memory.max and pids.max on the cgroup root. The limit is hierarchical and counts the reparented charge, so a later Exec is OOM-killed inside the cgroup tree. TestGateLeaseExecCaps gains the tmpfs case: one Exec fills ~60% of guest memory in /tmp and /var, the next allocates past what remains and ends non-zero, the root's oom count rises, and the agent is still PID 1. PR rossoctl#763 review, F1. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
… left Every lease Exec timeout ended the lease agent_dead: the host timer covers the gate wait, a cold restore and Resume, while the guest got the full timeout_s, so the host deadline always fired first and destroyed the VM. Ruling R8b. In lease mode the host deadline moves LeaseTimeoutSlack (5 s) past the budget, and the guest gets max(1, ceil(deadline - now)) computed right before Run, so its own timeout fires first: it kills the Exec's cgroup and answers with ga.TimeoutMessage. runLease recognises that answer (guestTimedOut, via a guestError that keeps the KindError message; its text is unchanged), keeps the lease and returns ErrTimeout as before. A guest that has not answered by budget + slack, a transport error, teardown_failed or an abort still ends the lease. Per-Exec timeouts are unchanged: no slack, the whole budget to the guest. The agent_dead KVM gate driver now aborts instead of timing out, and TestGateLeaseTimeoutKeepsTheLease checks the kept lease on a real guest. Spec §4.1 says a timeout keeps the lease and an abort ends it in v1. PR rossoctl#763 review, F2. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
retireLeaseState kept only a pending event, so a lease sandbox whose workspace the idle sweep or Reclaim removed (30 min by default) quietly served per-Exec afterwards, until something re-sent set_mode. The mode, epoch and Known are the control plane's, not the tree's, and epochs only go up, so keeping them cannot weaken stale-mode. Retiring now keeps them, sets root_wrote (the new tree's history is unknown, R7), clears Open and keeps a pending event (R9). The file is deleted only when nothing is worth keeping: no known epoch and nothing pending. PR rossoctl#763 review, F3. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
The lease tick called reclaimLeasesLocked for the whole overshoot once measured lease charges grew past the budget, so it ended the idle-longest lease even while idle per-Exec runs held standbys. An admission sheds standbys first; the tick now does the same. The donor ordering and the gather move out of evictForAdmissionLocked into standbyDonorsLocked and shedStandbysLocked, which both paths use; reclaimLeasesLocked gets what the standbys could not cover, and the MemAvailable deficit as before. Standbys the tick sheds count as BudgetEvictions. sweepLeasesLocked also ends at most MaxReclaimsPerScan leases per tick, bounding the state-file fsyncs it does under p.mu; the rest end at the next tick. Marking expiring and cutting at the grace limit are not capped. PR rossoctl#763 review, F4 and F8. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…imings leaseConfig converted SH_LEASE_*_S with time.Duration(v) * time.Second and SH_LEASE_*_MB with v << 20, both of which wrap: SH_LEASE_GRACE_S=10000000000 became a negative Duration that Normalize then replaced with the default, against "a malformed value is refused, never defaulted". Values above math.MaxInt64/int64(time.Second) seconds or math.MaxInt64>>20 MiB are now refused, naming the variable. Normalize also refuses two timings that cannot work: LeaseKeepaliveLoss under two of the MCP server's 30 s keepalive periods (spec §8.3), which would end every opted-in lease between keepalives, and LeaseScanInterval above LeaseIdleMin/4, which ends idle leases late. Two tests that slow the lease ticker raise the idle bounds with it, and the keepalive_lost KVM gate driver uses the 60 s minimum. PR rossoctl#763 review, F5 and F6. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Reclaim and the workspace sweep retired the key's lease state on every workspace removal, even with LeaseEnabled false: an os.Stat, and possibly a read, rewrite or remove, under p.mu on workers that never serve a lease. Both calls are now guarded by LeaseEnabled, so a per-Exec-only worker's reclaim paths do no lease-state work at all. PR rossoctl#763 review, F7. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…at an equal epoch A client acknowledges a lease event by its At, and a JS Date holds milliseconds, so an At with nanoseconds could never be acknowledged from one. Every event (start, end, the worker_restart end) is now minted at the millisecond (leaseEventAt). effectiveModeLocked served the Exec's mode at an equal epoch whatever was stored. It now serves the lower of the two (per-exec < lease < lease+processes) when they differ, as defence in depth for a downgrade: a token minted before a same-epoch SetMode cannot keep the higher mode, and the R18 re-level, which uses the served mode, cannot raise a lease back above it (ruling R19's same-epoch case). PR rossoctl#763 review, F9 and F10. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Review M1: execLease's gate check compared epochs only, so a same-epoch SetMode that landed while a lease Exec queued was undone: a queued lease+processes Exec re-levelled a just-downgraded lease back to level 2, and after a same-epoch downgrade to per-exec the queued Exec still ran in, or started, a lease. Under the gate the served mode is now recomputed as min(Exec mode, stored mode) at an equal epoch and drives the re-level and the lease start. When it is per-exec, the lease ends mode_change under the gate and execLease returns errServePerExec, and ExecPhased runs the Exec per-Exec on the per-Exec budget, without the slack. Ruling R21: LeaseTimeoutSlack is 8 s. The guest's timeout is rounded up by up to 1 s, and its teardown may take up to its 5 s bound before it answers. Review M4: spec §3.1 says a timeout is reported as a timeout:<n> error frame, and the host keeps the lease only for that frame. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
The per-Exec fallback after a same-epoch downgrade re-arms the Exec's timer at the per-Exec budget (pool.go), but no test failed with that re-arm removed. Two tests now cover it: a fallback whose budget was spent at the gate times out at once without running per-Exec, and one with 6 s of a 10 s budget left is killed at 10 s, not at budget + slack. Both fail with the re-arm deleted. The SetMode and relevelLeaseForExecLocked docs still described a queued lease Exec as refused stale-mode after a downgrade, and per-exec as never reaching the re-level. They now describe the served mode recomputed under the gate. Review of 5f44fc9, m1 and m2. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
e187b4f to
4a4f674
Compare
In lease mode the host's timer moved to the budget plus LeaseTimeoutSlack before the Exec waited on the gate, so an Exec whose budget ran out while it queued reached Run with the timer live, got the 1 s floor and ran 1 s past its budget. The timer now stays at the budget's end through the gate wait, the acquire and Resume. runLease checks the budget under the gate just before Run: a spent budget, or a timer that already fired, fails the Exec with the usual timeout:<n> and an abort fails it ErrAborted, with nothing sent to the guest and the lease kept. Only then does extend move the timer LeaseTimeoutSlack past the budget. The per-Exec fallback no longer has to move the timer back, since it was never extended. PR rossoctl#763 second review, G1. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
The ownership walk rode on the lease's first Exec, so the guest ran it, and the first request's one-time hardening, on top of the budget the host gave that Exec. A walk over a big tree tripped the host deadline (agent_dead), and since a failed Run left root_wrote set, a short-timeout Exec could keep looping into it. A lease start whose root_wrote is set now sends the guest `true` with NormaliseWorkspace first (normaliseLease), with LeaseNormaliseTimeout (10 min) of its own, under the caller's ctx but not the Exec's timer. A cut cancels it as it would a running Exec. root_wrote clears, in the start's save, only when the step exits 0; anything else fails the lease start like a failed Resume (VM destroyed, no lease recorded, RefuseSpawn "lease normalise: ...", or ErrAborted on an abort), and the next lease Exec retries it. The Exec's own Command never carries the flag, and a budget spent during the walk fails the Exec with its timeout without running (G1), lease kept. Phases gains Normalise. TestGateLeaseOwnership now expects the step's Run before the Exec's. PR rossoctl#763 second review, G2. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…emory With the cgroup root capped, files an Exec leaves in /tmp or /var stay charged to the root, and every later Exec of the lease is OOM-killed (exit 137) until they are deleted. The host sees only the exit code. After a lease Exec's cgroup is torn down, the agent reads its memory.events oom_kill count (before removal) and, after removal, the root's memory.current and memory.max. When the Exec was OOM-killed and the root still holds a quarter or more of its limit, it writes one line to the Exec's stderr before End: "guest-agent: this command was killed for memory; <N> MiB is still held in the lease (files in /tmp and /var count against its memory until deleted)". The line is a stderr frame of the agent's own (frameWriter.notice), outside the stream cap. No protocol change. The decision and text are platform-neutral (lease_caps.go); the cgroupfs reads are in lease_linux.go with a fake-tree test. TestGateLeaseExecCaps' tmpfs case now expects the line on the OOM-killed Exec's stderr. PR rossoctl#763 second review, G3. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Follow-up to our e187b4f review. This covers only the 3 new commits 4a4f674..e77e784 (14 files, +848/−63). All 3 open items are closed, and I checked each against the code:
- G1 timer slack (9129a42): ExecPhased keeps the host timer at the budget until
extend(), which runLease calls under the gate right before Run. A spent budget, or a timer that already fired, returnstimeout:<n>with nothing sent to the guest, and the lease is kept. The per-Exec fallback no longer needs re-arming. - G2 normalise (a8cb2f4):
normaliseLeaseis now a start step of its own (true+ NormaliseWorkspace, 10 minLeaseNormaliseTimeout). It runs under the caller's ctx, not runCtx, so the Exec timer can't cut it.RootWroteis cleared only on exit 0, together with the start save. Any failure runsfail()and keeps the flag. The user's Run never carries the flag. Guest hardening still happens on the first lease request, which is now the step. - G3 OOM hint (e77e784):
oom_killis read before the cgroup rmdir, and the root's current/max after it. The hint threshold is ≥ ¼ of max, andframeWriter.noticebypasses the stream cap and is dropped once sealed. A test asserts the /tmp-fill case.
Two small items below, neither blocking.
Author: pdettori (MEMBER, maintainer)
Areas reviewed: Go (vmpool, guestagent), Docs (spec §3.3/§4/§3.1)
Agent/IDE config (.claude/.vscode): none
Commits: 3 new (26 total), all signed off
CI status: DCO/Trivy/shellcheck/hadolint/dependency-review green. check, lint, proto, microvm-gates, k8s-kind-e2e, deploy-scripts and codeql were still pending at draft time, so check them before submitting.
Assisted-By: Claude Code
| default: | ||
| return nil | ||
| } | ||
| if ctx.Err() != nil { |
There was a problem hiding this comment.
suggestion: A grace-bound cut that lands during the normalise step (endLeaseWaiting with starting: it sets l.cut and calls l.cancel, which normaliseLease installed) isn't an abort, so ctx.Err() is nil. The Exec then fails with RefuseSpawn "lease normalise: … context canceled", not lease_ended(<reason>) the way runLease reports a cut. Check l.cut here (under p.mu) and return &LeaseEndedError{Reason: cut}, so a reset during a long walk reads like a reset and not like a spawn failure.
| Like every SBX record, it has no command text. | ||
|
|
||
| A lease Exec's timeout keeps the lease: the guest kills the Exec's cgroup and reports the timeout, | ||
| and the next Exec runs in the same guest. In v1 an abort (the caller cancels the Exec) ends the lease |
There was a problem hiding this comment.
nit: "In v1 an abort … ends the lease with agent_dead" no longer holds for an abort before Run: since 9129a42 that keeps the lease, because nothing reached the guest. Your new sentence two lines down covers a spent budget but not an abort. Worth saying "an abort during Run".
…o recreate, lease-off boot marker - janitor.sh: after reclaim frees <root>/<wsk>, remove <root>/.lease-state/<wsk>.json; also the state file of a sandbox terminated past the wait whose workspace is already gone (the worker's idle reclaim keeps it, PR rossoctl#763 F3). Only a regular file in a real .lease-state directory; a symlinked directory or file is refused as an error. - retireLeaseState writes a kept state back only while its file exists: a file the janitor removed is not recreated (the timing argument is in the comment). - New writes .lease-state/.boot = lease=on|lease=off. A lease-on boot after lease=off, or with no marker, sets root_wrote on every known state before serving: a lease-off worker records no per-Exec root writes. Failure fails New. - saveLeaseState's temp/fsync/rename/dir-fsync is factored into writeDurably, shared with the marker. BenchmarkSaveLeaseState measures one save. - TestGateReclamationCannotDeleteALiveWorkspace ignores .lease-state (the boot marker's dir). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[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 2 of 5: the worker. This PR adds the lease lifecycle to
remote-worker/internal/vmpool, plus the guest and snapshot changes it needs. It does not touch the wire: plan 3 fills the newExecfields and calls the newPoolmethods. Until thenvmpool.Runnersends only per-Execrequests, and every per-Execpath is unchanged.Spec:
docs/specs/2026-11-08-sbx-lease-mode-design.mdv0.2 (#718). Plan 1 (the guest agent) is #706.What it adds
<WorkspaceRoot>/.lease-state/, written atomically:stale-mode);ExecuntilSetMode(spec §8.2);Execrequest.SH_LEASE_START_MB;Execroot writes.memory.maxis raised toPerVMBytes + SH_LEASE_PAGECACHE_MB, and the cgroup is removed, not returned, at lease end.Execsweep: idle, keepalive loss, maximum duration then expiring, and the grace limit. A command cut by the grace limit returnsErrLeaseEnded.LeaseEvent, and there areLeaseStatus/AckLeaseEvent/EndLease(reset, sandbox_deleted).worker_restartonce.memory.current × SH_LEASE_HEADROOM), and reclaim of the idle-longest lease on lowMemAvailableor an over-budget admission (standbys first). A busy lease is never taken.memory.max= MemTotal − max(64 MiB, MemTotal/8) andpids.max= 4096. The agent'soom_score_adjis −1000, and the shim resets each Exec's to 0. This was deferred from feat(sbx): lease mode plan 1 — guest agent and image (level 1) #706's review.PUT /balloon {"amount_mib":0,"deflate_on_oom":false,"free_page_reporting":true}, in the one golden snapshot, advertised as the manifest featureballoon-fpr-v1. Per-Execlatency with it was measured unchanged (moca-experimentse17/results/followups/).Gate run
The test snapshot was built from this branch on the E15 metal rig (m7i.metal-24xl, Firecracker v1.17.0, guest kernel 6.18.44, 256 MiB guests to match SBX0):
p2-aeeb8c24, manifest hashsha256:086c4f12c4e5c…, featureslease-v1,balloon-fpr-v1.-run TestGateLease(12: plan 1's 3, plusOneSandbox,Teardown,StaleEpoch,Ownership,Notice,Reclaim,Secrets,FreePageReporting,ExecCaps)-run TestGate(every gate, per-Execincluded:NoVMReuse,LeakFreeTeardown,SnapshotHoldsNoSecrets,Clock,NoCrossRunBleed, …)EgressThroughVsockfirst failed on my overlong chroot base (socket path 111 > 108 bytes); with a shorter one, 3/3 PASSTestGateCredentialNeverInGuestd821842f, snapshotp2-d821842fbuilt with that CA)5f44fc9fe77e784d)/srv/lg2, with production kernel and rootfs read only. Snapshotsha256:37ebcaa7bef94…(SBX0's guest kernel 6.18.51, 256 MiB, test CA): guest agent root tests 41/0/0; every KVM gate 29/29 PASS (Ownershipwith the separate normalise step,ExecCapswith the OOM hint,TimeoutKeepsTheLease,CredentialNeverInGuest). The productionsbx-worker@sbx_defaultstayed active, with no restarts and no errors in its journalteardown_failed, which no command can trigger; it is unit-tested.memory_reclaimis checked only in the Reclaim gate: its pending reason, exactly one end, and the VM's artifacts gone. Its state file and ack are not checked there.go test ./...(14 packages),go test -raceonvmpool,GOOS=linux go vetandbuild-snapshot.test.shall pass.Review
Each task got its own review; three tasks needed fix rounds (Tasks 3 and 5, and the final wave). A final whole-branch review found no Critical or Important issues, and its recommended cleanup and one behaviour fix (R18, below) are in the last two commits. Rulings made while executing the plan:
Exec: an Exec with epoch 0 is served per-Execand never changes stored state.agent_dead. This was revised in review. The guest gets the budget left and the host 8 s of slack, and the lease is kept only for the guest's owntimeout:<n>frame. An abort still ends the lease in v1.Execadmissions, after standbys.lease+processestoleasekeeps the lease, under level 1's 8 h maximum.Carried to later plans
lease_ended(<reason>)wire error and the per-result expiring warning;SetMode/EndLeasecan block up toLeaseGraceLimit(30 min), so never call them on a dispatch slot or the relay's receive loop;LeaseEvent.atneeds nanoseconds forAckLeaseEventto match..lease-state/<key>.json, including keys with no workspace: since review F3 a state file outlives its workspace, andSetModeon a key with no run creates one;memory.maxis fixed at the first lease request;/tmpholding about 7/8 of RAM OOM-kills every later allocating Exec until it is cleaned.lease_ended(mode_change);memory.current; readingshmemfrommemory.statwould measure the tmpfs files exactly.pids.maxwill be shared with tracked processes, so size it against several uids.Assisted-By: Claude Code