Skip to content

feat(sbx): lease mode plan 2 — worker lease lifecycle, accounting, reclaim - #763

Merged
pdettori merged 26 commits into
rossoctl:mainfrom
pdettori:feat/sbx-lease-worker
Nov 12, 2026
Merged

pdettori merged 26 commits into
rossoctl:mainfrom
pdettori:feat/sbx-lease-worker

Conversation

@pdettori

@pdettori pdettori commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

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 new Exec fields and calls the new Pool methods. Until then vmpool.Runner sends only per-Exec requests, and every per-Exec path is unchanged.

Spec: docs/specs/2026-11-08-sbx-lease-mode-design.md v0.2 (#718). Plan 1 (the guest agent) is #706.

Rebased onto main after #718 merged (2026-11-12). The 26 commits are the 14 plan commits, 9 that address the first review (0d850288..4a4f674d after the rebase), and 3 that address the second (9129a420..e77e784d). The rebase left the branch's diff byte-identical; the suites pass on the rebased tree (go test ./..., -race on vmpool, GOOS=linux go vet, build-snapshot.test.sh).

What it adds

  • Mode and epoch state, in one file per key under <WorkspaceRoot>/.lease-state/, written atomically:
    • an older epoch is refused (stale-mode);
    • a lost or unreadable file fails closed to per-Exec until SetMode (spec §8.2);
    • epoch 0 is an unversioned per-Exec request.
  • The lease Exec path, gate-first (the ordering of the E15 resident patch):
    • one VM per key, resumed only once, and never returned to the standbys;
    • admission at SH_LEASE_START_MB;
    • the workspace ownership walk after per-Exec root writes.
  • The lease cgroup: when a standby becomes a lease VM, its cgroup leaves the pool. memory.max is raised to PerVMBytes + SH_LEASE_PAGECACHE_MB, and the cgroup is removed, not returned, at lease end.
  • The lease ticker, separate from the per-Exec sweep: idle, keepalive loss, maximum duration then expiring, and the grace limit. A command cut by the grace limit returns ErrLeaseEnded.
  • End reasons and status. All eleven end reasons leave exactly one pending LeaseEvent, and there are LeaseStatus / AckLeaseEvent / EndLease (reset, sandbox_deleted).
    • A downgrade waits up to the grace limit and ends only the lease it was called for.
    • A restart reports worker_restart once.
    • A command never runs on a lease that has been cut.
  • Memory: measured charge (memory.current × SH_LEASE_HEADROOM), and reclaim of the idle-longest lease on low MemAvailable or an over-budget admission (standbys first). A busy lease is never taken.
  • Guest: each lease Exec's cgroup gets memory.max = MemTotal − max(64 MiB, MemTotal/8) and pids.max = 4096. The agent's oom_score_adj is −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.
  • Snapshot: a reporting-only balloon, PUT /balloon {"amount_mib":0,"deflate_on_oom":false,"free_page_reporting":true}, in the one golden snapshot, advertised as the manifest feature balloon-fpr-v1. Per-Exec latency with it was measured unchanged (moca-experiments e17/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 hash sha256:086c4f12c4e5c…, features lease-v1, balloon-fpr-v1.

Gates Result
-run TestGateLease (12: plan 1's 3, plus OneSandbox, Teardown, StaleEpoch, Ownership, Notice, Reclaim, Secrets, FreePageReporting, ExecCaps) 12/12 PASS, no skips (177 s)
-run TestGate (every gate, per-Exec included: NoVMReuse, LeakFreeTeardown, SnapshotHoldsNoSecrets, Clock, NoCrossRunBleed, …) all PASS. EgressThroughVsock first failed on my overlong chroot base (socket path 111 > 108 bytes); with a shorter one, 3/3 PASS
TestGateCredentialNeverInGuest PASS (owner's OK, 2026-11-12). It ran against a snapshot built with a throwaway test interception CA (EC P-256, 2 days). The authenticated request reached the upstream with the injected credential; the planted canary was found in a file, an environment and memory; the fixture credential was found nowhere in the guest
After the review fixes (tree d821842f, snapshot p2-d821842f built with that CA) guest agent root tests 39/0/0; every KVM gate 29/29 PASS, the credential gate included; again 29/29 on 5f44fc9f
After the second review's fixes (e77e784d) on the SBX0 KVM host (the AWS rig had no capacity to restart), isolated from the live worker under /srv/lg2, with production kernel and rootfs read only. Snapshot sha256: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 (Ownership with the separate normalise step, ExecCaps with the OOM hint, TimeoutKeepsTheLease, CredentialNeverInGuest). The production sbx-worker@sbx_default stayed active, with no restarts and no errors in its journal
  • Free-page reporting: 12 MiB before, a 171 MiB peak, and 35 MiB 2.3 s after the Exec (bound 100 MiB).
  • After the run: no leftover gate cgroups and no Firecracker processes.
  • Not driven by any gate: teardown_failed, which no command can trigger; it is unit-tested. memory_reclaim is 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.
  • Other checks (before the review fixes): the guest agent's 37 root tests pass on a real cgroup v2 host (E15 rig, cgo off). go test ./... (14 packages), go test -race on vmpool, GOOS=linux go vet and build-snapshot.test.sh all 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:

  • Epoch 0 is per-Exec: an Exec with epoch 0 is served per-Exec and never changes stored state.
  • A missing state file counts as "root may have written": so the first lease on such a key always runs the ownership walk.
  • A timeout keeps the lease; an abort ends it as 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 own timeout:<n> frame. An abort still ends the lease in v1.
  • Lease reclaim also funds per-Exec admissions, after standbys.
  • The tick reclaims after post-admission growth.
  • A pending notice survives the workspace being reclaimed.
  • A downgrade from lease+processes to lease keeps the lease, under level 1's 8 h maximum.
  • R18: a level change on a newer epoch is applied to a running lease.

Carried to later plans

  • Plan 3:
    • the lease_ended(<reason>) wire error and the per-result expiring warning;
    • SetMode/EndLease can block up to LeaseGraceLimit (30 min), so never call them on a dispatch slot or the relay's receive loop;
    • the wire LeaseEvent.at needs nanoseconds for AckLeaseEvent to match.
  • Plan 4:
    • fix or measure the state-file fsyncs under the pool mutex before cohort enablement (the sweep's ends per tick are capped meanwhile);
    • have the janitor remove .lease-state/<key>.json, including keys with no workspace: since review F3 a state file outlives its workspace, and SetMode on a key with no run creates one;
    • a worker that switches from a lease-v1 snapshot to a non-lease one and back never records per-Exec root writes in between.
  • Also open (minor, from the fix review):
    • the slack also extends the gate wait;
    • normalisation time is not charged to the guest's budget;
    • the root memory.max is fixed at the first lease request;
    • a /tmp holding about 7/8 of RAM OOM-kills every later allocating Exec until it is cleaned.
  • From the second review (follow-ups):
    • a client abort sooner than a very long ownership walk (the SBX client waits timeout + 90 s) still cuts it, and the next lease walks again;
    • a grace cut during the walk reports a spawn error instead of lease_ended(mode_change);
    • the OOM hint uses the root's memory.current; reading shmem from memory.stat would measure the tmpfs files exactly.
  • Plan 5: the root's pids.max will be shared with tracked processes, so size it against several uids.

Assisted-By: Claude Code

@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 12, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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-wide p.mu from routeExec, SetMode, the sweep and sweepLeasesLocked, which has no cap on leases ended per tick. Already carried to plan 4. Capping the leases ended per tick (like MaxReclaimsPerScan) would bound the worst case until then.
  • AckLeaseEvent matches Pending.At.Equal(at) at nanosecond precision (already carried to plan 3). Truncating At to ms where it is created would also cover JS Date clients.
  • effectiveModeLocked at 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 serving min(e.Mode, s.Mode) would be cheap defence-in-depth for a downgrade.
  • SetMode for a key with no run leaves a .lease-state/<key>.json that 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)},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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).

Comment thread remote-worker/internal/vmpool/lease.go Outdated
switch {
case res.TeardownFailed:
reason = LeaseEndTeardownFailed
case timedOut.Load(), runErr != nil:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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, TeardownFailed or the dead-agent marker still end it.
  • An abort (caller cancel) still ends the lease agent_dead in 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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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)...)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 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.

Comment thread remote-worker/internal/vmpool/pool.go Outdated
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 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.

@pdettori
pdettori marked this pull request as ready for review November 12, 2026 12:31
@pdettori
pdettori requested a review from cwiklik as a code owner November 12, 2026 12:31
pdettori added a commit to pdettori/moca that referenced this pull request Nov 12, 2026
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]>
pdettori added a commit to pdettori/moca that referenced this pull request Nov 12, 2026
… 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]>
pdettori added a commit to pdettori/moca that referenced this pull request Nov 12, 2026
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]>
pdettori added a commit to pdettori/moca that referenced this pull request Nov 12, 2026
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]>
pdettori added a commit to pdettori/moca that referenced this pull request Nov 12, 2026
…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]>
pdettori added a commit to pdettori/moca that referenced this pull request Nov 12, 2026
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]>
pdettori added a commit to pdettori/moca that referenced this pull request Nov 12, 2026
…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]>
@pdettori

Copy link
Copy Markdown
Member Author

Thanks for the review. The inline comments each have a reply; here are the four review-body items:

  • The fsyncs under p.mu: the sweep now ends at most MaxReclaimsPerScan leases per tick (b870392), and the rest go next tick. That bounds the worst case until plan 4 moves the writes off the lock or measures them.
  • Ack precision: every LeaseEvent.At is minted at millisecond precision (d821842), so a JS Date round-trip acks. Events written before that commit keep nanoseconds, at most one per key.
  • Equal epoch, different mode: the worker now serves min(e.Mode, s.Mode) (d821842). It also recomputes that under the gate (5f44fc9), so a same-epoch SetMode that lands while an Exec is queued is not undone.
  • SetMode on a key with no run: added to plan 4's janitor item. F3 now keeps state files across a workspace reclaim, so the janitor must also cover keys with no workspace.

Re-verified on the E15 metal rig with the review-fix commits (snapshot p2-d821842f, 256 MiB, built with a throwaway test interception CA):

  • the guest agent's root tests: 39 pass, 0 fail, 0 skip;
  • every KVM gate, 29/29: the lease and per-Exec gates, the egress gates, and TestGateCredentialNeverInGuest, which is no longer skipped;
  • re-run on 5f44fc9f: 29/29 again.

Assisted-By: Claude Code

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread remote-worker/internal/vmpool/lease.go Outdated
res, runErr := vm.Run(execCtx, Command{
Command: e.Command,
Stdin: e.Stdin,
TimeoutS: leaseGuestTimeoutS(deadline, t0),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

  • RootWrote is cleared only when the step exits 0 cleanly.
  • A failed step fails the lease start, leaves RootWrote set, 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-timeout agent_dead loop 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: 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".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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]>
@pdettori
pdettori force-pushed the feat/sbx-lease-worker branch from e187b4f to 4a4f674 Compare November 12, 2026 15:14
@pdettori pdettori changed the title feat(sbx): lease mode plan 2 — worker lease lifecycle, accounting, reclaim (stacked on #718) feat(sbx): lease mode plan 2 — worker lease lifecycle, accounting, reclaim Nov 12, 2026
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 ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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:

  1. 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, returns timeout:<n> with nothing sent to the guest, and the lease is kept. The per-Exec fallback no longer needs re-arming.
  2. G2 normalise (a8cb2f4): normaliseLease is now a start step of its own (true + NormaliseWorkspace, 10 min LeaseNormaliseTimeout). It runs under the caller's ctx, not runCtx, so the Exec timer can't cut it. RootWrote is cleared only on exit 0, together with the start save. Any failure runs fail() 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.
  3. G3 OOM hint (e77e784): oom_kill is read before the cgroup rmdir, and the root's current/max after it. The hint threshold is ≥ ¼ of max, and frameWriter.notice bypasses 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: "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".

@pdettori
pdettori merged commit 6b5098d into rossoctl:main Nov 12, 2026
19 checks passed
pdettori added a commit to pdettori/moca that referenced this pull request Nov 13, 2026
…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]>
webchang added a commit to webchang/moca that referenced this pull request Nov 16, 2026
…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]>
pdettori added a commit to pdettori/moca that referenced this pull request Nov 16, 2026
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]>
@pdettori pdettori added this to the v0.11.0 milestone Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants