Skip to content

feat(control-plane): SBX0 idle lifetime - activity mints slide the deadline (#770) - #837

Merged
pdettori merged 12 commits into
mainfrom
feat/sbx-idle-lifetime-cp
Nov 17, 2026
Merged

pdettori merged 12 commits into
mainfrom
feat/sbx-idle-lifetime-cp

Conversation

@pdettori

@pdettori pdettori commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Plan 1 of 3 for #770 (spec: docs/specs/2026-11-16-sbx-idle-lifetime-design.md, merged in #820). The control plane now counts an SBX0 sandbox's lifetime as idle time.

  • Activity mints slide the deadline. POST /v1/sandboxes/{id}/token, POST …/mode-token and PUT …/mode move expiresAt to max(expiresAt, now + L) before signing, so every token is capped by the new deadline. It never moves backwards, and a deleted or expired sandbox is never revived. Reads, list, delete and the janitor route never extend.
  • activity: false (optional body on the two POST mints) mints without extending, for mints that run no command (the MCP lease keepalive, sbx get's lease status — plan 2). PUT …/mode refuses activity with 400.
  • Owner-chosen lifetime: POST /v1/sandboxes takes idleLifetimeS (3600 s to SH_SANDBOX_MAX_LIFETIME_SECONDS), and every Sandbox carries it. L = min(rec.idleLifetimeS ?? SH_SANDBOX_LIFETIME_SECONDS, SH_SANDBOX_MAX_LIFETIME_SECONDS), clamped to the maximum as it is now.
  • SH_SANDBOX_MAX_LIFETIME_SECONDS: when unset it equals SH_SANDBOX_LIFETIME_SECONDS, and the deadline does not slide (see Rollout). A control plane rolled out before deploy/sbx/setup.sh (plan 3) therefore offers nothing longer than today, while workers still clean up after 216 h. The spec is updated to match (5edbbbf).
  • Storage: SandboxStore.touch. The Redis implementation is one Lua TOUCH script that moves, together, the record's expiresAt, the live score, the record hash's EXPIREAT, the name key's PXAT (only while it names this sandbox) and the egress log's stream, meta and index score. A sealed log is left alone. Memory and Redis run one contract suite.
  • Egress log: a host's append now only extends the log's expiry. Before, a post computed from a record read before a concurrent touch could pull it back.
  • sandboxExpiresAt is in the token response, so long-lived clients can follow the deadline (plan 2).
  • API docs: OpenAPI 1.25.0, CHANGELOG, sandbox-v1-direct-client.md, change-policy.

No migration: records and hashes from before this change slide at the default lifetime from their next mint. Today's mocactl sends no body, so its mints count as activity.

Test evidence

  • packages/control-plane: 1905 passed, 3 skipped (Redis 7.2), after merging upstream/main (fix(control-plane): roll a sandbox create back when its start record fails #832's rollBackCreate kept). This includes the store contract against both stores, TOUCH TTL, score and egress tests, the never-backwards and no-write path, a mint racing a delete, a mode change racing a delete, the clamp, legacy records and hashes, the hint's refusals, and the OpenAPI drift test.
  • packages/mocactl contract.test.ts: 67 passed. tsc --noEmit is clean for control-plane and mocactl. Prettier is clean.
  • Each task got a spec and quality review, and the whole branch got a final review. Its findings are fixed in the last three commits.

Rollout

Extension stays off until SH_SANDBOX_MAX_LIFETIME_SECONDS is configured (slideOnActivity). With this PR alone, every deployment keeps today's absolute lifetime, and the new fields and the hint are accepted but inert. Plan 3's deploy/sbx/setup.sh writes the key together with the workers' SH_WORKSPACE_IDLE = max + 48 h, behind its SBX_ACK_HOSTS refusal, and every host's workers are then reinstalled the same day. That is when sliding starts.

This order matters for lease-mode deployments. Today's mocactl sbx mcp mints from its keepalive about every 14 minutes, and with no body those mints would count as activity. With workers still at 216 h, that leaves only a 48 h margin before a silent reset (review on this PR).

A long-running mocactl sbx mcp from before plan 2 may report expiring once its sandbox's original deadline passes, though the sandbox is still live. Restarting it fixes that.

Part of #770. Plans 2 (clients) and 3 (deploy) follow as separate PRs.

Assisted-By: Claude Code

)

A control plane upgraded before deploy/sbx/setup.sh writes
SH_SANDBOX_MAX_LIFETIME_SECONDS still runs over workers whose
SH_WORKSPACE_IDLE covers only the old 7-day lifetime, so with the key unset
it must offer nothing longer. setup.sh's own default stays 30 days.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…er may pick (#770)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ine (#770)

Adds SandboxStore.touch and the optional SandboxRecord.idleLifetimeS, with
the memory model and contract cases. RedisSandboxStore.touch is a stub that
throws until the next task.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…and name TTLs and the egress log (#770)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…hint; sandboxExpiresAt (#770)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ng (#770)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
setSandboxMode extends before it raises the epoch; lifetimeOf doc; tests; prefix comments.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 16, 2026
@pdettori
pdettori marked this pull request as ready for review November 16, 2026 21:07

@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

Idle-counted sandbox lifetimes: idleLifetimeS at create, an atomic TOUCH script in Redis that slides expiresAt (with the live score, record/name-key TTLs and the egress log keys) never backwards, activity mints on token/mode-token/mode routes with an activity: false opt-out for keepalives, and a clamped SH_SANDBOX_MAX_LIFETIME_SECONDS that defaults to the default lifetime when unset. OpenAPI bumped to 1.25.0 with a changelog entry; tests cover the store contract (both stores), the Redis script's TTL/score behaviour, race-with-delete proxies, and the handler grammar. Well put together — the TOUCH script keeping the record, name key and egress keys moving in one atomic write is the right shape.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (handlers, config, Redis scripts), OpenAPI/docs, tests
Agent/IDE config (.claude/.vscode): none
Commits: 9 commits, all signed-off: yes
CI status: passing (all checks)

No must-fix findings. The rest are suggestions/nits.

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

if redis.call('HGET', KEYS[5], 'sealed') ~= '1' then
redis.call('EXPIREAT', KEYS[4], new + ret)
redis.call('EXPIREAT', KEYS[5], new + ret)
redis.call('ZADD', KEYS[6], 'XX', new + ret, ARGV[4])

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 — ZADD KEYS[6] 'XX' new+ret id updates the egress expiry-index score unconditionally, while the egress append script (egress-log.ts) guards its ZADD with if (not cur) or tonumber(cur) < tonumber(exp). Today the two can't disagree (an unsealed log's score always equals end + retention, which only moves forward, and a sealed log is skipped by the sealed check above), but the asymmetry means a future writer that ever sets a higher score than end + retention would be silently pulled back by a touch. Consider the same ZSCORE guard here, or a line saying why the unconditional XX is safe.

Suggested fix:

local cur = redis.call('ZSCORE', KEYS[6], ARGV[4])
if (not cur) or tonumber(cur) < tonumber(new + ret) then redis.call('ZADD', KEYS[6], new + ret, ARGV[4]) end

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.

Applied in 46cd497. TOUCH now runs ZSCORE first and calls ZADD only when the member exists and its score is below new + ret, so it never lowers the score. An absent member still gets no add, as XX did before. A new Redis test seeds a higher score and checks that a touch leaves it alone.

const read = await assertSandboxOwner(ctx, deps, { admin: false });
const { cfg } = service(deps);
const now = seconds(deps);
const activity = parseActivity(asRecord(ctx.body).activity);

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 — parseActivity runs before requireLive, so a mint with a non-boolean activity on an already-terminated sandbox answers 400 invalid_request rather than sandbox_terminated. Parsing before any write is the right order and both 400s are documented on the route, so this is only a note that body validation takes precedence over state — worth a sentence in the changelog if a client uses keepalive mints to detect expiry.

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.

Added to the 1.25.0 CHANGELOG (6efafbc). Body validation comes before state: a non-boolean activity gets 400 invalid_request even on a terminated sandbox, not 409 sandbox_terminated.

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

Implements plan 1 of the #770 idle-lifetime spec cleanly. I checked it against spec §3–§6:

  • A refused body writes nothing.
  • TOUCH is atomic and never revives a deleted or expired record.
  • The record TTL, name PXAT and the egress stream, meta and index move together.
  • A mode change extends before setMode, so a refusal raises no epoch.
  • Old hashes read at the default.
  • Egress append is now extend-only.

Tests cover both stores, the races and the clamp. CI is green.

Before merge: this branch now conflicts with main (#832's rollBackCreate try/catch in createSandbox). Keep main's try/catch and pass cfg to sandboxBody, then re-run CI.

  • suggestion (inline): spell out the rollout ordering for lease-mode deployments. Today's mocactl sbx mcp keepalive mints count as activity, and until plan 3 raises SH_WORKSPACE_IDLE, the §7 margin is 48 h, not 25 days.
  • nit: docs/sbx/user-guide.md §7 still says a sandbox's lifetime "cannot be extended". That's fine if plan 2 ships in the same release; otherwise update it here.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (control plane, Redis Lua), OpenAPI/docs, tests
Agent/IDE config (.claude/.vscode): none
Commits: 9 commits, all signed-off: yes
CI status: passing

requireLive(read, now);
const rec = await underPolicy(deps, ctx.principal!.sub, read, now);
let rec = await underPolicy(deps, ctx.principal!.sub, read, now);
if (activity) rec = await extend(deps, rec, now);

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: rollout ordering vs. today's mocactl sbx mcp keepalive. With this PR alone deployed, SH_SANDBOX_MAX_LIFETIME_SECONDS is unset, so L = 7 d. The workers still run SH_WORKSPACE_IDLE = 216 h (L + 48 h). Today's mocactl sbx mcp on a lease-mode sandbox sends leaseKeepalive() every 30 s. Each call needs a token with 60 s left, so it mints with no body about every 14 min, and each of those mints is now an activity mint. The worker never resets lastExec on a keepalive (vmpool.Keepalive), and once the lease idles out, lastExec stays at the lease end.

A silent reset therefore only needs keepalive-only mints to run more than 48 h past the last Exec, for example an MCP window left open over a weekend. The CP's deadline is then later than the worker's reclaim at lastExec + 9 d, and a user who comes back in that window finds the workspace gone while the sandbox reads ready.

Spec §7 accepts this gap for older clients only with the margin plan 3 gives (768 h, so 25 days at the 7-day default). "The control plane can roll out first" holds for per-exec deployments, but not for ones whose SBX_MODES_ALLOWED names a lease mode. Could you either:

  • say in the Rollout notes and the CHANGELOG that lease-mode deployments should take this together with plan 3's SH_WORKSPACE_IDLE raise (or once users run plan 2's mocactl), or
  • leave extension off until the maximum is configured?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, and fixed in 6efafbc with your second option: extension stays off until SH_SANDBOX_MAX_LIFETIME_SECONDS is configured (SandboxConfig.slideOnActivity, checked in extend()). With this PR alone, every deployment keeps today's absolute lifetime, and activity, idleLifetimeS and sandboxExpiresAt are accepted but have no effect. Plan 3's setup.sh writes the key together with SH_WORKSPACE_IDLE = max + 48 h behind SBX_ACK_HOSTS, so the key being present means the workers were sized for sliding. Spec §6.1 and §6.3, the 1.25.0 CHANGELOG, the /token description and the PR's Rollout section now say so, including your lease-keepalive arithmetic.

…ime-cp

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…gured (#770)

Docs: spec 6.1/6.3, CHANGELOG 1.25.0 (also the validation-before-state note), OpenAPI /token.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori

Copy link
Copy Markdown
Member Author

Review follow-ups are pushed (c9a48ec..6efafbc):

  • Conflict with main: upstream/main is merged in (c9a48ec) rather than rebased, because plan 2 is stacked on this branch. fix(control-plane): roll a sandbox create back when its start record fails #832's rollBackCreate try/catch in createSandbox is kept, and sandboxBody gets cfg.
  • Rollout ordering: extension is off until the maximum is configured (6efafbc). See the inline reply and the updated Rollout section.
  • Egress index: TOUCH's egress-index ZADD is guarded (46cd497).
  • User-guide nit: with extension now off by default, this PR alone changes nothing users can see, so docs/sbx/user-guide.md is correct as is. Plan 2 rewrites the lifetime section and adds --lifetime.

Control-plane suite: 1905 passed, 3 skipped (Redis 7.2). mocactl contract: 67 passed. tsc and prettier are clean.

@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 review of 7ff717d..6efafbc (2 fix commits + 1 merge of main). Every open item from the 7ff717d round is closed:

  • Rollout ordering (our suggestion, sandbox-handlers.ts:3022): fixed in 6efafbc. SandboxConfig.slideOnActivity is true only when SH_SANDBOX_MAX_LIFETIME_SECONDS is non-empty, and extend() returns the record unchanged otherwise. That covers all three call sites: token mint, mode-token mint, and PUT mode. So this PR alone leaves today's absolute lifetime on every deployment, and the 216 h worker margin can no longer be outrun by mocactl sbx mcp keepalives. Tests cover the env parsing (unset, empty, set) and a handler test where a mint at day 6 leaves expiresAt at creation + 7 d and the sandbox expires at day 7. Spec §6.1/§6.3, CHANGELOG and OpenAPI /token are updated to match.
  • Egress index score (clawgenti, sandbox-redis.ts TOUCH): fixed in 46cd497. ZSCORE comes first, and ZADD runs only when the member exists and its score is lower, which keeps the old XX no-add semantics and never lowers the score. There is a new Redis test for this.
  • Validation-before-state (clawgenti nit): documented in the 1.25.0 CHANGELOG.
  • Conflict with main (#832 rollBackCreate): resolved correctly in c9a48ec. Main's try/catch around sandboxCreated is kept, and the return passes cfg to sandboxBody. The PR is now clean against main.
  • user-guide §7 nit: the author's rationale holds. With sliding off by default, nothing user-visible changes until plan 2, which rewrites that section.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane config/handlers/Redis Lua), tests, docs (spec, CHANGELOG, OpenAPI)
Agent/IDE config (.claude/.vscode): none
Commits: 2 new non-merge commits + 1 merge, all signed-off: yes
CI status: all passing (lint, check, CodeQL, k8s-kind-e2e, microvm-gates, deploy-scripts, DCO, etc.)

@pdettori
pdettori merged commit ff8af2d into main Nov 17, 2026
17 checks passed
@pdettori
pdettori deleted the feat/sbx-idle-lifetime-cp branch November 17, 2026 01:50
@pdettori pdettori added this to the v0.11.0 milestone Nov 17, 2026
webchang added a commit to webchang/moca that referenced this pull request Nov 17, 2026
Takes upstream main at 1a7f41e (19 merges since 032c8f6): the sandbox
idle lifetime across docs, control plane, clients and deploy (rossoctl#820, rossoctl#837,
rossoctl#842, rossoctl#843), grant redemption (rossoctl#822), the lease-check log line (rossoctl#824),
egress fixes (rossoctl#829, rossoctl#834), the mock wait (rossoctl#828), the deadline timer
(rossoctl#835), the create rollback (rossoctl#832), multi refusals and the rossoctl#363 leftovers
(rossoctl#833, rossoctl#838), the identity near-miss check (rossoctl#827), mocactl login errors
(rossoctl#836), the ghostunnel probes (rossoctl#830), refusal-burst deferral (rossoctl#831), a
sandbox-worker change (rossoctl#841) and the v0.11 doc truth (rossoctl#821).

Conflicts (one):

- deploy/sbx/README.md, the "Optional inputs" table. Upstream (rossoctl#843)
  rewrote the SBX_LIFETIME_DAYS row (the default idle lifetime, at most
  SBX_MAX_LIFETIME_DAYS) and added the SBX_MAX_LIFETIME_DAYS and
  SBX_LOWER_WORKSPACE_IDLE rows, which widened the table; the fork had
  added an SBX_GATE_RECORD_SCHEMA row at its end. Resolved by taking
  upstream's table whole and appending the fork's SBX_GATE_RECORD_SCHEMA
  row after SBX_PROFILE, then re-padding the table with prettier. The
  fork's env-file example line for SBX_GATE_RECORD_SCHEMA merged cleanly.

Merged without markers, checked: setup.sh keeps the fork's
SBX_GATE_RECORD_SCHEMA validation and its sbx-settings write (so it stays
in the settings hash) beside upstream's SH_SANDBOX_MAX_LIFETIME_SECONDS;
both ocp-sbx and ocp-combined patch-control-plane.yaml keep the optional
SH_GATE_RECORD_SCHEMA from sbx-settings beside the new optional
SH_SANDBOX_MAX_LIFETIME_SECONDS; setup.test.sh keeps the fork's cases
beside upstream's. The fork's RUNBOOK, README and template-onboarding
docs say nothing about sandbox lifetime, refusal bursts, login errors or
the create rollback, so none needed a correction; GUIDE.md is unchanged
and GUIDE.pdf is not regenerated.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Rong Chang <[email protected]>
pdettori added a commit that referenced this pull request Nov 17, 2026
… caveat (#770)

The idle-lifetime spec moves to v0.2, implemented in #837, #842 and #843 and
shipping in v0.11.0, and records what the build decided (sliding only once the
maximum is configured, doctor and sbx env, SBX_MAX_LIFETIME_DAYS=off, a
lowered maximum keeping the workers' idle). The registry row reads
implemented. The deploy README says to keep deploy/sbx/.generated/workers
until a lowered maximum's old value has passed: the kept idle lives only in
those bundles.

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

3 participants