Open History to see the last commit
1import {
2 LogConflictError,
3 LogTruncatedError,
4 OwnershipLostError,
5 NO_OWNER_EPOCH,
6 defineAIPersistence,
7} from './types'
8import { resolveBlobRange } from './blob-range'
9import type { ActivityRecord, ModelMessage } from '@tanstack/ai'
10import type {
11 ActivityStore,
12 ArtifactRecord,
13 ArtifactStore,
14 BlobBody,
15 BlobGetOptions,
16 BlobListOptions,
17 BlobObject,
18 BlobPutOptions,
19 BlobRange,
20 BlobRecord,
21 BlobStore,
22 GenerationRunRecord,
23 GenerationRunStore,
24 InterruptCommitEntry,
25 InterruptRecord,
26 InterruptStore,
27 LogRecord,
28 LogSnapshot,
29 LogStore,
30 OrphanedLog,
31 MessageStore,
32 MetadataStore,
33 RunRecord,
34 RunStore,
35 SessionIndexEntry,
36 SessionIndexKey,
37 SessionIndexListOptions,
38 SessionIndexStore,
39} from './types'
40
41const compareUtf8Bytes = (left: string, right: string): number => {
42 const leftBytes = new TextEncoder().encode(left)
43 const rightBytes = new TextEncoder().encode(right)
44 const length = Math.min(leftBytes.length, rightBytes.length)
45
46 for (let index = 0; index < length; index++) {
47 const leftByte = leftBytes[index]
48 const rightByte = rightBytes[index]
49 if (leftByte !== rightByte) {
50 return (leftByte ?? 0) - (rightByte ?? 0)
51 }
52 }
53
54 return leftBytes.length - rightBytes.length
55}
56
57class MemoryMessageStore implements MessageStore {
58 private readonly threads = new Map<string, Array<ModelMessage>>()
59 loadThread(
60 threadId: string,
61 _options?: { limit?: number; before?: string },
62 ): Promise<Array<ModelMessage>> {
63 return Promise.resolve(this.threads.get(threadId)?.slice() ?? [])
64 }
65 saveThread(threadId: string, messages: Array<ModelMessage>): Promise<void> {
66 this.threads.set(threadId, messages.slice())
67 return Promise.resolve()
68 }
69}
70
71class MemoryActivityStore implements ActivityStore {
72 private readonly threads = new Map<string, Array<ActivityRecord>>()
73 loadActivities(threadId: string): Promise<Array<ActivityRecord>> {
74 return Promise.resolve(this.threads.get(threadId)?.slice() ?? [])
75 }
76 saveActivities(
77 threadId: string,
78 activities: Array<ActivityRecord>,
79 ): Promise<void> {
80 this.threads.set(threadId, activities.slice())
81 return Promise.resolve()
82 }
83}
84
85class MemoryRunStore implements RunStore {
86 private readonly runs = new Map<string, RunRecord>()
87 createOrResume(
88 input: Parameters<RunStore['createOrResume']>[0],
89 ): Promise<RunRecord> {
90 const existing = this.runs.get(input.runId)
91 if (existing) return Promise.resolve(existing)
92 const record: RunRecord = {
93 runId: input.runId,
94 threadId: input.threadId,
95 status: input.status ?? 'running',
96 startedAt: input.startedAt,
97 ...(input.parentRunId !== undefined
98 ? { parentRunId: input.parentRunId }
99 : {}),
100 ...(input.subagentRunId !== undefined
101 ? { subagentRunId: input.subagentRunId }
102 : {}),
103 ...(input.name !== undefined ? { name: input.name } : {}),
104 ...(input.kind !== undefined ? { kind: input.kind } : {}),
105 ...(input.activity !== undefined ? { activity: input.activity } : {}),
106 ...(input.agent !== undefined ? { agent: input.agent } : {}),
107 ...(input.principal !== undefined ? { principal: input.principal } : {}),
108 }
109 this.runs.set(record.runId, record)
110 return Promise.resolve(record)
111 }
112 update(
113 runId: string,
114 patch: Parameters<RunStore['update']>[1],
115 ): Promise<void> {
116 const existing = this.runs.get(runId)
117 if (existing) this.runs.set(runId, { ...existing, ...patch })
118 return Promise.resolve()
119 }
120 get(runId: string): Promise<RunRecord | null> {
121 return Promise.resolve(this.runs.get(runId) ?? null)
122 }
123 findActiveRun(threadId: string): Promise<RunRecord | null> {
124 const active = [...this.runs.values()]
125 .filter((run) => run.threadId === threadId && run.status === 'running')
126 .sort((a, b) => b.startedAt - a.startedAt)
127 return Promise.resolve(active[0] ?? null)
128 }
129 listByThread(threadId: string): Promise<Array<RunRecord>> {
130 const matching = [...this.runs.values()]
131 .filter((run) => run.threadId === threadId)
132 .sort((a, b) => a.startedAt - b.startedAt)
133 return Promise.resolve(matching)
134 }
135 listByParentRun(parentRunId: string): Promise<Array<RunRecord>> {
136 const matching = [...this.runs.values()]
137 .filter((run) => run.parentRunId === parentRunId)
138 .sort((a, b) => a.startedAt - b.startedAt)
139 return Promise.resolve(matching)
140 }
141 listReclaimable(opts: {
142 now: number
143 ttlMs: number
144 }): Promise<Array<RunRecord>> {
145 const cutoff = opts.now - opts.ttlMs
146 const matching = [...this.runs.values()].filter(
147 (run) =>
148 run.status === 'running' &&
149 run.detachedSince !== undefined &&
150 run.detachedSince <= cutoff,
151 )
152 return Promise.resolve(matching)
153 }
154}
155
156class MemoryGenerationRunStore implements GenerationRunStore {
157 private readonly generationRuns = new Map<string, GenerationRunRecord>()
158 createOrResume(
159 input: Pick<
160 GenerationRunRecord,
161 'runId' | 'threadId' | 'activity' | 'provider' | 'model' | 'startedAt'
162 > & { status?: GenerationRunRecord['status'] },
163 ): Promise<GenerationRunRecord> {
164 const existing = this.generationRuns.get(input.runId)
165 if (existing) return Promise.resolve(existing)
166 const record: GenerationRunRecord = {
167 runId: input.runId,
168 threadId: input.threadId,
169 activity: input.activity,
170 provider: input.provider,
171 model: input.model,
172 status: input.status ?? 'running',
173 startedAt: input.startedAt,
174 }
175 this.generationRuns.set(record.runId, record)
176 return Promise.resolve(record)
177 }
178 update(
179 runId: string,
180 patch: Partial<
181 Pick<
182 GenerationRunRecord,
183 'status' | 'finishedAt' | 'error' | 'result' | 'artifacts' | 'usage'
184 >
185 >,
186 ): Promise<void> {
187 const existing = this.generationRuns.get(runId)
188 if (existing) this.generationRuns.set(runId, { ...existing, ...patch })
189 return Promise.resolve()
190 }
191 get(runId: string): Promise<GenerationRunRecord | null> {
192 return Promise.resolve(this.generationRuns.get(runId) ?? null)
193 }
194 findLatestForThread(threadId: string): Promise<GenerationRunRecord | null> {
195 const linked = [...this.generationRuns.values()]
196 .filter((run) => run.threadId === threadId)
197 .sort((a, b) => b.startedAt - a.startedAt)
198 return Promise.resolve(linked[0] ?? null)
199 }
200}
201
202function byRequestedAt(a: InterruptRecord, b: InterruptRecord): number {
203 return a.requestedAt - b.requestedAt
204}
205
206class MemoryInterruptStore implements InterruptStore {
207 private readonly interrupts = new Map<string, InterruptRecord>()
208 create(
209 record: Omit<InterruptRecord, 'status' | 'resolvedAt'>,
210 ): Promise<void> {
211 // Insert-if-absent (canonical semantics, matching the SQL backends'
212 // ON CONFLICT DO NOTHING): a duplicate id must never clobber an existing —
213 // possibly already resolved — interrupt back to pending.
214 if (!this.interrupts.has(record.interruptId)) {
215 this.interrupts.set(record.interruptId, { ...record, status: 'pending' })
216 }
217 return Promise.resolve()
218 }
219 resolve(interruptId: string, response?: unknown): Promise<void> {
220 const existing = this.interrupts.get(interruptId)
221 if (existing) {
222 this.interrupts.set(interruptId, {
223 ...existing,
224 status: 'resolved',
225 resolvedAt: Date.now(),
226 response,
227 })
228 }
229 return Promise.resolve()
230 }
231 cancel(interruptId: string): Promise<void> {
232 const existing = this.interrupts.get(interruptId)
233 if (existing) {
234 this.interrupts.set(interruptId, {
235 ...existing,
236 status: 'cancelled',
237 resolvedAt: Date.now(),
238 })
239 }
240 return Promise.resolve()
241 }
242 async commitBatch(
243 entries: ReadonlyArray<InterruptCommitEntry>,
244 ): Promise<void> {
245 const ids = new Set<string>()
246 for (const entry of entries) {
247 if (ids.has(entry.interruptId)) {
248 throw new Error(
249 `Interrupt batch contains duplicate id: ${entry.interruptId}.`,
250 )
251 }
252 ids.add(entry.interruptId)
253 const existing = this.interrupts.get(entry.interruptId)
254 if (!existing) {
255 throw new Error(
256 `Interrupt batch references missing id: ${entry.interruptId}.`,
257 )
258 }
259 if (existing.status !== 'pending') {
260 throw new Error(
261 `Interrupt batch references non-pending id: ${entry.interruptId}.`,
262 )
263 }
264 }
265 const resolvedAt = Date.now()
266 for (const entry of entries) {
267 const existing = this.interrupts.get(entry.interruptId)
268 if (!existing) continue
269 if (entry.status === 'resolved') {
270 this.interrupts.set(entry.interruptId, {
271 ...existing,
272 status: 'resolved',
273 resolvedAt,
274 response: entry.response,
275 })
276 } else {
277 this.interrupts.set(entry.interruptId, {
278 ...existing,
279 status: 'cancelled',
280 resolvedAt,
281 })
282 }
283 }
284 }
285 get(interruptId: string): Promise<InterruptRecord | null> {
286 return Promise.resolve(this.interrupts.get(interruptId) ?? null)
287 }
288 list(threadId: string): Promise<Array<InterruptRecord>> {
289 return Promise.resolve(
290 [...this.interrupts.values()]
291 .filter((interrupt) => interrupt.threadId === threadId)
292 .sort(byRequestedAt),
293 )
294 }
295 listPending(threadId: string): Promise<Array<InterruptRecord>> {
296 return Promise.resolve(
297 [...this.interrupts.values()]
298 .filter(
299 (interrupt) =>
300 interrupt.threadId === threadId && interrupt.status === 'pending',
301 )
302 .sort(byRequestedAt),
303 )
304 }
305 listByRun(runId: string): Promise<Array<InterruptRecord>> {
306 return Promise.resolve(
307 [...this.interrupts.values()]
308 .filter((interrupt) => interrupt.runId === runId)
309 .sort(byRequestedAt),
310 )
311 }
312 listPendingByRun(runId: string): Promise<Array<InterruptRecord>> {
313 return Promise.resolve(
314 [...this.interrupts.values()]
315 .filter(
316 (interrupt) =>
317 interrupt.runId === runId && interrupt.status === 'pending',
318 )
319 .sort(byRequestedAt),
320 )
321 }
322}
323
324class MemoryMetadataStore implements MetadataStore {
325 // Nested maps so composite identity is `(namespace, key)` without the
326 // `${namespace}:${key}` collision where `('a:b','c')` aliases `('a','b:c')`.
327 // (This parameter is an app-defined metadata namespace string — not the
328 // shared `Scope` identity type from `@tanstack/ai`.)
329 private readonly values = new Map<
330 string,
331 Map<string, { value: unknown; revision: string }>
332 >()
333 // One counter for the whole store, so a key that is deleted and set again
334 // never gets a revision that an earlier reader saw.
335 private lastRevision = 0
336 get(namespace: string, key: string): Promise<unknown | null> {
337 const entry = this.values.get(namespace)?.get(key)
338 return Promise.resolve(entry ? entry.value : null)
339 }
340 getVersioned(
341 namespace: string,
342 key: string,
343 ): Promise<{ value: unknown; revision: string } | null> {
344 const entry = this.values.get(namespace)?.get(key)
345 return Promise.resolve(entry ? { ...entry } : null)
346 }
347 set(namespace: string, key: string, value: unknown): Promise<void> {
348 this.write(namespace, key, value)
349 return Promise.resolve()
350 }
351 setIf(
352 namespace: string,
353 key: string,
354 value: unknown,
355 expectedRevision: string | null,
356 ): Promise<
357 { ok: true; revision: string } | { ok: false; reason: 'conflict' }
358 > {
359 const current = this.values.get(namespace)?.get(key)?.revision ?? null
360 if (current !== expectedRevision) {
361 return Promise.resolve({ ok: false, reason: 'conflict' })
362 }
363 return Promise.resolve({
364 ok: true,
365 revision: this.write(namespace, key, value),
366 })
367 }
368 private write(namespace: string, key: string, value: unknown): string {
369 let bucket = this.values.get(namespace)
370 if (!bucket) {
371 bucket = new Map()
372 this.values.set(namespace, bucket)
373 }
374 const revision = String(++this.lastRevision)
375 bucket.set(key, { value, revision })
376 return revision
377 }
378 delete(namespace: string, key: string): Promise<void> {
379 const bucket = this.values.get(namespace)
380 if (!bucket) return Promise.resolve()
381 bucket.delete(key)
382 if (bucket.size === 0) this.values.delete(namespace)
383 return Promise.resolve()
384 }
385}
386
387class MemoryArtifactStore implements ArtifactStore {
388 private readonly artifacts = new Map<string, ArtifactRecord>()
389 save(record: ArtifactRecord): Promise<void> {
390 this.artifacts.set(record.artifactId, { ...record })
391 return Promise.resolve()
392 }
393 get(artifactId: string): Promise<ArtifactRecord | null> {
394 return Promise.resolve(this.artifacts.get(artifactId) ?? null)
395 }
396 list(runId: string): Promise<Array<ArtifactRecord>> {
397 return Promise.resolve(
398 [...this.artifacts.values()]
399 .filter((a) => a.runId === runId)
400 .sort(
401 (a, b) =>
402 a.createdAt - b.createdAt ||
403 compareUtf8Bytes(a.artifactId, b.artifactId),
404 ),
405 )
406 }
407 listForThread(threadId: string): Promise<Array<ArtifactRecord>> {
408 return Promise.resolve(
409 [...this.artifacts.values()]
410 .filter((a) => a.threadId === threadId)
411 .sort(
412 (a, b) =>
413 a.createdAt - b.createdAt ||
414 compareUtf8Bytes(a.artifactId, b.artifactId),
415 ),
416 )
417 }
418 delete(artifactId: string): Promise<void> {
419 this.artifacts.delete(artifactId)
420 return Promise.resolve()
421 }
422 deleteForRun(runId: string): Promise<void> {
423 for (const artifact of this.artifacts.values()) {
424 if (artifact.runId === runId) this.artifacts.delete(artifact.artifactId)
425 }
426 return Promise.resolve()
427 }
428}
429
430interface MemoryBlobEntry {
431 record: BlobRecord
432 bytes: Uint8Array
433}
434
435const textEncoder = new TextEncoder()
436const textDecoder = new TextDecoder()
437
438function copyBytes(bytes: Uint8Array): Uint8Array {
439 return new Uint8Array(bytes)
440}
441
442function bytesToArrayBuffer(bytes: Uint8Array): ArrayBuffer {
443 const buffer = new ArrayBuffer(bytes.byteLength)
444 new Uint8Array(buffer).set(bytes)
445 return buffer
446}
447
448async function bytesFromStream(
449 stream: ReadableStream<Uint8Array>,
450): Promise<Uint8Array> {
451 const reader = stream.getReader()
452 const chunks: Array<Uint8Array> = []
453 let total = 0
454 try {
455 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
456 while (true) {
457 const { done, value } = await reader.read()
458 if (done) break
459 chunks.push(copyBytes(value))
460 total += value.byteLength
461 }
462 } finally {
463 reader.releaseLock()
464 }
465
466 const bytes = new Uint8Array(total)
467 let offset = 0
468 for (const chunk of chunks) {
469 bytes.set(chunk, offset)
470 offset += chunk.byteLength
471 }
472 return bytes
473}
474
475async function bytesFromBlobBody(body: BlobBody): Promise<Uint8Array> {
476 if (typeof body === 'string') {
477 return textEncoder.encode(body)
478 }
479 if (body instanceof ArrayBuffer) {
480 return new Uint8Array(body.slice(0))
481 }
482 if (ArrayBuffer.isView(body)) {
483 return copyBytes(
484 new Uint8Array(body.buffer, body.byteOffset, body.byteLength),
485 )
486 }
487 if (typeof Blob !== 'undefined' && body instanceof Blob) {
488 return new Uint8Array(await body.arrayBuffer())
489 }
490 if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) {
491 return bytesFromStream(body)
492 }
493 throw new TypeError('Unsupported blob body.')
494}
495
496function blobRecordSnapshot(record: BlobRecord): BlobRecord {
497 return {
498 ...record,
499 ...(record.customMetadata
500 ? { customMetadata: { ...record.customMetadata } }
501 : {}),
502 }
503}
504
505function blobObject(
506 record: BlobRecord,
507 bytes: Uint8Array,
508 range?: BlobRange,
509): BlobObject {
510 // `size` keeps reporting the whole object; only the bytes narrow.
511 const served = range
512 ? resolveBlobRange(bytes.byteLength, range)
513 : { offset: 0, length: bytes.byteLength }
514 const copied = copyBytes(
515 bytes.subarray(served.offset, served.offset + served.length),
516 )
517 return {
518 ...blobRecordSnapshot(record),
519 ...(range ? { range: served } : {}),
520 body: new ReadableStream<Uint8Array>({
521 start(controller) {
522 controller.enqueue(copyBytes(copied))
523 controller.close()
524 },
525 }),
526 arrayBuffer: () => Promise.resolve(bytesToArrayBuffer(copied)),
527 text: () => Promise.resolve(textDecoder.decode(copied)),
528 }
529}
530
531class MemoryBlobStore implements BlobStore {
532 private readonly blobs = new Map<string, MemoryBlobEntry>()
533 private nextEtag = 1
534
535 async put(
536 key: string,
537 body: BlobBody,
538 options?: BlobPutOptions,
539 ): Promise<BlobRecord> {
540 const bytes = await bytesFromBlobBody(body)
541 const existing = this.blobs.get(key)
542 const now = Date.now()
543 const record: BlobRecord = {
544 key,
545 size: bytes.byteLength,
546 etag: String(this.nextEtag++),
547 contentType:
548 options?.contentType ??
549 (typeof Blob !== 'undefined' && body instanceof Blob
550 ? body.type || undefined
551 : undefined),
552 customMetadata: options?.customMetadata
553 ? { ...options.customMetadata }
554 : undefined,
555 createdAt: existing?.record.createdAt ?? now,
556 updatedAt: now,
557 }
558 this.blobs.set(key, { record, bytes: copyBytes(bytes) })
559 return blobRecordSnapshot(record)
560 }
561
562 get(key: string, options?: BlobGetOptions): Promise<BlobObject | null> {
563 const entry = this.blobs.get(key)
564 return Promise.resolve(
565 entry ? blobObject(entry.record, entry.bytes, options?.range) : null,
566 )
567 }
568
569 head(key: string): Promise<BlobRecord | null> {
570 const entry = this.blobs.get(key)
571 return Promise.resolve(entry ? blobRecordSnapshot(entry.record) : null)
572 }
573
574 delete(key: string): Promise<void> {
575 this.blobs.delete(key)
576 return Promise.resolve()
577 }
578
579 list(options?: BlobListOptions): Promise<{
580 objects: Array<BlobRecord>
581 cursor?: string
582 truncated?: boolean
583 }> {
584 const limit = options?.limit
585 if (limit === 0) {
586 return Promise.resolve({ objects: [], truncated: false })
587 }
588 const keys = [...this.blobs.keys()]
589 .filter((key) => key.startsWith(options?.prefix ?? ''))
590 .filter((key) => options?.cursor === undefined || key > options.cursor)
591 .sort()
592 const pageKeys = limit === undefined ? keys : keys.slice(0, limit)
593 const objects = pageKeys.map((key) => {
594 const blob = this.blobs.get(key)
595 if (blob === undefined) {
596 throw new Error(`Missing blob for listed key: ${key}`)
597 }
598 return blobRecordSnapshot(blob.record)
599 })
600 const truncated = limit !== undefined && keys.length > limit
601 return Promise.resolve({
602 objects,
603 ...(truncated ? { cursor: pageKeys.at(-1), truncated } : {}),
604 })
605 }
606}
607
608/**
609 * A JSON copy, so a store never shares an object with a caller. Throws when
610 * the value cannot become JSON (a `BigInt`, a cycle).
611 */
612function copyJson<T>(value: T): T {
613 return JSON.parse(JSON.stringify(value))
614}
615
616/**
617 * Throw a `RangeError` for a duration that the log contract refuses: a value
618 * below 0, `NaN`, or 0 when `allowZero` is false.
619 */
620function assertMs({
621 name,
622 value,
623 allowZero,
624}: {
625 name: string
626 value: number
627 allowZero: boolean
628}) {
629 const isValid = allowZero ? value >= 0 : value > 0
630 if (!isValid) {
631 const rule = allowZero ? '0 or more' : 'more than 0'
632 throw new RangeError(`${name} must be ${rule}, got ${value}.`)
633 }
634}
635
636/**
637 * The ownership record of a log that a host acquired. The record stays after
638 * a release, because the epoch never goes down.
639 */
640interface Ownership {
641 harness: string
642 ownerId: string
643 epoch: number
644 /** Epoch milliseconds, from the store clock. */
645 expiresAt: number
646 released: boolean
647 /** Epoch milliseconds, from `release({ wakeInMs })`. */
648 wakeAt?: number
649}
650
651/** An input that a host offered to a log. */
652interface Offer {
653 record: LogRecord
654 /** Epoch milliseconds, from the store clock. */
655 offeredAt: number
656 /** True after an append consumed it. The id stays, so a retry is a duplicate. */
657 consumed: boolean
658}
659
660/** The offers of one log. */
661interface Lane {
662 /** The harness of the first offer, for `listLogsWithoutOwner`. */
663 harness: string
664 /** By input id, in offer order. */
665 inputs: Map<string, Offer>
666}
667
668/** The records that a log keeps. A truncate drops the first ones. */
669interface KeptLog {
670 /** The position of `records[0]`. A truncate moves it up. */
671 firstSeq: number
672 records: Array<LogRecord>
673}
674
675/**
676 * The last position of the log, or 0 for a log with no records. A truncate
677 * does not change it.
678 */
679function headOf(log: KeptLog) {
680 return log.firstSeq - 1 + log.records.length
681}
682
683/** The listeners of one store instance, by log id. */
684type Listeners = Map<string, Set<() => void>>
685
686/**
687 * The state of the memory log, shared by every store instance on it. Make one
688 * with {@link memoryLogState}. Two instances on one state act as two machines
689 * on one database: they see the same records, owners, offers, and snapshots,
690 * and a write on one calls the listeners of both.
691 */
692class MemoryLogState {
693 /** The store clock, in epoch milliseconds. */
694 readonly now: () => number
695 readonly logs = new Map<string, KeptLog>()
696 readonly snapshots = new Map<string, LogSnapshot>()
697 readonly owners = new Map<string, Ownership>()
698 // Kept apart from `owners`, so a pin stays when its owner releases the log.
699 readonly affinities = new Map<string, string>()
700 /** The deleted logs. Only an `acquireOwnership` lets a write or an offer in again. */
701 readonly deleted = new Set<string>()
702 /** When the heartbeat of each host expires, by its host id. */
703 readonly hosts = new Map<string, number>()
704 // Kept apart from `owners`, because any machine can offer to a log that no
705 // host acquired.
706 readonly lanes = new Map<string, Lane>()
707 /** The listeners of each store instance on this backend. */
708 readonly instances = new Set<Listeners>()
709
710 constructor(now: () => number) {
711 this.now = now
712 }
713
714 /**
715 * Call the listeners of `logId` on every store instance. The write is done,
716 * so a listener error must not fail it or stop the other listeners.
717 */
718 notify(logId: string) {
719 const instances = [...this.instances]
720 const listeners = instances.flatMap((instance) => [
721 ...(instance.get(logId) ?? []),
722 ])
723 for (const listener of listeners) {
724 try {
725 listener()
726 } catch (error) {
727 console.error('[ai-persistence] log listener failed', error)
728 }
729 }
730 }
731}
732
733/** The type of the shared state from {@link memoryLogState}. */
734export type { MemoryLogState }
735
736// The methods are `async`, so a thrown error becomes a rejection. They never
737// await, so each call runs to its end before the next one starts, also across
738// the store instances on one backend.
739class MemoryLogStore implements LogStore {
740 private readonly backend: MemoryLogState
741 private readonly listeners: Listeners = new Map()
742
743 constructor(backend: MemoryLogState) {
744 this.backend = backend
745 backend.instances.add(this.listeners)
746 }
747
748 /**
749 * The fence of `append`. A log that a host acquired needs the current epoch
750 * and an owner that did not release it. A log that no host acquired needs
751 * NO_OWNER_EPOCH. A deleted log refuses every write until an `acquireOwnership`.
752 */
753 private canWrite(logId: string, epoch: number) {
754 if (this.backend.deleted.has(logId)) return false
755 const owner = this.backend.owners.get(logId)
756 if (owner === undefined) return epoch === NO_OWNER_EPOCH
757 return owner.epoch === epoch && !owner.released
758 }
759
760 /**
761 * The fence of `pinToWorkers`, `putSnapshot`, and `truncate`: only the
762 * owner writes them, so a log that no host acquired refuses them.
763 */
764 private assertOwned(logId: string, epoch: number) {
765 const isOwned = epoch !== NO_OWNER_EPOCH && this.canWrite(logId, epoch)
766 if (!isOwned) throw new OwnershipLostError(logId, epoch)
767 }
768
769 /** The record, when `ownerId` holds the log at `epoch` and did not release it. */
770 private heldBy(logId: string, ownerId: string, epoch: number) {
771 const owner = this.backend.owners.get(logId)
772 const isHolder =
773 owner?.ownerId === ownerId && owner.epoch === epoch && !owner.released
774 return isHolder ? owner : undefined
775 }
776
777 /** The kept records of `logId`, or an empty log that is not stored yet. */
778 private logOf(logId: string) {
779 return this.backend.logs.get(logId) ?? { firstSeq: 1, records: [] }
780 }
781
782 /** The offers of `logId` that no append consumed, in offer order. */
783 private pending(logId: string) {
784 const inputs = this.backend.lanes.get(logId)?.inputs ?? []
785 return [...inputs].filter(([, offer]) => !offer.consumed)
786 }
787
788 async append({
789 logId,
790 seq,
791 epoch,
792 records,
793 consumes = [],
794 }: Parameters<LogStore['append']>[0]) {
795 const isNoop = records.length === 0 && consumes.length === 0
796 if (isNoop) return
797 // The fence comes first, so a stale writer gets OwnershipLostError, also
798 // at a taken position.
799 if (!this.canWrite(logId, epoch)) {
800 throw new OwnershipLostError(logId, epoch)
801 }
802 const log = this.logOf(logId)
803 // The position check comes before the consumes check, so the writer that
804 // lost a race gets LogConflictError, also when the winner consumed the
805 // same offers.
806 if (seq !== headOf(log) + 1) throw new LogConflictError(logId, seq)
807 const inputs = this.backend.lanes.get(logId)?.inputs
808 const offers = consumes.map((inputId) => {
809 const offer = inputs?.get(inputId)
810 const isPending = offer !== undefined && !offer.consumed
811 if (!isPending) {
812 throw new TypeError(
813 `Input ${JSON.stringify(inputId)} is not a pending offer of log ${JSON.stringify(logId)}.`,
814 )
815 }
816 return offer
817 })
818 // Copy the whole batch before the write, so a record that cannot become
819 // JSON rejects the batch with nothing written and nothing consumed.
820 const copies = records.map(copyJson)
821 log.records.push(...copies)
822 this.backend.logs.set(logId, log)
823 for (const offer of offers) offer.consumed = true
824 this.backend.notify(logId)
825 }
826
827 async read({ logId, after = 0, limit }: Parameters<LogStore['read']>[0]) {
828 const log = this.logOf(logId)
829 // The record at `after + 1` is dropped, so the page would have a hole.
830 if (after < log.firstSeq - 1) {
831 throw new LogTruncatedError(logId, log.firstSeq)
832 }
833 const start = after - (log.firstSeq - 1)
834 const end = limit === undefined ? log.records.length : start + limit
835 return log.records.slice(start, end).map((record, index) => ({
836 seq: after + index + 1,
837 record: copyJson(record),
838 }))
839 }
840
841 subscribe({ logId, listener }: Parameters<LogStore['subscribe']>[0]) {
842 let set = this.listeners.get(logId)
843 if (!set) {
844 set = new Set()
845 this.listeners.set(logId, set)
846 }
847 set.add(listener)
848 return () => {
849 set.delete(listener)
850 }
851 }
852
853 async acquireOwnership({
854 logId,
855 harness,
856 ownerId,
857 ttlMs,
858 affinity,
859 }: Parameters<LogStore['acquireOwnership']>[0]) {
860 assertMs({ name: 'ttlMs', value: ttlMs, allowZero: false })
861 const now = this.backend.now()
862 const owner = this.backend.owners.get(logId)
863 const isLive =
864 owner !== undefined && !owner.released && owner.expiresAt > now
865 if (isLive && owner.ownerId !== ownerId) return null
866 if (this.isPinnedElsewhere(logId, affinity, now)) return null
867 // The caller holds the log already: extend it at the same epoch.
868 if (isLive) {
869 owner.expiresAt = now + ttlMs
870 return { epoch: owner.epoch }
871 }
872 const epoch = (owner?.epoch ?? NO_OWNER_EPOCH) + 1
873 // Another owner that did not release: its ownership expired.
874 const expired =
875 owner !== undefined && !owner.released && owner.ownerId !== ownerId
876 // A new owner opens a deleted log again.
877 this.backend.deleted.delete(logId)
878 this.backend.owners.set(logId, {
879 harness,
880 ownerId,
881 epoch,
882 expiresAt: now + ttlMs,
883 released: false,
884 })
885 return expired ? { epoch, expired: true } : { epoch }
886 }
887
888 async renewOwnership({
889 logId,
890 ownerId,
891 epoch,
892 ttlMs,
893 }: Parameters<LogStore['renewOwnership']>[0]) {
894 assertMs({ name: 'ttlMs', value: ttlMs, allowZero: false })
895 // An expired owner can renew. A new acquire would have changed the epoch.
896 const owner = this.heldBy(logId, ownerId, epoch)
897 if (owner === undefined) return false
898 owner.expiresAt = this.backend.now() + ttlMs
899 return true
900 }
901
902 async releaseOwnership({
903 logId,
904 ownerId,
905 epoch,
906 wakeInMs,
907 }: Parameters<LogStore['releaseOwnership']>[0]) {
908 if (wakeInMs !== undefined) {
909 assertMs({ name: 'wakeInMs', value: wakeInMs, allowZero: true })
910 }
911 const owner = this.heldBy(logId, ownerId, epoch)
912 if (owner === undefined) return
913 owner.released = true
914 if (wakeInMs !== undefined) owner.wakeAt = this.backend.now() + wakeInMs
915 }
916
917 async markHostAlive({
918 hostId,
919 ttlMs,
920 }: Parameters<LogStore['markHostAlive']>[0]) {
921 assertMs({ name: 'ttlMs', value: ttlMs, allowZero: false })
922 this.backend.hosts.set(hostId, this.backend.now() + ttlMs)
923 }
924
925 /**
926 * True when `logId` is pinned to a host that is not `affinity`, and that
927 * host is alive: its heartbeat did not expire. The pin of a host with no
928 * live heartbeat does not count.
929 */
930 private isPinnedElsewhere(
931 logId: string,
932 affinity: string | undefined,
933 now: number,
934 ) {
935 const pin = this.backend.affinities.get(logId)
936 if (pin === undefined || pin === affinity) return false
937 return (this.backend.hosts.get(pin) ?? 0) > now
938 }
939
940 async pinToWorkers({
941 logId,
942 epoch,
943 affinity,
944 }: Parameters<LogStore['pinToWorkers']>[0]) {
945 this.assertOwned(logId, epoch)
946 if (affinity === null) this.backend.affinities.delete(logId)
947 else this.backend.affinities.set(logId, affinity)
948 }
949
950 async listLogsWithoutOwner({
951 limit,
952 harnesses,
953 affinity,
954 }: Parameters<LogStore['listLogsWithoutOwner']>[0]) {
955 const now = this.backend.now()
956 // A log with offers can have no ownership record, so look in both maps.
957 const logIds = new Set([
958 ...this.backend.owners.keys(),
959 ...this.backend.lanes.keys(),
960 ])
961 const due: Array<{ orphan: OrphanedLog; dueAt: number }> = []
962 for (const logId of logIds) {
963 const found = this.orphanOf(logId, now)
964 if (found === undefined) continue
965 const isOtherHarness =
966 harnesses !== undefined && !harnesses.includes(found.orphan.harness)
967 if (isOtherHarness || this.isPinnedElsewhere(logId, affinity, now)) {
968 continue
969 }
970 due.push(found)
971 }
972 // The log that is due first comes first.
973 due.sort((left, right) => left.dueAt - right.dueAt)
974 return due.slice(0, limit).map(({ orphan }) => orphan)
975 }
976
977 /**
978 * Why `logId` is orphaned and when it became due, or `undefined` when it
979 * has no work. The first reason that applies wins: `'expired'`, then
980 * `'offered'`, then `'wake'`.
981 */
982 private orphanOf(logId: string, now: number) {
983 const owner = this.backend.owners.get(logId)
984 const lane = this.backend.lanes.get(logId)
985 const [firstPending] = this.pending(logId)
986 const found = (
987 reason: OrphanedLog['reason'],
988 harness: string,
989 dueAt: number,
990 ) => ({ orphan: { logId, harness, reason }, dueAt })
991 // An owner that did not release the log has the work until it expires.
992 const isHeld = owner !== undefined && !owner.released
993 if (isHeld) {
994 const isExpired = owner.expiresAt <= now
995 return isExpired
996 ? found('expired', owner.harness, owner.expiresAt)
997 : undefined
998 }
999 if (lane !== undefined && firstPending !== undefined) {
1000 const [, offer] = firstPending
1001 return found('offered', owner?.harness ?? lane.harness, offer.offeredAt)
1002 }
1003 const wakeAt = owner?.wakeAt
1004 const isWakeDue = owner !== undefined && wakeAt !== undefined
1005 if (isWakeDue && wakeAt <= now) {
1006 return found('wake', owner.harness, wakeAt)
1007 }
1008 return undefined
1009 }
1010
1011 async offerInput({
1012 logId,
1013 harness,
1014 inputId,
1015 record,
1016 }: Parameters<LogStore['offerInput']>[0]) {
1017 // Copy first, so a record that cannot become JSON stores nothing.
1018 const copy = copyJson(record)
1019 // A late input must not start a deleted log again.
1020 if (this.backend.deleted.has(logId)) return 'deleted'
1021 const lane = this.backend.lanes.get(logId)
1022 const inputs = lane?.inputs ?? new Map<string, Offer>()
1023 // A consumed id stays taken too.
1024 const previous = inputs.get(inputId)
1025 if (previous !== undefined) {
1026 const isEqual = JSON.stringify(previous.record) === JSON.stringify(copy)
1027 return isEqual ? 'duplicate' : 'conflict'
1028 }
1029 inputs.set(inputId, {
1030 record: copy,
1031 offeredAt: this.backend.now(),
1032 consumed: false,
1033 })
1034 // The owner or the first offer names the harness of the log. A later
1035 // offer does not change it.
1036 const owned = lane?.harness ?? this.backend.owners.get(logId)?.harness
1037 this.backend.lanes.set(logId, { harness: owned ?? harness, inputs })
1038 this.backend.notify(logId)
1039 return 'offered'
1040 }
1041
1042 async listOfferedInputs({
1043 logId,
1044 }: Parameters<LogStore['listOfferedInputs']>[0]) {
1045 return this.pending(logId).map(([inputId, offer]) => ({
1046 inputId,
1047 record: copyJson(offer.record),
1048 offeredAt: offer.offeredAt,
1049 }))
1050 }
1051
1052 async getSnapshot({ logId }: Parameters<LogStore['getSnapshot']>[0]) {
1053 const snapshot = this.backend.snapshots.get(logId)
1054 return snapshot === undefined ? null : copyJson(snapshot)
1055 }
1056
1057 async putSnapshot({
1058 logId,
1059 epoch,
1060 seq,
1061 version,
1062 state,
1063 }: Parameters<LogStore['putSnapshot']>[0]) {
1064 this.assertOwned(logId, epoch)
1065 const log = this.logOf(logId)
1066 const head = headOf(log)
1067 if (seq > head) {
1068 throw new RangeError(
1069 `Snapshot position ${seq} is after the last position ${head} of log ${JSON.stringify(logId)}.`,
1070 )
1071 }
1072 // A reader replays the records after the snapshot. The records before
1073 // `firstSeq` are dropped, so the lowest snapshot is at `firstSeq - 1`.
1074 const lowest = log.firstSeq - 1
1075 if (seq < lowest) {
1076 throw new RangeError(
1077 `Snapshot position ${seq} is before position ${lowest} of log ${JSON.stringify(logId)}. The log dropped the records before ${log.firstSeq}.`,
1078 )
1079 }
1080 // Copy last, so a state that cannot become JSON keeps the old snapshot.
1081 this.backend.snapshots.set(logId, copyJson({ seq, version, state }))
1082 }
1083
1084 async truncate({
1085 logId,
1086 epoch,
1087 beforeSeq,
1088 }: Parameters<LogStore['truncate']>[0]) {
1089 this.assertOwned(logId, epoch)
1090 // A reader that gets LogTruncatedError loads the snapshot, so the
1091 // snapshot must hold every record that the cut drops.
1092 const snapshot = this.backend.snapshots.get(logId)
1093 const isCovered = snapshot !== undefined && snapshot.seq >= beforeSeq - 1
1094 if (!isCovered) {
1095 throw new RangeError(
1096 `Log ${JSON.stringify(logId)} has no snapshot at position ${beforeSeq - 1} or later, so it keeps the records before ${beforeSeq}.`,
1097 )
1098 }
1099 // A snapshot is never after the head, so the cut drops kept records
1100 // only. A cut before `firstSeq` drops nothing.
1101 const log = this.logOf(logId)
1102 const dropCount = beforeSeq - log.firstSeq
1103 if (dropCount <= 0) return
1104 log.records.splice(0, dropCount)
1105 log.firstSeq = beforeSeq
1106 }
1107
1108 async deleteLog({ logId }: Parameters<LogStore['deleteLog']>[0]) {
1109 this.backend.logs.delete(logId)
1110 this.backend.snapshots.delete(logId)
1111 this.backend.lanes.delete(logId)
1112 this.backend.affinities.delete(logId)
1113 // A late write must not bring the log back, so every write fails until
1114 // an `acquireOwnership`. Keep the epoch counter. The log has no owner now, as
1115 // after a release with no wake.
1116 this.backend.deleted.add(logId)
1117 const owner = this.backend.owners.get(logId)
1118 if (owner !== undefined) {
1119 owner.released = true
1120 owner.wakeAt = undefined
1121 }
1122 this.backend.notify(logId)
1123 }
1124}
1125
1126/**
1127 * In-process reference {@link LogStore}, for tests and one-process hosts. The
1128 * log is lost when the process stops. Records are JSON-copied in and out.
1129 *
1130 * `memoryPersistence()` has one. Make your own to share a
1131 * {@link memoryLogState} between two stores.
1132 *
1133 * @param options.state - The log state to use. Pass one
1134 * {@link memoryLogState} to two stores, and they act as two machines on
1135 * one database. Without it, the store makes its own state.
1136 *
1137 * @example
1138 * ```ts
1139 * const state = memoryLogState()
1140 * const machineA = defineAIPersistence({
1141 * stores: { ...memoryPersistence().stores, log: memoryLogStore({ state }) },
1142 * })
1143 * ```
1144 */
1145export function memoryLogStore({
1146 state = memoryLogState(),
1147}: { state?: MemoryLogState } = {}): LogStore {
1148 return new MemoryLogStore(state)
1149}
1150
1151/**
1152 * A new log state for {@link memoryLogStore}. Give one state to two stores
1153 * to test two hosts in one process: an append on one store calls the
1154 * listeners on the other, and both see one owner per log.
1155 *
1156 * @example
1157 * ```ts
1158 * const state = memoryLogState()
1159 * const hostA = memoryLogStore({ state })
1160 * const hostB = memoryLogStore({ state })
1161 * hostB.subscribe({ logId: 'session-1', listener: () => console.log('new') })
1162 * await hostA.append({
1163 * logId: 'session-1',
1164 * seq: 1,
1165 * epoch: NO_OWNER_EPOCH,
1166 * records: [{ type: 'hello' }],
1167 * })
1168 * // The listener on hostB ran.
1169 * ```
1170 *
1171 * @param options.now - The store clock, in epoch milliseconds. Ownership
1172 * expiry, wake times, and offer times use it. Default: `Date.now()`. Give a
1173 * test clock to move time in a test.
1174 *
1175 * @example
1176 * ```ts
1177 * let clock = 0
1178 * const state = memoryLogState({ now: () => clock })
1179 * // A wake time of 5 s from now is due after this:
1180 * clock += 5_000
1181 * ```
1182 */
1183export function memoryLogState({ now }: { now?: () => number } = {}) {
1184 return new MemoryLogState(now ?? (() => Date.now()))
1185}
1186
1187// Newest `updatedAt` first, then `threadId` order. The cursor uses it too.
1188const bySessionOrder = (
1189 a: Pick<SessionIndexEntry, 'updatedAt' | 'threadId'>,
1190 b: Pick<SessionIndexEntry, 'updatedAt' | 'threadId'>,
1191) => b.updatedAt - a.updatedAt || compareUtf8Bytes(a.threadId, b.threadId)
1192
1193// The cursor is `<updatedAt>:<threadId>` of the last entry of a page.
1194function parseSessionCursor(cursor: string) {
1195 const split = cursor.indexOf(':')
1196 const updatedAt = Number(cursor.slice(0, split))
1197 if (split <= 0 || !Number.isFinite(updatedAt)) {
1198 throw new Error(`Invalid session index cursor: ${cursor}`)
1199 }
1200 return { updatedAt, threadId: cursor.slice(split + 1) }
1201}
1202
1203class MemorySessionIndexStore implements SessionIndexStore {
1204 // Nested maps, tenant then thread. A joined `${tenant}:${thread}` key would
1205 // make `('a:b', 'c')` and `('a', 'b:c')` the same entry. A missing tenant is
1206 // the default tenant, `''`.
1207 private readonly tenants = new Map<
1208 string,
1209 Map<string, { entry: SessionIndexEntry; revision: string }>
1210 >()
1211 // One counter for the whole store, so an entry that is deleted and written
1212 // again never gets a revision that an earlier reader saw.
1213 private lastRevision = 0
1214 get(key: SessionIndexKey) {
1215 const stored = this.find(key)
1216 return Promise.resolve(stored && structuredClone(stored.entry))
1217 }
1218 getVersioned(key: SessionIndexKey) {
1219 const stored = this.find(key)
1220 return Promise.resolve(stored && structuredClone(stored))
1221 }
1222 upsert(entry: SessionIndexEntry) {
1223 this.write(entry)
1224 return Promise.resolve()
1225 }
1226 upsertIf({
1227 entry,
1228 revision,
1229 }: {
1230 entry: SessionIndexEntry
1231 revision: string | null
1232 }) {
1233 const current = this.find(entry)?.revision ?? null
1234 if (current !== revision) {
1235 return Promise.resolve({ ok: false, reason: 'conflict' } as const)
1236 }
1237 return Promise.resolve({ ok: true, revision: this.write(entry) } as const)
1238 }
1239 list(options: SessionIndexListOptions = {}) {
1240 const { limit, cursor, parentThreadId, memberId, search, harness } = options
1241 const after = cursor === undefined ? undefined : parseSessionCursor(cursor)
1242 const needle = search?.toLowerCase()
1243 const metadata = Object.entries(options.metadata ?? {})
1244 const tenant = this.tenants.get(options.tenantId ?? '')
1245 const stored = [...(tenant?.values() ?? [])]
1246 const matching = stored
1247 .map(({ entry }) => entry)
1248 .filter((entry) => {
1249 // `null` asks for the entries with no parent.
1250 const isChild =
1251 parentThreadId === undefined ||
1252 (entry.parentThreadId ?? null) === parentThreadId
1253 const isMember =
1254 memberId === undefined ||
1255 entry.members.some((member) => member.userId === memberId)
1256 const isAfterCursor =
1257 after === undefined || bySessionOrder(after, entry) < 0
1258 const isFound =
1259 needle === undefined ||
1260 (entry.title?.toLowerCase().includes(needle) ?? false)
1261 const isHarness = harness === undefined || entry.harness === harness
1262 const hasMetadata = metadata.every(
1263 ([key, value]) => entry.metadata?.[key] === value,
1264 )
1265 const isShown = options.withArchived === true || entry.archived !== true
1266 return (
1267 isShown &&
1268 isChild &&
1269 isMember &&
1270 isFound &&
1271 isHarness &&
1272 hasMetadata &&
1273 isAfterCursor
1274 )
1275 })
1276 .sort(bySessionOrder)
1277 const page = limit === undefined ? matching : matching.slice(0, limit)
1278 const last = page.at(-1)
1279 const hasMore =
1280 limit !== undefined && matching.length > limit && last !== undefined
1281 return Promise.resolve({
1282 entries: page.map((entry) => structuredClone(entry)),
1283 ...(hasMore
1284 ? { cursor: `${last.updatedAt}:${last.threadId}`, truncated: true }
1285 : {}),
1286 })
1287 }
1288 delete(key: SessionIndexKey) {
1289 const tenantId = key.tenantId ?? ''
1290 const tenant = this.tenants.get(tenantId)
1291 if (!tenant) return Promise.resolve()
1292 tenant.delete(key.threadId)
1293 if (tenant.size === 0) this.tenants.delete(tenantId)
1294 return Promise.resolve()
1295 }
1296 private find(key: SessionIndexKey) {
1297 return this.tenants.get(key.tenantId ?? '')?.get(key.threadId)
1298 }
1299 // Copies in and out, so a caller never changes a stored entry.
1300 private write(entry: SessionIndexEntry) {
1301 const tenantId = entry.tenantId ?? ''
1302 let tenant = this.tenants.get(tenantId)
1303 if (!tenant) {
1304 tenant = new Map()
1305 this.tenants.set(tenantId, tenant)
1306 }
1307 const revision = String(++this.lastRevision)
1308 tenant.set(entry.threadId, { entry: structuredClone(entry), revision })
1309 return revision
1310 }
1311}
1312
1313interface MemoryPersistenceStores {
1314 messages: MessageStore
1315 activities: ActivityStore
1316 runs: RunStore
1317 generationRuns: GenerationRunStore
1318 interrupts: InterruptStore
1319 metadata: MetadataStore
1320 artifacts: ArtifactStore
1321 blobs: BlobStore
1322 sessions: SessionIndexStore
1323 log: LogStore
1324}
1325
1326/**
1327 * In-process reference backend for the full state + generation store set.
1328 *
1329 * Returns messages + activities + runs + generationRuns + interrupts +
1330 * metadata + artifacts + blobs + sessions + log.
1331 * Plain `chat()` does not use `log`. A harness host keeps each session in
1332 * `log` and does not use `messages`. Locks are not included. Use
1333 * `InMemoryLockStore` + `withLocks` from `@tanstack/ai` when a test or
1334 * single-process app needs coordination.
1335 *
1336 * @example
1337 * ```ts
1338 * const persistence = memoryPersistence()
1339 * ```
1340 */
1341export function memoryPersistence() {
1342 const stores: MemoryPersistenceStores = {
1343 messages: new MemoryMessageStore(),
1344 activities: new MemoryActivityStore(),
1345 runs: new MemoryRunStore(),
1346 generationRuns: new MemoryGenerationRunStore(),
1347 interrupts: new MemoryInterruptStore(),
1348 metadata: new MemoryMetadataStore(),
1349 artifacts: new MemoryArtifactStore(),
1350 blobs: new MemoryBlobStore(),
1351 sessions: new MemorySessionIndexStore(),
1352 log: memoryLogStore(),
1353 }
1354 return defineAIPersistence({ stores })
1355}