Repository navigation
fix(platform): repair sandbox op metrics, slot wake and dead session lanes - #3226
Merged
Merged
Conversation
`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.
This was referenced Sep 27, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 ofcore/sandboxhelpers 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/external-turn-metrics+/sandbox/harness-healthfilteredkind = 'agent-run'; both now foldSANDBOX_AGENT_OP_KINDS(task-agent,workflow-agent), defined once incore/sandbox/session_constants.ts.agent-run(invisible to the run card); it filestask-agent, andclaimRecoveryResume.createMissing.kindis typed to the vocabulary.releaseProjectAgentSessionSlotis 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; deadmarkSessionStoppedremoved. Follow-up in the same PR:wakeParkedAgentRunsnever 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 carriesdeadline_at_ms > nowand the deadline lane owns such runs on every edge.WaitFifoError, REAP watchdog pass, constants) removed; 0.5 parks onproject_agent_runs.waiting_for_capacity_at_ms.provisionSession/parkAdmissionTicketand their types removed (hosts provision through the shim verbs).sessions.tsremoved;sandbox_agent_checkpointsno longer touched.lib/shared/sandbox-workdir.ts(+ test) deleted.core/sandboxexports deleted (readSandboxQuotaPolicy,sandboxCapacityWakeEventName,SANDBOX_SESSION_MAX_IDLE_MS,isLiveSessionStatus, the per-step naming helpers, a dead divergentsessionIdForProjectAgentcopy,WorkspaceActionContext,AGENT_GRANTABLE_TOOLS);SESSION_ACTION_SUBJECTSkept (source of the liveSessionActionSubjecttype).GET /api/v1/browser-sessions+POST /api/v1/browser-sessions/importon the REST machine door (the service's instance-admin +TALE_DEPLOYMENT_CONFIG_ADMINSgate applies unchanged, refusing with a stablecode); OpenAPI spec + parity case; the client-less/api/app/browser-sessionsroute 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:uiTest Files 455 passed (455)/Tests 3503 passed (3503)).bun run knip:check: exit 0 (one pre-existing configuration hint:cron-parserinignoreDependencies— no dependency change on this branch).b0e4e8813; the two later commits (6cb54c136,979abd2d8) touch onlybackend/integration-check.ts, on whichbunx tsc --noEmit(exit 0) andbunx oxlint --type-aware(exit 0) were re-run.run-itest.sh, real Postgres + MinIO, with PR fix(platform): pass the corpus scope rows as one jsonb parameter #3222'saa3d1d7a9cherry-picked temporarily per the campaign brief): run add--chat-max-widthCSS variable #3 on6cb54c136=463/466 checks passed across 133/133 lanes—corpus scope driftandwebdav re-homered exactly as onmain(identical in the other themes' logs), plustask-agent run ledgerred (settle=false), whose root cause979abd2d8fixes (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 on979abd2d8was 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):
6cb54c136is superseded by979abd2d8— kept in history (squash-merge folds both).Tables left in place on purpose:
app.sandbox_admission_ticketsandapp.sandbox_agent_checkpointsare no longer read or written by this code, but the previous image'smarkSessionDestroyedand watchdog stillDELETEfrom them mid-roll, so theDROP TABLEmigrations belong to a later release (create-migration doctrine: stop touching first, drop later). Noted in thesessions.tsheader.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
decideInstanceAdmingate (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/approute 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-homelane is red onmainbefore this campaign (known, not this theme).