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

store-reference.md

1,253 lines52.5 KB

1---
2title: Store Reference (Advanced)
3id: store-reference
4---
5​
6These are the store contracts in `@tanstack/ai-persistence`. Implement the stores you need. The middleware enables a feature when its store is present.
7​
8| Store | Holds | Used by | Guide |
9| --- | --- | --- | --- |
10| `messages` | The model-message history of each thread | `withPersistence` (required), `reconstructChat` (required) | [Chat persistence](./chat-persistence) |
11| `activities` | AG-UI activity rows of each thread | `withPersistence`, `reconstructChat` | [AG-UI activity rows](./chat-persistence-advanced#ag-ui-activity-rows-on-reload) |
12| `runs` | Run status, timing, errors, usage | `withPersistence`, `reconstructChat` | [Chat persistence](./chat-persistence) |
13| `interrupts` | Pending, resolved, or cancelled human waits. Needs `runs`. | `withPersistence` | [Chat persistence](./chat-persistence) |
14| `metadata` | App and integration key/value state | `withPersistence`, `withCompaction` | [Compaction](../advanced/compaction#compaction-and-persistence) |
15| `generationRuns` | Generation run status and result metadata | `withGenerationPersistence` (required), `reconstructGeneration` (required) | [Generation persistence](./generation-persistence) |
16| `artifacts` | File metadata. Needs `blobs`. | `withGenerationPersistence`, portable snapshots | [Keep generated files](./keep-generated-files) |
17| `blobs` | File bytes. Needs `artifacts`. | `withGenerationPersistence`, portable snapshots | [Keep generated files](./keep-generated-files) |
18| `log` | The append-only session log, with ownership, an input lane, and snapshots | A harness host (required) | [Session stores](#session-stores) |
19| `sessions` | One index entry per thread, for a list of sessions | `withPersistence` (subagent children), your host code | [Session stores](#session-stores) |
20​
21The named groups of chat stores (`ChatTranscriptStores`, `ChatPersistenceStores`, `ChatWithInterruptsStores`) are in [Controls](./controls). To build the stores, see [Build a chat adapter](./build-your-own-chat-adapter) and [Build a generation adapter](./build-your-own-generation-adapter). To test them, see [the conformance suite](./build-your-own-adapter#verify-with-the-conformance-suite).
22​
23## MessageStore
24​
25```ts
26import type { ModelMessage } from '@tanstack/ai'
27​
28type MessagePage =
29 | {
30 messages: Array<ModelMessage>
31 truncated: false
32 cursor?: never
33 }
34 | {
35 messages: Array<ModelMessage>
36 truncated: true
37 cursor: string
38 }
39​
40interface MessageStore {
41 loadThread(
42 threadId: string,
43 options?: { limit?: number; before?: string },
44 ): Promise<Array<ModelMessage> | MessagePage>
45 saveThread(threadId: string, messages: Array<ModelMessage>): Promise<void>
47```
48​
49Rules:
50​
51- `loadThread` with only `threadId` (the middleware calls it this way) returns the full array, never a `MessagePage`.
52- `loadThread` returns `[]`, never `null`, for a thread that was never saved.
53- `limit` and `before` are a paging hint for hydrate. You can ignore them and return the full array. `reconstructChat` then slices after the UI conversion.
54- To page in the database, return a `MessagePage`. `truncated: true` requires a `cursor`. The words `truncated` and `cursor` mean the same as in `BlobStore.list`.
55- If you ignore `before` and return the newest array again, `reconstructChat` loads the full thread and slices it.
56- `saveThread` gets the full merged list. It replaces the stored thread. It never appends. The merge by id happens in `withPersistence`, not in this store.
57​
58## ActivityStore
59​
60```ts
61import type { ActivityRecord } from '@tanstack/ai-persistence'
62​
63interface ActivityStore {
64 loadActivities(threadId: string): Promise<Array<ActivityRecord>>
65 saveActivities(
66 threadId: string,
67 activities: Array<ActivityRecord>,
68 ): Promise<void>
70```
71​
72Rules:
73​
74- `loadActivities` returns `[]`, never `null`, for a thread that was never saved.
75- `saveActivities` gets the complete activity list for the thread. It replaces the stored list.
76- Activity rows are never model messages. Do not store them in `messages`.
77​
78The store is optional. Without it, activity rows are not durable on the server. Type an implementation with `defineActivityStore`. See [AG-UI activity rows on reload](./chat-persistence-advanced#ag-ui-activity-rows-on-reload).
79​
80## RunStore
81​
82`RunStore` and `RunRecord` come from `@tanstack/ai`. `@tanstack/ai-persistence` re-exports both. `RunError` is exported from `@tanstack/ai` only. One shared definition lets chat persistence and a sandbox run driver use the same record for one run.
83​
84```ts
85import type { TokenUsage } from '@tanstack/ai'
86​
87type TerminalRunStatus = 'completed' | 'failed' | 'aborted'
88type RunStatus = 'running' | 'interrupted' | TerminalRunStatus
89​
90// Why a run failed. `message` is the provider's text, which changes between
91// model versions. `code` is the stable value to switch on (retry, escalate,
92// show a specific UI). Providers do not always supply one.
93interface RunError {
94 message: string
95 code?: string
97​
98interface RunRecord {
99 runId: string
100 threadId: string
101 // Present on a subagent child run. Absent on the parent chat run.
102 parentRunId?: string
103 subagentRunId?: string
104 name?: string
105 status: RunStatus
106 startedAt: number // epoch ms
107 finishedAt?: number // epoch ms, set at a terminal status
108 error?: RunError
109 usage?: TokenUsage // reported usage added up for this runId
110 // ---------------------------------------------------------------------------
111 // DURABLE SANDBOXED RUNS ONLY. A chat app never writes these four, and
112 // nothing in `@tanstack/ai-persistence` reads them. Leave the columns out
113 // until you use `withSandbox(sandbox, { runs, durability })`. See
114 // Build a Sandbox Adapter, "The four run fields".
115 // ---------------------------------------------------------------------------
116 sandboxKey?: string // the sandbox this run is bound to
117 detachedSince?: number // epoch ms since the last viewer left
118 cancelRequested?: boolean // an out-of-band cancel was recorded
119 driverEpoch?: number // fencing token, incremented by each host that claims the run
120 // ---------------------------------------------------------------------------
121 // HOST SESSIONS ONLY. A host that runs agents and activities for a long
122 // session writes these. `chat()` never writes them. A store that keeps the
123 // whole record keeps them too.
124 // ---------------------------------------------------------------------------
125 kind?: 'chat' | 'agent' | 'activity' | 'command' | 'compact'
126 activity?: string // the activity of a `kind: 'activity'` run
127 agent?: string // the agent name of a `kind: 'agent'` run
128 result?: unknown // terminal result metadata (ids, urls, text), never bytes
129 artifacts?: Array<{ artifactId: string; name?: string; mimeType?: string; url?: string }>
130 principal?: { id: string } // who started the run
131 leaseOwner?: string // the host that drives the run now
132 leaseExpiresAt?: number // epoch ms when that claim ends
133 // Crash-resume data from the last model or tool boundary.
134 checkpoint?: {
135 at: number
136 pendingTools?: Array<{ toolCallId: string; name: string; replay: 'safe' | 'never' }>
137 }
139​
140interface RunStore {
141 // Required. Insert-if-absent: an existing runId returns the stored record
142 // unchanged, so a resume never resets its startedAt or status.
143 createOrResume(input: {
144 runId: string
145 threadId: string
146 status?: RunStatus
147 startedAt: number
148 // Copied on the first insert only. A later call leaves them unchanged.
149 parentRunId?: string
150 subagentRunId?: string
151 name?: string
152 kind?: RunRecord['kind']
153 activity?: string
154 agent?: string
155 principal?: { id: string }
156 }): Promise<RunRecord>
157 // Required. A patch for an unknown runId does nothing. It does not throw.
158 update(
159 runId: string,
160 patch: Partial<
161 Pick<
162 RunRecord,
163 | 'status'
164 | 'finishedAt'
165 | 'error'
166 | 'usage'
167 | 'sandboxKey'
168 | 'detachedSince'
169 | 'cancelRequested'
170 | 'driverEpoch'
171 | 'result'
172 | 'artifacts'
173 | 'leaseOwner'
174 | 'leaseExpiresAt'
175 | 'checkpoint'
176 >
177 >,
178 ): Promise<void>
179 // Required.
180 get(runId: string): Promise<RunRecord | null>
181 // Required. The most recent 'running' run of a thread (greatest startedAt),
182 // or null when the thread is idle. reconstructChat uses it to report
183 // activeRun, which lets a hydrating client tail a run that still generates.
184 findActiveRun(threadId: string): Promise<RunRecord | null>
185 // Optional. Every run of a thread, startedAt ascending.
186 listByThread?(threadId: string): Promise<Array<RunRecord>>
187 // Optional. The child runs of one parent, oldest startedAt first.
188 listByParentRun?(parentRunId: string): Promise<Array<RunRecord>>
189 // Optional. Runs with status 'running' and detachedSince <= now - ttlMs.
190 listReclaimable?(opts: {
191 now: number
192 ttlMs: number
193 }): Promise<Array<RunRecord>>
195```
196​
197Required methods and their rules:
198​
199| Method | Rule |
200| --- | --- |
201| `createOrResume` | Idempotent. A second call for an existing `runId` returns the complete stored record unchanged, `usage` included. Retries can repeat the same run id. |
202| `createOrResume` | Copies `parentRunId`, `subagentRunId`, and `name` on the first insert only. If the caller leaves a field out, leave it out of the record. Do not write `''`. |
203| `update` | A patch for an unknown `runId` does nothing. |
204| `get` | Returns `null` for an unknown `runId`. |
205| `findActiveRun` | Must do a real query. A stub that returns `null` makes `reconstructChat` always report `activeRun: null`. A reloaded client then restores the transcript but never resumes the live reply, and nothing reports the fault, because `null` is also correct for an idle thread. |
206​
207Optional methods. Consumers feature-detect each one:
208​
209| Method | Used by | If you leave it out |
210| --- | --- | --- |
211| `listByThread` | `reconstructChat` (finds the parent run of a child that a tool call started), `includeRuns` timings | A reload loses those subagent cards. Declare the omission in `skipMethods` for the conformance suite. |
212| `listByParentRun` | `reconstructChat` (builds the subagent cards) | A reload shows the saved child text, without cards. The conformance suite skips the subagent checks. No `skipMethods` entry is necessary. |
213| `listReclaimable` | `reapDetachedRuns` from `@tanstack/ai-sandbox` | The reaper logs one line and sweeps nothing. Detached runs never finish and their sandboxes are never reclaimed. Declare the omission in `skipMethods`. |
214​
215The reaper is a function that your app schedules, so `listReclaimable` alone is not enough. `withSandbox`'s detach path fills in `detachedSince` for you. See [Takeover & Detached Runs](../sandbox/takeover#configuration) and [Reaping & Retention](../sandbox/reaping).
216​
217Usage: `withPersistence` adds up the numeric usage fields across the provider calls of one `runId`. The opaque `providerUsageDetails` field keeps the latest reported value. Known usage is saved when the run interrupts or reaches a terminal status.
218​
219The four durable-run fields are a sandbox concern. `runPersistenceConformance` does not test them, and a chat-only backend can leave the columns out. If you use durable sandboxed runs, run `runDurableRunFieldsConformance` from `@tanstack/ai-sandbox/testkit` against the same `runs` store. Each field breaks one mechanism without an error when it is dropped. See [Build a Sandbox Adapter](./build-a-sandbox-adapter#the-four-run-fields).
220​
221Capability tiers belong at the store level, not the method level. A backend with no run lifecycle declares `ChatTranscriptStores` and leaves out `runs`. It does not supply a `RunStore` with a stubbed method. The type system catches a missing store. An incomplete store fails at runtime with no error.
222​
223Two helpers come with the contract:
224​
225- `isTerminalRunStatus` is a type predicate. Inside the guard, the status is a `TerminalRunStatus`:
226​
227 ```ts
228 import { isTerminalRunStatus } from '@tanstack/ai-persistence'
229 import type { RunRecord, TerminalRunStatus } from '@tanstack/ai-persistence'
230​
231 function finalStatus(run: RunRecord): TerminalRunStatus | null {
232 return isTerminalRunStatus(run.status) ? run.status : null
233 }
234 ```
235​
236- `defineRunStore` is generic over the object you pass, so the result keeps that object's exact shape. An optional method that you implemented needs no `?.` in your own code. For example, `createRunStore(db).findActiveRun(threadId)` is a direct call on the store from the [chat walkthrough](./build-your-own-chat-adapter). A consumer that holds a plain `RunStore` still feature-detects the same method.
237​
238Reference implementations: `MemoryRunStore` in `packages/ai-persistence/src/memory.ts` and the SQLite adapter in `examples/ts-react-chat` (`src/lib/sqlite-persistence.ts`). Both implement all seven run methods.
239​
240## InterruptStore
241​
242```ts
243interface InterruptRecord {
244 interruptId: string
245 runId: string
246 threadId: string
247 status: 'pending' | 'resolved' | 'cancelled'
248 requestedAt: number // epoch ms
249 resolvedAt?: number // epoch ms, set when resolved or cancelled
250 payload: Record<string, unknown>
251 response?: unknown
253​
254type InterruptCommitEntry =
255 | { interruptId: string; status: 'resolved'; response?: unknown }
256 | { interruptId: string; status: 'cancelled' }
257​
258interface InterruptStore {
259 create(record: Omit<InterruptRecord, 'status' | 'resolvedAt'>): Promise<void>
260 commitBatch?(entries: ReadonlyArray<InterruptCommitEntry>): Promise<void>
261 resolve(interruptId: string, response?: unknown): Promise<void>
262 cancel(interruptId: string): Promise<void>
263 get(interruptId: string): Promise<InterruptRecord | null>
264 list(threadId: string): Promise<Array<InterruptRecord>>
265 listPending(threadId: string): Promise<Array<InterruptRecord>>
266 listByRun(runId: string): Promise<Array<InterruptRecord>>
267 listPendingByRun(runId: string): Promise<Array<InterruptRecord>>
269```
270​
271Rules:
272​
273- `create` takes a record without `status` and `resolvedAt`, so every interrupt starts as `'pending'`.
274- `create` is insert-if-absent. A duplicate `create` never changes an interrupt that is already resolved.
275- `resolve` and `cancel` do nothing for an unknown `interruptId`.
276- The `list*` methods return records in `requestedAt` ascending order.
277- With chat persistence, an `interrupts` store requires a `runs` store.
278​
279`commitBatch` is optional. If you implement it, write all entries in one database transaction. Reject the whole batch (throw and write nothing) when any entry:
280​
281- repeats an `interruptId`,
282- names an interrupt that does not exist, or
283- names an interrupt that is not `'pending'`.
284​
285Without `commitBatch`, the middleware calls `resolve` and `cancel` one entry at a time. That fallback is not atomic.
286​
287## MetadataStore
288​
289`MetadataStore` comes from `@tanstack/ai` and is re-exported here.
290​
291```ts
292interface MetadataStore {
293 get(namespace: string, key: string): Promise<unknown | null>
294 set(namespace: string, key: string, value: unknown): Promise<void>
295 delete(namespace: string, key: string): Promise<void>
296 // Optional: compare-and-set.
297 getVersioned?(
298 namespace: string,
299 key: string,
300 ): Promise<{ value: unknown; revision: string } | null>
301 setIf?(
302 namespace: string,
303 key: string,
304 value: unknown,
305 expectedRevision: string | null,
306 ): Promise<{ ok: true; revision: string } | { ok: false; reason: 'conflict' }>
308```
309​
310Rules:
311​
312- `(namespace, key)` is the identity. Your app owns the namespaces and the value schemas.
313- A stored `null` looks the same as an absent key. To store `null`, wrap it (for example, `{ value: null }`), or reject nullish values.
314- Do not put the transcript in metadata. The `messages` store owns it.
315​
316Add `getVersioned` and `setIf` when two writers can change the same key at the same time. Then the second write cannot erase the first:
317​
318- `getVersioned` returns the value and its revision, or `null` when the key is absent.
319- `setIf` writes only when the stored revision equals `expectedRevision`. Pass `null` to write only when the key is absent.
320- `setIf` returns `{ ok: true, revision }` on success. On a different revision, it returns `{ ok: false, reason: 'conflict' }` and does not write.
321- Every write gives the key a new revision, a plain `set` too. After `delete`, the next write gets a new revision. A deleted revision is never used again.
322​
323`memoryPersistence()` has both methods. The conformance suite tests them when your store has them.
324​
325`withPersistence` also provides this store through the core `MetadataCapability`. Other middleware can then use it without a dependency on `@tanstack/ai-persistence`. For example, `withCompaction` stores validated context checkpoints here.
326​
327## GenerationRunStore
328​
329The generation counterpart to `RunStore`. A record is keyed by its own `runId`. Its `threadId` is the slot that `findLatestForThread` looks it up by. `withGenerationPersistence` requires this store, not `runs`.
330​
331```ts
332import type { PersistedArtifactRef, TokenUsage } from '@tanstack/ai'
333​
334// The same values as a chat run's `RunStatus`, so one status column and one
335// set of checks cover both tables.
336type GenerationRunStatus =
337 | 'running'
338 | 'interrupted'
339 | 'completed'
340 | 'failed'
341 | 'aborted'
342​
343interface GenerationRunRecord {
344 runId: string
345 threadId: string // the slot this run fills, hydrated by findLatestForThread
346 activity: string // 'image' | 'audio' | 'tts' | 'video' | 'transcription'
347 provider: string
348 model: string
349 status: GenerationRunStatus
350 startedAt: number // epoch ms
351 finishedAt?: number // epoch ms, set at a terminal status
352 error?: { message: string; code?: string }
353 result?: unknown // terminal result metadata (ids, urls), never media bytes
354 artifacts?: Array<PersistedArtifactRef> // present with an artifacts + blobs backend
355 usage?: TokenUsage
357​
358interface GenerationRunStore {
359 createOrResume(input: {
360 runId: string
361 activity: string
362 provider: string
363 model: string
364 startedAt: number
365 threadId: string
366 status?: GenerationRunStatus
367 }): Promise<GenerationRunRecord>
368 update(
369 runId: string,
370 patch: Partial<
371 Pick<
372 GenerationRunRecord,
373 'status' | 'finishedAt' | 'error' | 'result' | 'artifacts' | 'usage'
374 >
375 >,
376 ): Promise<void>
377 get(runId: string): Promise<GenerationRunRecord | null>
378 // The most recent run filed under a thread (greatest startedAt), or null.
379 findLatestForThread(threadId: string): Promise<GenerationRunRecord | null>
381```
382​
383Rules:
384​
385- `createOrResume` is idempotent. A second call for an existing `runId` returns the stored record unchanged. It does not change `startedAt`, `activity`, `provider`, `model`, or `threadId`. `status` defaults to `'running'` on the first insert.
386- `update` for an unknown `runId` does nothing. It does not throw and does not create a record.
387- `findLatestForThread` is required. It is the only query that hydrates a generation. Without it, `persistence: true` restores nothing, and nothing reports the fault.
388​
389## ArtifactStore
390​
391Metadata rows for stored media. The bytes live in a `BlobStore`. Provide both stores together to keep generated bytes.
392​
393```ts
394interface ArtifactRecord {
395 artifactId: string
396 runId: string
397 threadId: string
398 blobKey: string // where the bytes live
399 name: string
400 mimeType: string
401 size: number
402 sourceUrl?: string // where the bytes were fetched FROM (provenance)
403 createdAt: number // epoch ms
405​
406interface ArtifactStore {
407 save: (record: ArtifactRecord) => Promise<void>
408 get: (artifactId: string) => Promise<ArtifactRecord | null>
409 list: (runId: string) => Promise<Array<ArtifactRecord>> // [] when the run has none
410 // Complete thread history, ordered by (createdAt, artifactId) ascending.
411 listForThread: (threadId: string) => Promise<Array<ArtifactRecord>>
412 delete: (artifactId: string) => Promise<void>
413 deleteForRun: (runId: string) => Promise<void>
415```
416​
417Rules:
418​
419- `save` inserts or overwrites the record.
420- `list` and `listForThread` sort by `createdAt` first, then by `artifactId` in bytewise order. Compare the UTF-8 bytes from left to right. Do not use locale collation.
421- `delete` and `deleteForRun` do nothing when there is nothing to delete.
422- Every record must have `blobKey`. With a custom `storageKey`, the path cannot be computed again from the record. See [Keep generated files](./keep-generated-files).
423​
424## BlobStore
425​
426A durable object store for the bytes. By default, `withGenerationPersistence` writes each generated file under the key `artifacts/<runId>/<artifactId>`.
427​
428```ts
429type BlobBody =
430 | ReadableStream<Uint8Array>
431 | ArrayBuffer
432 | ArrayBufferView
433 | string
434 | Blob
435​
436interface BlobRecord {
437 key: string
438 size?: number
439 etag?: string
440 contentType?: string
441 customMetadata?: Record<string, string>
442 createdAt?: number // epoch ms first written
443 updatedAt?: number // epoch ms last overwritten
445​
446interface BlobObject extends BlobRecord {
447 arrayBuffer(): Promise<ArrayBuffer>
448 text(): Promise<string>
449 body?: ReadableStream<Uint8Array>
450 // The slice served, when a range was requested. Absent on a whole read.
451 range?: { offset: number; length: number }
453​
454interface BlobListPage {
455 objects: Array<BlobRecord>
456 cursor?: string // present only when `truncated`
457 truncated?: boolean
459​
460interface BlobPutOptions {
461 contentType?: string
462 customMetadata?: Record<string, string>
463 // Exact byte length of `body`, when the producer knows it. Advisory: use it
464 // to pick an upload strategy (single-shot or multipart). Do not use it in
465 // place of counting the bytes you store.
466 expectedLength?: number
468​
469interface BlobRange {
470 offset: number // from the start of the object, must be inside it
471 length?: number // defaults to "to the end", clamped when it overshoots
473​
474interface BlobGetOptions {
475 range?: BlobRange
477​
478interface BlobListOptions {
479 prefix?: string
480 cursor?: string
481 limit?: number
483​
484interface BlobStore {
485 put(key: string, body: BlobBody, options?: BlobPutOptions): Promise<BlobRecord>
486 get(key: string, options?: BlobGetOptions): Promise<BlobObject | null>
487 head(key: string): Promise<BlobRecord | null>
488 delete(key: string): Promise<void>
489 list(options?: BlobListOptions): Promise<BlobListPage>
491```
492​
493Rules for `list`:
494​
495- `prefix` matches literally and is case-sensitive. Escape SQL `LIKE` metacharacters.
496- When `limit` is set and more keys match, return `truncated: true` with a `cursor`. That cursor returns the keys strictly after it, so paging visits every key once.
497- `limit: 0` returns an empty page that is not truncated.
498​
499Rules for `put`:
500​
501- The body can be a `ReadableStream` with **no declared length**. Your store must read a stream of unknown length to the end. Do not require a length first.
502- A URL-fetched artifact arrives without a length when the origin does not declare one that can be enforced: a chunked reply, or a compressed reply whose `content-length` counts the compressed bytes.
503- When the origin declares a usable length, the body arrives as `fetch` made it, and `expectedLength` has the same number.
504- A backend that needs a declared length for a single-shot upload (Cloudflare R2 on workerd is one) can attach `expectedLength` when it is present. When it is absent, stream through a multipart upload. The `ai-persistence/build-cloudflare-artifact-store` skill has that recipe.
505​
506The conformance testkit tests the length-less case, so a store that handles only byte bodies fails the suite.
507​
508Rules for `get`:
509​
510- With `options.range`, return **only that slice**. `size` still reports the whole object, and the returned `range` reports what you served. A media player needs these values for a `206` response when it seeks.
511- Use `resolveBlobRange(size, range)` to clamp. A `length` past the end is legal and clamps. An `offset` past the end throws, because a serve route answers `416` from the record's `size` before it calls the store.
512​
513```ts ignore
514import { resolveBlobRange } from '@tanstack/ai-persistence'
515​
516async get(key: string, options?: BlobGetOptions) {
517 const row = await selectBlob(key)
518 if (!row) return null
519 if (!options?.range) return blobObject(row, row.body)
520 const served = resolveBlobRange(row.size, options.range)
521 // Slice at the storage layer, not after loading the whole object.
522 const bytes = await selectBlobSlice(key, served.offset, served.length)
523 return blobObject(row, bytes, served)
525```
526​
527Range support is required for a store that holds bytes, and the conformance testkit tests it. A store that ignores `range` sends the whole file on every seek. Then `<video>` seeking fails, and Safari does not play the video at all. A reference-only backend that stores no bytes leaves out `blobs` completely. See [Keep generated files](./keep-generated-files) for the serve route.
528​
529## Session stores
530​
531A host that keeps long-lived sessions needs more than a transcript. It must remember
532the inputs it accepted, the state of each thread, which host works on which thread,
533and a list of sessions to show. Two stores hold that data:
534​
535- `log`: one append-only log per session tree. A harness host needs it.
536- `sessions`: one index entry per thread. `withPersistence` also uses it, to index
537 subagent children.
538​
539A harness host keeps the data of each tenant apart. In `log`, `metadata`, and the
540media artifacts, it writes the id of the root thread as
541`logIdOf({ tenantId, logId: threadId })` from `@tanstack/ai-harness`: `acme:thread-1`,
542or `:thread-1` in the default tenant. Keep it as an opaque string. The session index
543is the one store that keeps `tenantId` and `threadId` as two fields.
544​
545## LogStore
546​
547A host keeps the events, the transcript, the inputs, the runs, the interrupts, the
548settings, the plugin state, and the tool steps of a session tree in one append-only
549log. The root thread and its child threads (agent runs and subagents) share it. With the log, a turn survives a crash. When several machines
550serve the sessions, the log also records which host runs each session, and it keeps
551the inputs that any machine accepts. `LogStore` stores all of this.
552​
553The types, `NO_OWNER_EPOCH`, and the three errors come from `@tanstack/ai-persistence`:
554​
555```ts
556const NO_OWNER_EPOCH = 0 // the epoch of a log that no host ever acquired
557​
558interface LogRecord {
559 type: string
560 [key: string]: unknown
562​
563interface LogEntry {
564 seq: number // the first record of a log is at 1
565 record: LogRecord
567​
568interface LogSnapshot {
569 seq: number // the last position that `state` includes
570 version: string // the version of the `state` shape, yours to name
571 state: unknown // JSON
573​
574type OfferResult = 'offered' | 'duplicate' | 'conflict' | 'deleted'
575​
576interface OfferedInput {
577 inputId: string
578 record: LogRecord
579 offeredAt: number // epoch ms, from the store clock
581​
582interface OrphanedLog {
583 logId: string
584 harness: string // the name of the setup that runs the log
585 reason: 'expired' | 'offered' | 'wake'
587​
588interface LogStore {
589 // Records
590 append(batch: {
591 logId: string
592 seq: number
593 epoch: number
594 records: ReadonlyArray<LogRecord>
595 consumes?: ReadonlyArray<string> // input ids to consume in the same write
596 }): Promise<void>
597 read(query: {
598 logId: string
599 after?: number
600 limit?: number
601 }): Promise<Array<LogEntry>>
602 subscribe(watch: { logId: string; listener: () => void }): () => void
603​
604 // Ownership
605 acquireOwnership(claim: {
606 logId: string
607 harness: string
608 ownerId: string
609 ttlMs: number
610 affinity?: string
611 }): Promise<{ epoch: number; expired?: boolean } | null>
612 renewOwnership(claim: {
613 logId: string
614 ownerId: string
615 epoch: number
616 ttlMs: number
617 }): Promise<boolean>
618 releaseOwnership(claim: {
619 logId: string
620 ownerId: string
621 epoch: number
622 wakeInMs?: number
623 }): Promise<void>
624 pinToWorkers(pin: {
625 logId: string
626 epoch: number
627 affinity: string | null
628 }): Promise<void>
629 markHostAlive(beat: { hostId: string; ttlMs: number }): Promise<void>
630 listLogsWithoutOwner(query: {
631 limit: number
632 harnesses?: ReadonlyArray<string>
633 affinity?: string
634 }): Promise<Array<OrphanedLog>>
635​
636 // Input lane
637 offerInput(input: {
638 logId: string
639 harness: string
640 inputId: string
641 record: LogRecord
642 }): Promise<OfferResult>
643 listOfferedInputs(query: { logId: string }): Promise<Array<OfferedInput>>
644​
645 // Snapshots and lifecycle
646 getSnapshot(query: { logId: string }): Promise<LogSnapshot | null>
647 putSnapshot(
648 snapshot: { logId: string; epoch: number } & LogSnapshot,
649 ): Promise<void>
650 truncate(cut: {
651 logId: string
652 epoch: number
653 beforeSeq: number
654 }): Promise<void>
655 deleteLog(target: { logId: string }): Promise<void>
657```
658​
659`memoryLogStore()` is the reference store. `memoryPersistence()` includes one. To
660run two store instances on one memory log, as two machines on one database, share a
661`memoryLogState()`:
662​
663```ts
664import { memoryLogState, memoryLogStore } from '@tanstack/ai-persistence'
665​
666const state = memoryLogState()
667const first = memoryLogStore({ state })
668const second = memoryLogStore({ state })
669```
670​
671### Fence the writes with the epoch
672​
673Two machines can work on one log. Host A owns the log, and then it stops for a
674while: a long garbage collection pause, or a lost network. Its ownership expires,
675and host B acquires the log. When host A continues, it writes again. Without a
676fence, the log gets the records of two owners.
677​
678The epoch is the fence. Each `acquireOwnership` that starts a new ownership adds 1 to the
679epoch of the log. The owner sends that epoch with each write, and the store refuses
680an old epoch. So the late write of host A rejects with `OwnershipLostError`, and the
681log does not change.
682​
683`append`, `putSnapshot`, `truncate`, and `pinToWorkers` are fenced. They check the
684epoch before anything else:
685​
686- On a log that a host acquired, `epoch` must be the current epoch. A released log
687 refuses every epoch.
688- On a log that no host acquired, `append` needs `NO_OWNER_EPOCH`. A writer that never
689 calls `acquireOwnership` writes with it. `putSnapshot`, `truncate`, and `pinToWorkers` need
690 an owner, so they refuse `NO_OWNER_EPOCH`.
691- A deleted log refuses every epoch until the next `acquireOwnership`.
692- A call with any other epoch rejects with `OwnershipLostError`, and the store writes
693 nothing.
694​
695### Rules for records
696​
697`append` writes `records` at `seq`, `seq + 1`, and so on. The first record of a log
698is at 1. `append` checks in this order, and the first check that fails rejects:
699​
7001. The fence.
7012. `seq` is the next free position: the last position plus 1, or 1 for a new log.
702 Else it rejects with `LogConflictError`.
7033. Each id in `consumes` is a pending offer. Else it rejects with a `TypeError`.
7044. Each record can become JSON. Else it rejects with the error of the JSON copy.
705​
706The batch is atomic. The store writes all the records and consumes all of
707`consumes`, or it changes nothing. An empty batch with no `consumes` resolves. It
708writes nothing and checks nothing.
709​
710`read` gives the log back in order:
711​
712- It returns the entries with `seq` more than `after` (default 0), in `seq` order, at
713 most `limit`.
714- `limit: 0` returns `[]`. A log with no records returns `[]`.
715- If a truncate dropped the record at `after + 1`, `read` rejects with
716 `LogTruncatedError`.
717- The entries are copies. A change to them does not change the log.
718​
719`subscribe` wakes a host when the log changes:
720​
721- The store calls the listener after each successful `append`, each `offerInput` that
722 returns `'offered'`, and each `deleteLog` of the log.
723- The calls come from every store instance on the same backend. That is how one
724 machine hears the writes of another.
725- A store that cannot push must poll inside `subscribe`.
726- If a listener throws, the store logs the error with `console.error`. The write
727 still succeeds.
728​
729### Rules for ownership
730​
731Each log has one ownership record: `harness`, `ownerId`, the epoch, the expiry time,
732a released flag, and an optional affinity and wake time. The epoch never goes down.
733It stays after `releaseOwnership` and after `deleteLog`. The store clock decides each expiry,
734so callers pass `ttlMs` and `wakeInMs`, never a timestamp. A `ttlMs` of 0 or less,
735or a `wakeInMs` less than 0, rejects with `RangeError`.
736​
737`acquireOwnership` gives the log to `ownerId` for `ttlMs` milliseconds:
738​
739- It returns `null` when another owner holds a live record: not released, and not
740 expired.
741- It returns `null` when the log has an affinity that is not `claim.affinity`, and
742 the host of that affinity is alive.
743- For the owner of a live record, it extends the expiry and returns the same epoch.
744- Else it adds 1 to the epoch, stores `harness`, clears the wake time, opens a
745 deleted log again, and returns `{ epoch }`.
746- When the record had another owner that did not release, it returns
747 `{ epoch, expired: true }`. That owner stopped. The harness then sends
748 `harness.ownership.changed` with `reason: taken_over`.
749​
750For the other ownership methods:
751​
752- `renewOwnership` returns `true` only for the current epoch and owner of a log that is not
753 released. In that case, it sets the expiry to `ttlMs` from now. A renew after the
754 expiry also succeeds if no other host acquired the log in between.
755- `releaseOwnership` with the current epoch and owner marks the log released. With
756 `wakeInMs`, it also sets the wake time to `wakeInMs` from now. Any other `releaseOwnership`
757 does nothing.
758- `pinToWorkers` pins the log to the workers with that affinity, or unpins it with
759 `null`. Only the owner pins: it needs the current epoch of an acquired log.
760- `markHostAlive` marks the host `hostId` alive for `ttlMs` from now. `hostId` is the
761 affinity of its pins. A pin counts only while its host is alive, so the logs of a
762 host that stopped go to other hosts. A host that is alive keeps its pins, also on
763 the logs that it released.
764​
765`listLogsWithoutOwner` finds the logs that have work and no live owner. A worker sweep
766([`createHarnessWorker`](../harness/workers) or `host.resumePending`) calls it, then
767calls `acquireOwnership` for each log. A log is listed for the first reason that
768applies:
769​
7701. `'expired'`: the log is not released, and its expiry is due.
7712. `'offered'`: the log has pending offers, and no live owner.
7723. `'wake'`: the log is released, and its wake time is due.
773​
774Then:
775​
776- With `harnesses`, the store lists only the logs with one of those harness names.
777- A log with an affinity is listed only when the query has the same `affinity`, or
778 when the host of the affinity is not alive.
779- The log that is due first comes first, and the store lists at most `limit` logs.
780 `limit: 0` returns `[]`.
781​
782### Rules for the input lane
783​
784A client can send an input to any machine, but only the owner of the log runs it.
785`offerInput` keeps the input as a pending offer. The owner consumes it with
786`append({ consumes })`, in the same write as the records of the input.
787​
788- If `deleteLog` deleted the log and no host acquired it since, `offerInput` returns
789 `'deleted'` and stores nothing.
790- If the `inputId` is new, `offerInput` stores a pending offer with `offeredAt` from the
791 store clock. It calls the listeners and returns `'offered'`.
792- The harness of the owner names the log for `listLogsWithoutOwner`. A log with no owner
793 keeps the `harness` of its first offer. A later offer does not change it.
794- If the `inputId` was offered before (pending or consumed), `offerInput` changes nothing.
795 It returns `'duplicate'` when the JSON of the record is equal, else `'conflict'`.
796- If the record cannot become JSON, `offerInput` rejects and stores nothing.
797- Offers belong to one log. The same `inputId` on two logs gives two offers.
798- `listOfferedInputs` returns the pending offers in offer order.
799​
800### Rules for snapshots, truncate, and delete
801​
802A long log is slow to read from the start. A snapshot saves the state at one
803position. Then a reader loads the snapshot and reads only the records after it.
804With a snapshot, the owner can also drop the old records.
805​
806- `putSnapshot` needs the owner, and it replaces the previous snapshot. If `seq` is
807 after the last position, or before `firstSeq - 1`, it rejects with `RangeError`.
808 `firstSeq` is the first kept position, so an earlier snapshot needs records that
809 a truncate dropped.
810- `getSnapshot` returns the latest snapshot, or `null` when the log has none.
811- `truncate` needs the owner. It drops the records with `seq` less than `beforeSeq`.
812 If the log has no snapshot with a `seq` of `beforeSeq - 1` or more, it rejects
813 with `RangeError`.
814- After a truncate, the positions keep counting, so the next `append` is still at the
815 last position plus 1. A `read` from before the cut rejects with
816 `LogTruncatedError`, and its `firstSeq` is the first kept position.
817- `deleteLog` removes the records, the offers, the snapshot, the truncation point,
818 the affinity, and the wake time, and calls the listeners. The epoch counter stays.
819 Every fenced write fails until the next `acquireOwnership`, also with `NO_OWNER_EPOCH`. So a
820 late write cannot bring a deleted transcript back. An `offerInput` returns `'deleted'`
821 and stores nothing.
822​
823### In SQL
824​
825Run each method that writes in one transaction. Three tables hold the records, the
826ownership, and the offers:
827​
828- `log_records`: the primary key `(log_id, seq)` refuses a taken position.
829- `log_owner`: one row per log, with the epoch, the last position (`head`), and the
830 first kept position. `append`, `acquireOwnership`, and `deleteLog` insert the row with
831 `epoch` 0 when it is missing. Then one compare-and-set on `epoch` and `released`
832 fences every log: acquired, never acquired, and deleted.
833- `log_offers`: the unique key `(log_id, input_id)` finds a duplicate offer.
834​
835```sql
836CREATE TABLE log_records (
837 log_id TEXT NOT NULL,
838 seq BIGINT NOT NULL,
839 record TEXT NOT NULL,
840 PRIMARY KEY (log_id, seq)
841);
842​
843CREATE TABLE log_owner (
844 log_id TEXT PRIMARY KEY,
845 epoch BIGINT NOT NULL DEFAULT 0, -- 0 is NO_OWNER_EPOCH. It never goes down.
846 head BIGINT NOT NULL DEFAULT 0, -- the last position
847 first_seq BIGINT NOT NULL DEFAULT 1, -- the first kept position, after a truncate
848 harness TEXT,
849 owner_id TEXT,
850 expires_at TIMESTAMPTZ,
851 released BOOLEAN NOT NULL DEFAULT FALSE,
852 deleted BOOLEAN NOT NULL DEFAULT FALSE, -- set by deleteLog, cleared by acquire
853 affinity TEXT,
854 wake_at TIMESTAMPTZ
855);
856​
857CREATE TABLE log_hosts (
858 host_id TEXT PRIMARY KEY,
859 expires_at TIMESTAMPTZ NOT NULL -- the heartbeat expires
860);
861​
862CREATE TABLE log_offers (
863 id BIGSERIAL PRIMARY KEY, -- the offer order
864 log_id TEXT NOT NULL,
865 input_id TEXT NOT NULL,
866 harness TEXT NOT NULL,
867 record TEXT NOT NULL,
868 offered_at TIMESTAMPTZ NOT NULL DEFAULT now(),
869 consumed BOOLEAN NOT NULL DEFAULT FALSE,
870 UNIQUE (log_id, input_id)
871);
872```
873​
874`append` does the fence, the position check, and the consume in the same
875transaction as the insert:
876​
877```sql
878BEGIN;
879INSERT INTO log_owner (log_id) VALUES (:log_id) ON CONFLICT DO NOTHING;
880​
881-- The fence and the position in one compare-and-set.
882UPDATE log_owner SET head = :seq + :count - 1
883WHERE log_id = :log_id AND epoch = :epoch AND NOT released AND head = :seq - 1;
884-- No row changed: roll back. Read the row, then reject with
885-- OwnershipLostError (epoch or released) or LogConflictError (head).
886​
887-- One row for each record of the batch.
888INSERT INTO log_records (log_id, seq, record) VALUES (:log_id, :seq, :record);
889​
890UPDATE log_offers SET consumed = TRUE
891WHERE log_id = :log_id AND input_id = ANY(:consumes) AND NOT consumed;
892-- Fewer rows changed than ids in :consumes: roll back, and reject with TypeError.
893COMMIT;
894```
895​
896`acquireOwnership` adds the row too, so a host can take a new log before its first record.
897It reads the row first, because the result needs the old owner:
898​
899```sql
900BEGIN;
901INSERT INTO log_owner (log_id) VALUES (:log_id) ON CONFLICT DO NOTHING;
902​
903SELECT owner_id, released, NOT released AND expires_at > now() AS live
904FROM log_owner WHERE log_id = :log_id FOR UPDATE;
905-- Live, and owner_id is not :owner_id: roll back, and return null.
906-- A live pin of another host (see below): roll back, and return null.
907-- Live, and owner_id is :owner_id: set expires_at, and return { epoch }.
908​
909UPDATE log_owner
910SET epoch = epoch + 1, owner_id = :owner_id, harness = :harness,
911 expires_at = now() + :ttl_ms * interval '1 millisecond',
912 released = FALSE, deleted = FALSE, wake_at = NULL
913WHERE log_id = :log_id
914RETURNING epoch;
915-- expired: true when the row that you read had an owner_id that is not
916-- :owner_id, and released was FALSE.
917COMMIT;
918```
919​
920`deleted = FALSE` opens a deleted log again. For the other methods:
921​
922- `pinToWorkers`, `putSnapshot`, and `truncate` need the owner. Lock the row with
923 `SELECT 1 FROM log_owner WHERE log_id = :log_id AND epoch = :epoch AND epoch > 0
924 AND NOT released FOR UPDATE`. No row: reject with `OwnershipLostError`.
925- `offerInput` first reads `deleted` with `SELECT deleted FROM log_owner WHERE log_id =
926 :log_id FOR SHARE`. `TRUE`: return `'deleted'`, and insert nothing.
927- In `listLogsWithoutOwner`, the harness of a log is `log_owner.harness`. When it is `NULL`,
928 use the `harness` of the first offer of the log (the lowest `id`).
929- Use the database clock (`now()`) for each expiry, wake time, and `offeredAt`. The
930 clocks of the hosts can disagree.
931- `markHostAlive` is one upsert into `log_hosts`. In `acquireOwnership` and `listLogsWithoutOwner`, an
932 affinity counts only when its row has `expires_at > now()`:
933​
934```sql
935INSERT INTO log_hosts (host_id, expires_at)
936VALUES (:host_id, now() + :ttl_ms * interval '1 millisecond')
937ON CONFLICT (host_id) DO UPDATE SET expires_at = EXCLUDED.expires_at;
938​
939-- The pin of a log that `acquireOwnership` and `listLogsWithoutOwner` respect.
940SELECT o.affinity FROM log_owner o
941JOIN log_hosts h ON h.host_id = o.affinity AND h.expires_at > now()
942WHERE o.log_id = :log_id;
943```
944​
945- Keep the snapshot in one more table, with one row per log.
946- `deleteLog` deletes the rows of the log in the other tables. It inserts the
947 `log_owner` row when it is missing, and sets `head = 0`, `first_seq = 1`,
948 `released = TRUE`, `deleted = TRUE`, and no `wake_at` or `affinity`. It keeps
949 `epoch`. The released row refuses every write, also with `NO_OWNER_EPOCH`, and
950 `deleted` refuses every offer, until the next `acquireOwnership`. That owner starts a new
951 log at position 1.
952- Each record is JSON. Store it as text or as a JSON column. The store does not read
953 the records.
954​
955Your store is done when the
956[conformance suite](#check-the-session-stores-with-the-conformance-suite) passes
957with `twin`.
958​
959## SessionIndexStore
960​
961Your app shows a list of sessions: the title, the owner, the time of the last change,
962and the token totals. Reading every transcript to build that list is slow.
963`SessionIndexStore` keeps one small entry per tenant and thread. The index holds no
964messages. The data of each thread stays in the stores that hold it.
965​
966```ts
967interface SessionMember {
968 userId: string
969 role: 'owner' | 'member' | 'viewer' | 'operator'
971​
972interface SessionIndexKey {
973 tenantId?: string // without it, the default tenant
974 threadId: string
976​
977interface SessionIndexEntry {
978 tenantId?: string // with `threadId`, the key of the entry
979 threadId: string
980 members: Array<SessionMember> // the users who can open the thread. The owner has the role `owner`. Empty for a subagent child
981 harness?: string // the name of the setup that runs the thread
982 title?: string
983 parentThreadId?: string // the parent thread. A subagent child's own threadId is `subagent:<runId>`
984 parentToolCallId?: string // the tool call in the parent thread that started it
985 createdAt: number // epoch ms, the first open
986 updatedAt: number // epoch ms, the last change
987 pinned?: boolean
988 archived?: boolean // `list` leaves it out unless `withArchived` is `true`
989 usage?: {
990 turns: number // model calls
991 promptTokens: number
992 completionTokens: number
993 totalTokens: number
994 cachedTokens: number
995 cacheWriteTokens: number
996 cost?: number // USD
997 }
998 metadata?: Record<string, unknown> // app data, for example pinned files
1000​
1001interface SessionIndexListOptions {
1002 tenantId?: string // one tenant per list. Without it, the default tenant
1003 memberId?: string // only the entries with this user in `members`
1004 limit?: number
1005 cursor?: string
1006 parentThreadId?: string | null
1007 search?: string
1008 harness?: string
1009 metadata?: Record<string, string>
1010 withArchived?: boolean // `true`: also the entries with `archived: true`
1012​
1013interface SessionIndexPage {
1014 entries: Array<SessionIndexEntry>
1015 cursor?: string // only when `truncated`
1016 truncated?: boolean
1018​
1019interface SessionIndexStore {
1020 get(key: SessionIndexKey): Promise<SessionIndexEntry | undefined>
1021 getVersioned(
1022 key: SessionIndexKey,
1023 ): Promise<{ entry: SessionIndexEntry; revision: string } | undefined>
1024 upsert(entry: SessionIndexEntry): Promise<void>
1025 upsertIf(input: {
1026 entry: SessionIndexEntry
1027 revision: string | null
1028 }): Promise<{ ok: true; revision: string } | { ok: false; reason: 'conflict' }>
1029 list(options?: SessionIndexListOptions): Promise<SessionIndexPage>
1030 delete(key: SessionIndexKey): Promise<void>
1032```
1033​
1034The key of an entry is its `tenantId` and its `threadId` together. A key without
1035`tenantId` is in the default tenant. So one thread id in two tenants is two entries.
1036In SQL, store the default tenant as `''`, and make `(tenant_id, thread_id)` the
1037primary key.
1038​
1039Rules for `get`, `upsert`, and `delete`:
1040​
1041- `get` returns `undefined` for an unknown key, not `null`.
1042- `upsert` replaces the whole entry for the key of `entry`. A field that the new
1043 entry does not have is gone. Do not merge. To change one field, read the entry and
1044 write a changed copy with `upsertIf`.
1045- Keep `members` as they are written. The host decides what each role can do.
1046- `delete` is a hard delete. After it, `get` and `getVersioned` return `undefined`,
1047 and `upsertIf` with revision `null` writes a new entry. The messages, the log, and
1048 the other data of the thread stay. For an unknown key, `delete` does nothing.
1049​
1050Rules for `list`:
1051​
1052- Return the entries of one tenant only: the `tenantId` of the options, or the
1053 default tenant without it. Never return an entry of another tenant.
1054- Sort by `updatedAt`, the newest first. Entries with the same `updatedAt` go in
1055 `threadId` order. `pinned` gets no special place.
1056- `memberId` returns only the entries whose `members` have that user id, with any
1057 role. A subagent child has no members, so it never matches.
1058- `parentThreadId: 'x'` returns only the entries whose parent is `x`. `null` returns
1059 only the entries with no parent. `search` returns only the entries whose `title`
1060 contains the text, without case. `harness` and `metadata` match exact strings.
1061- Leave out the entries with `archived: true`, unless `withArchived` is `true`.
1062 Filter them in the query, so a page with `limit` stays full.
1063- All filters must match. With `limit`, when more entries match, return
1064 `truncated: true` and a `cursor`. The next call with that `cursor` returns the
1065 entries after the last entry of the page.
1066​
1067With `stores.sessions`, `withPersistence` writes an entry for each subagent child, in
1068the tenant of its `tenantId` option. The entry has the parent thread, the tool call
1069that started the child, and the `harness` of the parent entry. It has no members:
1070access to a child goes through its top-level thread.
1071​
1072### Keep the writes of several hosts
1073​
1074Two hosts can write one entry at the same time. For example, one host writes the
1075usage of a turn while another host writes the pinned files of the app. The host
1076changes an entry with `getVersioned` and `upsertIf`, so the second write never removes
1077the change of the first. Both methods are required: without them, `createHarnessHost`
1078throws.
1079​
1080Rules for `getVersioned` and `upsertIf`:
1081​
1082- `getVersioned` returns the entry and its revision, or `undefined` for an unknown
1083 key. The format of the revision is yours.
1084- A write that changes the entry gives it a new revision: `upsert` and `upsertIf`
1085 both. A revision can be a hash of the content (an ETag of S3 or Netlify Blobs).
1086 Then the same entry, written again after a `delete`, gets the same revision back.
1087- `upsertIf` writes only when the current revision of the key is `revision`, and
1088 returns `{ ok: true, revision }` with the new revision. Pass `null` to write only
1089 when the key has no entry.
1090- On any other revision, `upsertIf` writes nothing and returns
1091 `{ ok: false, reason: 'conflict' }`.
1092​
1093In SQL, keep a revision column. Then:
1094​
1095- For a revision, write with
1096 `UPDATE ... WHERE tenant_id = ? AND thread_id = ? AND revision = ?`. When no row
1097 changed, return a conflict.
1098- For `null`, write with `INSERT ... ON CONFLICT DO NOTHING`. When no row was
1099 added, return a conflict.
1100​
1101`memoryPersistence()` has every method. Its cursor is `<updatedAt>:<threadId>` of the
1102last entry of a page.
1103​
1104### Check the session stores with the conformance suite
1105​
1106`runPersistenceConformance` runs the cases of `log` and `sessions` when your
1107persistence has that store. A persistence without one
1108needs no `skip` entry for it. The `sessions` cases also check the tenants, the
1109`memberId` filter, the hard delete, and compare-and-set.
1110​
1111To check one session store alone, skip the stores that the suite reads by default:
1112​
1113```ts
1114import { runPersistenceConformance } from '@tanstack/ai-persistence/testkit'
1115import { mySessionIndex } from './session-index'
1116​
1117runPersistenceConformance(
1118 'my session index',
1119 () => ({ stores: { sessions: mySessionIndex() } }),
1121 skip: [
1122 'messages',
1123 'activities',
1124 'runs',
1125 'interrupts',
1126 'metadata',
1127 'generationRuns',
1128 'artifacts',
1129 'blobs',
1130 ],
1131 },
1133```
1134​
1135Some `log` cases need two machines on one backend:
1136​
1137- A listener on one instance runs after an append on the other.
1138- Only one instance gets the log from `acquireOwnership`.
1139- An offer on one instance is a `'duplicate'` on the other.
1140- A listener that throws does not stop the listeners of the other instance.
1141​
1142Pass `twin`: a function that returns a second store set on the same backend. Its `log`
1143must be a new store instance, not the same object. If your persistence has `log` and
1144no `twin`, these cases fail.
1145​
1146```ts
1147import { runPersistenceConformance } from '@tanstack/ai-persistence/testkit'
1148import { db } from './db'
1149import { myLogStore } from './log-store'
1150​
1151runPersistenceConformance(
1152 'my log store',
1153 () => ({ stores: { log: myLogStore(db) } }),
1155 skip: [
1156 'messages',
1157 'activities',
1158 'runs',
1159 'interrupts',
1160 'metadata',
1161 'generationRuns',
1162 'artifacts',
1163 'blobs',
1164 ],
1165 // A second store on the same database acts as a second machine.
1166 twin: (persistence) => ({
1167 stores: { ...persistence.stores, log: myLogStore(db) },
1168 }),
1169 },
1171```
1172​
1173For the memory store, share one `memoryLogState()`. Each
1174`memoryLogStore({ state })` call on it gives one more store instance on that
1175state.
1176​
1177## How the records relate
1178​
1179The thread is not a table. It exists as the `thread_id` that the other records refer to. `metadata` is separate, keyed by `(namespace, key)`. On the generation side, a run is keyed by its own `run_id` first. Its `thread_id` names the slot that the run fills, and `findLatestForThread` hydrates by it.
1180​
1181```mermaid
1182erDiagram
1183 MESSAGES ||--o{ RUN : "thread_id, a thread has many runs"
1184 RUN ||--o{ INTERRUPT : "run_id, a run can pause on interrupts"
1185 MESSAGES ||..o{ GENERATION_RUN : "thread_id, the slot a run fills"
1186 GENERATION_RUN ||--o{ ARTIFACT : "run_id, a run produces artifacts"
1187 ARTIFACT ||--|| BLOB : "blob_key, the bytes"
1188​
1189 MESSAGES {
1190 string thread_id PK
1191 json messages_json "full transcript, overwritten on save"
1193 RUN {
1194 string run_id PK
1195 string thread_id
1196 string status "running | interrupted | completed | failed | aborted"
1197 int started_at
1198 int finished_at
1200 INTERRUPT {
1201 string interrupt_id PK
1202 string run_id
1203 string thread_id
1204 string status "pending | resolved | cancelled"
1205 int requested_at
1207 GENERATION_RUN {
1208 string run_id PK
1209 string thread_id "the slot this run fills"
1210 string activity "image | audio | tts | video | transcription"
1211 string status "running | interrupted | completed | failed | aborted"
1213 ARTIFACT {
1214 string artifact_id PK
1215 string run_id
1216 string blob_key "where the bytes live"
1217 string mime_type
1218 int size
1220 BLOB {
1221 string key PK
1222 blob bytes
1224```
1225​
1226## Typing an adapter
1227​
1228Each store has a `define*Store` helper:
1229​
1230| Helper | Store |
1231| --- | --- |
1232| `defineMessageStore` | `messages` |
1233| `defineActivityStore` | `activities` |
1234| `defineRunStore` | `runs` |
1235| `defineInterruptStore` | `interrupts` |
1236| `defineMetadataStore` | `metadata` |
1237| `defineGenerationRunStore` | `generationRuns` |
1238| `defineArtifactStore` | `artifacts` |
1239| `defineBlobStore` | `blobs` |
1240| `defineLogStore` | `log` |
1241| `defineSessionIndexStore` | `sessions` |
1242​
1243The helpers compose into `defineAIPersistence`, which tracks exactly which stores exist. The stores you passed autocomplete on `persistence.stores`. A read of a store you did not pass is a compile error.
1244​
1245Those ten keys are the only ones that `stores` accepts. Any other key throws `Unknown AIPersistence store key` at construction.
1246​
1247To annotate the value, use a named shape:
1248​
1249| Shape | Stores |
1250| --- | --- |
1251| `ChatPersistence` | All four chat state stores: `messages`, `runs`, `interrupts`, `metadata` |
1252| `ChatTranscriptPersistence` | The `messages` floor |
1253| `AIPersistence` | All stores optional. `withPersistence` rejects it, because `stores.messages` can be `undefined`. |