Skip to content

feat(control-plane, sandbox-relay): release an ended sandbox's or session's workspace on its worker (PR C of #338) - #1003

Merged
pdettori merged 12 commits into
rossoctl:mainfrom
webchang:pr/i338-release-cp
Nov 24, 2026
Merged

pdettori merged 12 commits into
rossoctl:mainfrom
webchang:pr/i338-release-cp

Conversation

@webchang

@webchang webchang commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Refs #338

The control plane releases an ended sandbox's (or session's) workspace on its worker, through a new
release-only HTTP listener on the relay. This is PR C of #338, after the worker's Release frame (#949),
the relay routing and mocactl sbx rm (#951), and the worker's startup sweep (#954, #979); it follows
the four answers on #338 ("(a) on all four"), with their conditions.

Relay (packages/sandbox-relay/src/control-listener.ts)

  • Off unless MOCA_RELAY_CONTROL_ADDR is set. Set: a Node http listener (no new dependency) with
    one route, POST /v1/release {worker, workspaceKey}, forwarded through the existing release routing.
  • Authorized only by MOCA_RELAY_RELEASE_TOKEN, a credential file under CREDENTIALS_DIRECTORY. The
    relay refuses to boot when it equals any other relay bearer: the exec token, SH_RELAY_TOKEN[_<id>],
    or a file in SH_RELAY_TOKEN_DIR. A directory token written later that equals it is refused at attach.
  • Answers 200 {outcome} with the worker's ack (released / kept_busy / unknown_key), or
    release_unsupported as a distinct status; anything else is an error status. A body over the
    ceiling gets its 413 before the connection closes.
  • One sandbox_workspace_release audit line per call (via: "control"). Refused bearers log at most
    one line a minute, with a suppressed count; the bearer is never logged.

Control plane (SH_RELAY_CONTROL_URL plus the same bearer, which must differ from every other
control-plane secret, i.e. each of CONTROL_PLANE_SECRETS, and every egress and template host bearer)

  • The janitor's sweep releases every ended sandbox not yet answered, regardless of provenance. It
    waits at most 5 s for them and never fails for them.
  • deleteSandbox starts the same release after markDeleted. The DELETE never waits for it: it
    runs in the background with its own 5 s bound, every error caught, and none can become an
    unhandled rejection.
  • releasedAt is written on the record only on a terminal answer (released, kept_busy,
    unknown_key, unsupported). A transport failure leaves it unset, so the next sweep retries while
    the record is retained. The audit line follows the releasedAt write, so a failed write is not
    audited twice.
  • Sent once: a sender claims a sandbox's release atomically (Redis SET NX EX checked in one
    script with the record; 60 s), so a DELETE and a concurrent sweep, or two DELETEs, do not both
    send. An unanswered release drops its claim, and a crashed sender's claim lapses.
  • A session's delete reads its sandboxPod, else its last sandboxId, before the cascade, and
    starts the release only after the delete commits, without waiting for it, keyed by the session id
    (the workspace key of every turn that records a worker). It writes one session_workspace_release
    audit line, naming the worker under worker: the outcome, not_answered on failure, or
    no_worker (nothing sent) when no worker is recorded. An internal leaf run whose agent writes in
    its context view leases the worker's shared workspace (workspace_key: '') instead; it records no
    worker, an empty key is not releasable, and idle reclaim frees it. A session's release has no retry:
    unlike a sandbox's, it is not swept, so an unanswered one falls back to the worker's idle reclaim.
  • Note: expiry is noticed only when the host janitor sweeps (GET /v1/janitor/sandboxes, every
    15 minutes by default). Elsewhere, idle reclaim on the worker stays the backstop.

Deploy

  • deploy/k8s/base/relay-release-control (a Component): the listener, its own Service
    (sandbox-relay-control, 9445), a NetworkPolicy admitting only the control plane's pods, the
    control plane's egress to it, and SH_RELAY_CONTROL_URL.
  • deploy/sbx/setup.sh SBX_RELEASE_CONTROL=1 and deploy/k8s/setup.sh SH_RELAY_RELEASE_CONTROL=1
    generate the bearer once into its own Secret, moca-relay-release, and list the component. The
    Secret feeds both pods' hashes, so rotating it (delete the key, re-run) rolls the relay and the
    control plane and leaves moca-mu1 alone.
  • Off (the default): no Secret, no listener; the generated kustomization, RELAY_HASH, and the
    relay's Deployment, Services and NetworkPolicies are byte-for-byte as before (tested).
  • One-time control-plane roll: every overlay's control-plane credentials volume now names
    moca-relay-release as an optional source (mounted only when the Secret exists), with the switch on
    or off. The first setup.sh run of this release therefore rolls the control plane once (noted in
    the upgrade notes and the runbook).

Tests:

  • Relay: auth; the answer mapping, including release_unsupported; off when unset; the boot
    refusals; the 413; the refused-bearer throttle.
  • Control plane: releasedAt only on terminal answers; retry after a transport failure; the DELETE
    returning before a release that never settles; no unhandled rejection from a releaser that rejects
    or throws; one sender per release; session release only after commit; the no_worker line; a
    boot refusal per secret source.
  • Both setup scripts: the Secret, the hashes, rotation, and off-is-unchanged.

This leaves #338 open for the maintainer to close once this ships: an expiry is still noticed only
at the janitor's sweep, and idle reclaim is the backstop where no janitor runs.

Assisted-By: Claude Code

…plane (rossoctl#338)

MOCA_RELAY_CONTROL_ADDR opens a small HTTP listener (node:http, no new
dependency) with one route, POST /v1/release {worker, workspaceKey},
authorized by MOCA_RELAY_RELEASE_TOKEN alone (a credential file under
CREDENTIALS_DIRECTORY, else the env). It forwards through the existing
release routing (Relay.routeRelease) and answers 200 {outcome} with the
worker's ack (released, kept_busy, unknown_key) or release_unsupported for
a worker that predates release; every other result is an error status the
caller may retry. Unset, nothing changes: no listener, no bearer read.

The relay refuses to boot when the release bearer is missing, shorter than
32 characters, or equal to MOCA_RELAY_EXEC_TOKEN, SH_RELAY_TOKEN, any
SH_RELAY_TOKEN_<id> or any file in SH_RELAY_TOKEN_DIR, and refuses at
attach a directory token written later that equals it. One
sandbox_workspace_release audit line per call, marked via: control.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…e on its worker (rossoctl#338)

With SH_RELAY_CONTROL_URL and MOCA_RELAY_RELEASE_TOKEN (a credential
file, in CONTROL_PLANE_SECRETS), the control plane calls the relay's
control listener, POST /v1/release {worker, workspaceKey}:

- the janitor's sweep releases every ended sandbox not yet answered,
  regardless of provenance (expiry is noticed there), a few at a time;
- deleteSandbox releases after markDeleted;
- deleteSession reads the session's sandboxPod, else its last sandboxId,
  before the cascade and releases only after the cascade commits (keyed
  by the session id); with no worker recorded it sends nothing and writes
  a session_workspace_release audit line with outcome no_worker.

releasedAt is written on the sandbox record only on a terminal answer
(released, kept_busy, unknown_key, unsupported), so a transport failure
leaves it unset and the next sweep retries while the record is retained.
Every release is best-effort under RELEASE_BOUND_MS (5 s): it never fails
the DELETE or the sweep and never holds either past the bound. The bearer
must differ from every bearer the control plane accepts, or no boot.
Unset, nothing changes.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…tup scripts (rossoctl#338)

deploy/k8s/base/relay-release-control, a Component: the relay's
MOCA_RELAY_CONTROL_ADDR (0.0.0.0:9445) and `control` port, its release
bearer as a file under CREDENTIALS_DIRECTORY, the sandbox-relay-control
Service, a NetworkPolicy admitting only the control plane's pods to 9445
and the control plane's egress to it, and the control plane's
SH_RELAY_CONTROL_URL. Every overlay's control-plane credentials volume
names moca-relay-release as an optional source.

deploy/sbx/setup.sh SBX_RELEASE_CONTROL=1 and deploy/k8s/setup.sh
SH_RELAY_RELEASE_CONTROL=1 (sticky; kind, kind-ci and ocp) list the
component and generate MOCA_RELAY_RELEASE_TOKEN once into its own Secret,
moca-relay-release, never moca-mu1; a fresh token is redrawn on a clash
with any other bearer and a kept one that clashes is refused, naming keys
only. Its data feeds both pods' hashes (sbx: SETTINGS_HASH and
RELAY_HASH; k8s: a release-token-hash annotation), so a rotation rolls
the relay and the control plane and leaves moca-mu1 alone. Off, the
generated kustomization, RELAY_HASH and the relay's Deployment, Services
and NetworkPolicies render byte-for-byte as before (tested).

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

SBX0 design §3.7 (the control listener: off unless set, the one route,
the release-only bearer, the answers; when the control plane releases,
releasedAt on a terminal answer only, the bound), the configuration
reference (MOCA_RELAY_CONTROL_ADDR, MOCA_RELAY_RELEASE_TOKEN,
SH_RELAY_CONTROL_URL, SH_RELAY_RELEASE_CONTROL), the sandbox service's
install inputs and runbook (SBX_RELEASE_CONTROL, rotation, uninstall), the
Kubernetes guide (moca-relay-release, section 15), the direct API how-to,
and the P4 design's release note.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…er release (rossoctl#338)

Review of PR C (should-fix 1, nits 4 and 6):

- deleteSandbox and deleteSession start the release after the delete
  commits and return at once (inBackground): the release keeps its own
  5 s bound, every error is caught and logged, and nothing can become an
  unhandled rejection, a releaser that throws synchronously included.
  An unanswered sandbox release is left to the janitor's sweep, as
  before; a session's still writes its one audit line (not_answered).
- SandboxStore.claimRelease/unclaimRelease: a sender claims a sandbox's
  release atomically for RELEASE_CLAIM_TTL_S (Redis: SET NX EX on a key of
  its own, checked in one script with the record; memory: the same under
  nowS), so a DELETE and a concurrent sweep, or two DELETEs, send it once.
  An unanswered release drops its claim; a crashed sender's lapses.
- The sandbox_workspace_release audit line is written after releasedAt,
  so a failed write (the release is sent again) is not audited twice.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…-plane secret (rossoctl#338)

Review of PR C (should-fix 2): releaserFrom compared the release bearer
with the exchange, janitor, installer, egress and host bearers only,
missing SH_OPERATOR_INFERENCE_TOKEN and SH_TEST_USER_SECRET. It now
compares with every one of CONTROL_PLANE_SECRETS but itself, so a secret
added there is covered without a change here, plus the egress and
template host bearers from the config. A test per source (the exchange
token, the operator token, the test-user secret) and one over the list.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…r lines (rossoctl#338)

Review of PR C (nits 5 and 7):

- A body over MAX_CONTROL_BODY_BYTES is answered 413 (connection: close)
  and the request destroyed only once the answer is written; before, the
  destroy came first and the caller saw a reset.
- Refused-bearer audit lines are at most one per REFUSED_LOG_INTERVAL_MS
  (60 s); the next line carries `suppressed`, the refusals it stands for.
  The bearer is never logged.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…never waiting (rossoctl#338)

Review of PR C (wording 3): deploy/sbx/setup.sh's header said an off run
changes nothing, which is wrong for the control plane: its credentials
volume names moca-relay-release as an optional source whatever the
switch, a one-time change that rolls it with the release that brings it.
Reworded there, in deploy/k8s/setup.sh and the component, and noted in
the runbook's upgrade section, the upgrade notes and the Kubernetes
guide. The SBX0 design, runbook, configuration reference and Kubernetes
guide now say a DELETE does not wait for its release, and that a release
is claimed once.

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

CodeQL on PR C (rossoctl#137 js/polynomial-redos, rossoctl#138 and rossoctl#139
js/file-access-to-http, relay-release.ts:62/65/67):

- The listener's base URL loses its trailing slashes in a loop
  (releaseUrl), not with /\/+$/, which backtracks on many slashes.
- The release URL and bearer now travel as the control plane's other
  secrets do: configFromEnv reads them into the config
  (CpConfig.relayRelease, every profile, with the same boot checks), and
  the request that needs them builds the releaser from deps.config
  (releaserOf), as the operator inference token reaches its upstream.
  Before, depsFromEnv built a releaser that closed over values read from
  withCredentials' merged env, whose dynamic property writes of file data
  CodeQL counts as tainting every value read from it, the URL included.
  deps.relayRelease stays as the test seam.

A local CodeQL 2.27.5 run (security-extended, as CI) over the control
plane reports the three alerts at the previous head and none here.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 23, 2026

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

Solid PR: the release path is separated from every other bearer, fails closed on a missing or clashing token, and the DELETE never waits for it. Two things: one place where the doc comment's claim about the session workspace key does not hold, and one audit field that carries a worker name.

The separation is done properly on both sides. makeReleaseTokenValidator refuses to boot on a token that equals MOCA_RELAY_EXEC_TOKEN, SH_RELAY_TOKEN, any SH_RELAY_TOKEN_<id>, or any file in SH_RELAY_TOKEN_DIR, and length-checks before timingSafeEqual; the later-file case is closed again in makeDefaultValidateToken. On the control plane, MOCA_RELAY_RELEASE_TOKEN is in CONTROL_PLANE_SECRETS (so withCredentials resolves it from CREDENTIALS_DIRECTORY before configFromEnv reads it) and withRelayRelease compares it against every other secret plus the egress and template host bearers. The NetworkPolicy half is additive: base/control-plane.yaml already isolates the control plane's egress, so the new policy only adds the relay's 9445 rather than cutting its Redis path.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control plane, sandbox relay, k8s manifests, setup scripts), docs/spec, tests
Agent/IDE config (.claude/.vscode): none
Commits: 9 commits, all signed-off: yes
CI status: passing at this head

Suggestion (inline): the session release's workspace key.

Nit (inline): sandboxId: worker on the session_workspace_release audit line.

Verified by:

  • npx vitest run in packages/sandbox-relay — 29 files, 378 passed (including the 30 new control-listener tests).
  • npx vitest run in packages/control-plane against a local Redis on 6379 — 2165 passed, 4 skipped, 1 file skipped; the new relay-release.test.ts is 36 of those.
  • Read the Lua in sandbox-redis.ts against the memory store: CLAIM_RELEASE and MARK_RELEASED both refuse a live record (deletedAt absent and now < expiresAt) and HSETNX/SET NX EX keep the first time, so the memory store's purge (which only drops records past endOf + retentionS) and Redis agree.
  • Traced the session workspace key to harness/src/select-sandbox.ts:787-790 and harness/src/run-leaf.ts:803, which is where the suggestion comes from.
  • The pi-fork submodule is not built in this sandbox, so k8s-sandbox's @earendil-works/pi-coding-agent import was stubbed (factory functions that throw if called) to let the relay suite load; no relay or control-plane test reaches it.

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

await withinBound(deps.releaseBoundMs ?? RELEASE_BOUND_MS, async (signal) => {
let outcome: string;
try {
outcome = await releaserOf(deps)!.release(worker, rec.sessionId, signal);

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 session's workspace key is the session id only when the key was not dropped. harness/src/select-sandbox.ts:787-790 computes

const workspaceKey =
  agentWritesInContext && rec?.capabilities.includes(WORKSPACE_SUBDIR_CAPABILITY)
    ? ''
    : sessionId;

and harness/src/run-leaf.ts:803 sets agentWritesInContext for an internal leaf run whose context is a copy or a writable mount. On a container-capability record such a session executes under workspace_key: '', so releasing rec.sessionId here targets a key that was never created: the worker answers unknown_key (or released for a stale key of an older turn), and the '' workspace is left to idle reclaim — which the doc comment above rules out by saying sessionId is "the workspace key every leased turn of it sent".

This is best-effort either way, so nothing is stranded; the cost is that the fast path silently misses for exactly the configuration WORKSPACE_SUBDIR_CAPABILITY exists for.

Suggested fix: record the key alongside the worker — the runtime hash already has a place for self-reported fields (ownership.ts RUNTIME_FIELDS) — and send that; or, if the empty key can be released, try runtime.workspaceKey ?? rec.sessionId. If neither is wanted this release, say in the comment that the context-view case falls back to idle reclaim.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks. Addressed in 4f614dd as your third option. An empty key can't be released: the microVM pool's checkKey refuses '', and the container runner's dirFor treats it as invalid; on the container tier it is the worker's shared workspace, not the session's. The '' case comes only from the internal leaf path (run-leaf.ts:803), which passes an injected sandbox and records no runtime fields, so the control plane never learns a worker for it. Every turn that does record a worker leases under the session id. So recording the key would always carry the session id. The comment on releaseSessionWorkspace, SBX0 §3.7 and the Kubernetes guide §15 now say that the context-view case falls back to idle reclaim. That holds only while the leaf path reports no runtime fields, so f3e6363 names the coupling where the key is chosen (select-sandbox.ts).

Comment thread packages/control-plane/src/handlers.ts Outdated
sessionId: rec.sessionId,
decision: 'session_workspace_release',
outcome,
...(worker ? { sandboxId: worker } : {}),

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: sandboxId is documented in ownership.ts as "The sandbox a decision is about (SBX0 §5)", and this line puts a worker's pod name in it (runtime.sandboxPod wins over runtime.sandboxId at line 360). An audit consumer that groups by sandboxId will see moca-sandbox-0 where it expects a sandbox record id, and the two are different identifiers.

Suggested fix: drop this line and put the worker under its own key (the line already carries sessionId), or send runtime.sandboxId here and the pod name separately.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in f296ee9: the session_workspace_release line names the worker under its own key, worker, beside sessionId, and no longer writes sandboxId. Tests cover the sandboxPod and sandboxId cases and the no_worker line.

…s `worker` (rossoctl#338)

Review of rossoctl#1003 (clawgenti, nit at handlers.ts:367): the
session_workspace_release line put the worker's id in `sandboxId`, which
the audit entry documents as the sandbox record a decision is about. The
worker now has its own key, `worker` (in the entry type and the stream),
beside `sessionId`, and the line names no sandboxId. Tests: the line's
`worker` for a sandboxPod and for a sandboxId fallback, and no sandboxId.
The runbook names the key.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
… the empty-key case (rossoctl#338)

Review of rossoctl#1003 (clawgenti, suggestion at handlers.ts:376): the comment
claimed the session id is the key of every leased turn. It is the key of
every turn that records the worker the release goes to: the harness's
/turn paths (runtimeFieldsForTurn), which lease with workspace_key = the
session id. An internal leaf run whose agent writes in its context view,
on a worker with the workspace-subdir capability, leases with
workspace_key '' (run-leaf.ts agentWritesInContext): the worker's shared
workspace. That path records no runtime fields, '' is refused by both
worker tiers (empty-workspace-key on the microVM pool, invalid on the
container runner) and is not the session's alone, so it is not sent and
falls back to idle reclaim. Said in the comment, the SBX0 design and the
Kubernetes guide (option (c) of the review; (a) would record a value
that is always the session id on every path that records a worker).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
…the session release (rossoctl#338)

The control plane releases a deleted session's workspace by its session id, which is right only while
the leaf path (the one that may lease with an empty key) reports no runtime fields. Say so where the key
is chosen, so a change that makes runLeaf report them sees it.

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

PR C of #338: the control plane releases an ended sandbox's (or session's) workspace on its worker through a new release-only HTTP listener on the relay. No must-fix findings — the design holds together and the guard rails the PR body promises are present in the code. Ready for human review.

What I checked against head f3e6363:

  • Relay control listener — off unless MOCA_RELAY_CONTROL_ADDR; one route; the bearer is length-checked and compared in constant time, before the body is read; boot refusal when the release bearer equals MOCA_RELAY_EXEC_TOKEN, SH_RELAY_TOKEN, an SH_RELAY_TOKEN_<id> or a file in SH_RELAY_TOKEN_DIR, plus an attach-time refusal for a directory token added later. The "other" bearers are env-resident in the relay (makeExecAuth and makeDefaultValidateToken read env directly), so the env-vs-env clash check is the correct comparison, and it stays correct after the patch adds CREDENTIALS_DIRECTORY.
  • Terminal-answer state machine — releasedAt is written only on released / kept_busy / unknown_key / unsupported; a transport failure leaves it unset and drops the claim; the atomic SET NX EX claim (checked with the record in one Lua script) makes a DELETE and a concurrent sweep send once; markReleased keeps the first time and the record's retention.
  • Bounded and non-blocking — a DELETE runs its release in inBackground (never awaited, every error caught); the janitor waits at most RELEASE_BOUND_MS (5 s) via withinBound; both paths are concurrency-capped (8 on the control plane, 16 on the listener).
  • Credential wiring — MOCA_RELAY_RELEASE_TOKEN was added to CONTROL_PLANE_SECRETS, so withCredentials(process.env, …) resolves the credential file into env before depsFromEnv reads it; without that the k8s overlay, which mounts it as a file, would leave it undefined. The relay reads it through credentialValue. Both sides fail closed.
  • Deployment — with SH_RELAY_RELEASE_CONTROL / SBX_RELEASE_CONTROL unset or empty no component is listed and the relay, its Services and NetworkPolicies render as before; the control-plane credentials volume gains the optional moca-relay-release source in every overlay (the documented one-time control-plane roll); --target ocp-single refuses the switch.
  • Formatting — prettier --check passes on all 34 non-shell changed files. No .claude/ or .vscode/ changes.

I did not run the unit suites (this checkout has no installed workspace deps), so the behaviour above is from reading the diff and the new tests, not a green run; CI is the backstop, and the checks were still queued at review time.

Author: webchang (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane, sandbox-relay, harness), Shell (deploy scripts and tests), Kubernetes manifests, Docs, Tests
Agent/IDE config (.claude/.vscode): none
Commits: 12 commits, all signed-off: yes
CI status: pending at review time

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

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

Approved. No must-fix and no behavioural defect found across the relay listener, the control-plane releaser, the store changes and the deploy wiring. Three non-blocking comments inline (two suggestions, one doc nit). The two findings from the earlier review at 72f25da1 — the session workspace key's doc claim and the sandboxId-as-worker audit field — are closed at this head (f296ee9 names the field worker; 4f614dd/f3e6363 document why an internal leaf run's empty key is not the session's to release and note the coupling in select-sandbox.ts).

What I verified against the head source:

  • The relay listener is one route and fails closed. buildControlServer checks the path, then the method, then the bearer (constant-time, length-checked) before reading the body; every other path is 404 whoever asks. makeReleaseTokenValidator throws at boot without a ≥32-char MOCA_RELAY_RELEASE_TOKEN, and refuses a boot where it equals MOCA_RELAY_EXEC_TOKEN, SH_RELAY_TOKEN, any SH_RELAY_TOKEN_<id> or a directory token; makeDefaultValidateToken refuses a directory token added later that equals it, using the same .replace(/\n$/, '') normalisation as the boot check. routeRelease is the existing routing, so the live-worker check, WORKER_WITHOUT_RELEASE and the timeout are the same. The 413 is sent before the connection is closed, and the refused-bearer line is throttled with a suppressed count.
  • The control plane releases only after the record has ended. deleteSandbox starts the release after markDeleted (including the already case), in inBackground, never awaited; the janitor runs releaseEnded before recordExpiries, bounded, regardless of provenance. releasedAt is written only on a terminal answer; a transport failure or a failed write leaves it unset and drops the claim, so the next sweep retries. The audit follows the write, so a retried release is not audited twice.
  • Sent once. claimRelease is one Redis script (SET … NX EX keyed beside the record, after the ended/not-released checks), and the memory store does the same check-and-set without an await in between; a DELETE racing a sweep is covered at the store, not by the handler.
  • Session release. The runtime hash is read before the cascade and getRuntime returns {} rather than undefined, so no_worker is audited rather than skipped. The key is the session id; sandboxPod and the sandboxId fallback are ids the worker attaches under. The release is scheduled only after the delete commits and has no retry (documented, idle reclaim is the backstop). session_workspace_release now carries sessionId + worker, never sandboxId; OwnershipIndex writes the new field and the no_worker line carries neither.
  • Config and deploy. MOCA_RELAY_RELEASE_TOKEN is in CONTROL_PLANE_SECRETS, so withCredentials resolves it from CREDENTIALS_DIRECTORY before withRelayRelease compares it against every other secret plus the egress/template-host bearers. The relay keeps its other tokens on the env path (credentialValue falls back when no file exists). Off, the setup test asserts the relay, its Services, its NetworkPolicies and both pod hashes render byte-identically; on, the bearer is its own 0400 Secret file, both pod templates carry its digest, all five overlay patches that replace the projected volume list it as optional, and ocp-single refuses the switch.
  • Hygiene. No secrets or keys added, no workflow changes, no new dependency, no .claude//.vscode/ paths, and no injected instructions in the PR body, diff, commits or comments.

CI is still running at this head (DCO passed; 15 checks queued/in progress); it was 18/18 green at 72f25da1 (three commits earlier), and the three later commits are docs/audit-field only.

}, boundMs);
});
try {
await Promise.race([work(stop.signal).catch(() => {}), bound]);

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 — withinBound documents "Never rejects", but work(stop.signal) is evaluated while the array is built, before Promise.race is called: a callback that throws synchronously (rather than returning a rejected promise) propagates out of the async function and rejects withinBound. Every current caller passes an async arrow, so nothing triggers it today — but inBackground immediately above guards exactly this case (try { p = work() } catch { p = Promise.reject(err) }), and the janitor handler and the DELETE's background task both rely on the "never rejects" contract. Promise.resolve().then(() => work(stop.signal)).catch(() => {}) (or a try/catch around the call) would make the two helpers consistent and keep the documented guarantee.

Comment thread deploy/k8s/setup.sh
others="$(
secret_json moca-relay "$NS" | jq -r '.data // {} | .[] | @base64d'
secret_json "$P4_TOKENS_SECRET" "$NS" | jq -r '.data // {} | .[] | @base64d'
secret_json moca-mu1 "$NS" | jq -r '.data // {} | (.SH_EXCHANGE_TOKEN // empty) | @base64d'

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 pre-flight clash set is narrower than the control-plane boot check it is meant to backstop. withRelayRelease compares MOCA_RELAY_RELEASE_TOKEN against every other CONTROL_PLANE_SECRETS entry plus the egress and template-host bearers; here only moca-mu1's SH_EXCHANGE_TOKEN is read, so a kept token copied from SH_JANITOR_TOKEN or SH_INSTALLER_TOKEN (same Secret) passes in_lines and setup, and the control plane then refuses to boot with MOCA_RELAY_RELEASE_TOKEN must differ from every other control-plane secret and bearer — a crash-loop after a successful apply rather than the intended setup-time die. deploy/sbx/setup.sh covers janitor/installer/exchange but likewise omits SH_OPERATOR_INFERENCE_TOKEN, SH_TEST_USER_SECRET and SH_OIDC_CLIENT_SECRET. Reading every value of moca-mu1 and moca-oidc (as the moca-relay line above already reads every value) would cover the realistic bearer-shaped ones; the PEM/KEK entries can stay out, and the boot refusal remains the authoritative check.

| `SH_RELAY_TOKEN_<sandboxId>` | falls back to `SH_RELAY_TOKEN` | **Secret.** Looked up verbatim by sandbox id, so an id with a dash cannot have an env token where the environment cannot carry a dashed name (systemd drops them, so not on the VM or a microVM host). It is never looked up in `SH_RELAY_TOKEN_DIR` and uses `SH_RELAY_TOKEN` there. `setup-microvm.sh` rejects dashed ids and writes these | Per-sandbox attach token |
| `SH_RELAY_TOKEN_DIR` | unset | One file per sandbox id (ids must match `^[A-Za-z_][A-Za-z0-9_]*$`; `DIR` is reserved), read on each attach. An unreadable or empty file refuses the attach; a file equal to the exec token is refused at attach time, not at boot. K8s mounts `/run/relay-tokens` | Token directory |
| `MOCA_RELAY_CONTROL_ADDR` | unset (no control listener) | `host:port`. Set, the relay also serves a small HTTP listener with one route, `POST /v1/release {worker, workspaceKey}`, for the control plane to release an ended sandbox's or session's workspace on its worker; it answers `200 {outcome}` with `released`, `kept_busy`, `unknown_key` or `release_unsupported` (a worker that predates release), and an error status for anything else. Needs `MOCA_RELAY_RELEASE_TOKEN`. `deploy/k8s/base/relay-release-control` sets `0.0.0.0:9445` behind its own Service and a NetworkPolicy that admits the control plane alone | The control listener's bind address |
| `MOCA_RELAY_RELEASE_TOKEN` | none | **Secret**, a file under `CREDENTIALS_DIRECTORY` (else the env); required with `MOCA_RELAY_CONTROL_ADDR`, at least 32 characters. The listener's only credential, good for releases and nothing else. The relay refuses to boot when it equals `MOCA_RELAY_EXEC_TOKEN`, `SH_RELAY_TOKEN`, an `SH_RELAY_TOKEN_<id>` or a file in `SH_RELAY_TOKEN_DIR`, and refuses an attach whose directory token equals it | The control plane's release bearer; must equal the control plane's |

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 description ends mid-sentence: "The control plane's release bearer; must equal the control plane's". It never names what. Presumably "must equal the control plane's MOCA_RELAY_RELEASE_TOKEN" (this row is the relay side; the control-plane table row states the pairing the other way round).

@pdettori
pdettori merged commit 49d75d4 into rossoctl:main Nov 24, 2026
19 checks passed
webchang added a commit to webchang/moca that referenced this pull request Nov 28, 2026
…t-client token too

Upstream's release-only bearer (rossoctl#1003) is refused at boot when it equals any other relay bearer the
relay knows of upstream. The fork also has direct-client tokens (MOCA_RELAY_CLIENT_TOKENS), which upstream
doesn't know, so a client token equal to the release token would have let that client release workspaces.
Check those too, naming the entry by position and never the value. A test fails before and passes after.

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

5 participants