Skip to content

feat(control-plane,sbx,mocactl): activation leases, placement and the hosts' wanted state - #775

Merged
webchang merged 49 commits into
rossoctl:mainfrom
webchang:pr/i19-activation
Nov 14, 2026
Merged

webchang merged 49 commits into
rossoctl:mainfrom
webchang:pr/i19-activation

Conversation

@webchang

@webchang webchang commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Closes #742. On main (53b9e55): #772 (the template host agent), which this branch stacked on, is merged. Its own change is 3 commits (review range 64b0c900..fcc90f26), plus merges of main.

Limit to read first: the activation lock is in-process, so run one control-plane replica. A second replica would overshoot the quota and placement checks.

What it does: a template's build is activated on a lease, the control plane places it on a host, and the host agent starts and stops workers to match. Three signed-off commits:

  1. The control plane:
    • activation leases: activate and deactivate, from 60 to 86,400 s. The activate record is written first, and the lease holds its digest. all is admin-only;
    • placement: first leased, first placed, within each host's activeLimit, never evicting a leased build. A refusal is template_unavailable, no_active_slot with Retry-After, or 429 quota_exceeded {quota: active};
    • first use of an inactive template answers 409 template_not_active with Retry-After 30;
    • the host routes GET /wanted (it never stops a worker with a live sandbox) and workers/report, both host-authenticated;
    • readiness gains activating, deactivating and unavailable, and the hosts block in GET /v1/templates is filled;
    • openapi 1.11.0, with a CHANGELOG entry.
  2. The host agent: the wanted-state step, and --wanted-only on a 15 s timer (a new unit and timer), sharing one flock lock with the build poll.
  3. mocactl: sbx templates activate [--build] [--lease] [--wait [--timeout]] (exit 5 on a timeout) and deactivate. create and up wait out template_not_active, for up to 10 min.

Other limits:

Tests on the tip:

  • typecheck passes;
  • the control-plane suite passes, including the new test/activation.test.ts, whose 3 race tests fail without the lock;
  • mocactl passes, run serially (--no-file-parallelism);
  • host-agent, setup, overlay and install-host tests pass on bash 5 and 3.2, and shellcheck is clean;
  • prettier passes.

32 files, +2,391 / -120, counted over the review range.

Assisted-By: Claude Code

The host agent stands on both parents: the template store and self-serve create (rossoctl#766, with rossoctl#760 and
rossoctl#756) and the template build tooling (rossoctl#740's branch, with rossoctl#757). No conflicts.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…ds register by policy

A KVM host's agent builds the templates clients queue (template
lifecycle spec §6.1, §8.2). This adds its side in the control plane.

- Host identity: SH_TEMPLATE_HOSTS (a JSON list of {id}) and one bearer
  per host, SH_HOST_TOKEN_<ID> (64 hex, from the environment or a
  systemd credential, distinct from the exchange, janitor and every
  egress token; host-config.ts). A new route auth kind, `host`: every
  configured host is compared, and the host in the path must be the one
  whose token was presented. With no hosts, every host route is 401.
- Routes under /v1/hosts/{host}/, on both route profiles:
  inventory (what the host holds by manifest hash, and its limits);
  builds/claim (up to 4 queued builds, oldest first, subjects in turn,
  each moved to `building` and held by the host); blobs/{digest} (a
  gate record's exact bytes); builds/{build}/log (bounded entries, a
  build keeps its last 1000); builds/{build}/report (building, probing,
  failed with its step, or built with the template record and the
  manifest as files).
- A claimed build's job is the spec as the policy checked it: the
  template's id and the create's image always win over the spec's own,
  and the guest size is always named guest_ram_mb, the value the policy
  checked (template-build.sh reads only guest_ram_mb).
- On `built` the control plane stores both files byte for byte, writes
  a `build` record, checks them against the create's request (image,
  the rootfs's image digest, manifest hash and hash version 2, size,
  gate record, X12) and registers the build or rejects it naming the
  rule, with a `check` record either way. A registered build's id
  becomes its manifest hash; a template's first takes `default`. A
  report answers only a build this host claimed, and a failed or
  cancelled build takes no more.

The catalog's builds gain the claim, the queue time and the log. The
OpenAPI document adds the routes and the hostToken scheme (1.6.0), with
the changelog, the configuration row and spec §6.1.

Refs rossoctl#741

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
… and bundles

With SBX_TEMPLATE_STORE=1, SBX_TEMPLATE_HOSTS lists the KVM hosts
(space-separated ids, ^[a-z0-9][a-z0-9-]{0,30}$) whose sbx-host-agent
may build templates (template lifecycle spec §6.1).

- Each host gets a bearer, SH_HOST_TOKEN_<ID> (64 hex), in the Secret
  sbx-template-hosts: generated once and kept; a host no longer listed
  has its token removed by a null patch. With the store on and no host,
  the Secret is applied empty, since the credentials volume names it.
- SH_TEMPLATE_HOSTS (the JSON list of ids) goes into sbx-settings, and
  the Secret's data into the settings hash, so a new or revoked token
  rolls the control plane.
- One bundle per host under .generated/host-agent/<id>/: host-agent.env
  (the API URL and the host id, no secret), host-agent.token (the bearer
  alone) and api-ca.crt with SBX_API_CA_FILE; 0700/0600. A dropped
  host's bundle is deleted.
- The template-store component reads SH_TEMPLATE_HOSTS from
  sbx-settings and projects sbx-template-hosts into /run/credentials
  beside moca-mu1, restating sbx-egress as optional (a strategic merge
  replaces the source list).

SBX_TEMPLATE_HOSTS without the store, a bad id and a repeated id are
refused before anything is applied. setup.test.sh and overlay.test.sh
cover the bundles, the tokens, a re-run, a dropped host, egress
together, and the refusals.

Refs rossoctl#741

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…ost.sh installs from a record

deploy/sbx/host-agent.sh --once, run by sbx-host-agent.service and its
timer (every 2 minutes), is one poll of a KVM host's template agent
(template lifecycle spec §6.1): it reports the inventory (the snapshots
held, by manifest hash, from template-build.sh's records, and the
host's limits), claims queued builds, fetches a cited gate record and
checks its bytes against its sha256, runs template-build.sh, posts the
log's tail and reports building, then built with the template record and
the manifest, or failed with its step.

- No build is claimed below SBX_DISK_FLOOR_GB of free disk (default 60),
  more than SBX_BUILD_CONCURRENCY a poll (default 1, at most 4), or,
  with SBX_REGISTRY set, before REGISTRY_AUTH_FILE holds a login for it.
- Nothing that names where an image lives leaves the host: a failed
  build's reason and its log are redacted (SBX_REGISTRY exactly, then
  URLs, registry hosts, IP addresses and 12-digit account ids), the full
  log stays in $SBX_SRV/agent-logs (0700), and a template record or
  manifest that names SBX_REGISTRY is not sent (the build fails
  leak_refused). A reason leads with a code a client can branch on:
  pull_failed, probe_failed, disk_floor, spec_refused, build_failed or
  leak_refused, and the step follows from it.
- The token stays in a 0600 file and a 0600 header file, never in argv
  or the log; a bad setting is refused (exit 2) before any call.

The agent installs no worker. install-host.sh now installs a worker
from template-build.sh's record when there is one: the worker env names
it (SH_TEMPLATE_RECORD) and its id as SANDBOX_TEMPLATE, so the worker
checks the record against its snapshot and its id at every start. The
worker unit runs SBX0's own binary, SBX_WORKER_BIN (default
/usr/local/libexec/sbx/microvm-worker), never the /usr/local/bin one a
P4 worker on the same host may run; a missing one is refused before
systemd.

Known limit, in the RUNBOOK's new host agent section: a new template's
worker still needs an operator's SBX_WORKERS and setup.sh step, because
only setup.sh mints a worker's relay token.

Refs rossoctl#741

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…ed state

A template build is now wanted running only while a subject holds a
lease on it (template lifecycle spec §6.2-§6.4), and the control plane
tells each host which installed workers to run and stop.

- POST /v1/templates/{id}/activate {tag?, build?, leaseSeconds?} takes
  or renews the caller's lease on a registered build: 60-86400 s a
  grant, default the largest idle limit its hosts report, else 3600;
  renewed by calling again. Each grant is an `activate` record, and the
  lease stores its digest. POST .../deactivate drops the caller's
  leases (an admin's `all: true`, everyone's), with a `deactivate`
  record.
- Placement (activation.ts, pure functions): first leased, first
  placed, on a host whose inventory holds the snapshot, within its
  activeLimit, the least used first. A leased build is never evicted.
  Refusals keep no lease: 409 template_unavailable (no registered build,
  or no host holds it), 409 no_active_slot with Retry-After (every
  holder full), 429 quota_exceeded with quota: active. CpError can now
  carry Retry-After.
- One activation at a time: the quota and placement check, the record
  and the lease write run under one in-process lock across templates,
  so concurrent activations of different templates cannot together pass
  a quota or a host's limit. A lease taken in the same second as a
  placed build waits rather than displacing it.
- Activation on first use: with SH_TEMPLATE_HOSTS set, POST
  /v1/sandboxes on a registered build that is not active takes the
  caller's lease (reason: first_use) and answers 409
  template_not_active with readiness and Retry-After: 30; activate:
  false starts nothing. No sandbox record is kept while waiting. Before
  any host reports, an attached worker serves and an absent one is
  refused. The sandbox record's `lease` is the lease's activate record.
- GET /v1/hosts/{host}/wanted (host bearer) answers run (leased and
  placed here) and stop (held, no lease, no live sandbox: a worker is
  never stopped under one). POST /v1/hosts/{host}/workers/report
  records attached, refused and detached as activate and deactivate
  records by host:<id>; readiness still comes from the relay.
- Readiness gains activating, deactivating and unavailable; the hosts
  block of GET /v1/templates is filled from the agents' inventories;
  GET /v1/quota counts the caller's leased builds.

The OpenAPI document is 1.7.0, with the changelog, the HTTP API
reference and spec §6.2-§6.4.

Refs rossoctl#742

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…e; --wanted-only

deploy/sbx/host-agent.sh now applies the host's wanted state (template
lifecycle spec §6.3) after each build poll: it reads GET
/v1/hosts/{host}/wanted, starts each `run` worker whose sbx-worker@<id>
unit is installed and not active, stops each `stop` worker whose unit
is active, and reports each start, refusal and stop (attached, refused,
detached) to POST /v1/hosts/{host}/workers/report. A wanted worker that
is not installed is reported refused, never installed: a worker's relay
token is still minted only by setup.sh. The control plane leaves out a
worker with live sandboxes, so none is stopped under one.

- host-agent.sh --wanted-only reports the inventory and applies the
  wanted state, and claims and builds nothing. The new
  sbx-host-agent-wanted.service and its timer run it every 15 s beside
  the two-minute build poll, so an activation waits seconds, not behind
  a build.
- A lock ($SBX_SRV/.activation.lock, flock) keeps the two runs from
  starting or stopping workers at once; the one without it skips,
  saying why.
- A missing registry login or the disk floor holds builds, never the
  wanted state. systemctl and flock are required; a malformed worker id
  or wanted state is an error line, never a start.
- The summary line adds started and stopped.

host-agent.test.sh mocks systemctl and flock and covers the starts,
the refusal, the stops, a malformed id, --wanted-only and the lock. The
RUNBOOK's host agent section says how to install the wanted units and
size SBX_ACTIVE_LIMIT; the configuration reference and spec §6.3 follow.

Refs rossoctl#742

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…ait out an activation

The client part of activation leases (template lifecycle spec §6.3,
§6.4).

- `mocactl sbx templates activate ID [--build B] [--lease S] [--wait
  [--timeout S]]` takes or renews the caller's lease (the default tag,
  or build B; S seconds, 60-86400) and prints it. With --wait, a 409
  no_active_slot is retried after its Retry-After, and the build is read
  every 5 s until it is active, saying once each why it waits
  (activating, no host reported, no free slot); any other refusal fails
  at once. A wait past --timeout (default 1800 s) exits 5, the new
  SBX_EXIT.timedOut.
- `mocactl sbx templates deactivate ID` releases the caller's leases.
- `sbx create` and `sbx up` retry a 409 template_not_active after its
  Retry-After for up to 10 minutes, saying why; any other refusal is
  as before.

SandboxApiClient gains activateTemplate and deactivateTemplate, and
the contract test checks both against the OpenAPI document.

Refs rossoctl#742

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

@clawgenti clawgenti 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.

Summary

This PR is stacked on #772, and the review covers only what it adds over #772 (activation leases, placement, the hosts' wanted state, the host agent's --wanted-only timer and mocactl activate/deactivate). Placement, the deployment-wide activation lock, the record-first lease write and the first-use 409 flow match the PR body and the spec comments, and the new activation tests cover the race cases. One defect: when a request names no leaseSeconds, the default lease comes from the largest SBX_IDLE_LIMIT_S any host reports. That value is never bounded to the 60-86400 range the same function enforces, so a host with SBX_IDLE_LIMIT_S above a day (or between 1 and 59) makes every activate without --lease fail, and every first-use sandbox create too, with an invalid_request the client never caused.

Author: webchang (MEMBER — maintainer)
Areas reviewed: control-plane activation/placement (activation.ts, sandbox-handlers.ts, host-handlers.ts, routes.ts, errors.ts), host agent shell and systemd units, mocactl sbx activate/deactivate and create wait, openapi/CHANGELOG/RUNBOOK/configuration docs, tests, commit conventions/DCO
Agent/IDE config (.claude/.vscode): none
Commits: 4 commits in the increment (d4057ff, 1b2cb04, fcc90f2, merge b35b8c7), all signed-off: yes
CI status: passing (all 17 checks green, including DCO, shellcheck, deploy-scripts on bash 5 and 3.2, CodeQL)

1 must-fix, 0 suggestions, 0 nits.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

const DAY = 86_400;
const hosts = hostViewsOf(deps);
const defaultLease =
Math.max(...hosts.map((h) => deps.hosts!.get(h.id)!.limits.idleLimitSeconds), 0) || 3600;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix: defaultLease is the largest idleLimitSeconds any host reported. That is nonNeg() only (host-handlers.ts:110 and the inventory handler). host-agent.sh:88-91 accepts any whole number up to 9 digits for SBX_IDLE_LIMIT_S, and the RUNBOOK/configuration.md document no upper bound. The check two lines below (want < 60 || want > DAY) then applies to that default too. So if one host sets, say, SBX_IDLE_LIMIT_S=172800, every activate without leaseSeconds is refused with 400 invalid_request: leaseSeconds must be 60-86400. That also covers every first-use sandbox create (requireActive calls takeLease(..., undefined, 'first_use')), and mocactl create/up stop on it, since it is not template_not_active. A value between 1 and 59 has the same effect. Separately, RUNBOOK.md:654 says the default is "the largest of the hosts' that hold the build", but this takes the max over all hosts. Suggested fix: clamp the default and range-check only an explicit value, e.g. const holders = hosts.filter(h => h.holds[target.buildId] !== undefined); const dflt = Math.min(DAY, Math.max(60, Math.max(0, ...holders.map(h => deps.hosts!.get(h.id)!.limits.idleLimitSeconds)) || 3600));. Alternatively, have host-agent.sh refuse SBX_IDLE_LIMIT_S outside 0 or 60-86400. Add a test with a host reporting idleLimitSeconds: 172800 and an activate with no leaseSeconds.

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

Summary

The range adds activation leases (activate/deactivate, stored on the template catalog's build records under an in-process lock), first-leased-first-placed placement against each host's fixed activeLimit, the hosts' GET /wanted and workers/report routes, an activation gate on sandbox create (409 template_not_active), the host agent's start/stop step with a --wanted-only 15 s unit, and mocactl activate/deactivate plus create/up waiting. The lease and lock logic is careful and well tested for the single-replica case, but the create gate breaks env-imported templates as soon as any template host is configured, and placement only counts the builds it places, not the workers a host is really running.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript, Shell, systemd, OpenAPI
Agent/IDE config (.claude/.vscode): none
Commits: all signed-off: yes
CI status: all 17 checks pass

Inline: 1 must-fix, 3 suggestion, 2 nit. The head 8ec582c is a merge-only cascade of #757 up the stack (empty remerge-diff, no new non-merge commits); the review covers this PR's own range 64b0c900..fcc90f26, as the body asks.

AI-assisted review, approved by a maintainer before posting.

t: { doc: TemplateDoc; build: TemplateBuild },
activate: boolean,
): Promise<void> {
if (hostViewsOf(deps).length === 0 && !deps.config.templateHosts?.length) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix: Once SH_TEMPLATE_HOSTS is set (or any host has reported), this gate applies to every template, including the ones imported from SH_SANDBOX_TEMPLATES. An imported build's id is imported:<12 hex> and never appears in a host's holds (those are keyed by manifest hash), so after the first inventory readinessOf gives an unleased, attached imported worker deactivating (activation.ts:103). The create then takes a lease, and place marks it not_held, so the next try is 409 template_unavailable from takeLease. Before any inventory, an unattached imported build gets template_not_active on every retry, because nothing will ever start it. Either way, adding one host agent stops sandbox creates on the deployment's existing templates, the default one included. hostWanted never asks to run or stop these workers either: the deployment runs them. Suggested fix: skip the gate (and leave readiness as presence alone) for builds that no host can hold, e.g. build.buildId.startsWith('imported:') or profile === 'imported'. Add a test with one imported template and one host-built template on a deployment with hosts.

export function place(docs: TemplateDoc[], hosts: HostView[], nowS: number): Placement {
const placed = new Map<string, string>();
const unplaced = new Map<string, Unplaced>();
const used = new Map(hosts.map((h) => [h.id, 0]));

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: used counts only the builds this pass places, but the hosts run more workers than that, and activeLimit stands for pinned guest memory. (1) A build that is still leased but now placed on another host is in neither run nor stop for its old host (host-handlers.ts:224-225), so the old host keeps its worker running. This happens when two hosts hold the same build and an earlier lease ends: placement moves to the least-used holder, then sorts by id. That host's slot then counts as free, and another build can be started there. (2) A build with no lease left whose worker still has a live sandbox (draining) is excluded from stop but doesn't count against activeLimit either. In both cases a host can run more than activeLimit workers, and in (1) the same worker id runs on two hosts. Consider counting the workers each host reports running (or keeping placement sticky to the host already running the build), and counting draining workers in used.

}

/** The hosts as their agents last reported (§6.1), as placement reads them. */
export function hostViewsOf(deps: CpDeps): HostView[] {

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: HostState.at is stored but never checked. A host whose agent died or was removed stays in placement until the control plane restarts. Leases keep being placed on it (activating forever), it keeps taking activeLimit slots, and requireActive's comment ("a host down ... readiness is the worker's presence alone") doesn't match what happens. Consider leaving out hosts whose last inventory is older than a few poll intervals (e.g. 3 x the 2-minute timer).

Comment thread deploy/sbx/host-agent.sh
[[ "$w" =~ $WORKER_RE ]] || { error 'a wanted worker id is malformed'; continue; }
unit="sbx-worker@$w.service"
if [[ ! -f "$SBX_ENV_DIR/workers/$w.env" ]]; then
worker_report "$b" refused 'worker not installed on this host (install-host.sh with its setup.sh bundle)'

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: This runs every 15 s from the --wanted-only timer, for every wanted build whose worker isn't installed, and each refused report appends an activate record to the template's provenance stream (hostWorkerReport). A leased build that nobody has installed writes about 5,760 records a day, and the same happens below for a unit whose systemctl start keeps failing (start-limit-hit). The stream is append-only provenance, so this grows without bound. Consider reporting a refusal only when it changes, e.g. a small state file under $SBX_SRV keyed by worker and reason, or having the control plane drop a refused identical to that build's last one.

(readiness === 'inactive' || readiness === 'deactivating' || readiness === 'activating')
) {
// Its refusals (no_active_slot, quota_exceeded, template_unavailable) answer as activate's.
await takeLease(deps, p, t.doc, t.build, undefined, 'first_use');

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: readiness === 'activating' usually means the caller already holds a live lease, so mocactl create and up (which retry every 30 s for up to 10 min) renew the lease and write a new activate record (reason: first_use) on each retry: about 20 records for one wait. Consider skipping takeLease when the caller already has a live lease on this build, and just answering template_not_active.

});
}
if (pl.unplaced.get(target.buildId) === 'no_slot' || displaces) {
const free = Math.min(

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: The Retry-After is the earliest end of any live lease in the catalog, on every template and host, and it includes leases on builds other subjects still hold. It can say 1 s when no slot on this build's holders will free up for hours, and mocactl activate --wait then polls on that. Consider limiting it to builds placed on the target's holders.

@clawgenti clawgenti 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.

Summary

Re-review of the push since my last review (b35b8c7..8ec582c, review 5883320573). This PR's own commits are unchanged: git range-diff shows every earlier commit as equal. The push only merges the parent branches again ("Merge pr/i18-host-agent into pr/i19-activation", and the merges below it), and so brings in #757's five new fixes (381d7c4 too-large command closes its connection, b1beba6 lease keeps its VM on that refusal, ace1c43 build-snapshot.sh no writes through a symlink, ab347c1 install-host.sh removes the old jail path, 5181204 http-api doc). Those belong to #757 and are reviewed there. I checked the two conflicted merges on the way down (3ee0acf upstream/main into i10, d4445a2 i10 into i17) against their recorded resolutions. errors.go, guestconn.go, build-snapshot.sh, microvm-worker main.go and snapshot_test.go keep both sides, as the commit messages say, and main.go's single LoadManifest now feeds both ManifestFeatures and VerifyWith. No new findings. The earlier 1 must-fix still apply: none of the files they cite changed in this push. The earlier must-fix is still open: no file it cites changed.

Author: webchang (MEMBER — maintainer)
Areas reviewed: range-diff of this PR's own commits, the incoming #757 commits (scope only), the conflict resolutions in the two upstream merges, commits/DCO, CI, agent-config gate
Agent/IDE config (.claude/.vscode): none
Commits: 45 commits, all signed-off: yes
CI status: passing (all 17 checks green)

0 new must-fix, 0 new suggestions, 0 new nits.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

Conflict in deploy/sbx/install-host.sh: both branches wire a worker to its
template record. rossoctl#771's check_template_record is kept (jq, the schema,
the worker must match the bundle, refused before anything is written);
this branch's record_template_id is dropped as now unused. The header
keeps this branch's binary paths (SBX_WORKER_BIN). install-host.test.sh:
rossoctl#771's no-record assertion now checks the worker that has no record.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Conflict in packages/control-plane/src/sandbox-handlers.ts, createBuild:
rossoctl#766's reviewed form is taken (the owner's quota lock, normalizeSpec,
the charged owner, the audit line), with this branch's queuedAtMs on the
new build and its comment on the templates list's hosts block.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
… ends its poll

A failed build whose log held no non-blank line made the grep for its last
line exit 1; under pipefail and errexit that ended the whole poll, leaving
this build and every other build claimed in the same poll `building`, with
no `failed` report and no summary line. The grep is now guarded, and a
test runs a build that exits 137 with only blank lines.

Refs rossoctl#741

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Conflicts in docs only, both sides kept: openapi's getQuota description
(rossoctl#766's template and build counting, and this branch's activation
leases) and http-api.md's error-code list (rossoctl#766's template_exists,
policy_refused and quota_exceeded, and this branch's no_active_slot,
template_unavailable and template_not_active).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…n with as failed

Once a build is claimed the control plane holds it `building` for this host,
and nothing re-queues it. The post-claim early returns (a malformed template
id or gate record path, a gate record fetch that failed or whose bytes do not
match their digest, a building or built report not accepted, no template
record or manifest after the build) only logged an error, so the build stayed
`building` and counted against its owner's queue until cancelled by hand.

Each now reports `{event: failed, step, message: "agent_error: ..."}`, best
effort, through one helper (fail_claimed) that counts it failed and logs an
error only if the report itself fails. The message is the agent's own fixed
wording, never build output. A template record that is not JSON no longer
ends the poll under errexit. The spec and the runbook name the new code.
Tests: a gate digest mismatch, a failed gate fetch, no template record, and a
record that is not JSON are each reported failed.

Refs rossoctl#741

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…mplate update

The report handler refused reports for a terminal build on the status it
read at the start of the request, then awaited blob writes, provenance
appends and the policy read before its final catalog write, which rewrote
the build without looking at it again. An owner's cancel landing in that
window was overwritten: the build became `registered` (and could take
`default`), with both a `cancelled` and a `registered` outcome in its chain.
The building/probing and failed writes had the same gap.

Every report write now goes through one helper that finds the build as the
catalog holds it, inside the template's update queue, and refuses it unless
it is still this host's and building, probing or built. The `failed` record
and the `built` report's build and registration-check records are appended
inside that update, so a refused report leaves no record. Tests: a cancel
that lands while a built report is held in its blob write stands, and the
chain holds no built or registration record; building, probing and failed
reports on a cancelled build, and an unknown event, are refused.

Refs rossoctl#741

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…lready has is rejected

A registered build takes its manifest hash as its build id, but nothing
checked whether another build of the template already had that id. A
second create of the same image and spec under another profile or gate
record is not a reuse, so it queues a new build; template-build.sh then
finds the snapshot already built and reports the same manifest hash, and
the template held two builds with one build id (lookups by id returned the
first).

The registration check gains a rule, T.unique, evaluated inside the
template update: a build whose manifest hash another build of the template
already has is rejected, its reason naming that build. The spec says so.
Test: a second build of the same snapshot is rejected T.unique, the first
keeps the id and `default`.

Refs rossoctl#741

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings in upstream main (lease modes, API 1.6.0) through pr/i18-host-agent.

Conflicts:
- docs/api/CHANGELOG.md: this branch's activation section, renumbered 1.8.0, above
  pr/i18-host-agent's 1.7.0 and main's 1.6.0.
- docs/api/openapi.yaml: the Error code list keeps this branch's no_active_slot,
  template_unavailable and template_not_active, then main's mode_not_allowed.
- docs/reference/http-api.md: the host agents row at 1.7.0, then this branch's activation row at
  1.8.0.
- packages/control-plane/src/errors.ts, test/errors.test.ts: both sides' new codes and statuses.
- packages/control-plane/src/sandbox-handlers.ts: the sandbox-token import takes main's
  mintSetModeToken (this branch had moved the SubjectQueue import up); createSandbox parses main's
  mode and idleTimeoutS before this branch's requireActive, so a bad mode is refused before an
  activation starts.

Beyond the markers:
- packages/control-plane/test/openapi-contract.test.ts: the enrollment-checked route count is 22,
  main's two mode routes and this branch's activate and deactivate both added to 18 (each side
  had raised it to 20).

API version: this branch's activation moves from 1.7.0 to 1.8.0 (openapi info.version, the
changelog, and the two "API 1.7.0" mentions in docs/reference/http-api.md).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings in upstream main through f60db30 (turn grants, API 1.7.0) by pr/i17-build-tooling.

Conflicts:
- docs/api/CHANGELOG.md: this branch's host agent section, renumbered 1.8.0, above main's 1.7.0
  and 1.6.0.
- docs/reference/configuration.md: main's table (the grant settings) with this branch's
  SH_TEMPLATE_HOSTS row.
- packages/control-plane/src/main.ts: the sandbox config takes both this branch's templateHosts
  and main's grant TTLs.

API version: this branch's host routes move from 1.7.0 to 1.8.0 (openapi info.version, the
changelog, and the two "API 1.7.0" mentions in docs/reference/http-api.md).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings in upstream main through f60db30 (turn grants, API 1.7.0) by pr/i18-host-agent.

Conflicts:
- docs/api/CHANGELOG.md: this branch's activation section, renumbered 1.9.0, above
  pr/i18-host-agent's 1.8.0 and main's 1.7.0 and 1.6.0.
- docs/api/openapi.yaml: the Error schema keeps this branch's quota value active and readiness,
  then main's TurnGrants schema.
- docs/reference/http-api.md: the host agents row at 1.8.0, then this branch's activation row.

API version: this branch's activation moves from 1.8.0 to 1.9.0 (openapi info.version, the
changelog, and the two "API 1.8.0" mentions in docs/reference/http-api.md).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
webchang added a commit to webchang/moca that referenced this pull request Nov 13, 2026
… build's holders only

defaultLease was the largest idleLimitSeconds any host reported, never bounded to the 60-86400
range the same function enforces: a host reporting 172800 (or 5) made every activation that named
no lease fail with 400, and a host holding none of the build set its lease. The default is now the
largest idleLimitSeconds among the hosts that hold the build, or 3600 when none reports one,
clamped to 60-86400. Only an explicit leaseSeconds is range-checked, and one that is not a whole
number is refused instead of being replaced by the default. The API changelog and the lifecycle
spec say so.

Test (fails with the fix reverted): clamps the default lease from the holders' idle limits, and
range-checks only an explicit one (a host reporting 172800, one reporting 5, another host's longer
limit, explicit values that are refused).

(cherry picked from commit ceacc98)

Ports rossoctl#775 review fixes

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
webchang added a commit to webchang/moca that referenced this pull request Nov 13, 2026
…never gated by activation

Once a host was configured (or any host had reported), the activation gate applied to every
template, including the ones imported from SH_SANDBOX_TEMPLATES. Their builds (`imported:<12
hex>`) name no snapshot, so no host's inventory ever holds them: they could never become active
and every sandbox create on them was refused template_not_active for good. activation.ts gains
hostManaged(build), true only for a build named by its manifest hash. For any other build,
requireActive skips the gate; readinessOf reads the worker's presence alone; wantedBuilds leaves
the build out, so it is never placed, run or stopped; and activate and takeLease refuse it with
400 invalid_request, since the deployment runs its worker and it takes no lease. The API changelog
and the lifecycle spec say so.

Test (fails with the fix reverted): never gates a template imported from SH_SANDBOX_TEMPLATES,
beside a host-built one (one imported and one host-built template on a deployment with a
configured host, before and after the host's first inventory).

(cherry picked from commit 5ee6402)

Ports rossoctl#775 review fixes

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
webchang added a commit to webchang/moca that referenced this pull request Nov 13, 2026
… placement

HostState.at was stored but never checked: a host whose agent died or was removed stayed in
placement, in the hosts block and in the default lease until the control plane restarted, and
held activeLimit slots it would never use. Placement, the hosts block and the default lease now
leave out any host whose last inventory is older than HOST_STALE_S (360 s, three of the build
poll's two-minute intervals), until that host reports again (freshHosts). When every host is
silent, readiness is the workers' presence alone. The API changelog says so; the grace test's
agent keeps reporting through the grace, as a live agent does.

Test (fails with the fix reverted): leaves out a host whose last inventory is older than
HOST_STALE_S, until it reports again.

(cherry picked from commit 648baca)

Ports rossoctl#775 review fixes

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
webchang added a commit to webchang/moca that referenced this pull request Nov 13, 2026
…ps a running build on its host

`used` counted only the builds one placement pass placed, but the hosts run more workers than
that: an earlier lease ending could move a running build to another host (two copies of one worker
id), and a worker still draining a live sandbox took a host slot nobody counted.

- Each `holds` entry of an inventory may carry `running` (the build's worker unit runs); between
  inventories the host's attached, detached and refused reports keep it current.
- Placement is sticky: a wanted build already running on a holder stays on that host (the first
  by id if more than one runs it). Each host's count starts with the workers that stay running on
  it before anything else is placed: the wanted builds it runs and the unleased ones whose worker
  has a live sandbox (draining). `active.used` in the hosts block shows that count.
- When a host runs a leased build that placement keeps on another host, its wanted state lists
  that build in `stop` (never under a live sandbox), so one worker id does not stay on two hosts.
- With the memory rule, "running" is the union of the held builds marked running and the memory
  report's runningWorkers, and a worker started since the inventory (by an attached report) is
  counted as pending too, since the host's MemAvailable cannot show it yet (the upstream memory
  branch's merge of these fixes). activation.ts takes the upstream text, whose comments no longer
  name internal register ids.

The API changelog says so. The activation tests' host ids are neutral names, and their inventory
helper takes the builds a host marks running.

Tests (fail with the fix reverted): keeps a running build on its host: an earlier lease ending
moves nothing; counts a draining worker against its host's activeLimit until its last sandbox ends;
stops a host's copy of a leased build that another host runs and is placed on; sticky placement and
the memory rule together: running is the union of both reports. Also: keeps a build on the
memory-reporting host already running its worker, counting it once.

(cherry picked from commit c1872f7)
(cherry picked from commit 9748bc0)
(cherry picked from commit d7823e1)

Ports rossoctl#775 and rossoctl#776 review fixes

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
webchang added a commit to webchang/moca that referenced this pull request Nov 13, 2026
…ers before starting any

The control plane's placement now counts the workers a host runs and keeps a running build on its
host (the ported control-plane fix). The agent's inventory gives each held build `running`,
whether its worker's sbx-worker@ unit is active, so placement sees what the host really runs. And
the wanted state is applied stops first, then starts (the start book is read after the stops), so a
slot or the memory a stopped worker frees is free before a start takes it; a host told to stop its
copy of a build another host runs, and to start another, no longer passes its limit for a moment.

Tests (host-agent.test.sh, bash 5 and 3.2; fail with the fix reverted): the inventory names a held
build's running unit (`running: true`) and a stopped one (`running: false`); stops come before
starts in one poll.

Host-side (deploy/sbx/host-agent.sh).

(cherry picked from commit c1872f7)

Ports rossoctl#775 review fixes

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
webchang added a commit to webchang/moca that referenced this pull request Nov 13, 2026
…own holders

The Retry-After of a no_active_slot refusal was the earliest end of any live lease in the catalog:
a lease on another host's build, or one subject's lease on a build another subject keeps leased,
gave a wait after which nothing had freed. It is now the seconds until the soonest a build placed
on one of this build's holders loses its last live lease, which is when its slot frees, or 60 when
no lease gives that time (draining workers). The API changelog says so.

Test (fails with the fix reverted): answers Retry-After from the build's own holders: when one of
their leased builds loses its last lease (a lease ending soon on another host's build, and a shared
build whose first lease ends before its last).

(cherry picked from commit fd1c217)

Ports rossoctl#775 review fixes

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
webchang added a commit to webchang/moca that referenced this pull request Nov 13, 2026
…ly waits

A client retrying its own first use (409 template_not_active, Retry-After) renewed its lease and
wrote a new `activate` record on every retry while the worker started. requireActive now takes the
lease only when the caller holds no live lease on the build; otherwise it answers 409
template_not_active with the readiness and Retry-After, and writes nothing. Another subject's first
use still takes its own lease. The API changelog says so.

Test (fails with the fix reverted): starts the activation and answers 409 template_not_active; the
retry creates once active (three retries under one lease; the lease's end and the count of activate
records stay the same).

(cherry picked from commit eb7a678)

Ports rossoctl#775 review fixes

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
webchang added a commit to webchang/moca that referenced this pull request Nov 13, 2026
The host agent retries every 15 s, so a worker not installed, or a unit whose start keeps failing,
appended one `activate` record (event refused) to the template's append-only stream per poll. For
each build still in a host's `run`, hostWorkerReport now remembers the reason of that host's last
refusal; a refused report repeating it is answered `recorded: null` and appends nothing. A
different reason, any other report for the build, or the build leaving the host's `run` starts a
new episode, recorded again. The state outlives the inventory polls; after a control-plane
restart each build can get at most one extra record. openapi's `recorded` is a string or null; the
API changelog says so.

Test (fails with the fix reverted): records a repeated refusal once while the build stays in the
host's run.

(cherry picked from commit cbb09cb)

Ports rossoctl#775 review fixes

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings in upstream main through 949dc5f (template tags, edits and owner transfer, API 1.8.0) by
pr/i17-build-tooling.

Conflicts:
- docs/api/CHANGELOG.md: this branch's host agent section, renumbered 1.9.0, above main's 1.8.0,
  1.7.0 and 1.6.0.
- docs/reference/change-policy.md: version 1.9.0; main's list, then the template host agents.
- docs/reference/http-api.md: main's template admin row and paragraph, then this branch's host
  agent row and paragraph (API 1.9.0).
- docs/specs/2026-11-03-template-lifecycle-and-provenance-design.md: the status line names both
  §5.1-§5.2 and §6.1; main's §5, then this branch's §6.1.
- packages/control-plane/src/sandbox-handlers.ts: createBuild takes main's owner-transfer retry
  (OWNER_MOVED), with this branch's queuedAtMs on the new build.

API version: this branch's host routes move from 1.8.0 to 1.9.0 (openapi info.version, the
changelog, change-policy and the two "API 1.8.0" mentions in docs/reference/http-api.md).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings in upstream main through 949dc5f (template tags, edits and owner transfer, API 1.8.0) and
the host agent at API 1.9.0, by pr/i18-host-agent.

Conflicts:
- docs/api/CHANGELOG.md: this branch's activation section, renumbered 1.10.0, above the host
  agent's 1.9.0 and main's 1.8.0, 1.7.0 and 1.6.0.
- docs/api/openapi.yaml: main's tag, tag removal and owner paths, then this branch's activate and
  deactivate paths; info.version 1.10.0.
- docs/reference/change-policy.md: version 1.10.0; main's list, then the template host agents,
  then activation leases. Prettier re-pads the decisions table for the longer version.
- docs/reference/http-api.md: main's template admin row, the host agent row, then this branch's
  activation row; "API 1.10.0" in that row and in the activation paragraph.
- docs/specs/2026-11-03-template-lifecycle-and-provenance-design.md: the status line names
  §5.1-§5.2, §6.1 and §6.2-§6.4.
- packages/control-plane/src/routes.ts: main's four template admin routes, then this branch's
  activate and deactivate.
- packages/control-plane/src/sandbox-handlers.ts: both sides' imports; main's owner and admin
  actions (ownTemplate, ownerCheck, the tag, edit and transfer handlers) beside this branch's
  hosts block, activation lock, activate, deactivate and requireActive; the handler table holds
  both.
- packages/control-plane/test/routes.test.ts, route-profile.test.ts: both sides' routes.
- packages/control-plane/test/openapi-contract.test.ts: 26 enrollable routes (main's 24 plus
  activate and deactivate).
- packages/mocactl/src/sbx/api.ts: main's tag, untag, edit and transfer calls, then activate and
  deactivate.
- packages/mocactl/src/sbx/cli.ts: the usage lists both; main's NO_RECORD, TEMPLATE_ADMIN_SUBS
  and TEMPLATE_ONE_ID, with activate and deactivate added to TEMPLATE_SUBS and TEMPLATE_ONE_ID,
  activate to TAKES_BUILD and TAKES_TIMEOUT; the dispatch takes both.
- packages/mocactl/src/sbx/commands.ts: main's tag, untag, edit and transfer commands, then
  createWaitingForActivation.
- packages/mocactl/test/contract.test.ts: both sides' calls; 23 replies.

API version: this branch's activation moves from 1.9.0 to 1.10.0 (openapi info.version, the
changelog, change-policy and the two "API 1.9.0" mentions in docs/reference/http-api.md).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings in upstream main through ab8d10e (setup.sh's Redis image guard, the image's old esbuild
dropped) by pr/i17-build-tooling. No conflicts; setup.sh's Redis image check and this branch's
template hosts sit in separate functions.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings in upstream main through ab8d10e (setup.sh's Redis image guard, the image's old esbuild
dropped) by pr/i18-host-agent. No conflicts.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings rossoctl#771's template-register.sh fix: a symlinked env or templates
file is written through to its target, keeping the target's mode. No
conflicts.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings rossoctl#771's template-register.sh fix: a symlinked env or templates
file is written through to its target, keeping the target's mode. No
conflicts.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[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 at 92bb123. This is a merge of #772 31a8c77 (which carries #771's 1c371ea) only: it merges cleanly, and the net diff against d12bd5e is exactly that commit (same patch-id). 1c371ea (template-register.sh resolves a symlinked env/templates path, with a 40-level cap, then reads the target's mode with stat -L, writes the temp file beside the target and mvs it over the target, so the link stays a link. A path that doesn't resolve to a regular file is refused. Test 7 covers a relative and an absolute link with modes 600/640.) No own code changed. No new findings.

Author: webchang (MEMBER — maintainer)
Agent/IDE config (.claude/.vscode): none
Commits: merge only, no new own commits; DCO pass
CI status: all 16 checks green

AI-assisted review, approved by a maintainer before posting.

Main took API 1.9.0 (subject trust for gate records), so this branch's
host-agent section moves to 1.10.0.

Conflicts:
- docs/api/CHANGELOG.md: this branch's section is now ## 1.10.0, above
  main's ## 1.9.0 and the sections below it, which are unchanged.
- docs/reference/change-policy.md: main's list, then "the template host
  agents". Both version numbers are 1.10.0.
- docs/reference/configuration.md: main's SH_GATE_RECORD_SCHEMA row, then
  this branch's SH_TEMPLATE_HOSTS row.
- packages/control-plane/src/template-catalog.ts: TemplateBuild has both
  sides' fields: queuedAtMs and claim, and selfAttested,
  selfAttestProfile and gateFloor.

Also moved to 1.10.0: openapi info.version, and http-api.md's host-agent
row and "came with API" line.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings rossoctl#773's verify cache, now merged.

Conflict:
- deploy/sbx/tests/install-host.test.sh: the two-worker check keeps this
  branch's template-record and SANDBOX_TEMPLATE checks, plus main's
  SH_VERIFY_CACHE_DIR check, with this branch's pass line.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
Brings upstream main 01528b6 (rossoctl#769, rossoctl#782, rossoctl#771, rossoctl#773) through
pr/i18-host-agent. Main took API 1.9.0, and the host agents moved to
1.10.0, so this branch's activation section moves to 1.11.0.

Conflicts:
- docs/api/CHANGELOG.md: ## 1.11.0 activation, above ## 1.10.0 host
  agents and main's ## 1.9.0, which are unchanged.
- docs/api/openapi.yaml: main's 409 self_attested on the owner transfer,
  then this branch's activate and deactivate paths. info.version is
  1.11.0.
- docs/reference/change-policy.md: main's list, then "the template host
  agents, then activation leases". Both version numbers are 1.11.0.
- docs/reference/http-api.md: the host agents row (API 1.10.0), then the
  Activation row (API 1.11.0). "Activation came with API 1.11.0."
- packages/control-plane/src/sandbox-handlers.ts: ReadinessFacts carries
  both this branch's placement and nowS and main's trusted set. Its
  docs argument and both returns carry all three.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
@webchang
webchang merged commit ec0f840 into rossoctl:main Nov 14, 2026
19 checks passed
webchang added a commit that referenced this pull request Nov 14, 2026
Conflict in host-handlers.ts, hostWanted's doc comment only: #775's
sticky stop (a copy run while placement keeps the build elsewhere) and
this branch's egressSids sentence, both kept. #775's new exact
wanted-body test expects this branch's egressSids: [].

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[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.

Run template workers only while held: activation leases and the host's wanted state

4 participants