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

durability.md

162 lines5.9 KB

1---
2title: Sandbox Instance Durability
3id: sandbox-durability
4order: 9
5description: "Durable sandbox instance resume across processes with a SandboxInstanceStore passed to withSandbox."
6---
7​
8Your agent runs behind more than one server instance, or at the edge. A run
9spins up a sandbox, clones the repo, installs deps, does its work. The next run
10for the same thread should pick that sandbox back up. Instead it builds a fresh
11one every time and pays the whole cold-start cost again.
12​
13[Lifecycle & Snapshots](./lifecycle) already knows how to resume, but its
14bookkeeping is in-memory, so it only holds within one process. The moment a run
15lands on a different replica (or a fresh isolate), that instance has never seen
16the sandbox and re-creates it.
17​
18**Sandbox instance durability** is runtime placement, not chat history. It is
19owned by `@tanstack/ai-sandbox`, independent of `@tanstack/ai-persistence`
20(transcript / runs / interrupts). You may share a database with chat stores, but
21you compose a separate middleware.
22​
23Instance durability does not copy the workspace into your application storage.
24Use [Keep Files After Reload](./portable-snapshots-configure) when a new
25sandbox must rebuild completed files, artifacts, and the saved conversation.
26​
27It is also not the agent's *output*. This page keeps a sandbox findable across
28processes; keeping the run's event stream readable across processes is
29[The Run Journal](./journal). The two compose: a resumed sandbox still holds the
30journal of every **durable** run that executed in it, under `/tmp/tanstack-runs`.
31(Durable meaning `withSandbox` was given both `runs` and `durability`. Journaling
32is opt-in, and a run without it leaves no file there.)
33​
34Two pieces:
35​
36- **`SandboxInstanceStore`**: map of compound key → provider sandbox id (+
37 optional snapshot). Durable, shared across instances.
38- **`LockStore`** (from `@tanstack/ai/locks`): mutual exclusion around resume-or-create.
39 Multi-instance needs a distributed lock. See [Locks](../advanced/locks).
40​
41## Wire it up
42​
43Hand the store to `withSandbox`. The lock is a separate middleware because other
44middleware can share it, and it must come **before** `withSandbox`.
45​
46```ts
47import { chat } from '@tanstack/ai'
48import { InMemoryLockStore, withLocks } from '@tanstack/ai/locks'
49import { grokBuildText } from '@tanstack/ai-grok-build'
50import {
51 InMemorySandboxInstanceStore,
52 defineSandbox,
53 defineWorkspace,
54 withSandbox,
55} from '@tanstack/ai-sandbox'
56import type { ModelMessage } from '@tanstack/ai'
57​
58// Single-process: in-memory is fine for local dev.
59// Multi-instance: your durable SandboxInstanceStore + distributed LockStore.
60const instanceStore = new InMemorySandboxInstanceStore()
61const messages: Array<ModelMessage> = [{ role: 'user', content: 'hi' }]
62​
63const sandbox = defineSandbox({
64 id: 'repo',
65 provider: {
66 name: 'example',
67 capabilities: () => ({
68 fs: true,
69 exec: true,
70 env: true,
71 ports: false,
72 backgroundProcesses: false,
73 writableStdin: false,
74 killableProcesses: false,
75 snapshots: false,
76 networkPolicy: false,
77 durableFilesystem: false,
78 fork: false,
79 }),
80 create: () => {
81 throw new Error('example provider: wire a real SandboxProvider')
82 },
83 resume: () => Promise.resolve(null),
84 destroy: () => Promise.resolve(),
85 },
86 workspace: defineWorkspace({ source: { type: 'none' } }),
87})
88​
89chat({
90 adapter: grokBuildText('grok-build'),
91 messages,
92 middleware: [
93 withLocks(new InMemoryLockStore()),
94 withSandbox(sandbox, { instances: instanceStore }),
95 ],
96})
97```
98​
99With `reuse: 'thread'` (the default), the first run creates and records the
100instance. A later run for the same `threadId` resumes it when the store (and
101lock) are shared across processes.
102​
103Single sandbox, nothing else sharing the lock? Pass both as options and skip the
104extra middleware:
105​
106```ts
107import { InMemoryLockStore } from '@tanstack/ai/locks'
108import { withSandbox } from '@tanstack/ai-sandbox'
109import { instanceStore } from './instance-store'
110import { sandbox } from './sandbox'
111​
112const middleware = [
113 withSandbox(sandbox, {
114 instances: instanceStore,
115 locks: new InMemoryLockStore(), // multi-replica: a distributed LockStore
116 }),
118```
119​
120Optional chat persistence is independent:
121​
122```ts
123import { withLocks, InMemoryLockStore } from '@tanstack/ai/locks'
124import { withPersistence, memoryPersistence } from '@tanstack/ai-persistence'
125import { withSandbox } from '@tanstack/ai-sandbox'
126import { instanceStore } from './instance-store'
127import { sandbox } from './sandbox'
128​
129const middleware = [
130 withPersistence(memoryPersistence()), // chat state only
131 withLocks(new InMemoryLockStore()), // multi-replica: distributed LockStore
132 withSandbox(sandbox, { instances: instanceStore }),
134```
135​
136## Implement `SandboxInstanceStore`
137​
138The store is three methods (`get`, `upsert`, `delete`), each with an invariant that
139a conformance suite checks for you.
140[Build a Sandbox Adapter](../persistence/build-a-sandbox-adapter) walks through the
141implementation, the table, and the suite, alongside the choice of how much a
142sandboxed run should leave behind at all.
143​
144## Locks
145​
146A durable instance map without a distributed lock is still wrong across
147replicas: two concurrent runs for one thread both find no record and both
148create. Pair the store with a lock, either `withLocks` from
149`@tanstack/ai/locks` or the `locks` option above. Full guide:
150[Locks](../advanced/locks).
151​
152## See also
153​
154- [The Run Journal](./journal): durability of a run's output, as opposed to its sandbox
155- [Takeover & Detached Runs](./takeover): surviving a client disconnect. A
156 detached run keeps its sandbox up, and `RunStore.sandboxKey` /
157 `RunStore.detachedSince` is how a later host finds it again
158- [Build a Sandbox Adapter](../persistence/build-a-sandbox-adapter): implement this store, and
159 choose how much a sandboxed run leaves behind
160- [Locks](../advanced/locks)
161- [Lifecycle](./lifecycle)
162- [Persistence overview](../persistence/overview): chat state only