Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

reaping.md

692 lines32.2 KB

1---
2title: Reaping & Retention (Advanced)
3id: sandbox-reaping
4order: 14
5description: "Schedule the sweep that finalizes detached runs, prunes journals, and reclaims sandboxes — and understand why a durable run that nothing reaps never lands its transcript."
6keywords:
7 - reapDetachedRuns
8 - probeRunExit
9 - pruneJournals
10 - reclaimSandbox
11 - sandboxReclaimer
12 - SandboxReclaimFailedError
13 - detachedRunTtlMs
14 - retention
15---
16​
17[Takeover & Detached Runs](./takeover) makes a disconnect survivable: the agent
18keeps working, the sandbox stays up, and the run record remembers that nobody is
19watching. That is only half a lifecycle. Something has to be the *end* of a run
20that no viewer ever came back for.
21​
22That something is `reapDetachedRuns`, and it is a **function, not a scheduler**.
23​
24## Read this first: nothing schedules it for you
25​
26An application that wires `runs` + `durability` and never schedules
27`reapDetachedRuns` is not running a reduced version of this feature. It is
28running a broken one, in three distinct ways at once:
29​
30- **No detached run's delivery log is ever closed.** A detached run's log is
31 deliberately left OPEN and un-terminalized so a takeover can continue it. If
32 nothing ever terminalizes it, every client that attaches parks forever waiting
33 for an event that will not arrive.
34- **`detachedRunTtlMs` is enforced by nothing.** It is not a timer. It is a
35 cutoff the sweep compares `detachedSince` against, and it exists only as an
36 argument to `reapDetachedRuns` — there is no `withSandbox` equivalent. With no
37 sweep, it is a number nobody ever reads and an abandoned agent burns tokens
38 until something else kills it.
39- **Sandboxes bill indefinitely.** Detach-on-disconnect exists precisely so the
40 sandbox is *not* destroyed. Reclaiming it is the sweep's job.
41​
42There is no default cron, no background timer, and no warning at setup — a timer
43inside a library is wrong on every serverless platform the sandbox packages
44target. So treat scheduling as a hard requirement of wiring `durability`, on the
45same footing as passing a real `LockStore`.
46​
47## Why the reaper is correctness, not just cost
48​
49The cost story is the obvious one. The correctness story is the reason
50`'finalized'` exists as an outcome at all.
51​
52`withPersistence` saves a run's transcript in **`onFinish`**. A run that
53completes while detached never reaches anyone's `onFinish`: the host that would
54have run it is the host that left when the client disconnected. The agent
55finished, its bytes are in the in-sandbox journal, the delivery log is frozen at
56the last chunk that was actually delivered, and the message store has nothing.
57​
58Nothing recovers that on its own. A later takeover would — but a takeover only
59happens if a user comes back, and the entire premise of a detached run is that
60they might not. `reapDetachedRuns` is the actor that drives such a run through
61`chat()`'s normal middleware path so `onFinish` fires and the transcript lands.
62That is what `'finalized'` means, and it is why a reaper you never schedule
63silently loses completed work rather than merely wasting money.
64​
65## `reapDetachedRuns`
66​
67```ts
68import { reapDetachedRuns } from '@tanstack/ai-sandbox'
69```
70​
71One sweep, in order:
72​
731. Ask `RunStore.listReclaimable({ now, ttlMs: 0 })` — **once**. `ttlMs: 0` is
74 *every* detached run, because that is the candidate set for finalization: a
75 run that hit its sentinel one second after the viewer left has an unsaved
76 transcript and must not wait out the TTL. Expiry is then classified
77 in-process against `now - detachedRunTtlMs`, inclusively, so the store is not
78 asked twice to compute a subset.
792. For each run in the batch (capped by `maxRuns`, default `25`): classify
80 expiry first, otherwise probe, and only then claim, quiesce, drive, and
81 reclaim.
82​
83`listReclaimable` is optional on `RunStore`. A backend that omits it answers
84`{ considered: 0 }` and one log line — it cannot be reaped at all.
85​
86The function **never rejects**. It runs from a cron, an `alarm()`, or a
87`waitUntil`, where nobody is there to catch it, so every per-run failure is
88logged and folded into the returned `ReapResult`.
89​
90### Outcomes
91​
92`ReapResult.runs` is one `ReapRunEntry` per run, and `ReapResult.outcomes` counts
93them by `ReapRunOutcome`:
94​
95| Outcome | Meaning |
96| --- | --- |
97| `finalized` | The probe saw the exit sentinel, the run was driven to terminal, the transcript is saved. The happy path. |
98| `expired` | Past `detachedRunTtlMs`. Cancelled first (so the teardown is an explicit cancel that destroys the sandbox), then driven to terminal. The probe is skipped — the outcome is terminal either way. Reported even when `runBudgetMs` is what ended the drive: on this path that is the mechanism, not an anomaly. The run's `status` tells the two apart — an agent that had already finished replays to `completed`, one still producing when the budget fired is `aborted`. |
99| `producing` | Still working. `pipeToRunLog` was never entered: nothing appended, no record written, `close()` not called, `detachedSince` untouched. |
100| `unknown` | The probe could not answer. Left exactly as untouched as `producing`, but an operator should see it. |
101| `budget-exceeded` | Anomaly, and **finalization only**. A run the journal already said was finished outran `runBudgetMs`. The record *is* terminal and the log *is* closed, so this is a diagnostic, not a leak. An expired run that outran its budget reports `expired` instead. The entry also carries `terminalizedAnyway`, which is set **if and only if** this anomaly happened — so it survives even when a subsequent failed reclaim overwrites the outcome. |
102| `not-claimed` | Another host holds the claim, or took it mid-drive. Normal — a real viewer attaching mid-sweep is exactly this. |
103| `reclaim-failed` | The run reached terminal and its transcript **is** saved — only `ReapOptions.reclaim` threw, so the sandbox is still up. **Not retryable by the sweep**: the record is terminal by now, so it has already left `listReclaimable` for good, and nothing will sweep it again. This is the outcome that says the cost leak the reaper exists to stop is still leaking; the entry's `error` is the only notice you get. The shipped `sandboxReclaimer` **rejects** on its `destroy-failed` arm precisely so this is reachable without a custom `reclaim`. Overwrites `budget-exceeded` when both happened — the leak is what needs acting on, and `terminalizedAnyway` preserves the other half. |
104| `failed` | Something threw. Logged, counted, and the sweep continued. |
105​
106There is deliberately no "still running" outcome distinct from `producing`, and
107no outcome meaning "we drove it and it turned out not to be finished" — see
108below for why that state is unreachable by construction.
109​
110### It never drives a run to find out whether it finished
111​
112This is the one rule that shapes the whole module, and it is worth understanding
113before you wire anything, because the obvious alternative is worse than it looks.
114​
115The tempting design is: hand the run to `pipeToRunLog` under a short budget and
116see whether it terminalizes. That does not work, because `pipeToRunLog` is total
117by construction — it **always** writes a terminal status and **always** calls
118`durability.close()`, on every path. Against a run that has *not* finished, all
119three producer shapes are destructive:
120​
121| The producer's reaction to the budget signal | Stored status | `close()` |
122| --- | --- | --- |
123| Ignores it and keeps producing | `aborted` | called |
124| Returns on abort (the realistic `drive`) | `aborted` | called |
125| Throws an `AbortError` | `failed` | called |
126​
127The middle row used to read `completed`, and that was the fatal one: a
128signal-aware producer — the shape a *well-behaved* `drive` actually has — exits
129its loop normally, and `pipeToRunLog` checked its abort signal only per chunk, so
130a healthy mid-flight run was recorded as `'completed'` with a `finishedAt`. That
131gap is fixed; `pipeToRunLog` re-checks the signal after the loop, so an aborted
132drive is never recorded as completed.
133​
134The rule is unchanged, though, because the status was never the whole harm: every
135row above writes a terminal record and closes a log that was deliberately left
136open, ending every attached client's stream — and a terminal record drops out of
137`listReclaimable` **forever**, so TTL expiry can never reclaim that run's sandbox.
138A cost leak with no recovery path.
139​
140So finished-ness is learned **out of band**, from the in-sandbox journal, and
141`pipeToRunLog` is entered only for a run already known to have finished or one
142whose TTL has expired (terminal either way). On the finalization path `runBudgetMs`
143therefore degrades from a load-bearing mechanism into a safety net whose expiry is
144a genuine anomaly. On the expiry path it stays load-bearing: nothing polls the
145cancel the reaper records, so the budget is what stops an expired run whose agent
146is still producing.
147​
148The sweep also **never clears `detachedSince`**. That field is what the reaper
149selects on and the evidence its TTL accounting used. Clearing it would reset the
150TTL on every sweep and a detached run would never expire. (The takeover path
151clears it, because there a real viewer genuinely stopped the clock.)
152​
153## `probeRunExit`, and why `hasFinished` is injected
154​
155`ReapOptions.hasFinished` is a required option you supply. `probeRunExit` is the
156shipped implementation:
157​
158```ts
159import { probeRunExit } from '@tanstack/ai-sandbox'
160```
161​
162It reads the **tail** of the run's journal (4 KB by default,
163`DEFAULT_EXIT_PROBE_BYTES`) and answers whether the `{"__exit":N}` sentinel is
164there. Read-only: no append, no record write, no `close()`. Its three-armed
165answer — `finished` / `producing` / `unknown` — is not a boolean on purpose, so a
166provider `exec` that rejected can never be mistaken for "the agent exited". Any
167failure answers `unknown`; an empty tail answers `producing`, the fail-safe
168direction (a journal that does not exist yet is indistinguishable from one with
169no sentinel, and both mean *do not touch this run*).
170​
171It is injected rather than resolved inside the reaper for two reasons, both
172structural:
173​
174- **The delivery log cannot answer the question.** After a detach nothing appends
175 to it — the host that would have appended is the host that left — so the log is
176 frozen at the last delivered chunk while the *journal* keeps growing. The log
177 can only ever say "no news".
178- **Only your application can resolve a `SandboxHandle`.**
179 `SandboxInstanceStore` is `get` / `upsert` / `delete` with no `list` (see
180 [the named limitation](#the-limitation-there-is-no-instance-store-list)), and
181 mapping a `RunRecord.sandboxKey` to a live handle is application knowledge.
182​
183`ReapOptions.reclaim` is injected for the same reason, and
184`sandboxReclaimer` is its ready-made implementation.
185​
186## Server: wire the sweep once
187​
188Everything the sweep needs is what your `POST` route already has, plus a way to
189resolve a sandbox handle from a key. Put it in one module and let each schedule
190call it.
191​
192```ts
193import {
194 probeRunExit,
195 reapDetachedRuns,
196 sandboxReclaimer,
197} from '@tanstack/ai-sandbox'
198import { durableStream } from '@tanstack/ai-durable-stream'
199import type { RunRecord } from '@tanstack/ai'
200import type { ReapResult, RunExitProbe } from '@tanstack/ai-sandbox'
201// Your distributed LockStore, the same one `withSandbox` gets.
202import { locks } from './locks'
203// Your persistence — the SAME RunStore the chat routes use.
204import { persistence } from './persistence'
205// Your `defineSandbox(...)` result and the `SandboxInstanceStore` you passed to
206// `withSandbox(sandbox, { instances })`.
207import { instances, sandbox } from './sandbox'
208// The same `drive` the attach route passes to `sandboxRunDriver` — a function of
209// `{ runId, threadId, signal }` that runs `chat()` with `durability.attach: true`.
210// See ./takeover, "Server: take the run over".
211import { driveRun } from './drive-run'
212​
213const { runs } = persistence.stores
214​
215// The per-run log factory, and it MUST resolve the same log the producing route
216// wrote — otherwise the sweep terminalizes an empty log while the real one stays
217// open. A cron has no incoming request, so synthesize one naming the run.
218//
219// `?runId` is the form to use here: `durableStream` resolves a run from the
220// `X-Run-Id` header first, then `?runId` (the same precedence core's own
221// `memoryStream` uses), but a synthesized `Request` has no reason to carry a
222// header when a query param is just as easy to set — either addresses the
223// same `agent-runs/<runId>` the chat routes' `durableStream(request,
224// durableOptions)` addresses. No resume offset is set, because the reaper is
225// a producer, not a replaying client.
226//
227// The same backend and options the chat routes use — see ../resumable-streams/
228// advanced for the full option set. `durableStream` talks to it over HTTP, so a
229// synthesized request works exactly like a real one: the run's state lives in
230// the backend, not in this process.
231const durableOptions = {
232 server: 'https://streams.example.com',
233 streamPrefix: 'agent-runs',
235​
236function durabilityFor(runId: string) {
237 const url = new URL('https://reaper.internal/')
238 url.searchParams.set('runId', runId)
239 return durableStream(new Request(url), durableOptions)
241​
242// Only the application can map a recorded `sandboxKey` back to a live handle:
243// the instance store answers `get(key)` but never enumerates, and resolving the
244// provider sandbox id it holds is your provider's `resume`. Anything this cannot
245// answer must be `unknown`, never `finished`.
246async function hasFinished(record: RunRecord): Promise<RunExitProbe> {
247 if (record.sandboxKey === undefined) return { state: 'unknown' }
248 try {
249 const instance = await instances.get(record.sandboxKey)
250 if (instance === null) return { state: 'unknown' }
251 const handle = await sandbox.provider.resume({
252 id: instance.providerSandboxId,
253 })
254 if (handle === null) return { state: 'unknown' }
255 return await probeRunExit({ handle, runId: record.runId })
256 } catch (error) {
257 return { state: 'unknown', error }
258 }
260​
261export function sweepDetachedRuns(): Promise<ReapResult> {
262 return reapDetachedRuns({
263 runs,
264 locks,
265 durability: durabilityFor,
266 hasFinished,
267 drive: driveRun,
268 now: Date.now(),
269 // The only place this TTL is configured — there is no `withSandbox`
270 // equivalent. In milliseconds.
271 detachedRunTtlMs: 30 * 60 * 1000,
272 // Sequential by design — each run costs a lock, a provider round-trip, and a
273 // full replay. Keep the batch inside your platform's invocation budget.
274 maxRuns: 25,
275 reclaim: sandboxReclaimer({
276 provider: sandbox.provider,
277 instances,
278 }),
279 })
281```
282​
283`reapDetachedRuns` resolves rather than rejects, so log the summary and let the
284schedule keep its cadence:
285​
286```ts
287import type { ReapResult } from '@tanstack/ai-sandbox'
288import { sweepDetachedRuns } from './sweep'
289​
290// Plain Node, no platform cron. One in flight at a time: a sweep that overruns
291// its interval must not be started twice, or two invocations race for the same
292// claims and every second one reports `not-claimed`.
293let inFlight = false
294​
295async function tick(): Promise<void> {
296 if (inFlight) return
297 inFlight = true
298 try {
299 const result: ReapResult = await sweepDetachedRuns()
300 console.log('reap', result.considered, result.outcomes)
301 for (const run of result.runs) {
302 if (run.outcome === 'failed' || run.outcome === 'unknown') {
303 console.warn('reap needs attention', run.runId, run.outcome, run.error)
304 }
305 }
306 } finally {
307 inFlight = false
308 }
310​
311setInterval(() => void tick(), 60_000)
312```
313​
314### Vercel Cron
315​
316A cron route is a plain `GET`. Guard it — it drives runs and destroys sandboxes,
317so it must not be publicly callable.
318​
319```ts
320import { sweepDetachedRuns } from './sweep'
321​
322export async function GET(request: Request) {
323 const secret = process.env.CRON_SECRET
324 if (
325 secret === undefined ||
326 request.headers.get('authorization') !== `Bearer ${secret}`
327 ) {
328 return new Response('Unauthorized', { status: 401 })
329 }
330 const result = await sweepDetachedRuns()
331 return Response.json({
332 considered: result.considered,
333 probed: result.probed,
334 outcomes: result.outcomes,
335 })
337```
338​
339Register it in `vercel.json` with a `path` and a `schedule` (`*/5 * * * *` is a
340reasonable start — see [sizing](#sizing-detachedrunttl-and-the-sweep-interval)).
341​
342### Cloudflare: a Durable Object `alarm()`
343​
344A DO alarm is the natural scheduler on Workers: it is single-instance, so the
345"one sweep in flight" guard is free, and it re-arms itself.
346​
347```ts
348import { sweepDetachedRuns } from './sweep'
349​
350// The slice of `DurableObjectState` this needs. In a real Worker this is
351// `state.storage` from your Workers types.
352interface AlarmStorage {
353 setAlarm: (scheduledTime: number) => Promise<void>
355​
356export class RunReaper {
357 constructor(private readonly storage: AlarmStorage) {}
358​
359 async alarm(): Promise<void> {
360 try {
361 const result = await sweepDetachedRuns()
362 console.log('reap', result.considered, result.outcomes)
363 } finally {
364 // Re-arm in `finally`. An alarm that throws without rescheduling stops
365 // reaping forever, which is exactly the failure mode this page is about.
366 await this.storage.setAlarm(Date.now() + 60_000)
367 }
368 }
370```
371​
372### Cloudflare's stall watchdog is not a reaper
373​
374`createCloudflareSandboxAgent({ stallTimeoutMs })` sets an app-wide policy for
375both `do-drives` and `colocated` modes. Omit it for the `300000` ms default, pass
376a positive safe-integer millisecond value to customize it, or pass `false` to
377disable it. Its alarm checks about every 30 seconds.
378​
379Persisted events and authenticated `/_bridge` or `/tool-exec` callback arrival
380and completion refresh the run record's `updatedAt`; unknown-run and
381unauthorized requests do not. Silent native operations therefore need a timeout
382longer than their longest expected quiet period. In-flight authenticated
383callbacks are protected. A callback that never completes can leave an orphaned
384`running` record. Disabling the watchdog with `false` can do the same.
385​
386The watchdog atomically marks a stale log `failed`, but may not kill the
387underlying process and never probes a journal or reclaims a sandbox. You must
388still schedule `sweepDetachedRuns`; see the
389[Cloudflare stall-watchdog details](./cloudflare#stall-watchdog).
390​
391## `pruneJournals`: bounding the journal directory
392​
393The reaper terminalizes runs and reclaims sandboxes. It does not tidy the
394journal directory *inside* a sandbox that is still alive — a `keepAlive` sandbox
395serving many turns accumulates journals for every run whose exit sentinel nobody
396was there to observe.
397​
398```ts
399import { pruneJournals } from '@tanstack/ai-sandbox'
400import { persistence } from './persistence'
401import { handleForSandbox } from './sandbox-handles'
402​
403const { runs } = persistence.stores
404​
405export async function sweepJournals(sandboxKey: string) {
406 const result = await pruneJournals({
407 handle: await handleForSandbox(sandboxKey),
408 // Only `get` is used: the sweep asks about the runIds it found on disk and
409 // never enumerates the store, so no optional `RunStore` method is needed.
410 runs,
411 })
412 if (result.ageGate === 'unavailable') {
413 console.warn('journal sweep could not age-gate; kept every orphan')
414 }
415 return result
417```
418​
419**It fails closed everywhere.** The journal is the only copy of the bytes a
420successor host needs to replay a run a dead host abandoned, so the decision
421procedure is not "delete unless there is a reason to keep" — it is the opposite,
422and every arm that is not a *proven*-safe deletion keeps:
423​
424| What the store says | Action | Why |
425| --- | --- | --- |
426| Terminal (`isTerminalRunStatus`) | **delete** | The delivery log, not the journal, is the record a late takeover aligns against. A non-zero exit is terminal too. |
427| Non-terminal — including `'interrupted'` | keep | An interrupt is a human-in-the-loop *pause*; interrupt-resume continues from that journal. |
428| Nothing (unknown runId) | keep until `orphanTtlMs` | The reader **creates** the journal before the record exists, so "unknown runId" is the normal state of a run that started moments ago. |
429| The lookup threw | keep | An unanswered question is not a licence to delete. |
430| The filename did not decode | keep | A truncated name decodes to a plausible but *wrong* runId, so asking the store would answer about some other — possibly live — run. |
431| The mtime age gate is unavailable | keep every age-gated entry | Cannot age-gate ⇒ cannot expire. `unavailable` is a first-class result, never an empty listing. |
432​
433That last row is the trap the module exists to not fall into. BusyBox `find`
434prints its "unrecognized option" diagnostic to stderr and exits **1 with empty
435stdout**; code that reads that as "no file is newer than the cutoff" and
436concludes "therefore every file is old" deletes the whole directory, live runs
437included. The mtime listing carries a self-witness line and reports
438`unavailable` rather than `[]`, and `pruneJournals` honors that as "I keep".
439​
440Deletions per sweep are capped by `maxDeletes` (default `DEFAULT_MAX_DELETES`,
441200); the remainder is reported as kept with reason `max-deletes` and picked up
442next time. `orphanTtlMs` defaults to `DEFAULT_ORPHAN_TTL_MS` (one hour) —
443three orders of magnitude of headroom on the create-then-record race, because the
444cost of too long is bytes and the cost of too short is a destroyed live run.
445`pruneJournals` never rejects either; failures land in
446`PruneJournalsResult.failures`.
447​
448## `reclaimSandbox` and `sandboxReclaimer`
449​
450```ts
451import { reclaimSandbox, sandboxReclaimer } from '@tanstack/ai-sandbox'
452```
453​
454`reclaimSandbox(record, { provider, instances })` destroys the sandbox a terminal
455run was bound to, using `RunRecord.sandboxKey` — recorded by the detach path at
456the moment it still knew the compound key, because the reaper has none of the
457inputs (`threadId`, workspace hash, tenant, reuse strategy) needed to re-derive
458it. It answers `'destroyed'`, `'destroy-failed'`, `'no-sandbox-key'`,
459`'not-found'`, or `'provider-mismatch'`.
460​
461Two orderings are load-bearing:
462​
463- **The provider check comes first**, before either `destroy` or `delete`. A
464 multi-provider app would otherwise hand a Docker container id to Daytona's
465 `destroy`, which at best errors and at worst matches an unrelated sandbox in
466 the other provider's id namespace. A mismatch therefore touches **nothing**,
467 including the instance record, which the *right* provider still needs.
468- **`destroy` before `delete`, and `delete` regardless of whether `destroy`
469 threw.** The provider sandbox may already be gone (idle-reclaimed, region
470 wiped, container pruned). Keeping an instance record that points at nothing
471 guarantees a failed `resume` on the thread's next turn — a broken user
472 experience — whereas an orphaned provider sandbox is a bounded cost the
473 provider itself reclaims. `delete` is therefore unconditional, but the
474 *outcome* must not claim success when `destroy` threw: `'destroy-failed'` is
475 reported instead of `'destroyed'`, because the instance record is gone
476 either way and an operator needs to tell "torn down cleanly" apart from
477 "possibly still billing, and now unreachable from here since
478 `SandboxInstanceStore` has no `list`". `sandboxReclaimer` logs
479 `'destroy-failed'` above debug level for exactly that reason — every other
480 outcome is bookkeeping an operator never needs to see.
481​
482`sandboxReclaimer(options)` is the same thing adapted to `ReapOptions.reclaim`:
483it logs the outcome and resolves — **except on `'destroy-failed'`, where it
484rejects** with a `SandboxReclaimFailedError`. The reaper calls it **only** once
485the record actually reached a terminal status, and with the *originally listed*
486record rather than the one the drive returned — a failed terminal `update`
487yields a locally rebuilt record with no `sandboxKey`, which would answer
488`'no-sandbox-key'` and leak the sandbox silently on exactly the path where
489something already went wrong.
490​
491That rejection is deliberate, and it is what makes the `reclaim-failed` outcome
492reachable at all. `ReapOptions.reclaim` is `(record) => Promise<void>`, so a
493rejection is the sweep's only channel for "the sandbox was NOT reclaimed":
494​
495Wire the reclaimer as shown above (`reclaim: sandboxReclaimer({ provider,
496instances })`), then inspect the summary the sweep hands back:
497​
498```ts
499import { SandboxReclaimFailedError } from '@tanstack/ai-sandbox'
500import type { ReapResult } from '@tanstack/ai-sandbox'
501​
502export function alertOnLeakedSandboxes(
503 result: ReapResult,
504 alert: (message: string, detail: Record<string, unknown>) => void,
505): void {
506 // Watch this counter — it is the leak alarm.
507 if (result.outcomes['reclaim-failed'] === 0) return
508​
509 for (const run of result.runs) {
510 if (run.outcome !== 'reclaim-failed') continue
511 // The transcript IS saved and the record IS terminal; only the teardown
512 // failed. `status`/`exitCode` are reported exactly as `finalized` reports
513 // them, which is what distinguishes this from a `failed` sweep.
514 const leakedKey =
515 run.error instanceof SandboxReclaimFailedError
516 ? run.error.sandboxKey
517 : undefined
518​
519 alert('sandbox may still be billing', {
520 runId: run.runId,
521 status: run.status,
522 sandboxKey: leakedKey,
523 // Present ONLY if the drive also outran `runBudgetMs`. `reclaim-failed`
524 // overwrites the `budget-exceeded` outcome, so this field is what keeps
525 // that second diagnostic on the entry.
526 budgetAnomaly: run.terminalizedAnyway !== undefined,
527 })
528 }
530```
531​
532A `reclaim-failed` run has already left `listReclaimable` for good, so no later
533sweep retries it — that entry is the only notice you will get. A custom
534`reclaim` should follow the same convention: reject when the sandbox was not
535torn down, resolve when there was nothing to tear down.
536​
537## Sizing `detachedRunTtlMs` and the sweep interval
538​
539`detachedRunTtlMs` is a wall-clock cap, in milliseconds, on a *running agent
540with nobody watching*. There is no default and no string parsing: it is a
541required, plain number on `ReapOptions`, and deliberately lives only there —
542`withSandbox` cannot enforce a TTL itself, since `reapDetachedRuns` runs from a
543cron with no chat request in flight and has no capability bus to read it
544from. Passing it directly to the sweep is what keeps it a single source of
545truth instead of two settings that could silently disagree.
546​
547Size it from your agent's honest p99 task duration, not from user patience: too
548short and you cancel real work a user was going to come back to; too long and an
549abandoned run bills for that long. If a coding agent legitimately runs 20
550minutes, 30 minutes (`30 * 60 * 1000`) is tight and an hour is defensible.
551​
552Then keep the sweep interval well **under** the TTL. The interval bounds how
553long *past* the TTL an expired run survives, and it also bounds how long a run
554that finished while detached waits before its transcript lands. A one-minute
555alarm against a 30-minute TTL costs one cheap store query per minute and makes
556both windows negligible. Sweeping every 30 minutes against a 30-minute TTL means
557an expiry can be an hour late.
558​
559`maxRuns` (default 25) and the sequential per-run loop exist so one invocation
560cannot outrun a Worker's CPU budget or a Lambda timeout and be killed mid-drive.
561If a backlog exceeds the batch, the next tick takes the next batch — reduce the
562interval rather than raising the cap.
563​
564## Retention: three clocks, and only one of them is ours
565​
566The reaper closes runs and reclaims sandboxes. It does **not** garbage-collect
567your stored data, and the split is deliberate:
568​
569- **Event-log retention is your durability backend's job**, inside whatever
570 `StreamDurability` you wired. The framework never deletes from it, because it
571 does not own the storage — `memoryStream` evicts completed runs after a grace
572 window, `durableStream` retains per its backend's own policy, and a custom
573 adapter retains per yours. **30 days is a reasonable default**: long enough
574 that a user who reopens a thread the next morning still gets an exact replay of
575 the run, short enough that a chatty deployment does not accumulate raw chunk
576 logs forever.
577- **Message retention is the message store's job**, and it must **outlive** event
578 retention. The transcript is the durable artifact; the event log is a delivery
579 detail. Once a run's events age out, the thread must still render — see the
580 client half below.
581- **Journals are bounded inside the sandbox** by `pruneJournals`, and vanish with
582 the sandbox when `reclaimSandbox` destroys it.
583​
584The ordering is what matters: events may age out first, messages must not.
585​
586## Client: tolerate an aged-out event log
587​
588The usual case needs nothing. `useChat` with `persistence: true` fetches the
589transcript on mount and only then tails whatever run is still generating, so a
590run whose event log is gone simply paints from messages.
591​
592```tsx
593import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
594​
595export function Thread({ threadId }: { threadId: string }) {
596 // On mount this GETs the transcript from the message store, then tails an
597 // `activeRun` if `reconstructChat` reports one. An aged-out event log means
598 // the tail yields nothing — the transcript is already painted, so the thread
599 // still renders correctly. This is why message retention must outlive event
600 // retention.
601 const { messages, sendMessage } = useChat({
602 threadId,
603 connection: fetchServerSentEvents('/api/chat'),
604 persistence: true,
605 })
606​
607 return (
608 <div>
609 <p>{messages.length} messages</p>
610 <button onClick={() => void sendMessage('Continue')}>Continue</button>
611 </div>
612 )
614```
615​
616If you drive the rejoin yourself, make the fallback explicit: join the run, and
617if it yields nothing, fall back to the stored transcript rather than showing an
618empty thread.
619​
620```tsx
621import { fetchServerSentEvents } from '@tanstack/ai-client'
622import { useEffect, useState } from 'react'
623import type { StreamChunk } from '@tanstack/ai'
624​
625export function ThreadView({ threadId, runId }: {
626 threadId: string
627 runId: string
628}) {
629 const [status, setStatus] = useState('joining')
630 const [chunks, setChunks] = useState<Array<StreamChunk>>([])
631​
632 useEffect(() => {
633 const controller = new AbortController()
634 const connection = fetchServerSentEvents('/api/chat')
635​
636 async function join(): Promise<void> {
637 let received = 0
638 for await (const chunk of connection.joinRun(runId, controller.signal)) {
639 received += 1
640 setChunks((previous) => [...previous, chunk])
641 }
642 // Zero chunks from a run the server knew about means its delivery log
643 // aged out (or was pruned). The transcript is still authoritative.
644 if (received === 0) setStatus('replaced-by-transcript')
645 else setStatus('joined')
646 }
647​
648 void join().catch(() => setStatus('replaced-by-transcript'))
649 return () => controller.abort()
650 }, [runId])
651​
652 // Reconstructed from the message store — always render this, and let the
653 // joined events refine it. Never gate the thread on the event log existing.
654 return (
655 <div>
656 <p>
657 {status}: {chunks.length} live events, thread {threadId}
658 </p>
659 </div>
660 )
662```
663​
664The same rule applies server-side: a `GET` that only replays the log will serve
665an empty stream for an aged-out run. Route reconstruct-from-messages first and
666resume second, as [Persistence Overview](../persistence/overview) shows.
667​
668## The limitation: there is no instance-store `list`
669​
670`SandboxInstanceStore` is `get` / `upsert` / `delete`, with no enumeration, and
671that is a deliberate refusal: adding `list` would force every backend and the
672conformance suite to grow an enumeration for one hypothetical caller.
673​
674The consequence is real and documented rather than hidden. **A sandbox whose run
675record was deleted before any sweep saw it is unreachable.** Nothing can name its
676key, so `reclaimSandbox` can never be called for it, and it survives until the
677provider's own idle reclamation takes it. Two things keep that rare: prune run
678records only after their runs are terminal *and* their sandboxes reclaimed, and
679set a provider-side idle timeout as the backstop.
680​
681## See also
682​
683- [Durable Runs Explained](./durable-runs): where this sweep fits in the whole
684 picture, in plain language and with no code
685- [Takeover & Detached Runs](./takeover): how a run becomes detached in the first
686 place, `sandboxRunDriver`, and the single-writer fencing the sweep reuses
687- [The Run Journal](./journal): the journal `probeRunExit` reads and
688 `pruneJournals` bounds
689- [Store Reference](../persistence/store-reference):
690 `listReclaimable`, and the run fields a reapable backend must round-trip
691- [Sandbox Instance Durability](./durability): the instance store
692 `reclaimSandbox` deletes from