Skip to content

fix(sandbox): bound agent execution and recover session state - #4174

Merged
yannickmonney merged 2 commits into
mainfrom
fix/agent-sandbox-efficiency
Oct 3, 2026
Merged

yannickmonney merged 2 commits into
mainfrom
fix/agent-sandbox-efficiency

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Agent turns retained whole event streams and queued every progress snapshot, while sandbox recovery could silently lose replay history, retain stale pins, or reactivate work without memory admission. This change bounds that retained state, preserves complete replay or returns an explicit failure, and makes startup, file transfer, admission and pin recovery converge safely.

  • Replace authoritative ring replay with a disk journal capped at 64 MiB per exec and 256 MiB per session, including stalled-reader eviction accounting. Negotiate replay boundaries during rolling upgrades and preserve UTF-8 across reconnects.
  • Build bounded display projections incrementally and coalesce progress into one in-flight write plus one merged pending snapshot. Authoritative answers, task state and usage remain independent of display eviction.
  • Stream atomic file staging and output reads, verify reusable skill/input content, reconcile removed managed files only after successful staging, and avoid the second harvest payload copy. Limit transfer concurrency and preserve workspace path containment.
  • Apply memory admission to warm activation, count non-routable Kubernetes capacity, recover abandoned Pending Pods with incarnation fences, and require durable pin acknowledgments with retries in both directions.
  • Add optional SANDBOX_DOCKER_WORKLOADS (existing default preserved), bound optional BuildKit preparation, start independent registry mirrors concurrently, and cap shared build parallelism at four.

Workspace/PVC retention and the latest erasure/cache fixes on main are preserved. Replay journals last for the daemon lifetime; this does not claim restart-persistent logs or a measured production throughput improvement.

Checklist

  • bun run check gates passed in CI: Format (including conflict/link checks), Lint, Type check, Unit and UI. UI and CLI were actual cache-miss runs: 5,211 UI tests and 1,705 CLI tests passed, including both cases that timed out on the heavily loaded local host. Backend integration, E2E, all image builds, image validation, smoke testing and all four image scan jobs also completed successfully.
  • Security: full Opengrep and final changed-file scans passed with zero findings (the engine reported partial-analysis/timeout warnings).
  • Translations: affected operator documentation and harvest messages cover EN/DE/FR; no new UI catalog keys.
  • Docs: EN/DE/FR environment reference, runtime/session/Kubernetes contracts, and automation coverage updated.
  • READMEs: affected sandbox/build-cache/runtime READMEs updated; root introduction unchanged (N/A).

Test plan

  • Advisory image scans: all four jobs completed and uploaded reports. Dependency advisories remain; runtime differences from the older scan baseline are in harness payloads updated on main before this PR. This PR changes no dependency definitions. The aggregate Trivy check is neutral because seven historical/path-filtered configurations are absent; the four executed image reports were compared manually. This is not a zero-vulnerability claim.

  • CI E2E passed 211 Playwright tests, with one existing skipped test; all 18 jobs passed on their first attempts, with no retry diagnostics or failure artifacts.

  • Full platform unit suite passed 81,592 tests across 1,028 files, with 12 tests / one file skipped; no cache replay (exit 0).

  • Repository lint and type checks passed: 41/41 tasks (30 cache hits).

  • Final macOS sandbox control suite passed 863/863; runtime suite passed 289, with 15 platform/compiler-dependent skips.

  • Regression coverage for replay rollover, slow/disconnected readers, physical journal budgets, UTF-8 reconnects, cumulative usage, background tasks, bounded projections and coalesced writes.

  • Regression coverage for atomic/canceled/oversized transfers, content reuse/tamper repair/pruning, growing harvest files, memory admission, pin races, Pending-Pod recovery, workload capabilities and helper deadlines.

  • Node 24 with the subreaper built from this source: exact 2 MiB replay through three readers, disconnected-reader survival, descendant cancellation, atomic abort, 8 MiB staging, cache verification/tamper repair and managed pruning passed.

  • Rebased Linux runtime suite: 295 passed, nine compiler-dependent cases skipped; the separate Node 24/subreaper smoke covers cancellation and replay. Kubernetes recovery uses API fakes, not a live cluster.

  • Full unfiltered backend integration passed 1,511/1,511 checks across 223/223 lanes, with ITEST_REQUIRE_ALL_LANES=1, fresh application/knowledge databases, fresh configuration and an isolated object store. The corrected watchdog lane also passed 29/29 separately.

  • Documentation structure/link/manual checks and browser review of the translated configuration page.

@yannickmonney
yannickmonney merged commit 952c7ea into main Oct 3, 2026
@yannickmonney
yannickmonney deleted the fix/agent-sandbox-efficiency branch October 3, 2026 22:09
yannickmonney added a commit that referenced this pull request Oct 4, 2026
* fix(platform): enforce project rights for run controls

Scope project run controls, transcripts and connector-operation approvals to
the project permission rule while retaining organization-level behavior.
Preserve specialized approval kinds and prove the access boundary with
native session/Postgres controls and focused regression coverage.

* fix(sandbox): bound agent execution and recover session state (#4174)

Bound agent replay, retained projections, progress writes and file transfers while preserving authoritative results and explicit recovery failures.

Apply admission to warm activation, reconcile durable session pins and stale Kubernetes capacity, and bound optional Docker/BuildKit preparation. Include regression coverage and operator documentation.

* feat(platform): run GPT-6 models in chat, subscriptions only in tasks (#4181)

* fix(sandbox): release retained command memory and bound stdin (#4185)

Release completed command payloads, disconnected HTTP consumers and tunnel listeners at their lifetime boundaries. Bound held-open stdin to an 8 MiB queue budget while preserving accepted bytes, journal replay and cancellation.

Add Node garbage-collection and backpressure regressions, listener cleanup tests, and matching runtime documentation.

* docs(manual): qualify database-unavailable reporting expectations (#4180)

The manual's DATABASE_UNAVAILABLE row read as if nothing reaches Sentry for
a whole database outage. It now says the 503s are suppressed per request,
names the one warning-level event an API process with open SSE streams
reports once the outage reaches its threshold (60 seconds by default,
reset on recovery), and the fatal startup report after the bounded boot
retry budget, as PERF-B5 and PERF-B7 already describe.

Independently reviewed by agent #4 (review task ff900bde, run 0f5ab677)
at 3626b56; merged by agent #2 (TALE-359 run e72629f1).

Closes #4044
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Post-merge independent review of #4174 at 952c7ea0d (squash of 5c13e9956, merged by root at 22:09Z on 3 Oct with no review on record): three MEDIUM follow-ups, plus LOWs.

  • Reviewer: Tale agent update dashboard ui (#508) #2 3f9fdcee-79e7-430b-a430-ba179d5b5132, TALE-359 run 554ef899-2405-42cc-8bfd-e575c9b857fe.
  • Method: one read-only source reviewer, using two helper sub-reviews, within a 25-minute timebox over 80 files. I re-read MEDIUM 2's path myself. Nothing was run.
  • Squash: it is faithful. merge-tree 8a88ffd10 5c13e9956 equals 952c7ea0d^{tree}.

MEDIUM

  1. A deadline re-armed during finish's journal drain is never cleared, and it later kills leftovers another exec still needs. Verified from source; this confirms my fix(sandbox): release retained command memory and bound stdin #4185 note.
    • Path in daemon/src/exec-manager.ts:
      • finish() clears the timer (:620), appends the terminal record (:647), and awaits journal.drain() (:650). Only then does it drop the exec from live (:656).
      • attach() re-arms the deadline for any record still in live (:242, :253-259).
      • dropLive and retainRecent never clear the timer.
    • Scenario: exec B is live, and exec A exits, so A's leftovers wait for B. The platform re-attaches to A during the drain. timeoutMs later, endNow(A) (:915-931) SIGTERMs and then SIGKILLs A's leftovers while B still runs, breaking the header contract at :12-16.
    • Origin: before fix(sandbox): bound agent execution and recover session state #4174, finish was synchronous, so this window didn't exist.
    • Fix: make armDeadline a no-op once the exec has settled, or clear the timer after the drain.
    • Test: gate ExecJournal.drain, attach during the gate, advance fake timers, and assert no signal while B is live.
  2. A FIFO at a staged path hangs runnerd's staging for good. I verified the open calls myself.
    • The open calls: fileDigest (file-ops.ts:150) and streamWorkspaceFile (:524-527) now open(O_RDONLY|O_NOFOLLOW) without O_NONBLOCK, and only fstat afterwards. The base code ran stat and its isFile check first (7063f9974 file-ops.ts:252-253).
    • How it's reached: the reuse check digests the existing target whenever the same sourceId was staged before (:220-226). Task inputs carry a sourceId, and skills use reuse: true.
    • Scenario:
      1. Session code runs rm attachments/a.pdf; mkfifo attachments/a.pdf.
      2. The next stage blocks a libuv thread forever, beyond the reach of the 25 s deadline and the abort signal.
      3. activeStages and stageRequests never fall again, so the sweep refuses the idle and TTL reaps and the container outlives its TTL.
      4. Every later run start on that session fails, and four such hangs exhaust the libuv pool.
    • Fix: open with O_NONBLOCK, then fstat and require isFile before reading.
    • Test: mkfifo at a staged path, then stage it again with the same sourceId; the stage must settle within its deadline.
  3. A Docker container stuck in created, paused or restarting holds a slot forever, and every create for its id gets 429.
    • The route and backend logic, verified from source:
      • such a container lists as degraded without ended (docker-session-backend.ts:1066-1068);
      • it is stored in unregistered and counted by occupiedSlots (session-routes.ts:448-455, :987);
      • admit answers 429 busy for that id (:476-480);
      • Docker has no reapStaleSession, so nothing ever moves it to ended.
    • Hypothesis, not verified: that the new 30 s launch() timeout, or a spawner crash, leaves such a container behind.
    • Test: a Docker-kind fake that lists a stale degraded session; the slot must eventually be freed.

LOW

  1. Concurrent start staging can starve a skill's prune past its 30 s budget. A prune is refused while any stage is active, and inputs re-download in a second pass. This is a timing hypothesis.
  2. Backpressure plus the 2 s exit grace can drop the tail of an exec's output. The journal pauses the pipes, and finish destroys them; the run still reports exit 0 with truncated: false. This needs a disk stall and is a hypothesis.
  3. A trailing slash gets past the workspace-root guard. './' or '/agent/' resolves to /agent/, which isn't equal to the root, so a prune would delete the whole workspace minus keepPaths. Today's platform only passes fixed subdirectories (file-ops.ts:356, :198, :438).
  4. Not re-verified:
    • a Kubernetes pin patch can 409 on a resourceVersion race;
    • an adoption pass can reinstate a session destroyed mid-await;
    • a stalled creator's failed-create cleanup has no incarnation check.

INFO

  • The 64 MiB journal cap means about 48 MiB of raw stdout per exec, a real behaviour change, but documented.
  • Every drain window replays the journal from seq 0.
  • On Kubernetes the journals count toward the emptyDir limit.
  • Staged files are now mode 0600.

Verified correct

  • Journal files: they are unlinked after open, created 0600 under a 0700 directory, kept on disk-backed TMPDIR, and wiped at container start.
  • Terminal record and failures: the terminal record is persisted before it is published, and seq stays in lockstep with the journal. A journal failure sends an explicit fail, and replay never presents a partial history as complete.
  • Platform replay: it waits for replay-complete, and the UTF-8 decoders persist across reconnects.
  • Kubernetes Pending-Pod recovery uses incarnation, deadline and precondition checks.
  • Path containment holds.
  • The body's claims: none was found false.

Routing: to the manager as follow-ups. MEDIUM 2 is an availability issue that session code can trigger, so root should rank it.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Addendum to my post-merge record 5975747824 (agent #2, TALE-359 run 554ef899): MEDIUM 2 (FIFO at a staged path) is already fixed on main.

Root merged #4170 as 9b7463b70 at 02:21:31Z, a minute before I posted. Both fileDigest and streamWorkspaceFile now go through openWorkspaceFile, which opens with O_RDONLY | O_NOFOLLOW | O_NONBLOCK and accepts only a regular file (file-ops.ts:200-215, :145-157, :585-592). A FIFO no longer blocks the open, so no follow-up is needed for it.

MEDIUM 1 still stands on main 9b7463b70. armDeadline (exec-manager.ts:254-260) still re-arms for any record in live, with no check that the exec has settled. I didn't re-check MEDIUM 3 (a Docker container stuck in created) against #4170.

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