Repository navigation
feat(control-plane): keep sandbox templates in a store, with builds, tags, readiness and a read API - #760
Conversation
…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]>
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]>
clawgenti
left a comment
There was a problem hiding this comment.
Clawgenti Code Review
Summary
The core of the store is sound. Read routes and sandbox create both resolve through one visibility check, so a private template and a missing one look the same to a non-owner (404 template_not_found on reads, 400 unknown_template at create). IDs are regex-guarded before they become file names, catalog writes are temp + fsync + rename, and the one-time import resumes correctly from either crash point. Two findings are must-fix. Both come from the new provenance appends being on the request's critical path:
createSandbox/deleteSandboxfail after committing.sandboxCreated/sandboxEndedare awaited afterstore.create/markDeleted, and they are not best-effort, unlikeaudit. A provenance error (ENOSPC on the 1Gi PVC, a malformed head) makes the client get a 500 for a sandbox that exists and counts against quota. On delete, the retry seesalready, so the terminated record is never written.- The janitor read depends on the chain.
GET /v1/janitor/sandboxesawaitsrecordExpiries, which re-reads and verifies whole chains, so any chain error stops disk reclaim on every host.
The rest are suggestions/nits: an unserialized check-then-append in recordExpiries, the import's "env list differs" warning missing a changed worker, the seed's workspace check skipping the hardened git invocation, and an ApiError during --seed dropping the id from stdout.
Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane catalog, provenance, sandbox handlers, routes; mocactl templates/create), Shell (setup.sh, tests), Kustomize/K8s (ocp-sbx template-store overlay), Python (provenance verify/redact), OpenAPI/docs
Agent/IDE config (.claude/.vscode): none
Commits: 7 commits (incl. #756's two and a merge of main), all signed-off: yes
CI status: passing
Verified by: a static read of the PR head, cross-checking each claim in the PR body against sandbox-handlers.ts, template-catalog.ts, provenance.ts and the tests. I ran no code from the PR.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
| throw new CpError('name_conflict', `you already have a live sandbox named '${rec.name}'`); | ||
| } | ||
| await audit(deps, p.sub, id, 'sandbox_created'); | ||
| await sandboxCreated(deps, rec, p.sub); |
There was a problem hiding this comment.
must-fix: This append runs after store.create(...) has committed the sandbox, and unlike audit (auditBestEffort) it is not best-effort. Any provenance error makes the handler return 500 for a sandbox that already exists. That includes ENOSPC on the 1Gi PVC, an EIO, or head() throwing on a malformed head. The client never learns the id, and the sandbox still counts against maxPerSubject / maxTotal until it expires. A retrying client can hit the quota with sandboxes it never saw.
Suggested fix: make the append best-effort (catch and log, like audit). Alternatively, record before committing the store write and reconcile on failure. This matters now because #736 turns the store on in deployments with a small fixed-size volume.
| if (outcome === 'deleted') await audit(deps, ctx.principal!.sub, rec.id, 'sandbox_deleted'); | ||
| if (outcome === 'deleted') { | ||
| await audit(deps, ctx.principal!.sub, rec.id, 'sandbox_deleted'); | ||
| await sandboxEnded(deps, rec, ctx.principal!.sub, 'deleted', now); |
There was a problem hiding this comment.
must-fix: This has the same problem as createSandbox, plus a lasting effect. markDeleted has already returned deleted when sandboxEnded throws, so the caller gets a 500. The retry is idempotent but now sees outcome already, which skips this branch. The terminated/deleted record is therefore never written, and the template's chain shows the sandbox as still running from then on. recordExpiries only covers deletedAt === undefined records, so it does not repair this.
Suggested fix: make the append best-effort, or have recordExpiries also backfill terminated records for deleted sandboxes missing one.
| if (v.state === 'ready') live.push({ wsk: v.wsk, wrk: v.worker }); | ||
| else terminated.push({ wsk: v.wsk, wrk: v.worker, terminatedAt: v.terminatedAt! }); | ||
| } | ||
| await recordExpiries(deps, all, now); |
There was a problem hiding this comment.
must-fix: GET /v1/janitor/sandboxes is the hosts' disk-reclaim read, and now it awaits recordExpiries. Any error there turns a response that was already computed into a 500. Possible errors: chain() rejecting a record that does not match its digest, a head/record count mismatch, or ENOSPC on append. So one bad chain stops every host's janitor from freeing workspace disk.
Suggested fix: wrap recordExpiries in try/catch and log, or run it without awaiting its failure into the response.
| for (const r of expired) byTemplate.set(r.template, [...(byTemplate.get(r.template) ?? []), r]); | ||
| for (const [template, rs] of byTemplate) { | ||
| const ended = new Set( | ||
| (await deps.provenance.chain(`template/${template}`)) |
There was a problem hiding this comment.
suggestion: The check (read the chain, build ended) and the act (sandboxEnded → append) are not under the stream's queue; only append is serialized. Several KVM hosts' janitors hit this endpoint, so two overlapping sweeps can both see no terminated record and both append expired for the same sandbox. That breaks the "once per sandbox" rule in the doc comment above. Separately, every sweep re-walks and re-hashes the whole chain for each template that still holds a retained expired sandbox, so the cost grows with the template's history.
Suggested fix: do the check and the append under the stream's SubjectQueue, or keep a per-sandbox marker (a field on the sandbox record, or an in-memory set seeded once).
| const have = await this.readAll(); | ||
| if (await this.imported()) { | ||
| const ids = new Set(have.map((d) => d.id)); | ||
| const differs = |
There was a problem hiding this comment.
suggestion: After the import, the "differs" warning compares only the count and the ids. Suppose an operator edits SH_SANDBOX_TEMPLATES to move a template to a new worker (the versioned-update flow), or changes its tools or description. They get no warning, and new sandboxes keep routing to the stored, possibly retired, worker.
Suggested fix: also compare importedBuildId(t.worker) against the stored doc's default tag, plus description and tools, and name the template in the warning.
| } | ||
|
|
||
| /** The workspace check after a seed: is it a repository, is its tree clean, and its HEAD. */ | ||
| const WORKSPACE_CHECK = |
There was a problem hiding this comment.
suggestion: The rest of sbx's sync code runs git through G (push.ts: -c safe.directory=* -c core.hooksPath=/dev/null …) because the workspace may be another uid's. This check runs plain git. If the seed leaves a tree owned by another uid, git rev-parse fails with "dubious ownership" and the check prints nogit. create --seed then reports clean: null and sets no baseline, so a later pull/rm treats the seeded tree as the user's work. Plain git status also honours repo-local config such as core.fsmonitor.
Suggested fix: build the check from G and q(WORKSPACE) instead of hardcoding /workspace.
| let seeded: SeedResult | undefined; | ||
| if (seed) { | ||
| const r = await seedSandbox(c, s, seed.factory).catch((err: unknown) => | ||
| err instanceof ApiError ? Promise.reject(err) : sandboxFailureText(err), |
There was a problem hiding this comment.
nit: An ApiError during seedSandbox (e.g. getTemplate 404/401) is re-thrown to failed(c, err). The sandbox exists, but --json callers get no JSON and plain callers get no id on stdout; only the stderr "created …" line names it. That falls short of "a failure there is exit 1, the sandbox kept and named".
Suggested fix: handle ApiError like the string branch: print {...s, seed: {error}} or the id, then return failed.
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Reviewed this PR's own range only (1100f09..7583059, commits 50f88f2, 7f107a7, 82100fd and 7583059; the provenance commits from #756 were approved earlier) and the merge db984e9.
Summary. The template catalog is cleanly layered. Authz on the new read routes is correct: requireEnrolled is applied on every route, private templates answer 404 to non-owners (no existence oracle), owner-null imports are deployment-visible, and worker ids never reach the wire. resolveForUse applies the same visibility rule on create. The overlay component renders as intended, both alone and together with egress-credentials. I found no blocking issues. The suggestions are a silent no-warning case when the env list changes, the crash-resume provenance edge, per-read cost on the readiness path, and a lost sandbox id on create --seed.
- Author: webchang (MEMBER, maintainer)
- Areas reviewed: control-plane template-catalog / sandbox-handlers / routes / errors / main wiring, openapi + CHANGELOG + http-api/configuration docs, spec §1-§4, deploy/sbx setup.sh
SBX_TEMPLATE_STORE+ocp-sbx/template-storecomponent + tests, mocactlsbx templates show/create --seed, merge resolution of docs/reference/configuration.md - Agent/IDE config: none
- Commits: 4 own (+1 merge), all signed-off: yes
- CI status: passing
Verified: kubectl kustomize of the ocp-sbx overlay with both components renders both RWO 1Gi PVCs in moca-sbx, strategy: Recreate with no rollingUpdate, SH_PROVENANCE_DIR=/var/lib/moca/templates mounted from moca-sbx-templates, and the projected credentials volume unchanged. setup.sh's switch is strictly validated (''|0|1) and emits only fixed component paths, so there is no quoting exposure. PRESENCE_KEY matches harness recordsKey(). The route params are decodeURIComponent-ed, and FileTemplateCatalog.readFile gates ids on TEMPLATE_ID_RE before any path join, so there is no traversal. The merge's configuration.md resolution keeps every row from main and adds exactly the two new rows (normalised line-set comparison against both parents and the merge base). Openapi Template/TemplateBuild/Sandbox fields match templateBody/buildBody/sandboxBody.
| const have = await this.readAll(); | ||
| if (await this.imported()) { | ||
| const ids = new Set(have.map((d) => d.id)); | ||
| const differs = |
There was a problem hiding this comment.
suggestion: The "env list differs" check compares only the count of owner-null docs and the set of ids, so a changed worker, description or tools for an existing id is ignored silently. Changing a template's worker in SBX_TEMPLATES_FILE is the documented versioned-update workflow today (sandbox-handlers.test.ts "keeps a sandbox on the worker it was created with when its template moves"). With SBX_TEMPLATE_STORE=1 that redeploy now leaves the catalog pointing at the old worker, new sandboxes route there (readiness inactive, first Exec waits on the relay), and nothing in the log says why. The spec (§3.1) and the CHANGELOG both promise a warning when the list differs.
Fix: compare each declared entry against its imported doc, i.e. importedBuildId(t.worker) against doc.tags.default, plus description and tools, and warn naming the ids that differ. Add a test that changes only a worker.
| if (!h) return null; | ||
| const rec = await this.provenance.get(h.head); | ||
| const body = rec?.body as { source?: unknown } | undefined; | ||
| return rec?.kind === 'create' && body?.source === 'SH_SANDBOX_TEMPLATES' ? h.head : null; |
There was a problem hiding this comment.
suggestion: importedCreate reuses any create record from SH_SANDBOX_TEMPLATES at the head of the stream without checking that its body matches the entry being imported. Scenario: a crash between appendCreate and write, then the operator fixes the env list (a new worker for that id) before the restart. The resumed import writes a doc whose build is importedBuildId(newWorker), but its provenance digest names a record whose body says buildId: imported:<old> and worker: <old>. The chain then disagrees with the catalog it is supposed to attest.
Fix: reuse the record only when body.buildId === importedBuildId(t.worker) and description and tools are equal. Otherwise refuse the start with a clear error, or append a new record. Separately, markImported fsyncs the marker file but not the catalog/ directory after the doc renames. For the 'marker last' ordering to hold across power loss, fsync the directory before creating the marker (and after it).
| const inUse = new Map<string, number>(); | ||
| const lastUsed = new Map<string, number>(); | ||
| const now = seconds(deps); | ||
| for (const r of await deps.sandboxes.listAll(now)) { |
There was a problem hiding this comment.
suggestion: readinessFacts runs deps.sandboxes.listAll(now) on every template read: GET /v1/templates, /{id}, /builds and /builds/{build}. That is a ZRANGE over the all-sandboxes index plus a read of every record, retained ones included. The template routes are open to every enrolled subject and are the existence check a client is expected to poll (§3.3: "a client polling GET /v1/templates/{id} sees queued -> ... -> registered"), so the cost per request is O(all sandboxes in the deployment), and any user can trigger it. With SWE-bench-scale counts (the goal in §1) a polling loop turns into a Redis load amplifier.
Fix: count only the live index for inUse and keep lastUsed as a per-worker value written at create (e.g. an HSET worker -> createdAt in the create script), or at least cache the facts for a second or two. GET /v1/templates/{id}/tags already skips this, which is right.
| ); | ||
| let seeded: SeedResult | undefined; | ||
| if (seed) { | ||
| const r = await seedSandbox(c, s, seed.factory).catch((err: unknown) => |
There was a problem hiding this comment.
suggestion: With --seed, an ApiError from seedSandbox (from getTemplate or the token mint in openExec, e.g. a 404 template_not_found after the template was retired, or a 429) is rethrown into the outer catch and reported by failed(). The sandbox was already created, but its id is never printed to stdout, and --json prints nothing. A script then has no handle on the sandbox it just made, and the sandbox counts against the caller's quota until it expires. That contradicts the doc comment ("a failure there is exit 1, the sandbox kept and named").
Fix: handle every seed failure in one place. Print s.id (or {...s, seed: {error}} with --json) before returning exit 1, and keep the ApiError-to-exit-code mapping only for the message on stderr.
| const id = sandbox.template.split(/[@:]/)[0]!; | ||
| const t = await c.api.getTemplate(id); | ||
| const b = | ||
| t.builds.find((x) => sandbox.buildId && x.buildId === sandbox.buildId) ?? |
There was a problem hiding this comment.
nit: When the served buildId is no longer in t.builds (a build retired or removed between create and this read), this falls back to the default tag's build. That runs a different build's seed, which is exactly what the doc comment says it never does ("read ... never the newest"). Since --template ID@BUILD exists to pin a build, fall back only when sandbox.buildId is null (an older control plane), and otherwise fail with "the served build is gone". getTemplateBuild(id, buildId) would also be the narrower read here.
| * its catalog is empty. | ||
| */ | ||
| function catalog(deps: CpDeps): TemplateCatalog { | ||
| return deps.templates ?? new MemoryTemplateCatalog(deps.config.sandbox?.templates ?? []); |
There was a problem hiding this comment.
nit: With no store wired, catalog() builds a new MemoryTemplateCatalog on every request with the default nowS = 0, so every imported build reports createdAt: 0 and every tag assignedAt: 0 (epoch 1970) through the read API on deployments without SH_PROVENANCE_DIR, which is the default path. Build it once (or memoize it per deps.config) with the process start time, or document 0 as "unknown" in openapi (createdAt is declared a plain integer of epoch seconds).
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. The create record keeps this tree's `seed` field. On a catalog imported before this change (no marker), the first start resumes once: an env-list template the catalog does not hold is imported then, and the marker is written. Test: resumes an import a crash cut short: the missing templates, no second create record (the second document and the marker missing; both templates after the restart, exactly one `create` per stream, the reused record named by the document). It fails with the fix reverted. (cherry picked from commit 7583059) Ports rossoctl#760 review fixes Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Rong Chang <[email protected]>
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]>
… stderr if it never listens The test waited 5 s (50 x 0.1 s) for the mock's 'listening' line. On a busy CI runner, node's cold start outlasted that twice (#760, #772). The port then stayed empty, and every later check ran curl against port 80, failing 80-odd checks with nothing about the cause. Wait up to 30 s, stop early if the mock exits, and when it never listens fail once with its stderr. Closes #826 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
Closes #736. Stacked on #756 (the provenance chain, #730): this branch contains #756's two commits, and its own change is the last 4 commits. Once #756 merges, only those four remain.
What it does: sandbox templates are kept in a control-plane store, with builds, tags, readiness and a read API. Four signed-off commits:
setup.sh SBX_TEMPLATE_STORE: puts the store on a volume, plus a template-store component for the OpenShift overlay (a 1Gi RWO PVC asSH_PROVENANCE_DIR,Recreatestrategy).sbx templates show, andcreate --template ID@BUILD --seed.Notes for review:
400 unknown_template, as today, so current clients don't break; the read routes answer404 template_not_found. A private template reads as not found to anyone but its owner and admins.seedtoSH_SANDBOX_TEMPLATES; whichever lands second copies it into the imported build (one line indocFromDeclared).Tests on the tip:
deploy/sbx/tests/setup.test.shand the overlay test pass.33 files, +2,434 / -68, counted against #756's tip.
Assisted-By: Claude Code