Skip to content

fix(platform): repair sandbox op metrics, slot wake and dead session lanes - #3226

Merged
larryro merged 14 commits into
mainfrom
fix/sandbox-harness-hardening
Sep 6, 2026
Merged

larryro merged 14 commits into
mainfrom
fix/sandbox-harness-hardening

Conversation

@larryro

@larryro larryro commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Summary

Sandbox-domain hardening from the backend deep review: the two live sandbox metric reads counted an op kind no writer produces, the most frequent slot release woke nobody, three 0.4-era lanes (FIFO admission tickets, provisionSession, the op/checkpoint API) and a handful of core/sandbox helpers had no production caller, and the browser-session pool the video-link ingest claims from had no way to be populated. Nine commits, each with the regression or probe that pins it.

Findings fixed

  • sandbox-domain-harnesses-1 — /sandbox/external-turn-metrics + /sandbox/harness-health filtered kind = 'agent-run'; both now fold SANDBOX_AGENT_OP_KINDS (task-agent, workflow-agent), defined once in core/sandbox/session_constants.ts.
  • sandbox-domain-harnesses-2 — the task re-attach sweep created a missing op row as agent-run (invisible to the run card); it files task-agent, and claimRecoveryResume.createMissing.kind is typed to the vocabulary.
  • sandbox-domain-harnesses-3 — releaseProjectAgentSessionSlot is now the one owner-keyed, running-op/pinned-guarded seam (shim + deadline watchdog) and wakes the org's oldest parked run when a slot was actually freed; dead markSessionStopped removed. Follow-up in the same PR: wakeParkedAgentRuns never claims a parked run past its deadline — the integration proof caught the deadline sweep's release waking the overdue parked run it was about to fail (parked=queued), so the claim predicate now carries deadline_at_ms > now and the deadline lane owns such runs on every edge.
  • sandbox-domain-harnesses-v1 — the FIFO admission-ticket lane (ticket seam on both slot verbs, helpers, WaitFifoError, REAP watchdog pass, constants) removed; 0.5 parks on project_agent_runs.waiting_for_capacity_at_ms.
  • sandbox-domain-harnesses-4 — provisionSession / parkAdmissionTicket and their types removed (hosts provision through the shim verbs).
  • sandbox-domain-harnesses-5 — the eleven dead op/checkpoint exports in sessions.ts removed; sandbox_agent_checkpoints no longer touched.
  • sandbox-domain-harnesses-7 — orphan lib/shared/sandbox-workdir.ts (+ test) deleted.
  • sandbox-domain-harnesses-8 — orphan core/sandbox exports deleted (readSandboxQuotaPolicy, sandboxCapacityWakeEventName, SANDBOX_SESSION_MAX_IDLE_MS, isLiveSessionStatus, the per-step naming helpers, a dead divergent sessionIdForProjectAgent copy, WorkspaceActionContext, AGENT_GRANTABLE_TOOLS); SESSION_ACTION_SUBJECTS kept (source of the live SessionActionSubject type).
  • sandbox-domain-harnesses-6 — the browser-session pool gets its door: GET /api/v1/browser-sessions + POST /api/v1/browser-sessions/import on the REST machine door (the service's instance-admin + TALE_DEPLOYMENT_CONFIG_ADMINS gate applies unchanged, refusing with a stable code); OpenAPI spec + parity case; the client-less /api/app/browser-sessions route retired; docs en/de/fr rewritten (real curl import, the two gates, the false "also backs web-fetch and crawler" claim dropped) and the API reference row added.

Skipped

None.

Tests & gates observed

  • bunx tsc --noEmit (services/platform): exit 0.
  • bunx oxlint --type-aware (services/platform): exit 0.
  • bunx vitest --run --project server (services/platform): Test Files 495 passed (495) / Tests 5975 passed (5975).
  • bun run --filter @tale/docs test: Test Files 30 passed (30) / Tests 194 passed (194).
  • bun run check (repo root): Tasks: 40 successful, 40 total (exit 0; test:ui Test Files 455 passed (455) / Tests 3503 passed (3503)).
  • bun run knip:check: exit 0 (one pre-existing configuration hint: cron-parser in ignoreDependencies — no dependency change on this branch).
  • The gates above were observed on b0e4e8813; the two later commits (6cb54c136, 979abd2d8) touch only backend/integration-check.ts, on which bunx tsc --noEmit (exit 0) and bunx oxlint --type-aware (exit 0) were re-run.
  • Integration proof (run-itest.sh, real Postgres + MinIO, with PR fix(platform): pass the corpus scope rows as one jsonb parameter #3222's aa3d1d7a9 cherry-picked temporarily per the campaign brief): run add --chat-max-width CSS variable #3 on 6cb54c136 = 463/466 checks passed across 133/133 lanes — corpus scope drift and webdav re-home red exactly as on main (identical in the other themes' logs), plus task-agent run ledger red (settle=false), whose root cause 979abd2d8 fixes (the notify-driven worker fetches a wake's turn job within ms, so the earlier retire-DELETE could never win; the ledger run now rides a phantom agent the handler's agent-gone guard skips). Run optimize rag action #4 on 979abd2d8 was in progress when this PR was opened — its summary line will be posted as a comment; treat the ledger lane as unproven until then.

Notes for the reviewer

  • Ledger probe (f3): 6cb54c136 is superseded by 979abd2d8 — kept in history (squash-merge folds both).

  • Tables left in place on purpose: app.sandbox_admission_tickets and app.sandbox_agent_checkpoints are no longer read or written by this code, but the previous image's markSessionDestroyed and watchdog still DELETE from them mid-roll, so the DROP TABLE migrations belong to a later release (create-migration doctrine: stop touching first, drop later). Noted in the sessions.ts header.

  • Door choice for the pool (f6): REST v1 rather than a CLI command or a settings form — the pool is an operator concern with no in-app surface, the key acts as its user so the existing decideInstanceAdmin gate (org admin + editor allowlist) applies without a second policy copy, and the family is covered by the OpenAPI parity suite. The listing stays org-member + masked, as the retired /api/app route was.

  • MIGRATION.md's inc-70 ledger row still names /api/app/browser-sessions — a historical record of what that increment shipped; left untouched.

  • The itest's webdav re-home lane is red on main before this campaign (known, not this theme).

`GET /sandbox/external-turn-metrics` and `GET /sandbox/harness-health`
filtered `app.sandbox_session_ops` on `kind = 'agent-run'` — the 0.4
vocabulary. Every 0.5 writer files an agent turn as `task-agent`
(the task-agent host) or `workflow-agent` (the automation agent host),
so both live UI reads aggregated nothing in every deployment; the only
rows they ever counted were the ones the task re-attach sweep CREATED
under `agent-run` for a turn whose op row was missing — and that row
was in turn invisible to the run card, whose read is keyed on
`task-agent` and whose drive upsert never rewrites `kind`.

- `SANDBOX_AGENT_OP_KINDS` / `SandboxAgentOpKind` define the vocabulary
  once (core/sandbox/session_constants.ts); both routes fold with
  `kind = ANY(...)`; `claimRecoveryResume.createMissing.kind` is typed to
  it so a re-attach lane cannot file a row under a foreign kind again.
- tasks/reattach.ts creates the missing row as `task-agent`.
- The stale `'exec' | 'agent-run'` contract in sessions.ts and the
  0017 column comment say the real kinds.
- Integration probes seed `task-agent`; the task re-attach probe asserts
  the created row's kind and that `getAgentRunSandboxOp` returns it, the
  automation twin asserts `workflow-agent`; a unit lock on the sweep's
  INSERT rides reattach.stalled.test.ts.

Findings: sandbox-domain-harnesses-1, sandbox-domain-harnesses-2.
…slot

The most frequent capacity release in the system — a project-agent turn
finishing (`releaseProjectAgentSessionSlot`, run by the host after every
settle and after a failed resume-create) — flipped the standing session
to `stopped` and returned. The release-edge wake lived only in
`markSessionStopped`, which no production path called, and in the
destroy/expiry edges. With N parked runs an org therefore drained one
run per 2-minute `watchdog.task_agents` tick while freed slots sat idle.

`releaseProjectAgentSessionSlot` in sessions.ts is now the one seam
behind the shim verb and the deadline watchdog's inline copy of the same
UPDATE: owner-keyed, running-op and pinned guarded, and it wakes the
org's oldest parked run when a slot was actually freed (best-effort — a
wake failure never fails the release). The dead `markSessionStopped` is
gone.

Regression: sessions.release.test.ts (guards + wake-on-release + no wake
when nothing freed + wake failure swallowed); the tasks watchdog test
asserts it frees the slot through the seam; the run-ledger integration
probe parks a run, releases the agent's slot and asserts the slot
hibernated, one fewer parked run and one more `task.agent_turn` job —
without running the watchdog.

Finding: sandbox-domain-harnesses-3.
No production caller of `reserveSessionSlot` / `resumeSessionSlot` ever
passed a `ticket`: the shim slot verbs and the websites render lane omit
it, and the only caller that did — `provisionSession` — was itself only
reached by its integration probe (the hosts provision through the shim
verbs, with phantom/adopt handling of their own). So the FIFO
park-on-capacity subsystem twinned from 0.4 was unreachable end to end:
`WaitFifoError` was never thrown, `pollAdmission` / `parkAdmissionTicket`
/ `deleteAdmissionTicket` had no caller, and the watchdog's REAP pass
deleted from an always-empty `app.sandbox_admission_tickets` every five
minutes while its docblock and `jobs/tasks.ts` called it "the only guard
against queue-head starvation". 0.5 parks capacity on
`project_agent_runs.waiting_for_capacity_at_ms` instead — a second copy
of the concept the run ledger already implements.

Removed: the `ticket?` seam on both slot verbs and their ticket branches,
the ticket helpers, `WaitFifoError`, the three admission constants,
`provisionSession` + its arg/result types (service.ts keeps the live
teardown/pin/reconcile verbs), the REAP pass + `reaped` result + log
wording, the ticket DELETE in `markSessionDestroyed`. The sessions.ts
header now says how capacity parking actually works. The table itself is
dropped in a later release: the previous image's `markSessionDestroyed`
and watchdog still touch it mid-roll (create-migration doctrine: stop
reading first, drop later).

Probes: `checkSandboxSessions` keeps the caps, the freed-slot admission,
resume and token/op lanes; `checkSandboxSpawner` provisions through the
slot verbs + signed client the hosts use and keeps the HMAC + admin
surface + workspace-tool door assertions; watchdog lane 3 no longer seeds
tickets.

Findings: sandbox-domain-harnesses-v1, sandbox-domain-harnesses-4, and
the SANDBOX_ADMISSION_* part of sandbox-domain-harnesses-8.
sessions.ts shipped eleven exports nothing in the product reached:
`listLiveSessionsForOwner`, `revokeTokensForSession`, `startSessionOp`,
`flushOpProgress`, `finalizeSessionOp`, `latestAgentRunForThread`,
`listAbandonedOps`, `saveAgentCheckpoint`, `loadAgentCheckpoint`,
`deleteAgentCheckpoint` and the `AgentCheckpoint` interface — referenced
only by the integration probe. The op trio was a divergent second copy of
the live op path (the shim upsert in agent-turn-shim.ts + recovery.ts),
and the checkpoint design was superseded by `automation_runs.checkpoints`,
so `app.sandbox_agent_checkpoints` had no production writer — only the
DELETE in `markSessionDestroyed`, now gone too. `SessionOpRow` /
`listRunningOpsBySession` stay (the admin surface reads them).

The table is dropped in a later release: the previous image's
`markSessionDestroyed` still DELETEs from it mid-roll (create-migration
doctrine — stop touching first, drop later; noted in the sessions.ts
header).

Probe: `checkSandboxSessions` proves the token lifecycle on the live
path — minted, read by hash, and revoked by the destroy that frees the
slot — instead of the deleted direct revoke; the op lifecycle is covered
by the turn-drive probes, whose writer is the real one.

Finding: sandbox-domain-harnesses-5.
core/sandbox and lib/shared carried 0.4-era exports nothing in the
product reached (repo-wide grep per symbol, tests and integration probe
excluded):

- lib/shared/sandbox-workdir.ts — the thread-level workdir guard whose
  consumers left in the #2857 rewrite; only its own test imported it,
  while its header still called itself "the only workspace-confinement
  guard".
- quota_policy.ts readSandboxQuotaPolicy — read the retired configCache;
  0.5 reads the policy through readGovernancePolicyForOrg.
- session_constants.ts sandboxCapacityWakeEventName (the durable-step
  awaitEvent wake that no longer exists), SANDBOX_SESSION_MAX_IDLE_MS
  (the spawner reads its own env), isLiveSessionStatus.
- session_naming.ts userOwnerId, sessionIdForWorkflowRun,
  workflowRunOwnerId, SandboxSessionScope, agentCheckpointKey,
  resolveWorkflowSandboxSession (the per-step lane and checkpoint keys),
  plus a dead divergent copy of sessionIdForProjectAgent — the live
  derivation is the run ledger's (tasks/agent-runs.ts).
- workspace_access.ts WorkspaceActionContext; tool_names.ts
  AGENT_GRANTABLE_TOOLS. SESSION_ACTION_SUBJECTS stays: it is the source
  of the live SessionActionSubject type.

The remaining docblocks say what the live lanes are; the naming and
tool-name tests cover the live derivations only.

Findings: sandbox-domain-harnesses-7, sandbox-domain-harnesses-8.
The warmed browser-session pool the video-link ingest claims to get past a
platform's bot wall could never be populated: its list + import lived on
`/api/app/browser-sessions`, which no app adapter, CLI command, e2e or
REST route called, and the shipped docs told operators to "import it
through the `importBrowserSession` internal action" — a 0.4 Convex action
that no longer exists. `claimBrowserSession` therefore answered null in
every deployment and `browser.sweep` swept an always-empty table.

The pool is an operator concern with no in-app surface, so its door is
the REST machine door: `GET /api/v1/browser-sessions` (masked listing)
and `POST /api/v1/browser-sessions/import`. The key acts as its user, so
the service's instance-admin + `TALE_DEPLOYMENT_CONFIG_ADMINS` editor
gate applies unchanged and refuses with a stable `code`; the jar is
encrypted before the INSERT sees it. The client-less `/api/app` route is
retired.

- rest/v1-browser-sessions.ts + unit test (masked list, 400 body, both
  403 gates, 201 with only the encrypted jar in the INSERT).
- OpenAPI: `Browser sessions` tag, both paths, `BrowserSession` /
  `BrowserSessionImport` schemas; the parity suite covers the list shape;
  `public/openapi.json` regenerated.
- Integration probe re-keyed to the REST door with a minted API key and
  asserts the editor-gate refusal code.
- Docs (en/de/fr): the video-ingestion page's Layer 3 now shows the real
  import (curl + jq) and the two gates, and drops the false claim that the
  pool also backs the web-fetch tool and crawler (only the video ingest
  draws from it); the API reference gains the family's row.

Finding: sandbox-domain-harnesses-6.
…y wake

The release-edge wake `releaseProjectAgentSessionSlot` now fires from
the task-agent watchdog too: when the deadline lane fails an overdue
RUNNING run and frees its slot, `wakeParkedAgentRuns` claims the org's
oldest parked run. With a parked run that was itself past its deadline,
the wake un-parked it (cleared `waiting_for_capacity_at_ms`, enqueued
its `task.agent_turn`) before the same sweep's overdue-parked pass —
keyed on `waiting_for_capacity_at_ms IS NOT NULL` — could fail it. The
run launched past its time limit instead of being stopped, and the
integration probe caught it (`parked=queued`, want `failed`).

The claim predicate now excludes `deadline_at_ms <= now`: a parked run
past its deadline is the deadline lane's on every edge (host settle,
destroy, expiry, sweep), never a wake candidate. Unit lock on the claim
predicate and the un-park + enqueue in agent-runs.test.ts; the watchdog
integration probe stays the real-schema proof.

Finding: sandbox-domain-harnesses-3 (follow-up to 05f8d02).
…jobs

The run-ledger probe drives park/claim/wake on a hand-inserted run so the
live pg-boss worker cannot race its assertions — but every wake it
triggers (the direct `wakeParkedAgentRuns` and, since 05f8d02, the
release-edge wake) enqueues the run's REAL `task.agent_turn` job. When
the worker fetched one within its 2 s poll, `startTaskAgentTurnImpl`
failed the run on the probe's fake model ("no configured provider serves
model \"itest-model\"") before the probe's own launch + settle, and the
lane went red at `settle=false`.

Each wake's turn job is now retired as soon as its count is taken (the
`pgboss.job` delete the seam probes already use), so the worker never
sees a job for this run.

Finding: sandbox-domain-harnesses-3 (probe hardening).
6cb54c1 tried to keep the live worker off the run-ledger probe's
hand-inserted run by deleting each wake's `task.agent_turn` job right
after its count was taken. That cannot work: the boss runs with
`useListenNotify` and every queue is `notify: true`, so the worker
fetches a job within milliseconds of its INSERT — the 2 s poll is only
the recovery backstop — and the lane stayed red (`settle=false`, the run
failed on "no configured provider serves model itest-model" between the
release edge and the probe's own settle).

The run's agent is now a PHANTOM id with no `project_agents` row: the
job handler's agent-gone guard skips every turn job the wakes (and the
reuse kick) enqueue before it touches the run, deterministically. The
retire DELETE is gone, and the rekick assertion is exact again (2 runs —
no auto-retry attempts ride in any more).

Finding: sandbox-domain-harnesses-3 (probe hardening, replaces the
6cb54c1 approach).
…er on

The three per-lane op reads (the task run's op, the workflow session's
op, the automation shim's running op) still filtered `kind` by a raw SQL
literal, so a rename of either kind would compile clean and silently
return no rows. TASK_AGENT_OP_KIND / WORKFLOW_AGENT_OP_KIND are typed
against SandboxAgentOpKind next to SANDBOX_AGENT_OP_KINDS, and the three
predicates read them as parameters. No behaviour change.

Follow-up to sandbox-domain-harnesses-1 (PR #3226 review, non-blocking).
The import is a v1 write, so a key whose user belongs to several
organizations must send X-Organization-Slug or gets 400. The curl example
now carries the header the way every api-reference example does, and the
gate paragraph says when it is required (en/de/fr).

Follow-up to sandbox-domain-harnesses-6 (PR #3226 review, non-blocking).
… door

The historical row still sent a reader to /api/app/browser-sessions,
which PR #3226 retired in favour of /api/v1/browser-sessions.
@larryro
larryro merged commit 56af298 into main Sep 6, 2026
@larryro
larryro deleted the fix/sandbox-harness-hardening branch September 6, 2026 01:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant