Skip to content

feat(control-plane): self-serve template create, gated by policy, with quotas - #766

Merged
pdettori merged 28 commits into
rossoctl:mainfrom
webchang:pr/i14a-self-serve-create
Nov 13, 2026
Merged

pdettori merged 28 commits into
rossoctl:mainfrom
webchang:pr/i14a-self-serve-create

Conversation

@webchang

Copy link
Copy Markdown
Member

Part of #737. Stacked on #760 (the template store, which is itself stacked on #756): this branch contains #760's commits, and its own change is the last 4 commits (plus one merge of #760's tip). Once #760 merges, only those remain.

What it does: a user creates a sandbox template self-serve, and a machine-checked policy decides whether the create is allowed. Four signed-off commits:

  1. The control plane: POST /v1/templates for a signed-in user, checked against the stored policy (profiles, image rules, gate records) with per-user quotas. A taken id answers 409 template_exists; a refusal answers 422 policy_refused and names the rule. openapi 1.5.0.
  2. The docs: GATING-RULES.md §1–§3, the onboarding examples and their test (examples.test.sh), and the policy's place in the lifecycle design (§4, §8).
  3. A fix: a refused create is recorded only on a stream the caller may write.
  4. The docs: the gating rules read as a contract for whoever builds the image.

Notes for review:

Tests on the tip (main at 4c16c29):

  • control plane 1,313 passed, 3 skipped (with Redis), plus typecheck;
  • deploy/sbx/template-onboarding/tests/examples.test.sh passes on bash 5 and bash 3.2;
  • make test-deploy passes, and shellcheck -S warning over deploy/ and scripts/ is clean.

26 files, +2,482 / -33, counted against #760's tip.

Assisted-By: Claude Code

…fiable offline

Add an append-only provenance store to the control plane: one hash
chain per stream (`policy`, `template/<id>`), kept in a directory on the
control plane's persistent volume, exportable as one JSON document and
verifiable offline with the Python standard library alone.

- provenance.ts: ProvenanceStore (one file per record named by the
  sha256 of its canonical JSON, one head per stream, cited documents
  under blobs/; a record is written before its head moves, appends to
  a stream are serialized, the directory is checked writable at start),
  canonicalJson, export() (moca-provenance-export/1) and verifyExport.
  Record kinds: policy, create, gate, build, check, activate,
  deactivate, tag, visibility, owner, retire, reject, use, sandbox,
  session.
- sandbox-handlers.ts: with deps.provenance set, a sandbox's create, its
  delete, and its expiry (once, from the janitor's sweep) are recorded
  as `sandbox` records on its template's chain. Without a store nothing
  is recorded and no behavior changes; main.ts does not open a store
  yet (that comes with the template store, rossoctl#736, which shares the directory).
- deploy/sbx/template-onboarding/verify-provenance.py: the same checks
  as verifyExport, plus --head to compare a head kept elsewhere.
  redact-provenance.py: rewrites one stream from its first match, moves
  the head and logs counts only; dry run by default.
- Tests run the Python verifier on the same exports as verifyExport,
  cover tampering, concurrent appends, restart continuity and
  redaction, and the sandbox span on its template's chain.
- Docs: the provenance section (§7) of the template lifecycle design.

Refs rossoctl#730

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

CodeQL's file-system race rule flagged writeOnce(): after an exclusive open failed with EEXIST, it
read the existing file by path to compare the bytes. writeOnce now writes the bytes to a temp file in
the same directory (exclusive create, fsync), puts it at the record's name with link(2), which is
atomic and fails with EEXIST, and on EEXIST reads the existing file through its own handle (O_RDONLY |
O_NOFOLLOW) to compare, never by a second lookup of the path. The temp file is always removed. As a
side effect a crash mid-write can no longer leave a torn file under a record's name.

Test: a file under a blob's name with other bytes is refused and left as it is, and no temp file is
left behind in blobs/ or records/.

Refs rossoctl#730

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

Templates were a fixed SH_SANDBOX_TEMPLATES list, read on the sandbox
profile only, each id mapped straight to one worker. They now live in a
catalog the control plane owns (template-catalog.ts, template lifecycle
spec §3-§4):

- A template is a name over immutable builds, with tags naming builds;
  `default` is what a bare id names. An env-list entry is one registered
  build, `imported:<12 hex>` (stable per worker, never the worker id),
  owned by no one (`owner: null`).
- With SH_PROVENANCE_DIR set, the provenance store and a file catalog
  open together on that directory (templateCatalogFromEnv). The env list
  is imported once into an empty catalog, a provenance `create` record
  per template, and ignored after that, with a warning when it differs.
  Unset, templates come from the env list at every start, as before.
- A sandbox names `id`, `id:tag` or `id@<build id>`. The reference is
  resolved to one registered build at create and kept for the sandbox's
  life: the record and the Sandbox carry `buildId` and
  `templateManifestHash` (null for an imported build), and the sandbox's
  provenance records name its build. An unknown reference stays
  `400 unknown_template`. A sandbox keeps its worker when its template
  moves to a new one.
- Readiness comes from facts: a registered build is `active` while the
  relay holds its worker's presence record (with its capacity and live
  sandboxes), `inactive` without one, `unknown` when presence cannot be
  read.
- GET /v1/templates keeps its first three fields and adds owner,
  visibility, onboarding, readiness, tags, builds and a `hosts` block
  (empty until a host agent reports). New GET /v1/templates/{id},
  /builds, /builds/{build} (each build with its spec) and /tags. All
  mount on both route profiles. A private template is visible to its
  owner and admins only; anyone else gets 404 template_not_found, as for
  an unknown template or build.

API 1.4.0 (additive), with its changelog entry, the HTTP and
configuration references, and §1-§4 of the template lifecycle design.

Refs rossoctl#736

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

SBX_TEMPLATE_STORE=1 adds the overlay component
ocp-sbx/template-store to the control plane:

- a 1 GiB RWO PVC, moca-sbx-templates, mounted as SH_PROVENANCE_DIR,
  for the template catalog and the provenance records;
  SBX_TEMPLATES_FILE is imported into it once, at the first start;
- the Recreate strategy, since an RWO volume cannot attach to a surge
  pod.

Unset or 0 renders exactly as before. Turning it off leaves the PVC and
its records in place. Any other value is refused before anything is
applied. setup.test.sh covers on, off, a re-run, egress together, and
the refusals; overlay.test.sh renders the component.

Refs rossoctl#736

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
The client part of the template store's read API:

- `sbx templates` shows each template's readiness and tags when the
  control plane sends them; an older one's list prints as before.
- `sbx templates show ID [--build BUILD] [--json]`: a template and its
  builds (status, readiness with capacity, tags), or one build with its
  spec.
- `sbx create --template ID[:TAG|@build]` passes the reference through.
  With `--seed`, the build the create was served (its `buildId`, never
  the newest) has its seed run as the sandbox's first command, and
  /workspace is checked for a clean tree. Its HEAD becomes the sbx
  baseline, so `pull` returns only later changes and `rm` needs no
  `--force`. A failed seed, a dirty tree or a build with no seed is
  exit 1, with the sandbox kept and named.
- A 404 template_not_found is reported as itself, not as a control
  plane without sandbox routes.

The contract test covers the two new calls and the fields they read.

Refs rossoctl#736

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
The import of SH_SANDBOX_TEMPLATES into an empty catalog skipped itself whenever the catalog held any
document, so a crash after the first document lost the rest for good, and a crash between a template's
`create` record and its document re-imported it with a second `create` on its stream. The import now
writes a marker (`catalog/.imported`) last; a start without it resumes: it writes only the templates not
yet in the catalog, and reuses a template's `create` record from the env list when its stream already
ends in one. With the marker present the catalog holds the templates and a differing env list is only
warned about, as before.

Test: a crash after the first document (the second document and the marker missing) resumes to both
templates, with exactly one `create` per stream and the reused record named by the document.

Refs rossoctl#736

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

An enrolled client creates a sandbox template from an image pinned by digest, and a policy, not a
person, admits or refuses it before anything is queued. All routes mount on both route profiles and
need SH_PROVENANCE_DIR:

- POST /v1/templates {id, image, spec, gateRecord?, profile?, visibility?} answers 202 {templateId,
  buildId: null, build, status: queued}, the build addressed by a b-<26 hex> handle; POST
  /v1/templates/{id}/builds adds a build to the caller's own template; POST
  /v1/templates/{id}/builds/{build}/cancel withdraws a queued, building or probing build (failed,
  step cancelled, a build record naming who).
- The policy (moca-template-policy/1, template-policy.ts, stored by template-policy-store.ts beside
  the template store): profiles (base, benchmark) with their rules and size envelope, allowed
  registries, trusted gate records by sha256, quotas. GET /v1/policy for any enrolled client; PUT
  /v1/policy for an admin, each change a policy record naming who. GET /v1/quota shows the caller's
  limits and use, and on the sandbox profile the live-sandbox cap.
- Rules carry the gating-rule ids (M1, M7 field by field with M7.spec_id and M7.spec_image, M8, M9,
  the registry allowlist, the envelope; for benchmark X1 and X1.trusted, X10, X11, X12, X14, X15). A
  refusal is 422 policy_refused {rule, message} and a check record; over quota is 429
  quota_exceeded naming which; another subject's id is 409 template_exists (404 when private).
- An admitted create writes create, gate and check provenance records. A create with the same image,
  spec, profile and gate record sha256 on the caller's own template answers that build with
  reused: true (200 registered, 202 on its way); a failed or rejected build is never reused.

The examples (deploy/sbx/template-onboarding/examples/: the default sandbox image's spec, and a
SWE-bench instance's spec and gate record, kept byte for byte) are what the tests create. TemplateBuild
adds handle and reason, and a build is found by its handle. The catalog gains a
serialized update(). API 1.5.0, with a changelog entry.

Tests: template-create.test.ts (the worked examples admitted, each rule's refusal and its check
record, ids unique per deployment, reuse, quotas, cancel, the policy and quota routes); the route
tables, the error taxonomy and the OpenAPI contract.

Refs rossoctl#737

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

The rules a template create is refused by are named in a gating-rules document:
deploy/sbx/template-onboarding/governance/GATING-RULES.md, §1 the image (Moca's M1-M6, the image
builder's X1-X9), §2.1-§2.2 the template (M7-M17, X10-X16) and §3 the provenance each rule's
evidence lives in. Where the create-time policy enforces a rule (X1, X11, X14, X15 on the
benchmark profile), its status says so.

deploy/sbx/template-onboarding/tests/examples.test.sh checks the samples in examples/: each a
well-formed template spec (M1, M7, M8, M9, field by field with jq), none naming a private registry,
an account id or a token, and a gate record beside a sample being the one its spec names, passed,
and backing its skipped identity check (X1, X10, X12). make test-deploy runs it.

The template lifecycle design gains §4's create, reuse and cancel as built, and §8, policy: the
profiles, the checks at create, registration once a host agent reports, trusted gate records by
sha256, and the benchmark id rule (not enforced yet). The HTTP API reference lists the self-serve
routes.

Refs rossoctl#737

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

A policy refusal of any well-formed id appended a `check` record to `template/<id>`, so any enrolled
subject could grow another owner's stream without bound by sending refused creates for that id. A
refusal is now recorded only when no template holds the id yet, the template is the caller's own, or
an admin is adding a build; on another subject's id it is only answered (the same 422, so no
existence oracle). The design says so, and that refusals on the caller's own and new ids are bounded
only by the request rate.

Test: another subject's refused create writes nothing to the owner's stream; the owner's own refusal,
and a refusal on a new id, are recorded.

Refs rossoctl#737

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
One conflict, docs/reference/configuration.md's control-plane table: main's rows kept, with this
stack's SH_PROVENANCE_DIR and SH_SANDBOX_TEMPLATES rows (merged row by row; none changed on both sides).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…o pr/i14a-self-serve-create

One conflict, docs/reference/configuration.md's control-plane table: merged row by row; this PR's
SH_PROVENANCE_DIR wording kept beside main's rows.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
An image builder's review of the rules for outside builders: §1.2 says which X rules a general gate
record (a self-serve user's, rossoctl#738) proves and that X2 and X3 do not apply to it; M3 states the rule
without its history; X8's container user is the image's own; X9 says what the hosts file must map;
§3's fields table notes the general record's null recipe and base digest, and that G must be
published where `gate_record.commit` points for an offline check.

Refs rossoctl#737

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

Self-serve POST /v1/templates with create-time policy rules, provenance records and per-subject quotas. The rule set in checkCreate lines up with GATING-RULES.md, and the refusal paths are well covered by tests. One finding: the per-subject quotas are checked inside the per-id catalog lock, so concurrent creates under different ids can all pass the same quota check (reproduced below). No must-fix issues.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane, mocactl), Shell (deploy/sbx), K8s overlays, OpenAPI/docs, Python helpers (read only)
Agent/IDE config (.claude/.vscode): none
Commits: 12 commits, all signed-off: yes
CI status: passing (17/17)

Verified at head be419cd: control-plane vitest run gave 1241 passed. The 9 failures are all Redis-backed suites (ECONNREFUSED 127.0.0.1:6379, no Redis on the review host), and CI runs them green. tsc --noEmit is clean. I ran a throwaway vitest probe for the quota race and then deleted it.

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

// register under one manifest hash).
reused = cur?.builds.find((x) => REUSABLE.has(x.status) && buildReuseKey(x) === want);
if (reused) return cur!;
const u = await usage(cat, p.sub);

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 quotas can be exceeded by concurrent creates.

usage(cat, p.sub) runs inside cat.update(id, …), but FileTemplateCatalog.update serializes per id only (this.queue.run(id, …)). Creates for different ids from the same subject run concurrently. Each one reads the same usage before any of them writes, so all of them pass u.templates >= quota.templates (and u.buildsQueued >= quota.buildsQueued).

Probe (throwaway vitest at head, now deleted), with policy quota: { templates: 1, buildsQueued: 10 } and the worked benchmark body:

  • Promise.allSettled of 5 creates with ids a1..a5 gave ok=5, and listTemplates returned 5 templates
  • control: the same 3 creates run sequentially gave ok=1

Suggested fix: serialize the quota check and the write per subject, e.g. a second queue.run(owner:${p.sub}, …) around the usage + cat.update pair in createBuild, or a per-subject counter updated under the same lock. Then add a parallel-create test like the probe above. This matters now because quota_exceeded is a new public contract in openapi 1.5.0.

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

Self-serve POST /v1/templates with a stored policy, per-subject quotas, cancel, and the policy/quota routes. The routing, openapi 1.5.0, error codes, the 404/409 non-oracle split and the 4f84d23 fix (no check written to another subject's stream) all check out, and the merge 955636a's remerge-diff is only a clean resolution of the configuration.md table. Three blocking problems: the quotas can be bypassed with concurrent creates, the envelope/X15 can be bypassed with guest_mb + guest_ram_mb, and X10/X12 are only partly checked outside the benchmark profile, which the design and GATING-RULES say they apply to.

  • Author: webchang (MEMBER — maintainer)
  • Areas reviewed: POST /v1/templates and /{id}/builds (policy check, quotas, id uniqueness, reuse), cancel, GET/PUT /v1/policy, GET /v1/quota, template-policy.ts rules and image-reference parsing, FilePolicyStore, FileTemplateCatalog.update, openapi 1.5.0 + CHANGELOG + http-api, GATING-RULES.md (incl. be419cd), the lifecycle design §4/§8, the examples and examples.test.sh
  • Agent/IDE config: none
  • Commits: 4 (+1 merge), all signed-off: yes
  • CI status: passing

Not on a diff line:

  • Id uniqueness itself is fine: the check and the write both happen inside cat.update's per-id queue, so two creates for one id cannot both create it (single process, as SH_PROVENANCE_DIR documents). Path traversal in ids is blocked by TEMPLATE_ID_RE and the catalog's own ID_RE.
  • A refused create on a new id still writes a check record to template/<id>, for any id an attacker picks. The design says this is "bounded only by the request rate", but it lets any enrolled subject create unlimited provenance streams, which no quota bounds. Consider not recording refusals on ids that don't exist.

// register under one manifest hash).
reused = cur?.builds.find((x) => REUSABLE.has(x.status) && buildReuseKey(x) === want);
if (reused) return cur!;
const u = await usage(cat, p.sub);

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: the quota check isn't atomic, so concurrent creates go past it.

cat.update serializes per id (FileTemplateCatalog.update → this.queue.run(id, …)). But usage() counts across every id with cat.list(), and the new document is only written after several awaits (usage, putBlob, three prov.appends, then write). Two creates for different ids from one subject run their mutators at the same time. Both read the same usage, both pass, and both write.

Failure scenario: with quota.templates: 1 (or buildsQueued: 10), a client sends N POST /v1/templates in parallel with distinct ids. All N are admitted and N builds are queued, because none of them sees another's document. buildsQueued has the same problem, including two parallel POST /v1/templates/{id}/builds on two of one's own templates. The test (enforces the per-subject quotas) only runs creates one after another.

Fix: run the quota check and the write under a per-subject lock as well, e.g. a second SubjectQueue keyed by p.sub wrapping the whole cat.update call. Taking the subject lock outside the id lock keeps the order consistent. Alternatively, keep an in-process reservation counter per subject that is taken before the awaits and released on throw. Add a test that fires two creates for different ids with Promise.all under templates: 1 and expects exactly one 429.

let buildsQueued = 0;
for (const d of await cat.list()) {
if (d.owner !== subject) continue;
if (d.builds.some((b) => b.status !== 'retired')) templates++;

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: three problems with how usage() counts.

  1. A template slot can never be freed. A template counts while any build is not retired, and this PR adds no route that retires or deletes one. A cancelled build becomes failed, which still counts. So a subject whose first create was cancelled, or whose build later fails on the host, holds that slot forever. Once quota.templates such ids exist, the subject is locked out, and only someone editing the store on disk can free it. Either count only templates with a build in REUSABLE (registered or on its way), or document that failed/cancelled-only templates count until a delete route lands, and link the issue.
  2. probing is not counted in buildsQueued (line 416). It is still host work in flight and CANCELLABLE treats it as not built, so a subject can hold more than buildsQueued builds in progress. Count probing too, or rename the quota.
  3. Admin builds are charged to the admin. When an admin adds a build to another subject's template (existing && isAdmin(p)), usage(cat, p.sub) counts the admin's own builds, not the owner's, so the owner's buildsQueued is bypassed and the admin's is used up. Use usage(cat, cur?.owner ?? p.sub) for the buildsQueued check.

IMAGE_RE.test(input.image ?? '') && policy.allowedRegistries.includes(registryOf(input.image)),
`image registry ${IMAGE_RE.test(input.image ?? '') ? registryOf(input.image) : '?'} is not allowed (policy allowedRegistries)`,
);
const guest = s.guest_mb ?? s.guest_ram_mb;

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: the envelope can be bypassed through the guest-size alias.

The policy reads s.guest_mb ?? s.guest_ram_mb, so guest_mb wins when both are present. The build tool reads only guest_ram_mb: template-build.sh in #771 does RAM="$(field guest_ram_mb)" and writes guest_ram_mb into T, and every sample spec in this PR uses guest_ram_mb. The spec is stored and handed to the host unchanged (request.spec).

Failure scenario: spec: {guest_mb: 4096, guest_ram_mb: 16384, vcpus: 2, …} under benchmark passes envelope and X15, which both read 4096. The host then builds a 16 GiB guest. Under base, guest_mb: 1024, guest_ram_mb: 999999 gets past maxGuestMb. GATING-RULES says X15 is enforced by "the benchmark profile's envelope (policy)", and nothing on the host checks it, so the policy is the only check and it can be bypassed.

Fix: accept exactly one key. Refuse a spec that has both (or two that differ) as M7.guest, and normalize to the key the build tool reads before storing request.spec. Add a test with both keys.

gate.observed?.guest?.git_identity === 'none',
'skip_git_identity_check, but the gate record does not show commits refused (X5: agent_can_commit no, git_identity none, both measured) (X12)',
);
} else if (req.has('X12') && s.skip_git_identity_check === true) {

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: the gate rules that the docs say apply under any profile are only partly checked outside benchmark.

The design (§8.1) says "X10 and X12 whenever the spec names a gate record or skips the git identity check, whatever the profile", and GATING-RULES X10 says "the gate record with that digest passed (X1)". Outside a profile that requires X1/X12:

  • X10 (lines 290-301) only checks that source_record_digest equals the image digest and that some JSON object was sent. gate.passed and gate.image.digest are never checked (those checks sit only under req.has('X1')). On base, a spec naming a gate record whose gate failed, or a record for a different image, is admitted. The check record then says X10 passed, and a gate record is stored for it. template-build.sh --gate-record refuses both cases, so the control plane admits what the host will refuse, which goes against "refuses early".
  • X12: skip_git_identity_check: true with no gate record on base adds no X12 result at all (the else if needs req.has('X12')). The host only checks X5 when given --gate-record, so neither side checks the skip.

Fix: when source_record_digest is present (any profile), also add X1 (gate.gate?.passed === true) and X1.image (gate.image?.digest === digest). Then either make X12 apply to every skip (refuse a skip that has no gate record) or change §8.1 and GATING-RULES to say that base allows an unbacked skip. Add tests for both on base.


/** The template id rule (M7); refused past 31 characters, never truncated. */
export const TEMPLATE_ID_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;
const IMAGE_RE = /^[^\s@]+@sha256:[0-9a-f]{64}$/;

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: IMAGE_RE (^[^\s@]+@sha256:…) accepts any non-space, non-@ text as the repository. That includes Images/X, -x, a//b, ../x, x:tag@sha256:… and control characters. registryOf then calls most of these <default>, so they pass registry under the default policy.

These are not valid references, so podman refuses them on the host. The cost is host time the policy promises to save ("a refused create costs no host time"). A repository starting with - also reaches podman pull "$PULL" / podman image exists "$PULL" without a --, so it is read as an option.

The name:tag@sha256: form is accepted, which is fine because the digest wins. But nothing says so, and the reuse key treats x:1@d and x@d as different builds.

Fix: validate against the distribution reference grammar: an optional host[:port]/, lowercase path components [a-z0-9]+(?:[._-][a-z0-9]+)* separated by /, and no tag (or strip the tag before the reuse key). Lowercase the host before allowedRegistries.includes, because a host written GHCR.io is refused today even when allowed. Add registryOf/M1 cases for these to the test.

if (!/^[a-z][a-z0-9-]{0,30}$/.test(n))
out.push(`profile name ${n} must match ^[a-z][a-z0-9-]{0,30}$`);
const e = pr?.envelope;
if (!Array.isArray(pr?.requires) || !pr.requires.every((r) => typeof r === 'string'))

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: requires takes any string, but checkCreate only acts on X1, X10, X11, X12, X14, X15. An admin who writes requires: ['X13'] or ['x11'] gets no error, and the profile silently enforces nothing extra. envelope.exact isn't validated either: {guestMb: "4096"} makes X15 refuse every create. Reject unknown ids (an exported list of the rule ids checkCreate knows) and check exact's fields as positive integers.

Comment thread docs/reference/http-api.md Outdated
`digest_mismatch`, `configRef_invalid`, `credential_required`, `credential_ambiguous`, `endpoint_unresolved`, `model_unavailable`), 401 (`token_required`,
`token_invalid`, `token_expired`, `unauthorized`), 403 `forbidden`, 404 (`session_not_found`, `config_bundle_not_found`,
`credential_not_found`, `turn_not_found`), 409 (`turn_not_cancellable`, `turn_not_claimable`), 410 `device_code_expired`, 428 `authorization_pending`, 429
`credential_not_found`, `template_not_found`, `turn_not_found`), 409 (`turn_not_cancellable`, `turn_not_claimable`), 410 `device_code_expired`, 428 `authorization_pending`, 429

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 control-plane error-code list here doesn't have this PR's codes: template_exists under 409, policy_refused as 422, and quota_exceeded under 429. The paragraph above names all three. Add them so the list matches errors.ts.

…per-subject lock

The review found the quota check was not atomic: the catalog serializes per
template id, but the quotas count across every id a subject owns, so
concurrent creates for different ids all read the same use and all passed.
The quota read and the build's write now run under one lock per subject
(a SubjectQueue per catalog), taken outside the catalog's id lock. A test
fires parallel creates under templates: 1 and parallel new builds under
buildsQueued, and expects exactly one admitted.

Refs rossoctl#737

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

The review asked for three changes to how a subject's use is counted:
- a template counts only while a build is registered or on its way there,
  so a template whose builds all failed or were cancelled no longer holds
  a slot that nothing could free;
- buildsQueued counts probing builds too, the host work still in flight;
- a build an admin adds to another subject's template is charged to the
  template's owner, under the owner's lock, not to the admin.
The policy type, openapi's Quota and GET /v1/quota, the changelog and the
lifecycle design say so. Tests cover the freed slot, a probing build and
an admin-added build.

Refs rossoctl#737

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

The review found the size envelope (and X15) could be bypassed: the policy
read guest_mb before guest_ram_mb, while the build tool reads only
guest_ram_mb, so a spec with guest_mb inside the envelope and a larger
guest_ram_mb passed the policy and built the larger guest. A spec with both
keys is now refused as M7.guest (even when equal), and the alias guest_mb
alone is stored as guest_ram_mb before the spec is recorded, kept for the
build or compared for reuse (normalizeSpec). The examples' test refuses a
sample with both; openapi, GATING-RULES M7 and the lifecycle design say so.

Refs rossoctl#737

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

The review found the gate rules the design applies whatever the profile
were only partly checked outside benchmark: a spec naming a gate record
on base was admitted when that record's gate failed or was for another
image, and a skip of the git identity check with no gate record added no
X12 result at all, so neither the control plane nor the build host
checked it. Now, under any profile, a spec that names a gate record (or a
create that sends one) also passes X1 (the gate passed) and X1.image (the
record is for this image); only X1.trusted stays the profile's. And X12
refuses any skip no gate record backs. Tests cover the three cases on
base; GATING-RULES X10/X12 and the lifecycle design §8.1 say so.

Refs rossoctl#737

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

The review found the image check accepted any non-space, non-@ text as the
repository (Images/X, -x, a//b, ../x, control characters, name:tag@digest),
which the build host then refuses after spending its time, and a leading
`-` would reach the host's podman calls as an option. M1 now takes the
distribution reference grammar: an optional host[:port]/ (a first
component with a `.` or `:`, or localhost), lowercase path components,
then @sha256:<64 hex>, at most 255 characters before the `@`, and no tag
beside the digest (so the reuse key never sees two spellings of one
image). registryOf lowercases the host, and allowedRegistries compares
case-insensitively, so GHCR.io matches ghcr.io. Tests list accepted and
refused references; openapi and GATING-RULES M1 say so.

Refs rossoctl#737

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…s on, and a whole-number exact envelope

The review noted that `requires` took any string, so `['X13']` or
`['x11']` was accepted and enforced nothing, and that `envelope.exact`
was unchecked, so `{guestMb: "4096"}` made X15 refuse every create.
policyProblems now refuses a rule id outside PROFILE_RULES (exported: the
ids checkCreate acts on, X1, X10, X11, X12, X14, X15) and an `exact` that
is not two positive whole numbers. openapi's Policy says the same.

Refs rossoctl#737

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

As the review asked, the list in http-api.md now has `template_exists`
under 409, `policy_refused` as 422 and `quota_exceeded` under 429, as in
errors.ts and the paragraph above it.

Refs rossoctl#737

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…hecked against the templates quota

A template whose builds all failed, were cancelled or were retired holds
no templates slot, but the templates quota was checked only for a new
id. A subject could bring such templates back with
POST /v1/templates/{id}/builds, or a create on its own id, and go past
quota.templates. The check now applies whenever the template does not
hold a slot yet. Test: checks the templates quota when a template that
holds no slot gets a new build.

Refs rossoctl#737

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

The examples test still matched images with the old pattern (any
non-space, non-@ text, then a digest), so a sample the policy refuses,
such as Images/x@sha256:..., passed it. The check now uses the
distribution reference grammar as the policy's isPinnedImage does (an
optional host[:port]/, lowercase path components, no tag, at most 255
characters before the @), and the test runs the filter on references
the policy accepts and refuses.

Refs rossoctl#737

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

Since a failed or cancelled-only template holds no templates slot, a
create-then-cancel loop freed both templates and buildsQueued every
time, so nothing bounded the template ids, catalog documents and
provenance streams one subject opens. A new per-subject quota, owned,
counts the ids a subject owns in any status and is checked for a new id
only, so the subject's own ids still take new builds. A policy that does
not set it gets 200 (DEFAULT_OWNED); a stored policy without the field
stays valid. GET /v1/quota shows it, and quota_exceeded names it.
Tests: bounds the template ids a subject owns in any status, applies
the default owned quota to a policy that does not set one, and the
policy check refuses a malformed owned.

Refs rossoctl#737

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
It counts template ids in any status, retired ones included, and a
retired id is spent for good; so a user who retires as they go reaches
it in time, and only an admin raises it. The CHANGELOG and design §4
say so.

Refs rossoctl#737

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

Copy link
Copy Markdown
Member Author

On the owned quota: it counts retired ids too, and a retired id is spent, so it works in effect as a lifetime cap per subject. An admin raises it per subject; it becomes the fourth counter of PUT /v1/quota in #786.

Thanks for the follow-up review and the re-review. The open points are addressed on the new head (cd85927), in 3 commits:

  • Templates quota: a new build of a template that holds no slot is now checked against the quota. This was the must-fix.
  • Template ids: a new owned quota bounds the ids a subject owns in any status, so a create-then-cancel loop stops.
  • Examples test: its M1 check now uses the policy's reference grammar.

Thread by thread:

packages/control-plane/src/sandbox-handlers.ts:537 (must-fix; bot thread, and the review summary)

"the templates quota is only checked when !cur. So a subject can bring such a template back ... and go over quota.templates."

Fixed in 2687244. The templates quota is now checked whenever the template does not hold a slot yet. That covers a new id, and also an existing template whose builds all failed, were cancelled or were retired. The check no longer runs only for !cur. A template that holds its slot still takes new builds at the limit. Test: checks the templates quota when a template that holds no slot gets a new build. It follows the probe's steps: create, cancel, create other-template, then a new build of the first template through POST /v1/templates/{id}/builds and through a create on its own id. Both are refused with quota: templates, and GET /v1/quota shows templates.used: 1. Before the fix, this test fails. openapi's Quota, the changelog and the design §4 say so.

packages/control-plane/src/sandbox-handlers.ts:422 (suggestion)

"nothing bounds how many template ids a subject owns ... Consider a separate cap on ids owned in any status"

Fixed in cd85927, with a separate cap. A new per-subject quota, owned, counts the template ids a subject owns in any status, failed or cancelled-only ones included. It is checked for a new id only. The subject's own ids therefore still take new builds, and a failure never locks the subject out of rebuilding them. A create-then-cancel loop frees templates and buildsQueued, but never owned. The field is optional in Quota. A policy that does not set it gets 200 (DEFAULT_OWNED), so a stored policy from before this change stays valid. policyProblems refuses an owned that is not a whole number. GET /v1/quota shows owned, and quota_exceeded names it as quota: owned. Tests:

  • bounds the template ids a subject owns in any status: a create-then-cancel loop stops: the refused new id leaves no catalog document and no provenance stream;
  • applies the default owned quota to a policy that does not set one;
  • cases for a malformed owned in the PUT /v1/policy validation test.

openapi (Quota, Error.quota, GET /v1/quota), the changelog and the design §4 and §8 say so. Until a delete or retire route lands, a subject at the owned limit can still rebuild its own ids but cannot open new ones.

deploy/sbx/template-onboarding/tests/examples.test.sh:20 (bot, nit)

"the M1 check here still uses the old ^[^\s@]+@sha256: pattern"

Fixed in 9ebdbed. The test now checks M1 with the distribution reference grammar, as the policy's isPinnedImage does:

  • an optional host[:port]/: a first component with a . or a :, or localhost;
  • lowercase path components;
  • no tag;
  • @sha256:<64 hex>, with at most 255 characters before the @.

The test also runs the filter on references the policy accepts (images/x, ghcr.io/a/b-c, GHCR.io/x, localhost:5000/x) and refuses (Images/X, -x, a//b, ../x, x:tag, ghcr.io/x:1, a missing or short digest, an over-long name). So a sample such as Images/x@sha256:… now fails the test. The test passes on bash 5 and bash 3.2.

deploy/sbx/template-onboarding/tests/examples.test.sh:22 (bot, must-fix; outdated)

"this jq filter now fails for every spec"

Fixed in cbec01c (earlier round): the guest-size binding is parenthesized. The bot's re-review confirmed it, and deploy-scripts passes.

Earlier threads (outdated)

  • packages/control-plane/src/sandbox-handlers.ts:495, the quota check isn't atomic (and the bot's thread on the same line): fixed in 6b2cf3b and 36fdba0 (earlier round).
  • packages/control-plane/src/sandbox-handlers.ts:415, how usage() counts: fixed in 36fdba0 (earlier round). Point 1's rebuild bypass is closed by 2687244 above, and its unbounded-ids follow-up by cd85927.
  • packages/control-plane/src/template-policy.ts:177, the guest-size alias: fixed in a187e99 (earlier round).
  • packages/control-plane/src/template-policy.ts:337, X10/X12 outside benchmark: fixed in 75590d4 (earlier round).
  • packages/control-plane/src/template-policy.ts:79, IMAGE_RE: fixed in 142b96f (earlier round). The examples test now matches it (9ebdbed).
  • packages/control-plane/src/template-policy.ts:378, requires and exact validation: fixed in 76a9d70 (earlier round).
  • docs/reference/http-api.md:220, the error-code list: fixed in 68f0a9e (earlier round).

Review summary note

"on base, X12 can be satisfied by a self-written gate record, because X1.trusted stays a profile requirement ... not blocking."

Not changed. As the note says, this matches the build host's --gate-record check, and the docs claim no more than that.

New tip: cd85927

Assisted-By: Claude Code

@pdettori
pdettori merged commit 6c08f5d into rossoctl:main Nov 13, 2026
17 checks passed

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

Re-review at ef65b8a.

Since cbec01c there are 4 new commits:

  • 2687244b checks the templates quota on a new build of a template that holds no slot.
  • 9ebdbed2 makes the examples M1 check use the policy's reference grammar.
  • cd85927c adds an owned quota: template ids owned in any status, checked for new ids only, default 200.
  • ef65b8ac updates the docs.

Prior findings:

  • Fixed: templates quota bypass through a new build of a failed or cancelled-only template. The check is now !holdsSlot && u.templates >= quota.templates, and there is a new test for it. With the old !cur condition restored, that test fails (positive control).
  • Fixed: the examples M1 check now uses the distribution reference grammar, with accept and refuse cases taken from the policy's own test. I also tried a reference with an embedded newline: refused.
  • Fixed earlier (still holds): concurrent creates for different ids are serialized per subject (quotaLock), and holds the quotas under concurrent creates for different ids passes.
  • Fixed earlier (still holds): the M7 jq precedence fix.

No new must-fix. There is one suggestion inline: a stored policy that sets templates above 200 but leaves out owned gets a lower cap than it asked for, without any warning.

All checks pass. Ready for human review.

  • Author: webchang (MEMBER — maintainer)
  • Areas reviewed: the holdsSlot templates check, the new owned quota in createBuild, usage and getQuota, ownedLimit/DEFAULT_OWNED and policyProblems validation, the examples M1 grammar in jq, and the matching openapi 1.5.0, CHANGELOG and spec text
  • Agent/IDE config (.claude/.vscode): none
  • Commits: 28 commits, all signed-off: yes
  • CI status: all 17 checks pass, including deploy-scripts, deploy-scripts-bash32, k8s-kind-e2e and DCO

Verified by:

  • npx vitest run test/template-create.test.ts at head: 50/50 pass
  • Positive control: with !cur restored in place of !holdsSlot, checks the templates quota when a template that holds no slot gets a new build fails
  • Full control-plane suite against a local redis-server: 62 files passed, 1 skipped (1328 tests passed, 3 skipped). Without Redis, only the Redis-backed files fail (ECONNREFUSED).
  • tsc --noEmit is clean, and prettier --check is clean on packages/control-plane and docs/api
  • examples.test.sh on jq 1.8.2 passes, including the new M1 accept/refuse cases
  • tsx probe: policyProblems accepts quota: {templates: 500, buildsQueued: 10, active: 8} with no error, and ownedLimit returns 200 for it

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

export const DEFAULT_OWNED = 200;

/** The `owned` quota in force: the policy's, else DEFAULT_OWNED. */
export const ownedLimit = (q: Quota): number => q.owned ?? DEFAULT_OWNED;

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 policy without owned silently caps a subject below its own templates quota.

ownedLimit falls back to 200 no matter what templates is. A tsx probe at head, with quota: { templates: 500, buildsQueued: 10, active: 8 }, gives policyProblems(...) = [] and ownedLimit(...) = 200. So an admin who raises templates to 500 and leaves owned out has the 201st create refused with quota: 'owned', even though GET /v1/quota shows templates.used well under 500. The same thing happens when owned is set explicitly below templates.

Suggested fix: default to Math.max(DEFAULT_OWNED, q.templates), e.g. q.owned ?? Math.max(DEFAULT_OWNED, q.templates). Also have policyProblems refuse owned < templates when both are set, or document that owned caps templates. Add a test case for the default.

@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

Follow-up at ef65b8a (cbec01c..ef65b8a, 4 commits, fast-forward). It closes everything we still had open:

  • must-fix (sandbox-handlers.ts:537), fixed in 2687244: the templates quota is now checked whenever the template holds no slot (!holdsSlot), not just when !cur. A failed or cancelled-only template can no longer come back past quota.templates. The check stays inside the owner's quotaLock. There's a regression test that covers both routes (createTemplateBuild and create-on-own-id).
  • suggestion (sandbox-handlers.ts:422), fixed in cd85927: a new owned quota counts ids in any status. It is checked for new ids only, defaults to 200 (DEFAULT_OWNED), is validated in policyProblems, and shows up in GET /v1/quota, openapi, the CHANGELOG and the design §4/§8. The test shows that the refused id leaves no doc and no provenance stream. ef65b8a documents that this is effectively a lifetime cap (retired ids count), which an admin raises via #786.
  • clawgenti's M1 nit (examples.test.sh), fixed in 9ebdbed: the test now uses the reference grammar, with positive and negative cases.

One new nit (below).

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane quota/policy), tests, Shell (examples.test.sh), openapi/docs
Agent/IDE config (.claude/.vscode): none
Commits: 4 new, all signed-off: yes
CI status: all 17 checks pass (check, k8s-kind-e2e, deploy-scripts, deploy-scripts-bash32, lint, codeql, trivy, …)

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

# distribution reference grammar, an optional host[:port]/ (a first component with a `.` or a `:`,
# or localhost), lowercase path components, no tag, pinned by digest, at most 255 characters before
# the `@`.
M1_JQ='(split("@")[0] | length) <= 255 and test("^(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)(?:\\.(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?))+(?::[0-9]+)?|(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?):[0-9]+|localhost(?::[0-9]+)?)/)?[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*(?:/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)*@sha256:[0-9a-f]{64}$")'

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 jq M1 filter is a little looser than isPinnedImage. The policy treats a first component that contains . or : as a host and then requires DOMAIN_RE. The jq alternation instead falls back to treating it as a path component, so a_b.c/x@sha256:… passes this check while the policy refuses it (registry/M1). This is harmless for the shipped examples. A negative case for it would pin the behaviour (or anchor the path branch so a dotted or colon first component must be a valid host).

webchang added a commit to webchang/moca that referenced this pull request Nov 13, 2026
Brings rossoctl#766's quota changes: the templates quota is checked whenever a
template holds no slot, and the new per-subject owned quota.

Conflicts:
- packages/control-plane/src/sandbox-handlers.ts (getQuota): kept this
  branch's live-lease count for active and added owned from rossoctl#766.
- docs/api/openapi.yaml (Error.quota): enum is templates, buildsQueued,
  owned and active, the description names both create and activation
  quotas, and the readiness property is kept.
- docs/api/openapi.yaml (GET /v1/quota description): kept the live
  activation lease wording and added owned.

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
Brings rossoctl#766's quota changes (the templates quota for a template holding
no slot, and the owned quota) through pr/i19-activation.

Conflicts: none.

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
Brings rossoctl#766's quota changes (the templates quota for a template holding
no slot, and the owned quota) through pr/i21-memory-placement.

Conflicts: none.

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
Brings rossoctl#766's quota changes (the templates quota for a template holding
no slot, and the owned quota) through pr/i19-activation.

Conflicts: none.

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
Brings rossoctl#766's quota changes (the templates quota for a template holding
no slot, and the owned quota) through pr/i26-retire.

Conflicts: none.

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
Brings rossoctl#766's quota changes (the templates quota for a template holding
no slot, and the owned quota) through pr/i26-retire.

Conflicts:
- packages/control-plane/src/template-policy.ts (policyProblems): kept
  this branch's quota and quotaBySubject validation (an override holds
  the three counters alone) and added rossoctl#766's check of the default's
  optional owned.
- packages/control-plane/src/sandbox-handlers.ts (getQuota): kept
  quotaFor and quotaSource, added owned.
- docs/api/openapi.yaml (GET /v1/quota description): both texts.

Resolved beyond the conflict markers, where the two sides meet:
- createBuild checks owned against the deployment default's
  (ownedLimit(pol.quota)), not quotaFor's: an override holds no owned,
  so it would otherwise have fallen to 200 whatever the default says.
- PUT /v1/quota/default keeps the default's owned, which the write
  does not set, instead of dropping it.
- ?expect= ignores an owned key: the default policy now carries owned,
  so the quota a client reads from GET /v1/policy (as mocactl sends it)
  was refused as a key beyond the three.
- openapi PUT /v1/quota/{subject} says both.

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
Brings rossoctl#766's quota changes (the templates quota for a template holding
no slot, and the owned quota) through pr/i19-activation.

Conflicts: none.

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
Brings rossoctl#766's quota changes (the templates quota for a template holding
no slot, and the owned quota) through pr/i27-combined-plane.

Conflicts: none.

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
…per-subject lock

The quota check was not atomic: the catalog serializes per template id, but the quotas count
across every id a subject owns, so concurrent creates for different ids all read the same use and
all passed. The quota read and the build's write now run under one lock per subject (a
SubjectQueue per catalog, quotaLock), taken outside the catalog's id lock, always in that order.
The lifecycle spec says so.

Test: holds the quotas under concurrent creates for different ids (three parallel creates for
distinct ids under `templates: 1`, exactly one admitted; two parallel new builds with one
buildsQueued slot left, exactly one admitted). It fails with the fix reverted.

(cherry picked from commit 6b2cf3b)

Ports rossoctl#766 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
…ged to the owner

Three problems with how usage() counted:
- A template counted while any build was not retired, so a template whose builds all failed or
  were cancelled held a slot for good. It now counts only while one of its builds is registered or
  on its way there (REUSABLE).
- buildsQueued counted queued and building builds but not probing ones; it now counts the
  CANCELLABLE set (queued, building, probing).
- A build an admin adds to another subject's template was charged to the admin. It is charged to
  the template's owner, under the owner's quota lock and against the owner's quota (its override,
  else the default).

The Quota type, openapi's Quota schema and GET /v1/quota, the API changelog and the lifecycle spec
say what is counted. Comments in createBuild no longer name internal register ids.

Tests (fail with the fix reverted): counts a probing build as queued, and charges an admin-added
build to the owner; frees the template slot of a template whose only build was cancelled.

(cherry picked from commit 36fdba0)

Ports rossoctl#766 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
… as guest_ram_mb

The size envelope could be bypassed through the guest-size alias: the policy read
`guest_mb ?? guest_ram_mb`, the build tool reads only `guest_ram_mb`, so a spec with a small
guest_mb and a large guest_ram_mb passed M7 and the envelope and then built the large guest.

A spec with both keys is now refused as M7.guest, even when the two are equal. When the alias
guest_mb comes alone, it is renamed to guest_ram_mb (normalizeSpec) before the spec is recorded in
the create record, kept as request.spec or used in the reuse key, so the policy and the build
always read one number. openapi, the API changelog, GATING-RULES M7 and the lifecycle spec say so.
The tests' fixtures that sent both keys now send the guest size once.

Tests (fail with the fix reverted): refuses both guest-size keys (differing, and equal) with 422
policy_refused M7.guest; stores the guest_mb alias as guest_ram_mb, the key the build reads, and
reuses across the two.

(cherry picked from commit a187e99)
(cherry picked from commit 29be5d7)

Ports rossoctl#766 and rossoctl#774 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
…ign says

The gate rules the design applies whatever the profile were only partly checked outside
benchmark: a spec naming a gate record on base was admitted when that record's gate failed or was
for another image, and a skip of the git identity check with no gate record added no X12 result
at all, so neither the control plane nor the build host checked it.

Under any profile, a spec that names a gate record (or a create that sends one) now also passes X1
(the gate passed) and X1.image (the record is for this image), and the offline-floor check where
the profile asks for it; only X1.trusted stays the profile's. X12 refuses any skip no gate record
showing commits refused backs. The self-attestation rules are unchanged. GATING-RULES X10/X12, the
lifecycle spec §8.1 and the API changelog (with the upgrade note for base) say so.

Tests (fail with the fix reverted): applies X10 and X12 under base too: refuses a gate record that
failed; a gate record for another image; skip_git_identity_check with no gate record.

(cherry picked from commit 75590d4)
(cherry picked from commit 59f8357)

Ports rossoctl#766 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
…hosts compare case-insensitively

M1's IMAGE_RE accepted any non-space, non-@ text as the repository, so `Images/X`, `-x`, `a//b`,
`../x`, a tag beside the digest or control characters passed the control plane and were left to
the build host to refuse (or misread). isPinnedImage now takes the distribution reference grammar:
an optional host[:port]/ (a first component with a `.` or a `:`, or `localhost`, checked as a
domain), then lowercase path components, then @sha256:<64 hex>, with at most 255 characters before
the @. A tag beside the digest is refused, so the reuse key never sees two spellings of one image,
and a path never starts with `-`. registryOf lowercases the host, and allowedRegistries is compared
case-insensitively. openapi, GATING-RULES M1 and the API changelog say so.

Tests (fail with the fix reverted): M1 takes the distribution reference grammar, pinned by digest,
no tag (accepted and refused references); reads the registry host of an image reference (GHCR.io).

(cherry picked from commit 142b96f)

Ports rossoctl#766 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
…s on, and a whole-number exact envelope

`requires` took any string, so `['X13']` or `['x11']` was accepted and enforced nothing, and
`envelope.exact` was unchecked, so `{guestMb: "4096"}` made X15 refuse every create.
policyProblems now refuses a rule id outside PROFILE_RULES (exported: the ids checkCreate acts on,
X1, X10, X11, X12, X14, X15) and an `exact` that is not two positive whole numbers; the
self-attestation checks of a profile are unchanged. openapi's Policy has an enum on `requires`,
and `exact`'s fields are required with a minimum of 1. The API changelog's upgrade note says that
a stored policy failing the new checks fails closed when read, so it is to be fixed before
upgrading.

Test (fails with the fix reverted): PUT /v1/policy refuses a rule id no check acts on, and an exact
envelope not of whole numbers (X13, x11, a string guestMb, a missing vcpus, zero, null).

(cherry picked from commit 76a9d70)
(cherry picked from commit 0cbcfb9)

Ports rossoctl#766 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
…template's stream the caller may write

A refused create on any well-formed id wrote a `check` record on that id's stream: on another
subject's template (growing a stream its owner cannot stop), and on an id no template holds, which
let any enrolled subject open provenance streams without bound, counted by no quota.

A refusal is now recorded as a `check` only on the stream of a template that exists and whose
stream the caller may write: its own, or an admin's when adding a build. A refusal on another
subject's id is only answered. A refusal on an id no template holds writes one line to the capped
audit stream instead, through the best-effort audit helper, as `template_create_refused`, naming
the subject, the templateId and the failed rules (the audit entry gains `templateId` and
`rules`). openapi, the API changelog and the lifecycle spec say so.

Test (fails with the fix reverted): records a refusal on the caller's own id, never on a new id or
another subject's (a refusal on a new id leaves one audit entry and no provenance stream).

(cherry picked from commit 4f84d23)
(cherry picked from commit 3ed43b4)
(cherry picked from commit 118a1ee)

Ports rossoctl#766 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
…hecked against the templates quota

The templates quota was only checked for a new id (`!cur`). A template whose builds all failed,
were cancelled or were retired holds no slot (usage does not count it), so a subject could bring
such templates back with new builds and go past quota.templates. The quota is now checked whenever
the template does not hold a slot yet: a new id, or one whose builds all failed, were cancelled or
retired. A template that holds its slot still takes new builds at the limit. openapi's Quota, the
API changelog and the lifecycle spec say so.

Test (fails with the fix reverted): checks the templates quota when a template that holds no slot
gets a new build (create, cancel, create another template, then a new build of the first through
POST /v1/templates/{id}/builds and through a create on its own id: both refused `quota: templates`).

(cherry picked from commit 2687244)

Ports rossoctl#766 review fixes

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
webchang added a commit that referenced this pull request Nov 14, 2026
The host agent stands on both parents: the template store and self-serve create (#766, with #760 and
#756) and the template build tooling (#740's branch, with #757). No conflicts.

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.

4 participants