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

reaping.md

207 lines7.6 KB

1---
2title: Reaping & Retention (Advanced)
3id: sandbox-reaping
4order: 14
5description: "Schedule the sweep that ends detached sandbox runs nobody came back for: it saves finished transcripts, cancels runs past their time limit, and destroys their sandboxes."
6keywords:
7 - reapDetachedRuns
8 - probeRunExit
9 - pruneJournals
10 - reclaimSandbox
11 - sandboxReclaimer
12 - SandboxReclaimFailedError
13 - detachedRunTtlMs
14 - retention
15---
16​
17The reaper stops a detached run that the user never resumes.
18​
19- **The sandbox bills forever.** Detach exists so the sandbox is not destroyed, so something else must destroy it.
20- **Clients wait forever.** A detached run's log stays open on purpose, so a client that joins waits for an event that never comes.
21- **Finished work is lost.** `withPersistence` saves the transcript in `onFinish`, on the host that drives the run. A run that finishes while detached has no such host, so its transcript is never saved.
22​
23`reapDetachedRuns` ends these runs. It is a function, not a scheduler. **Your app must call it on a schedule.** Nothing does it for you, and nothing warns you when you forget. A timer inside a library does not work on serverless platforms, so the library ships none.
24​
25## Set up the sweep
26​
27This setup uses the `run-setup.ts` module from [Takeover & Detached Runs](./takeover#set-up-the-server).
28​
291. Write the sweep once.
30​
31```ts
32// sweep.ts
33import {
34 probeRunExit,
35 reapDetachedRuns,
36 sandboxReclaimer,
37} from '@tanstack/ai-sandbox'
38import type { RunRecord } from '@tanstack/ai'
39import type { ReapResult, RunExitProbe } from '@tanstack/ai-sandbox'
40import {
41 durabilityFor,
42 driveRun,
43 instances,
44 locks,
45 runs,
46 sandbox,
47} from './run-setup'
48​
49// Did the agent exit? Read the journal tail in the run's sandbox.
50// Anything this cannot answer must be 'unknown', never 'finished'.
51async function hasFinished(record: RunRecord): Promise<RunExitProbe> {
52 if (record.sandboxKey === undefined) return { state: 'unknown' }
53 try {
54 const instance = await instances.get(record.sandboxKey)
55 if (instance === null) return { state: 'unknown' }
56 const handle = await sandbox.provider.resume({
57 id: instance.providerSandboxId,
58 })
59 if (handle === null) return { state: 'unknown' }
60 return await probeRunExit({ handle, runId: record.runId })
61 } catch (error) {
62 return { state: 'unknown', error }
63 }
65​
66export function sweepDetachedRuns(): Promise<ReapResult> {
67 return reapDetachedRuns({
68 runs,
69 locks,
70 // Must resolve the same log the chat routes wrote.
71 durability: durabilityFor,
72 hasFinished,
73 // The same drive the takeover route uses.
74 drive: driveRun,
75 now: Date.now(),
76 // The only place this time limit is set. In milliseconds.
77 detachedRunTtlMs: 30 * 60 * 1000,
78 maxRuns: 25,
79 reclaim: sandboxReclaimer({ provider: sandbox.provider, instances }),
80 })
82```
83​
842. Call it on a schedule. Pick the one that fits your platform.
85​
86**Plain Node.** Keep one sweep in flight at a time. Two at once race for the same runs, and every second one reports `not-claimed`.
87​
88```ts
89import { sweepDetachedRuns } from './sweep'
90​
91let inFlight = false
92​
93async function tick(): Promise<void> {
94 if (inFlight) return
95 inFlight = true
96 try {
97 const result = await sweepDetachedRuns()
98 console.log('reap', result.considered, result.outcomes)
99 for (const run of result.runs) {
100 if (
101 run.outcome === 'failed' ||
102 run.outcome === 'unknown' ||
103 run.outcome === 'reclaim-failed'
104 ) {
105 console.warn('reap needs attention', run.runId, run.outcome, run.error)
106 }
107 }
108 } finally {
109 inFlight = false
110 }
112​
113setInterval(() => void tick(), 60_000)
114```
115​
116**Vercel Cron.** The route drives runs and destroys sandboxes, so guard it with `CRON_SECRET`.
117​
118```ts
119// app/api/cron/reap/route.ts
120import { sweepDetachedRuns } from '../../../../sweep'
121​
122export async function GET(request: Request) {
123 const secret = process.env.CRON_SECRET
124 if (
125 secret === undefined ||
126 request.headers.get('authorization') !== `Bearer ${secret}`
127 ) {
128 return new Response('Unauthorized', { status: 401 })
129 }
130 const result = await sweepDetachedRuns()
131 return Response.json({
132 considered: result.considered,
133 probed: result.probed,
134 outcomes: result.outcomes,
135 })
137```
138​
139```json
141 "crons": [{ "path": "/api/cron/reap", "schedule": "*/5 * * * *" }]
143```
144​
145**Cloudflare Durable Object `alarm()`.** A Durable Object runs one alarm at a time, so you get the "one sweep in flight" guard for free.
146​
147```ts
148import { sweepDetachedRuns } from './sweep'
149​
150// The part of DurableObjectState this needs. In a real Worker, pass
151// `state.storage` from your Workers types.
152interface AlarmStorage {
153 setAlarm: (scheduledTime: number) => Promise<void>
155​
156export class RunReaper {
157 constructor(private readonly storage: AlarmStorage) {}
158​
159 async alarm(): Promise<void> {
160 try {
161 const result = await sweepDetachedRuns()
162 console.log('reap', result.considered, result.outcomes)
163 } finally {
164 // Re-arm in `finally`. An alarm that throws without a new alarm stops
165 // reaping forever.
166 await this.storage.setAlarm(Date.now() + 60_000)
167 }
168 }
170```
171​
1723. Leave a run detached and wait one sweep. Its sandbox is destroyed, and if the agent had finished, its transcript is in the message store.
173​
174> [!WARNING]
175> Watch the `reclaim-failed` count. It means the transcript is saved but the sandbox destroy failed, so the sandbox can still bill. No later sweep retries it. That log line is the only notice you get. See [Reaping Internals](./reaping-advanced#reclaimsandbox-and-sandboxreclaimer).
176​
177## How it works
178​
179Each sweep:
180​
1811. Lists every detached run once, with `RunStore.listReclaimable`.
1822. Takes up to `maxRuns` of them (25 by default) and handles them one at a time.
1833. Never rejects. Every failure is logged and counted in the returned `ReapResult`.
184​
185For each run:
186​
187| The run is | The sweep | Outcome |
188| --- | --- | --- |
189| Past `detachedRunTtlMs` | Cancels it, drives it to a final status, destroys the sandbox. | `expired` |
190| Finished (the journal has the exit line) | Drives it to a final status so `onFinish` saves the transcript, then destroys the sandbox. | `finalized` |
191| Still working | Touches nothing. | `producing` |
192| Not readable (no sandbox, a failed probe) | Touches nothing. | `unknown` |
193| Claimed by another host | Touches nothing. A viewer probably came back. | `not-claimed` |
194​
195The sweep learns that a run finished from the journal in the sandbox, never by driving the run to see. It also never clears `detachedSince`, so the time limit keeps counting. The full outcome list, and why it works this way, is in [Reaping Internals](./reaping-advanced).
196​
197The reaper does not tidy journals inside a sandbox that stays alive. If you use `keepAlive` sandboxes, also schedule [`pruneJournals`](./reaping-advanced#prunejournals-bounding-the-journal-directory).
198​
199## Size the time limit and the interval
200​
201- **Set `detachedRunTtlMs` from your agent's p99 task time**, not from user patience. If an agent can run 20 minutes, 30 minutes is tight and an hour is safe. Too short cancels real work. Too long lets an abandoned run bill for that long.
202- **Sweep well under the time limit.** The interval is how late an expired run can be, and how long a finished run waits for its transcript. Every minute against a 30-minute limit is cheap: one store query per minute. Every 30 minutes against a 30-minute limit can be an hour late.
203- **Do not raise `maxRuns` for a backlog.** The cap keeps one call inside a Worker CPU budget or a Lambda timeout. Sweep more often instead.
204​
205## Go deeper
206​
207For every outcome, the journal probe, `pruneJournals`, sandbox reclaim, data retention, and the instance-store limit, see [Reaping Internals](./reaping-advanced).