@tanstack/ai-persistence 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/esm/blob-range.d.ts +51 -0
  2. package/dist/esm/blob-range.js +84 -0
  3. package/dist/esm/blob-range.js.map +1 -0
  4. package/dist/esm/capabilities.d.ts +5 -0
  5. package/dist/esm/capabilities.js +16 -0
  6. package/dist/esm/capabilities.js.map +1 -0
  7. package/dist/esm/index.d.ts +13 -0
  8. package/dist/esm/index.js +9 -0
  9. package/dist/esm/memory.d.ts +19 -0
  10. package/dist/esm/memory.js +319 -0
  11. package/dist/esm/memory.js.map +1 -0
  12. package/dist/esm/middleware.d.ts +252 -0
  13. package/dist/esm/middleware.js +872 -0
  14. package/dist/esm/middleware.js.map +1 -0
  15. package/dist/esm/reconstruct-generation.d.ts +129 -0
  16. package/dist/esm/reconstruct-generation.js +148 -0
  17. package/dist/esm/reconstruct-generation.js.map +1 -0
  18. package/dist/esm/reconstruct.d.ts +79 -0
  19. package/dist/esm/reconstruct.js +75 -0
  20. package/dist/esm/reconstruct.js.map +1 -0
  21. package/dist/esm/retrieve.d.ts +40 -0
  22. package/dist/esm/retrieve.js +54 -0
  23. package/dist/esm/retrieve.js.map +1 -0
  24. package/dist/esm/testkit/conformance.d.ts +33 -0
  25. package/dist/esm/testkit/conformance.js +997 -0
  26. package/dist/esm/testkit/conformance.js.map +1 -0
  27. package/dist/esm/types.d.ts +554 -0
  28. package/dist/esm/types.js +103 -0
  29. package/dist/esm/types.js.map +1 -0
  30. package/package.json +71 -0
  31. package/skills/ai-persistence/SKILL.md +218 -0
  32. package/skills/ai-persistence/build-cloudflare-adapter/SKILL.md +313 -0
  33. package/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md +693 -0
  34. package/skills/ai-persistence/build-custom-adapter/SKILL.md +328 -0
  35. package/skills/ai-persistence/build-drizzle-adapter/SKILL.md +562 -0
  36. package/skills/ai-persistence/build-prisma-adapter/SKILL.md +518 -0
  37. package/skills/ai-persistence/server/SKILL.md +210 -0
  38. package/skills/ai-persistence/stores/SKILL.md +485 -0
  39. package/src/blob-range.ts +101 -0
  40. package/src/capabilities.ts +18 -0
  41. package/src/index.ts +114 -0
  42. package/src/memory.ts +491 -0
  43. package/src/middleware.ts +1795 -0
  44. package/src/reconstruct-generation.ts +244 -0
  45. package/src/reconstruct.ts +149 -0
  46. package/src/retrieve.ts +77 -0
  47. package/src/testkit/conformance.ts +1288 -0
  48. package/src/types.ts +878 -0
@@ -0,0 +1,1288 @@
1
+ /**
2
+ * Shared conformance suite for the `AIPersistence` store contract.
3
+ *
4
+ * Every backend runs this identical suite — the in-memory reference store and
5
+ * every adapter you write against your own database — so that schema drift or
6
+ * an implementation gap fails immediately. It exercises every method of every
7
+ * store the persistence exposes and is the authoritative compatibility gate for
8
+ * the store interfaces in `../types.ts`.
9
+ *
10
+ * Covers all seven stores: the four chat state stores (`messages`, `runs`,
11
+ * `interrupts`, `metadata`) and the three generation stores (`generationRuns`,
12
+ * `artifacts`, `blobs`). Locks are not part of this suite — they are a separate
13
+ * coordination concern (`LockStore` + `withLocks`), not a store.
14
+ *
15
+ * SKIPPING (declare or fail): a backend that deliberately omits a store must
16
+ * declare it in `options.skip`, and one that omits an OPTIONAL store method
17
+ * must declare it in `options.skipMethods`. Anything absent and not declared
18
+ * fails the suite loudly, and anything declared absent is reported by vitest as
19
+ * a SKIPPED case, never as a pass. Silent gaps are not allowed: a case that did
20
+ * not run must never be indistinguishable from one that did. A chat-only
21
+ * adapter therefore passes `skip: ['generationRuns', 'artifacts', 'blobs']`,
22
+ * and a generation-only one skips the four state stores.
23
+ *
24
+ * NOT COVERED HERE: the four durable-run fields on `RunRecord` (`sandboxKey`,
25
+ * `detachedSince`, `cancelRequested`, `driverEpoch`). They exist for durable
26
+ * sandboxed runs, a chat app never writes them, and requiring them here made every
27
+ * backend implement four columns and an omitted-vs-explicit-undefined rule it had no
28
+ * use for. They are proven by `runDurableRunFieldsConformance` from
29
+ * `@tanstack/ai-sandbox/testkit`, next to the takeover and reaper suites that consume
30
+ * them. A backend that never runs sandboxes can leave the columns out.
31
+ *
32
+ * RESERVED RUN-ID PREFIX: `rc-` belongs to the `listReclaimable` case, which
33
+ * filters the method's (not thread-scoped) result down to `rc-` ids before an
34
+ * exact-set assertion. A new case in `describe('runs')` must NOT seed a run id
35
+ * starting with `rc-`, or it silently changes that expected set.
36
+ */
37
+ import { beforeAll, describe, expect, it } from 'vitest'
38
+ import type { ModelMessage } from '@tanstack/ai'
39
+ import type {
40
+ AIPersistence,
41
+ AIPersistenceStores,
42
+ ArtifactRecord,
43
+ RunStore,
44
+ } from '../types'
45
+
46
+ type MakePersistence = () => Promise<AIPersistence> | AIPersistence
47
+
48
+ /**
49
+ * Methods that are optional on the `RunStore` contract.
50
+ *
51
+ * `findActiveRun` is deliberately NOT here: it is REQUIRED, per the evolution
52
+ * policy in `../types.ts`. It was optional for one release cycle and silently
53
+ * disabled reconnect on every backend that had not caught up.
54
+ */
55
+ type OptionalRunStoreMethod = 'listByThread' | 'listReclaimable'
56
+
57
+ /** Dotted `store.method` key a backend passes to declare an omitted method. */
58
+ export type PersistenceConformanceMethodKey = `runs.${OptionalRunStoreMethod}`
59
+
60
+ /**
61
+ * Unwrap a value the store contract says must be present. Fails the test with a
62
+ * readable message instead of a non-null assertion (banned in this package) or
63
+ * an early `return` that would pass silently.
64
+ */
65
+ function required<TValue>(
66
+ value: TValue | null | undefined,
67
+ what: string,
68
+ ): TValue {
69
+ if (value == null) {
70
+ throw new Error(`AIPersistence conformance: expected ${what} to exist`)
71
+ }
72
+ return value
73
+ }
74
+
75
+ /** Read a `BlobObject.body` to completion as one contiguous buffer. */
76
+ async function drainStream(
77
+ stream: ReadableStream<Uint8Array>,
78
+ ): Promise<Uint8Array> {
79
+ const chunks: Array<Uint8Array> = []
80
+ let total = 0
81
+ const reader = stream.getReader()
82
+ for (;;) {
83
+ const { value, done } = await reader.read()
84
+ if (done) break
85
+ chunks.push(value)
86
+ total += value.byteLength
87
+ }
88
+ const bytes = new Uint8Array(total)
89
+ let offset = 0
90
+ for (const chunk of chunks) {
91
+ bytes.set(chunk, offset)
92
+ offset += chunk.byteLength
93
+ }
94
+ return bytes
95
+ }
96
+
97
+ export interface PersistenceConformanceOptions {
98
+ /**
99
+ * Store keys this backend intentionally does not provide. Any store that is
100
+ * absent from the persistence and NOT listed here fails the suite, so a
101
+ * dropped/misconfigured store can never pass silently.
102
+ */
103
+ skip?: Array<keyof AIPersistenceStores>
104
+ /**
105
+ * OPTIONAL store methods this backend intentionally does not implement, as
106
+ * `'runs.listByThread'` and friends. A method that is absent and NOT listed
107
+ * here fails the suite; a listed one is reported as a skipped case.
108
+ */
109
+ skipMethods?: Array<PersistenceConformanceMethodKey>
110
+ }
111
+
112
+ /**
113
+ * Register a Vitest suite that validates `makePersistence()` against the full
114
+ * `AIPersistence` contract — every store it provides, and none it declares
115
+ * skipped.
116
+ */
117
+ export function runPersistenceConformance(
118
+ name: string,
119
+ makePersistence: MakePersistence,
120
+ options?: PersistenceConformanceOptions,
121
+ ): void {
122
+ const skip = new Set<keyof AIPersistenceStores>(options?.skip ?? [])
123
+ const skipMethods = new Set<PersistenceConformanceMethodKey>(
124
+ options?.skipMethods ?? [],
125
+ )
126
+
127
+ describe(`AIPersistence conformance: ${name}`, () => {
128
+ let persistence: AIPersistence
129
+
130
+ beforeAll(async () => {
131
+ persistence = await makePersistence()
132
+ })
133
+
134
+ /**
135
+ * Return the store for `key`, or `null` when the backend intentionally
136
+ * skips it. Throws (failing the test) when a store is missing but was not
137
+ * declared in `options.skip`.
138
+ */
139
+ function resolveStore<TKey extends keyof AIPersistenceStores>(
140
+ key: TKey,
141
+ ): NonNullable<AIPersistenceStores[TKey]> | null {
142
+ const store = persistence.stores[key]
143
+ if (store) return store
144
+ if (skip.has(key)) return null
145
+ throw new Error(
146
+ `AIPersistence conformance: store '${key}' is missing. ` +
147
+ `Provide it, or pass { skip: ['${key}'] } if the omission is intentional.`,
148
+ )
149
+ }
150
+
151
+ /**
152
+ * Narrow `runs` to a store that definitely implements the optional method
153
+ * `methodName`, so the case can call it without a non-null assertion.
154
+ *
155
+ * Returns `false` only when the omission was declared in
156
+ * `options.skipMethods` (the caller then reports a skip). An undeclared
157
+ * omission throws, mirroring `resolveStore`: a case that cannot run must
158
+ * never be reported as a pass.
159
+ */
160
+ function hasRunsMethod<TName extends OptionalRunStoreMethod>(
161
+ runs: RunStore,
162
+ methodName: TName,
163
+ ): runs is RunStore & Required<Pick<RunStore, TName>> {
164
+ if (runs[methodName]) return true
165
+ const key: PersistenceConformanceMethodKey = `runs.${methodName}`
166
+ if (skipMethods.has(key)) return false
167
+ throw new Error(
168
+ `AIPersistence conformance: optional method '${key}' is not implemented. ` +
169
+ `Implement it, or pass { skipMethods: ['${key}'] } if the omission is intentional.`,
170
+ )
171
+ }
172
+
173
+ describe('messages', () => {
174
+ it('round-trips a thread and returns [] for unknown threads', async (ctx) => {
175
+ const store = resolveStore('messages')
176
+ if (!store) return ctx.skip('store not provided')
177
+
178
+ expect(await store.loadThread('thread-unknown')).toEqual([])
179
+
180
+ await store.saveThread('thread-msg', [
181
+ { role: 'user', content: 'hi' },
182
+ { role: 'assistant', content: 'hello' },
183
+ ])
184
+ expect(await store.loadThread('thread-msg')).toEqual([
185
+ { role: 'user', content: 'hi' },
186
+ { role: 'assistant', content: 'hello' },
187
+ ])
188
+
189
+ // Overwrites, not appends.
190
+ await store.saveThread('thread-msg', [
191
+ { role: 'user', content: 'redo' },
192
+ ])
193
+ expect(await store.loadThread('thread-msg')).toEqual([
194
+ { role: 'user', content: 'redo' },
195
+ ])
196
+ })
197
+
198
+ it('round-trips rich message shapes with deep equality', async (ctx) => {
199
+ const store = resolveStore('messages')
200
+ if (!store) return ctx.skip('store not provided')
201
+
202
+ const rich: Array<ModelMessage> = [
203
+ { role: 'user', content: 'plain string' },
204
+ {
205
+ // Tool-call message with JSON arguments.
206
+ role: 'assistant',
207
+ content: '',
208
+ toolCalls: [
209
+ {
210
+ id: 'call-1',
211
+ type: 'function',
212
+ function: {
213
+ name: 'search',
214
+ arguments: '{"query":"weather in Paris"}',
215
+ },
216
+ },
217
+ ],
218
+ },
219
+ {
220
+ // Tool result message.
221
+ role: 'tool',
222
+ content: '{"temperature":21,"unit":"C"}',
223
+ toolCallId: 'call-1',
224
+ },
225
+ {
226
+ // Multi-part content: text + image reference.
227
+ role: 'user',
228
+ content: [
229
+ { type: 'text', content: 'What is in this image?' },
230
+ {
231
+ type: 'image',
232
+ source: {
233
+ type: 'url',
234
+ value: 'https://example.com/cat.png',
235
+ mimeType: 'image/png',
236
+ },
237
+ },
238
+ ],
239
+ },
240
+ {
241
+ // Reasoning / thinking part.
242
+ role: 'assistant',
243
+ content: 'Here is my answer.',
244
+ thinking: [
245
+ {
246
+ content: 'The user is asking about the image.',
247
+ signature: 'sig-1',
248
+ },
249
+ ],
250
+ },
251
+ ]
252
+
253
+ await store.saveThread('thread-rich', rich)
254
+ expect(await store.loadThread('thread-rich')).toEqual(rich)
255
+ })
256
+ })
257
+
258
+ describe('runs', () => {
259
+ it('creates, resumes idempotently, updates, and gets', async (ctx) => {
260
+ const store = resolveStore('runs')
261
+ if (!store) return ctx.skip('store not provided')
262
+
263
+ expect(await store.get('run-missing')).toBeNull()
264
+
265
+ const created = await store.createOrResume({
266
+ runId: 'run-1',
267
+ threadId: 'thread-1',
268
+ startedAt: 1000,
269
+ })
270
+ expect(created).toMatchObject({
271
+ runId: 'run-1',
272
+ threadId: 'thread-1',
273
+ status: 'running',
274
+ startedAt: 1000,
275
+ })
276
+
277
+ // createOrResume is idempotent: returns the existing record unchanged.
278
+ const resumed = await store.createOrResume({
279
+ runId: 'run-1',
280
+ threadId: 'thread-different',
281
+ startedAt: 9999,
282
+ })
283
+ expect(resumed).toMatchObject({
284
+ runId: 'run-1',
285
+ threadId: 'thread-1',
286
+ startedAt: 1000,
287
+ })
288
+
289
+ await store.update('run-1', {
290
+ status: 'completed',
291
+ finishedAt: 2000,
292
+ usage: { promptTokens: 3, completionTokens: 4, totalTokens: 7 },
293
+ })
294
+ const done = await store.get('run-1')
295
+ expect(done).toMatchObject({
296
+ runId: 'run-1',
297
+ status: 'completed',
298
+ finishedAt: 2000,
299
+ usage: { promptTokens: 3, completionTokens: 4, totalTokens: 7 },
300
+ })
301
+
302
+ // `error` is a structured RunError: the prose `message` plus the
303
+ // optional machine-branchable `code`. Both must survive the round-trip,
304
+ // so a backend that flattens the record to a bare string fails here.
305
+ await store.update('run-1', {
306
+ status: 'failed',
307
+ error: { message: 'boom', code: 'provider_overloaded' },
308
+ })
309
+ const failed = await store.get('run-1')
310
+ expect(failed?.status).toBe('failed')
311
+ expect(failed?.error).toEqual({
312
+ message: 'boom',
313
+ code: 'provider_overloaded',
314
+ })
315
+
316
+ // Updating a missing run is a no-op (does not throw, does not create).
317
+ await store.update('run-absent', { status: 'completed' })
318
+ expect(await store.get('run-absent')).toBeNull()
319
+ })
320
+
321
+ // The idempotency invariant has teeth precisely where it is dangerous:
322
+ // resuming a run that already FINISHED must not resurrect it. An adapter
323
+ // written as `INSERT ... ON CONFLICT DO UPDATE SET status='running'`
324
+ // looks correct on a still-running record and silently revives dead ones,
325
+ // after which `findActiveRun` hands clients a run that will never emit
326
+ // again. Assert the terminal status and `finishedAt` both survive.
327
+ it('createOrResume never resurrects a finished run', async (ctx) => {
328
+ const store = resolveStore('runs')
329
+ if (!store) return ctx.skip('store not provided')
330
+
331
+ await store.createOrResume({
332
+ runId: 'nc-1',
333
+ threadId: 'nc-t',
334
+ startedAt: 10,
335
+ })
336
+ await store.update('nc-1', { status: 'completed', finishedAt: 20 })
337
+
338
+ // Resume with a DIFFERENT status/startedAt: both must be ignored.
339
+ const resumed = await store.createOrResume({
340
+ runId: 'nc-1',
341
+ threadId: 'nc-t',
342
+ startedAt: 999,
343
+ status: 'running',
344
+ })
345
+ expect(resumed).toMatchObject({
346
+ runId: 'nc-1',
347
+ status: 'completed',
348
+ startedAt: 10,
349
+ finishedAt: 20,
350
+ })
351
+
352
+ // And the stored record itself was not rewritten either.
353
+ expect(await store.get('nc-1')).toMatchObject({
354
+ status: 'completed',
355
+ startedAt: 10,
356
+ finishedAt: 20,
357
+ })
358
+ })
359
+
360
+ it('findActiveRun returns the most recent running run for a thread', async (ctx) => {
361
+ const store = resolveStore('runs')
362
+ if (!store) return ctx.skip('store not provided')
363
+
364
+ const thread = 'thread-active'
365
+ expect(await store.findActiveRun(thread)).toBeNull()
366
+
367
+ await store.createOrResume({
368
+ runId: 'active-1',
369
+ threadId: thread,
370
+ startedAt: 1000,
371
+ })
372
+ await store.createOrResume({
373
+ runId: 'active-2',
374
+ threadId: thread,
375
+ startedAt: 2000,
376
+ })
377
+ // Most-recent running run wins.
378
+ expect(await store.findActiveRun(thread)).toMatchObject({
379
+ runId: 'active-2',
380
+ status: 'running',
381
+ })
382
+
383
+ // A different thread's running run is not returned.
384
+ await store.createOrResume({
385
+ runId: 'other-1',
386
+ threadId: 'thread-other',
387
+ startedAt: 3000,
388
+ })
389
+ expect(await store.findActiveRun(thread)).toMatchObject({
390
+ runId: 'active-2',
391
+ })
392
+
393
+ // Once the newest finishes, the older running run becomes active.
394
+ await store.update('active-2', {
395
+ status: 'completed',
396
+ finishedAt: 2500,
397
+ })
398
+ expect(await store.findActiveRun(thread)).toMatchObject({
399
+ runId: 'active-1',
400
+ status: 'running',
401
+ })
402
+
403
+ // With none running, it is null.
404
+ await store.update('active-1', {
405
+ status: 'completed',
406
+ finishedAt: 1500,
407
+ })
408
+ expect(await store.findActiveRun(thread)).toBeNull()
409
+ })
410
+
411
+ // `listByThread` is optional on the RunStore contract; a declared omission
412
+ // is reported as skipped and an undeclared one fails. Any backend that has
413
+ // it must return that thread's runs ordered ascending by `startedAt`.
414
+ it('lists runs by thread when supported', async (ctx) => {
415
+ const runs = resolveStore('runs')
416
+ if (!runs) return ctx.skip('store not provided')
417
+ if (!hasRunsMethod(runs, 'listByThread')) {
418
+ return ctx.skip('runs.listByThread not implemented')
419
+ }
420
+
421
+ await runs.createOrResume({
422
+ runId: 'lt-b',
423
+ threadId: 'lt',
424
+ startedAt: 2,
425
+ })
426
+ await runs.createOrResume({
427
+ runId: 'lt-a',
428
+ threadId: 'lt',
429
+ startedAt: 1,
430
+ })
431
+ const listed = await runs.listByThread('lt')
432
+ expect(listed.map((r) => r.runId)).toEqual(['lt-a', 'lt-b'])
433
+ })
434
+
435
+ // `listReclaimable` is optional on the RunStore contract; a declared
436
+ // omission is reported as skipped and an undeclared one fails. Any
437
+ // backend that has it must
438
+ // surface only runs where ALL THREE hold: status === 'running',
439
+ // detachedSince is set, and detachedSince <= now - ttlMs (inclusive
440
+ // cutoff). Each negative fixture below pins one of those conditions so
441
+ // a backend that drops any single check (e.g. "return every run", or
442
+ // "ignore status", or "ignore detachedSince") fails this case. Do not
443
+ // simplify these away to a bare `toContain` — that is exactly the
444
+ // weakness this case was strengthened to catch.
445
+ it('lists reclaimable detached runs when supported', async (ctx) => {
446
+ const runs = resolveStore('runs')
447
+ if (!runs) return ctx.skip('store not provided')
448
+ if (!hasRunsMethod(runs, 'listReclaimable')) {
449
+ return ctx.skip('runs.listReclaimable not implemented')
450
+ }
451
+
452
+ const now = 10_000
453
+ const ttlMs = 5_000
454
+ const cutoff = now - ttlMs // 5_000
455
+
456
+ // Positive: running, detached well past the cutoff.
457
+ await runs.createOrResume({
458
+ runId: 'rc-included',
459
+ threadId: 'rc-t',
460
+ startedAt: 1,
461
+ })
462
+ await runs.update('rc-included', { detachedSince: 1_000 })
463
+
464
+ // Positive boundary: detachedSince exactly equals the cutoff. Pins
465
+ // the `<=` (inclusive) semantics — a backend that uses `<` instead
466
+ // would wrongly exclude this run.
467
+ await runs.createOrResume({
468
+ runId: 'rc-boundary',
469
+ threadId: 'rc-t',
470
+ startedAt: 1,
471
+ })
472
+ await runs.update('rc-boundary', { detachedSince: cutoff })
473
+
474
+ // Negative: still running, but detached AFTER the cutoff (not yet
475
+ // abandoned long enough). Pins the `<= cutoff` comparison — a
476
+ // backend that returns every detached run regardless of how recent
477
+ // would wrongly include this one.
478
+ await runs.createOrResume({
479
+ runId: 'rc-too-recent',
480
+ threadId: 'rc-t',
481
+ startedAt: 1,
482
+ })
483
+ await runs.update('rc-too-recent', { detachedSince: cutoff + 1 })
484
+
485
+ // Negative: detached past the cutoff, but no longer running (already
486
+ // completed). Pins the `status === 'running'` check — a backend
487
+ // that ignores status would wrongly include this one.
488
+ await runs.createOrResume({
489
+ runId: 'rc-completed',
490
+ threadId: 'rc-t',
491
+ startedAt: 1,
492
+ })
493
+ await runs.update('rc-completed', {
494
+ detachedSince: 1_000,
495
+ status: 'completed',
496
+ finishedAt: 2_000,
497
+ })
498
+
499
+ // Negative: running, but never detached at all. Pins the
500
+ // `detachedSince !== undefined` check — a backend that treats a
501
+ // missing `detachedSince` as "always reclaimable" would wrongly
502
+ // include this one.
503
+ await runs.createOrResume({
504
+ runId: 'rc-never-detached',
505
+ threadId: 'rc-t',
506
+ startedAt: 1,
507
+ })
508
+
509
+ const reclaimable = await runs.listReclaimable({ now, ttlMs })
510
+
511
+ // Scope the assertion to ids seeded by this case: `listReclaimable`
512
+ // is not thread-scoped, so it also sees `'running'` runs seeded by
513
+ // sibling cases in this shared-store `describe('runs', ...)` block
514
+ // (e.g. `other-1`, `lt-a`, `lt-b`). Those all lack `detachedSince`,
515
+ // so a correct implementation already excludes them — but filtering
516
+ // here keeps this assertion from depending on that fact holding for
517
+ // every other case forever. Ordering is not part of this method's
518
+ // contract, so sort before an exact-set comparison.
519
+ const ourIds = reclaimable
520
+ .map((r) => r.runId)
521
+ .filter((id) => id.startsWith('rc-'))
522
+ .sort()
523
+ expect(ourIds).toEqual(['rc-boundary', 'rc-included'])
524
+
525
+ // The four assertions below are scoped by exact runId (never by the
526
+ // `rc-` exact-set comparison above), so each uses its own randomUUID
527
+ // fixture and cannot perturb the fixed-set assertion just made.
528
+
529
+ // (1) `ttlMs: 0` pins the cutoff as inclusive: a run detached at
530
+ // exactly `now` (cutoff === now) must still come back. A backend
531
+ // using strict `<` instead of `<=` would silently never reclaim a
532
+ // run detached exactly at the boundary.
533
+ const zeroTtlRunId = `rc-${crypto.randomUUID()}`
534
+ await runs.createOrResume({
535
+ runId: zeroTtlRunId,
536
+ threadId: 'rc-t',
537
+ startedAt: 1,
538
+ })
539
+ await runs.update(zeroTtlRunId, { detachedSince: now })
540
+ const zeroTtlReclaimable = await runs.listReclaimable({
541
+ now,
542
+ ttlMs: 0,
543
+ })
544
+ expect(
545
+ zeroTtlReclaimable.find((r) => r.runId === zeroTtlRunId)
546
+ ?.detachedSince,
547
+ ).toBe(now)
548
+
549
+ // (2) Re-attaching — `update(runId, { detachedSince: undefined })`
550
+ // — must drop the run out of the list. This is the most important
551
+ // assertion in this case: a SQL `SET`-clause builder that filters
552
+ // `undefined` out of the patch (`'field' in patch` instead of
553
+ // `patch.field !== undefined`) keeps the old `detachedSince`, so a
554
+ // run a user has actively re-attached to still looks detached — and
555
+ // the reaper then cancels a run someone is watching.
556
+ const reattachedRunId = `rc-${crypto.randomUUID()}`
557
+ await runs.createOrResume({
558
+ runId: reattachedRunId,
559
+ threadId: 'rc-t',
560
+ startedAt: 1,
561
+ })
562
+ await runs.update(reattachedRunId, { detachedSince: 1_000 })
563
+ await runs.update(reattachedRunId, { detachedSince: undefined })
564
+ const afterReattach = await runs.listReclaimable({ now, ttlMs })
565
+ expect(afterReattach.some((r) => r.runId === reattachedRunId)).toBe(
566
+ false,
567
+ )
568
+
569
+ // (3) No terminal status (`completed` / `failed` / `aborted`) ever
570
+ // appears, whatever its `detachedSince`.
571
+ const terminalStatuses = ['completed', 'failed', 'aborted'] as const
572
+ const terminalRunIds = await Promise.all(
573
+ terminalStatuses.map(async (status) => {
574
+ const runId = `rc-${crypto.randomUUID()}`
575
+ await runs.createOrResume({ runId, threadId: 'rc-t', startedAt: 1 })
576
+ await runs.update(runId, {
577
+ status,
578
+ detachedSince: 1_000,
579
+ finishedAt: 2_000,
580
+ })
581
+ return runId
582
+ }),
583
+ )
584
+ const afterTerminal = await runs.listReclaimable({ now, ttlMs })
585
+ expect(
586
+ afterTerminal.some((r) => terminalRunIds.includes(r.runId)),
587
+ ).toBe(false)
588
+
589
+ // (4) `'interrupted'` does not appear. The documented predicate is
590
+ // `status === 'running'`; an interrupted run is a human-in-the-loop
591
+ // pause that interrupt-resume continues, not abandoned work a reaper
592
+ // should tear down.
593
+ const interruptedRunId = `rc-${crypto.randomUUID()}`
594
+ await runs.createOrResume({
595
+ runId: interruptedRunId,
596
+ threadId: 'rc-t',
597
+ startedAt: 1,
598
+ })
599
+ await runs.update(interruptedRunId, {
600
+ status: 'interrupted',
601
+ detachedSince: 1_000,
602
+ })
603
+ const afterInterrupted = await runs.listReclaimable({ now, ttlMs })
604
+ expect(afterInterrupted.some((r) => r.runId === interruptedRunId)).toBe(
605
+ false,
606
+ )
607
+ })
608
+ })
609
+
610
+ describe('interrupts', () => {
611
+ it('creates, resolves, cancels, and lists by thread and run', async (ctx) => {
612
+ const store = resolveStore('interrupts')
613
+ if (!store) return ctx.skip('store not provided')
614
+
615
+ expect(await store.get('int-missing')).toBeNull()
616
+
617
+ await store.create({
618
+ interruptId: 'int-1',
619
+ runId: 'run-i',
620
+ threadId: 'thread-i',
621
+ requestedAt: 10,
622
+ payload: { tool: 'search', args: { q: 'x' } },
623
+ })
624
+ await store.create({
625
+ interruptId: 'int-2',
626
+ runId: 'run-i',
627
+ threadId: 'thread-i',
628
+ requestedAt: 20,
629
+ payload: { tool: 'write' },
630
+ })
631
+ await store.create({
632
+ interruptId: 'int-3',
633
+ runId: 'run-other',
634
+ threadId: 'thread-i',
635
+ requestedAt: 30,
636
+ payload: {},
637
+ })
638
+
639
+ const one = await store.get('int-1')
640
+ expect(one).toMatchObject({
641
+ interruptId: 'int-1',
642
+ runId: 'run-i',
643
+ threadId: 'thread-i',
644
+ status: 'pending',
645
+ requestedAt: 10,
646
+ payload: { tool: 'search', args: { q: 'x' } },
647
+ })
648
+
649
+ expect(
650
+ (await store.list('thread-i')).map((r) => r.interruptId),
651
+ ).toEqual(['int-1', 'int-2', 'int-3'])
652
+ expect(
653
+ (await store.listByRun('run-i')).map((r) => r.interruptId),
654
+ ).toEqual(['int-1', 'int-2'])
655
+ expect(
656
+ (await store.listPending('thread-i')).map((r) => r.interruptId),
657
+ ).toEqual(['int-1', 'int-2', 'int-3'])
658
+
659
+ await store.resolve('int-1', { ok: true })
660
+ const resolved = await store.get('int-1')
661
+ expect(resolved?.status).toBe('resolved')
662
+ expect(resolved?.response).toEqual({ ok: true })
663
+ expect(typeof resolved?.resolvedAt).toBe('number')
664
+
665
+ await store.cancel('int-2')
666
+ const cancelled = await store.get('int-2')
667
+ expect(cancelled?.status).toBe('cancelled')
668
+ expect(typeof cancelled?.resolvedAt).toBe('number')
669
+
670
+ expect(
671
+ (await store.listPending('thread-i')).map((r) => r.interruptId),
672
+ ).toEqual(['int-3'])
673
+ expect(
674
+ (await store.listPendingByRun('run-i')).map((r) => r.interruptId),
675
+ ).toEqual([])
676
+ })
677
+
678
+ it('create is insert-if-absent: a duplicate id never clobbers a resolved interrupt', async (ctx) => {
679
+ const store = resolveStore('interrupts')
680
+ if (!store) return ctx.skip('store not provided')
681
+
682
+ await store.create({
683
+ interruptId: 'int-dup',
684
+ runId: 'run-dup',
685
+ threadId: 'thread-dup',
686
+ requestedAt: 100,
687
+ payload: { attempt: 1 },
688
+ })
689
+ await store.resolve('int-dup', { answer: 42 })
690
+
691
+ // A second create with the SAME id must be a no-op — not overwrite the
692
+ // now-resolved record back to pending with a fresh payload.
693
+ await store.create({
694
+ interruptId: 'int-dup',
695
+ runId: 'run-dup',
696
+ threadId: 'thread-dup',
697
+ requestedAt: 200,
698
+ payload: { attempt: 2 },
699
+ })
700
+
701
+ const after = await store.get('int-dup')
702
+ expect(after?.status).toBe('resolved')
703
+ expect(after?.response).toEqual({ answer: 42 })
704
+ expect(after?.payload).toEqual({ attempt: 1 })
705
+ expect(after?.requestedAt).toBe(100)
706
+ })
707
+
708
+ it('lists ordered by requestedAt ascending even when inserts are out of order', async (ctx) => {
709
+ const store = resolveStore('interrupts')
710
+ if (!store) return ctx.skip('store not provided')
711
+
712
+ // Insert later-timestamped first so Map insertion order would reverse
713
+ // requestedAt order without an explicit sort.
714
+ await store.create({
715
+ interruptId: 'int-late',
716
+ runId: 'run-order',
717
+ threadId: 'thread-order',
718
+ requestedAt: 300,
719
+ payload: {},
720
+ })
721
+ await store.create({
722
+ interruptId: 'int-early',
723
+ runId: 'run-order',
724
+ threadId: 'thread-order',
725
+ requestedAt: 100,
726
+ payload: {},
727
+ })
728
+ await store.create({
729
+ interruptId: 'int-mid',
730
+ runId: 'run-order',
731
+ threadId: 'thread-order',
732
+ requestedAt: 200,
733
+ payload: {},
734
+ })
735
+
736
+ expect(
737
+ (await store.list('thread-order')).map((r) => r.interruptId),
738
+ ).toEqual(['int-early', 'int-mid', 'int-late'])
739
+ expect(
740
+ (await store.listPending('thread-order')).map((r) => r.interruptId),
741
+ ).toEqual(['int-early', 'int-mid', 'int-late'])
742
+ expect(
743
+ (await store.listByRun('run-order')).map((r) => r.interruptId),
744
+ ).toEqual(['int-early', 'int-mid', 'int-late'])
745
+ })
746
+ })
747
+
748
+ describe('generationRuns', () => {
749
+ it('creates, resumes idempotently, updates, and gets', async () => {
750
+ const store = resolveStore('generationRuns')
751
+ if (!store) return
752
+
753
+ expect(await store.get('gen-missing')).toBeNull()
754
+
755
+ const created = await store.createOrResume({
756
+ runId: 'gen-1',
757
+ threadId: 'gen-thread-1',
758
+ activity: 'image',
759
+ provider: 'openai',
760
+ model: 'gpt-image-1',
761
+ startedAt: 1000,
762
+ })
763
+ expect(created).toMatchObject({
764
+ runId: 'gen-1',
765
+ activity: 'image',
766
+ provider: 'openai',
767
+ model: 'gpt-image-1',
768
+ status: 'running',
769
+ startedAt: 1000,
770
+ })
771
+ // threadId is the slot the run fills and is required: it must round-trip
772
+ // exactly, since findLatestForThread is the only query that finds a run.
773
+ expect(created.threadId).toBe('gen-thread-1')
774
+
775
+ // Idempotent: the stored record comes back untouched by the new input.
776
+ const resumed = await store.createOrResume({
777
+ runId: 'gen-1',
778
+ activity: 'video',
779
+ provider: 'google',
780
+ model: 'veo-3',
781
+ startedAt: 9999,
782
+ threadId: 'thread-late',
783
+ })
784
+ expect(resumed).toMatchObject({
785
+ runId: 'gen-1',
786
+ activity: 'image',
787
+ provider: 'openai',
788
+ model: 'gpt-image-1',
789
+ startedAt: 1000,
790
+ })
791
+ // Idempotency covers threadId too: the late scope must not overwrite the
792
+ // one the run was filed under.
793
+ expect(resumed.threadId).toBe('gen-thread-1')
794
+
795
+ await store.update('gen-1', {
796
+ status: 'completed',
797
+ finishedAt: 2000,
798
+ result: { images: [{ url: 'https://example.com/a.png' }] },
799
+ artifacts: [
800
+ {
801
+ role: 'output',
802
+ artifactId: 'art-1',
803
+ runId: 'gen-1',
804
+ threadId: 'thread-gen',
805
+ name: 'a.png',
806
+ mimeType: 'image/png',
807
+ size: 3,
808
+ createdAt: '2024-01-01T00:00:00.000Z',
809
+ source: {
810
+ activity: 'image',
811
+ path: 'images.0',
812
+ provider: 'openai',
813
+ model: 'gpt-image-1',
814
+ },
815
+ },
816
+ ],
817
+ usage: { promptTokens: 1, completionTokens: 2, totalTokens: 3 },
818
+ })
819
+ const done = await store.get('gen-1')
820
+ expect(done).toMatchObject({
821
+ status: 'completed',
822
+ finishedAt: 2000,
823
+ result: { images: [{ url: 'https://example.com/a.png' }] },
824
+ usage: { promptTokens: 1, completionTokens: 2, totalTokens: 3 },
825
+ })
826
+ expect(done?.artifacts).toHaveLength(1)
827
+ expect(done?.artifacts?.[0]).toMatchObject({
828
+ artifactId: 'art-1',
829
+ mimeType: 'image/png',
830
+ })
831
+
832
+ await store.update('gen-1', {
833
+ status: 'failed',
834
+ error: { message: 'boom', code: 'provider_error' },
835
+ })
836
+ const failed = await store.get('gen-1')
837
+ expect(failed?.status).toBe('failed')
838
+ expect(failed?.error).toEqual({
839
+ message: 'boom',
840
+ code: 'provider_error',
841
+ })
842
+
843
+ // Patching a missing run is a no-op (does not throw, does not create).
844
+ await store.update('gen-absent', { status: 'completed' })
845
+ expect(await store.get('gen-absent')).toBeNull()
846
+ })
847
+
848
+ // `findLatestForThread` is REQUIRED: `reconstructGeneration` hydrates a
849
+ // server-driven client from the stable thread id alone, so a backend that
850
+ // always answers `null` silently restores nothing rather than degrading.
851
+ it('findLatestForThread returns the most recently started linked run', async () => {
852
+ const store = resolveStore('generationRuns')
853
+ if (!store) return
854
+
855
+ const thread = 'thread-gen-latest'
856
+ expect(await store.findLatestForThread(thread)).toBeNull()
857
+
858
+ // Insert out of order so insertion order cannot stand in for startedAt.
859
+ await store.createOrResume({
860
+ runId: 'gen-late',
861
+ activity: 'image',
862
+ provider: 'openai',
863
+ model: 'gpt-image-1',
864
+ startedAt: 3000,
865
+ threadId: thread,
866
+ })
867
+ await store.createOrResume({
868
+ runId: 'gen-early',
869
+ activity: 'image',
870
+ provider: 'openai',
871
+ model: 'gpt-image-1',
872
+ startedAt: 1000,
873
+ threadId: thread,
874
+ })
875
+ expect(await store.findLatestForThread(thread)).toMatchObject({
876
+ runId: 'gen-late',
877
+ })
878
+
879
+ // Another thread's run is never returned, and unlike findActiveRun a
880
+ // TERMINAL run still counts — this is "the latest", not "the active".
881
+ await store.createOrResume({
882
+ runId: 'gen-other',
883
+ activity: 'image',
884
+ provider: 'openai',
885
+ model: 'gpt-image-1',
886
+ startedAt: 9000,
887
+ threadId: 'thread-gen-other',
888
+ })
889
+ await store.update('gen-late', {
890
+ status: 'completed',
891
+ finishedAt: 3500,
892
+ })
893
+ expect(await store.findLatestForThread(thread)).toMatchObject({
894
+ runId: 'gen-late',
895
+ status: 'completed',
896
+ })
897
+
898
+ // A run with no thread link is not attributed to any thread.
899
+ expect(await store.findLatestForThread('thread-unlinked')).toBeNull()
900
+ })
901
+ })
902
+
903
+ describe('artifacts', () => {
904
+ const artifact = (
905
+ overrides: Partial<ArtifactRecord> & Pick<ArtifactRecord, 'artifactId'>,
906
+ ): ArtifactRecord => ({
907
+ runId: 'run-art',
908
+ threadId: 'thread-art',
909
+ name: 'image.png',
910
+ mimeType: 'image/png',
911
+ size: 3,
912
+ createdAt: 100,
913
+ ...overrides,
914
+ })
915
+
916
+ it('saves as an upsert, gets, and lists by run', async () => {
917
+ const store = resolveStore('artifacts')
918
+ if (!store) return
919
+
920
+ expect(await store.get('art-missing')).toBeNull()
921
+ expect(await store.list('run-unknown')).toEqual([])
922
+
923
+ await store.save(
924
+ artifact({
925
+ artifactId: 'art-a',
926
+ blobKey: 'artifacts/run-art/art-a',
927
+ createdAt: 100,
928
+ }),
929
+ )
930
+ await store.save(
931
+ artifact({
932
+ artifactId: 'art-b',
933
+ sourceUrl: 'https://provider.example/expiring.png',
934
+ createdAt: 200,
935
+ }),
936
+ )
937
+ await store.save(
938
+ artifact({ artifactId: 'art-c', runId: 'run-art-other' }),
939
+ )
940
+
941
+ expect(await store.get('art-a')).toMatchObject({
942
+ artifactId: 'art-a',
943
+ runId: 'run-art',
944
+ threadId: 'thread-art',
945
+ blobKey: 'artifacts/run-art/art-a',
946
+ name: 'image.png',
947
+ mimeType: 'image/png',
948
+ size: 3,
949
+ createdAt: 100,
950
+ })
951
+ expect(await store.get('art-b')).toMatchObject({
952
+ sourceUrl: 'https://provider.example/expiring.png',
953
+ })
954
+
955
+ expect((await store.list('run-art')).map((r) => r.artifactId)).toEqual([
956
+ 'art-a',
957
+ 'art-b',
958
+ ])
959
+
960
+ // save() is insert-OR-OVERWRITE: re-saving an id corrects the record.
961
+ await store.save(
962
+ artifact({ artifactId: 'art-a', name: 'renamed.png', size: 9 }),
963
+ )
964
+ const updated = await store.get('art-a')
965
+ expect(updated).toMatchObject({ name: 'renamed.png', size: 9 })
966
+ expect(updated?.blobKey).toBeUndefined()
967
+ expect((await store.list('run-art')).map((r) => r.artifactId)).toEqual([
968
+ 'art-a',
969
+ 'art-b',
970
+ ])
971
+ })
972
+
973
+ it('deletes one artifact and every artifact for a run', async () => {
974
+ const store = resolveStore('artifacts')
975
+ if (!store) return
976
+
977
+ await store.save(artifact({ artifactId: 'art-d1', runId: 'run-del' }))
978
+ await store.save(artifact({ artifactId: 'art-d2', runId: 'run-del' }))
979
+ await store.save(
980
+ artifact({ artifactId: 'art-keep', runId: 'run-keep' }),
981
+ )
982
+
983
+ await store.delete('art-d1')
984
+ expect(await store.get('art-d1')).toBeNull()
985
+ expect((await store.list('run-del')).map((r) => r.artifactId)).toEqual([
986
+ 'art-d2',
987
+ ])
988
+
989
+ // Deleting an absent id is a silent no-op, mirroring BlobStore.delete.
990
+ await store.delete('art-d1')
991
+
992
+ await store.deleteForRun('run-del')
993
+ expect(await store.list('run-del')).toEqual([])
994
+ expect(await store.get('art-d2')).toBeNull()
995
+ // Scoped to the run: another run's artifacts survive.
996
+ expect((await store.list('run-keep')).map((r) => r.artifactId)).toEqual(
997
+ ['art-keep'],
998
+ )
999
+ // deleteForRun on a run with no artifacts is a no-op.
1000
+ await store.deleteForRun('run-del')
1001
+ })
1002
+ })
1003
+
1004
+ describe('blobs', () => {
1005
+ it('round-trips bytes and metadata through put/get/head', async () => {
1006
+ const store = resolveStore('blobs')
1007
+ if (!store) return
1008
+
1009
+ expect(await store.get('blob-missing')).toBeNull()
1010
+ expect(await store.head('blob-missing')).toBeNull()
1011
+
1012
+ const bytes = new Uint8Array([1, 2, 3, 4])
1013
+ const put = await store.put('blob/a', bytes, {
1014
+ contentType: 'image/png',
1015
+ customMetadata: { runId: 'run-blob' },
1016
+ })
1017
+ expect(put).toMatchObject({
1018
+ key: 'blob/a',
1019
+ size: 4,
1020
+ contentType: 'image/png',
1021
+ customMetadata: { runId: 'run-blob' },
1022
+ })
1023
+
1024
+ const object = required(await store.get('blob/a'), 'blob/a')
1025
+ expect(new Uint8Array(await object.arrayBuffer())).toEqual(bytes)
1026
+ expect(object).toMatchObject({
1027
+ key: 'blob/a',
1028
+ size: 4,
1029
+ contentType: 'image/png',
1030
+ customMetadata: { runId: 'run-blob' },
1031
+ })
1032
+
1033
+ const head = await store.head('blob/a')
1034
+ expect(head).toMatchObject({ key: 'blob/a', size: 4 })
1035
+
1036
+ // A string body encodes as UTF-8 and reads back through text().
1037
+ await store.put('blob/text', 'héllo')
1038
+ const text = required(await store.get('blob/text'), 'blob/text')
1039
+ expect(await text.text()).toBe('héllo')
1040
+
1041
+ // An ArrayBuffer body is accepted too.
1042
+ await store.put('blob/buffer', new Uint8Array([9, 9]).buffer)
1043
+ const buffered = required(await store.get('blob/buffer'), 'blob/buffer')
1044
+ expect(new Uint8Array(await buffered.arrayBuffer())).toEqual(
1045
+ new Uint8Array([9, 9]),
1046
+ )
1047
+ })
1048
+
1049
+ it('accepts a stream body with no declared length', async () => {
1050
+ const store = resolveStore('blobs')
1051
+ if (!store) return
1052
+
1053
+ // A TransformStream's readable side carries no declared length —
1054
+ // exactly what a fetch-based producer hands the store when the origin
1055
+ // chunks its reply (or its length can't be trusted). Byte bodies take
1056
+ // a different branch in most stores and prove nothing about the
1057
+ // streaming path, so this case is the one that keeps a store honest:
1058
+ // it must drain the stream, not require a length up front.
1059
+ const bytes = new Uint8Array(64 * 1024).map((_, i) => i % 251)
1060
+ const source = required(new Response(bytes).body, 'response body')
1061
+ const lengthless = source.pipeThrough(
1062
+ new TransformStream<Uint8Array, Uint8Array>(),
1063
+ )
1064
+ const put = await store.put('blob/stream', lengthless, {
1065
+ contentType: 'application/octet-stream',
1066
+ })
1067
+ expect(put.size).toBe(bytes.byteLength)
1068
+
1069
+ const object = required(await store.get('blob/stream'), 'blob/stream')
1070
+ expect(new Uint8Array(await object.arrayBuffer())).toEqual(bytes)
1071
+ expect(object.size).toBe(bytes.byteLength)
1072
+ })
1073
+
1074
+ it('accepts expectedLength as an advisory hint for a stream body', async () => {
1075
+ const store = resolveStore('blobs')
1076
+ if (!store) return
1077
+
1078
+ // The real-world combination: a length-less stream PLUS the hint —
1079
+ // which is what the artifact middleware sends when the origin declared
1080
+ // a trustworthy `content-length`. The hint is advisory (a store may
1081
+ // use it to pick an upload strategy); the drained bytes stay the
1082
+ // record of truth, so `size` must still be the count of what arrived.
1083
+ const bytes = new Uint8Array(9 * 1024).map((_, i) => i % 251)
1084
+ const source = required(new Response(bytes).body, 'response body')
1085
+ const lengthless = source.pipeThrough(
1086
+ new TransformStream<Uint8Array, Uint8Array>(),
1087
+ )
1088
+ const put = await store.put('blob/stream-hint', lengthless, {
1089
+ expectedLength: bytes.byteLength,
1090
+ })
1091
+ expect(put.size).toBe(bytes.byteLength)
1092
+
1093
+ const object = required(
1094
+ await store.get('blob/stream-hint'),
1095
+ 'blob/stream-hint',
1096
+ )
1097
+ expect(new Uint8Array(await object.arrayBuffer())).toEqual(bytes)
1098
+ expect(object.size).toBe(bytes.byteLength)
1099
+ })
1100
+
1101
+ it('serves a byte range and reports the slice it served', async () => {
1102
+ const store = resolveStore('blobs')
1103
+ if (!store) return
1104
+
1105
+ // Range reads are what a serve route turns into `206` +
1106
+ // `Content-Range` — the shape `<video>` seeking is built on. `size`
1107
+ // keeps reporting the WHOLE object so the route can finish the
1108
+ // `Content-Range` header from the same result.
1109
+ const bytes = new Uint8Array(1024).map((_, i) => i % 251)
1110
+ await store.put('blob/range', bytes)
1111
+
1112
+ const middle = required(
1113
+ await store.get('blob/range', { range: { offset: 100, length: 50 } }),
1114
+ 'blob/range',
1115
+ )
1116
+ expect(new Uint8Array(await middle.arrayBuffer())).toEqual(
1117
+ bytes.slice(100, 150),
1118
+ )
1119
+ expect(middle.size).toBe(bytes.byteLength)
1120
+ expect(middle.range).toEqual({ offset: 100, length: 50 })
1121
+
1122
+ // No `length`: from the offset to the end.
1123
+ const tail = required(
1124
+ await store.get('blob/range', { range: { offset: 1000 } }),
1125
+ 'blob/range',
1126
+ )
1127
+ expect(new Uint8Array(await tail.arrayBuffer())).toEqual(
1128
+ bytes.slice(1000),
1129
+ )
1130
+ expect(tail.range).toEqual({ offset: 1000, length: 24 })
1131
+
1132
+ // A `length` past the end is clamped, not an error: `bytes=1000-2000`
1133
+ // against a 1 KiB object is a legal request that serves 24 bytes.
1134
+ const clamped = required(
1135
+ await store.get('blob/range', {
1136
+ range: { offset: 1000, length: 1000 },
1137
+ }),
1138
+ 'blob/range',
1139
+ )
1140
+ expect(clamped.range).toEqual({ offset: 1000, length: 24 })
1141
+ expect((await clamped.arrayBuffer()).byteLength).toBe(24)
1142
+
1143
+ // The streaming accessor carries the same slice as arrayBuffer().
1144
+ const streamed = required(
1145
+ await store.get('blob/range', { range: { offset: 10, length: 5 } }),
1146
+ 'blob/range',
1147
+ )
1148
+ const body = streamed.body
1149
+ if (body) {
1150
+ expect(await drainStream(body)).toEqual(bytes.slice(10, 15))
1151
+ }
1152
+
1153
+ // A whole-object read reports no `range` — a caller that sees one
1154
+ // takes the bytes for a slice and would answer `206` for all of them.
1155
+ const whole = required(await store.get('blob/range'), 'blob/range')
1156
+ expect(whole.range).toBeUndefined()
1157
+ })
1158
+
1159
+ it('overwrites an existing key and deletes silently', async () => {
1160
+ const store = resolveStore('blobs')
1161
+ if (!store) return
1162
+
1163
+ const first = await store.put('blob/over', new Uint8Array([1]), {
1164
+ contentType: 'text/plain',
1165
+ customMetadata: { v: '1' },
1166
+ })
1167
+ const second = await store.put('blob/over', new Uint8Array([2, 2, 2]), {
1168
+ contentType: 'application/octet-stream',
1169
+ customMetadata: { v: '2' },
1170
+ })
1171
+
1172
+ expect(second).toMatchObject({
1173
+ size: 3,
1174
+ contentType: 'application/octet-stream',
1175
+ customMetadata: { v: '2' },
1176
+ })
1177
+ // When a backend exposes etags at all, new bytes get a new one.
1178
+ if (first.etag !== undefined && second.etag !== undefined) {
1179
+ expect(second.etag).not.toBe(first.etag)
1180
+ }
1181
+ const after = required(await store.get('blob/over'), 'blob/over')
1182
+ expect(new Uint8Array(await after.arrayBuffer())).toEqual(
1183
+ new Uint8Array([2, 2, 2]),
1184
+ )
1185
+
1186
+ await store.delete('blob/over')
1187
+ expect(await store.get('blob/over')).toBeNull()
1188
+ expect(await store.head('blob/over')).toBeNull()
1189
+ // Deleting an absent key is a no-op, not an error.
1190
+ await store.delete('blob/over')
1191
+ })
1192
+
1193
+ it('lists by literal prefix in ascending key order', async () => {
1194
+ const store = resolveStore('blobs')
1195
+ if (!store) return
1196
+
1197
+ // `_` and `%` are LIKE metacharacters: a SQL backend that forgets to
1198
+ // escape them would match `list-x/…` here. And SQLite's LIKE is
1199
+ // case-insensitive for ASCII, so `LIST_/` must not match either.
1200
+ await store.put('list_/b', new Uint8Array([2]))
1201
+ await store.put('list_/a', new Uint8Array([1]))
1202
+ await store.put('list_/c', new Uint8Array([3]))
1203
+ await store.put('list-x/d', new Uint8Array([4]))
1204
+ await store.put('LIST_/e', new Uint8Array([5]))
1205
+
1206
+ const page = await store.list({ prefix: 'list_/' })
1207
+ expect(page.objects.map((o) => o.key)).toEqual([
1208
+ 'list_/a',
1209
+ 'list_/b',
1210
+ 'list_/c',
1211
+ ])
1212
+ expect(page.truncated).toBeFalsy()
1213
+
1214
+ expect(
1215
+ (await store.list({ prefix: 'list_/nothing-here' })).objects,
1216
+ ).toEqual([])
1217
+ })
1218
+
1219
+ it('pages with a cursor and returns an empty page for limit 0', async () => {
1220
+ const store = resolveStore('blobs')
1221
+ if (!store) return
1222
+
1223
+ for (const key of ['page/a', 'page/b', 'page/c', 'page/d', 'page/e']) {
1224
+ await store.put(key, new Uint8Array([1]))
1225
+ }
1226
+
1227
+ const empty = await store.list({ prefix: 'page/', limit: 0 })
1228
+ expect(empty.objects).toEqual([])
1229
+ expect(empty.truncated).toBeFalsy()
1230
+ expect(empty.cursor).toBeUndefined()
1231
+
1232
+ // Walk every key exactly once: each page's cursor resumes strictly
1233
+ // after the last key it returned.
1234
+ const seen: Array<string> = []
1235
+ let cursor: string | undefined
1236
+ for (let guard = 0; guard < 10; guard++) {
1237
+ const result = await store.list({
1238
+ prefix: 'page/',
1239
+ limit: 2,
1240
+ ...(cursor !== undefined ? { cursor } : {}),
1241
+ })
1242
+ seen.push(...result.objects.map((o) => o.key))
1243
+ if (!result.truncated) break
1244
+ expect(result.cursor).toBe(result.objects.at(-1)?.key)
1245
+ cursor = result.cursor
1246
+ }
1247
+ expect(seen).toEqual(['page/a', 'page/b', 'page/c', 'page/d', 'page/e'])
1248
+
1249
+ // An exact-fit limit is not truncated: no key matches beyond the page.
1250
+ const exact = await store.list({ prefix: 'page/', limit: 5 })
1251
+ expect(exact.objects.map((o) => o.key)).toEqual(seen)
1252
+ expect(exact.truncated).toBeFalsy()
1253
+ })
1254
+ })
1255
+
1256
+ describe('metadata', () => {
1257
+ it('sets, gets, namespaces, and deletes without composite-key collisions', async (ctx) => {
1258
+ const store = resolveStore('metadata')
1259
+ if (!store) return ctx.skip('store not provided')
1260
+
1261
+ expect(await store.get('scope-a', 'k')).toBeNull()
1262
+
1263
+ await store.set('scope-a', 'k', { n: 1 })
1264
+ await store.set('scope-b', 'k', { n: 2 })
1265
+ expect(await store.get('scope-a', 'k')).toEqual({ n: 1 })
1266
+ expect(await store.get('scope-b', 'k')).toEqual({ n: 2 })
1267
+
1268
+ await store.set('scope-a', 'k', { n: 3 })
1269
+ expect(await store.get('scope-a', 'k')).toEqual({ n: 3 })
1270
+
1271
+ await store.delete('scope-a', 'k')
1272
+ expect(await store.get('scope-a', 'k')).toBeNull()
1273
+ // Delete is namespaced: scope-b untouched.
1274
+ expect(await store.get('scope-b', 'k')).toEqual({ n: 2 })
1275
+
1276
+ // Composite identity must not alias across colon-containing parts.
1277
+ // ('a:b','c') and ('a','b:c') are distinct pairs.
1278
+ await store.set('a:b', 'c', 'left')
1279
+ await store.set('a', 'b:c', 'right')
1280
+ expect(await store.get('a:b', 'c')).toBe('left')
1281
+ expect(await store.get('a', 'b:c')).toBe('right')
1282
+ await store.delete('a:b', 'c')
1283
+ expect(await store.get('a:b', 'c')).toBeNull()
1284
+ expect(await store.get('a', 'b:c')).toBe('right')
1285
+ })
1286
+ })
1287
+ })
1288
+ }