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

durability.test.ts

374 lines13.2 KB

1import { describe, expect, expectTypeOf, it, vi } from 'vitest'
2import { EventType, InMemoryRunStore, memoryStream } from '@tanstack/ai'
3import { DEFAULT_JOURNAL_DIR } from '../src/journal'
4import {
5 DurableRunIdRequiredError,
6 alignedIfAttaching,
7 journalOptionsFor,
8 resolveDurableRunId,
9 resolveSandboxDurability,
10} from '../src/durability'
11import { captureLogger, collectChunks, fakeLog, fromChunkValues } from './fakes'
12import type {
13 SandboxDurabilityOptions,
14 SandboxRunDurability,
15} from '../src/durability'
16import type { StreamChunk, StreamDurability } from '@tanstack/ai'
17​
18const adapterFor = (runId: string): StreamDurability =>
19 memoryStream(new Request(`https://x/run?runId=${runId}`))
20​
21function text(messageId: string, delta: string): StreamChunk {
22 return {
23 type: EventType.TEXT_MESSAGE_CONTENT,
24 messageId,
25 delta,
26 timestamp: 1,
27 }
29​
30function bridged(name: string): StreamChunk {
31 return { type: EventType.CUSTOM, name, value: {}, timestamp: 1 }
33​
34/**
35 * `resolveSandboxDurability` never returns `undefined` for a fully-wired pair,
36 * but its type says it might. Narrowing here (rather than `!`) keeps the
37 * assertion in the test where a regression that DID return `undefined` would
38 * fail loudly instead of being asserted away.
39 */
40function resolvedDurability(
41 durability: Parameters<typeof resolveSandboxDurability>[0],
42): NonNullable<ReturnType<typeof resolveSandboxDurability>> {
43 const resolved = resolveSandboxDurability(durability)
44 if (resolved === undefined) {
45 throw new Error('expected resolveSandboxDurability to resolve')
46 }
47 return resolved
49​
50describe('resolveDurableRunId', () => {
51 it('returns a caller-supplied runId unchanged, durable or not', () => {
52 const fallback = vi.fn(() => 'generated')
53 for (const durable of [true, false]) {
54 expect(
55 resolveDurableRunId('caller-run', {
56 durable,
57 adapter: 'codex',
58 fallback,
59 }),
60 ).toBe('caller-run')
61 }
62 expect(fallback).not.toHaveBeenCalled()
63 })
64​
65 it("falls back when durability is OFF, preserving today's behavior exactly", () => {
66 const fallback = vi.fn(() => 'generated')
67 expect(
68 resolveDurableRunId(undefined, {
69 durable: false,
70 adapter: 'codex',
71 fallback,
72 }),
73 ).toBe('generated')
74 expect(fallback).toHaveBeenCalledTimes(1)
75 })
76​
77 it('throws when durability is ON and no runId was supplied', () => {
78 const fallback = vi.fn(() => 'generated')
79 expect(() =>
80 resolveDurableRunId(undefined, {
81 durable: true,
82 adapter: 'codex',
83 fallback,
84 }),
85 ).toThrow(DurableRunIdRequiredError)
86 // Decisive: the fallback must NOT run. A generated id would produce a
87 // journal path no successor host can recompute — an unrecoverable run that
88 // LOOKS durable.
89 expect(fallback).not.toHaveBeenCalled()
90 })
91​
92 it('names the adapter and the fix in the message', () => {
93 try {
94 resolveDurableRunId(undefined, {
95 durable: true,
96 adapter: 'claude-code',
97 fallback: () => 'x',
98 })
99 expect.unreachable('should have thrown')
100 } catch (error) {
101 expect(error).toBeInstanceOf(DurableRunIdRequiredError)
102 expect((error as Error).message).toContain('claude-code')
103 expect((error as Error).message).toContain('runId')
104 }
105 })
106​
107 it('rejects an empty string, which journalPaths would reject anyway', () => {
108 const fallback = vi.fn(() => 'generated')
109 expect(() =>
110 resolveDurableRunId('', { durable: true, adapter: 'codex', fallback }),
111 ).toThrow(DurableRunIdRequiredError)
112 expect(fallback).not.toHaveBeenCalled()
113 })
114​
115 it('falls back on an empty string when durability is OFF, never returning it', () => {
116 // An empty runId is not a runId. Non-durable callers get a generated id
117 // rather than an id that would resolve to the journal directory itself.
118 expect(
119 resolveDurableRunId('', {
120 durable: false,
121 adapter: 'codex',
122 fallback: () => 'generated',
123 }),
124 ).toBe('generated')
125 })
126})
127​
128describe('the reaper owns the detached-run TTL, and nothing else declares one', () => {
129 // `ReapOptions.detachedRunTtlMs` is the single source of truth. A duplicate
130 // TTL on `withSandbox` was read by NOBODY — the only enforcer,
131 // `reapDetachedRuns`, runs from a cron with no `CapabilityContext`, so it
132 // cannot reach the capability bus this option's parsed value was published
133 // on. Two knobs in two units at two call sites is silent divergence: `'30m'`
134 // here and `5 * 60_000` at the sweep expired runs at five minutes while the
135 // config claimed thirty, and nothing warned.
136 //
137 // These are TYPE assertions, which this repo checks (`pnpm exec tsc` covers
138 // `tests/**`). Re-adding the option makes both of them hard errors.
139 it('withSandbox durability options declare no TTL', () => {
140 expectTypeOf<SandboxDurabilityOptions>().not.toHaveProperty(
141 'detachedRunTtl',
142 )
143 expectTypeOf<SandboxRunDurability>().not.toHaveProperty('detachedRunTtlMs')
144 })
145​
146 it('rejects a TTL passed to withSandbox durability at the type level', () => {
147 const options: SandboxDurabilityOptions = {
148 adapter: adapterFor('r-ttl'),
149 // @ts-expect-error -- `detachedRunTtl` no longer exists; the reaper's
150 // `detachedRunTtlMs` is the only TTL. A typo can no longer become a
151 // silent 30-minute token burn, because there is nothing to mistype.
152 detachedRunTtl: '30m',
153 }
154 void options
155 })
156})
157​
158describe('resolveSandboxDurability', () => {
159 it('requires BOTH stores, and says nothing when only one is wired', () => {
160 const runs = new InMemoryRunStore()
161 // Neither.
162 expect(resolveSandboxDurability(undefined)).toBeUndefined()
163 expect(resolveSandboxDurability({})).toBeUndefined()
164 // Only `runs`: a record with no event log cannot be replayed.
165 expect(resolveSandboxDurability({ runs })).toBeUndefined()
166 // Only `durability`: a log with no record cannot be found, claimed, or
167 // reaped.
168 expect(
169 resolveSandboxDurability({ durability: { adapter: adapterFor('r1') } }),
170 ).toBeUndefined()
171 })
172​
173 it('resolves both stores into the capability payload with defaults', () => {
174 const runs = new InMemoryRunStore()
175 const adapter = adapterFor('r1')
176 const resolved = resolveSandboxDurability({ runs, durability: { adapter } })
177 expect(resolved).toEqual({
178 runs,
179 adapter,
180 journalDir: DEFAULT_JOURNAL_DIR,
181 attach: false,
182 detachOnDisconnect: true,
183 })
184 // Omitted, not present-and-undefined: the field is optional and the
185 // capability payload must not carry an explicit `undefined`.
186 expect(Object.keys(resolved ?? {})).not.toContain('pollIntervalMs')
187 })
188​
189 it('carries every explicit option through, including a false detach', () => {
190 const runs = new InMemoryRunStore()
191 const adapter = adapterFor('r2')
192 expect(
193 resolveSandboxDurability({
194 runs,
195 durability: {
196 adapter,
197 journal: '/srv/runs',
198 attach: true,
199 detachOnDisconnect: false,
200 pollIntervalMs: 250,
201 },
202 }),
203 ).toEqual({
204 runs,
205 adapter,
206 journalDir: '/srv/runs',
207 attach: true,
208 detachOnDisconnect: false,
209 pollIntervalMs: 250,
210 })
211 })
212})
213​
214describe('journalOptionsFor', () => {
215 it('is undefined when the run is not durable, so spawnNdjson keeps its old path', () => {
216 // `isJournaled` tests `options.journal !== undefined`, so `undefined` here
217 // is what preserves the unjournaled spawn path byte for byte.
218 expect(journalOptionsFor(undefined, 'joff-1')).toBeUndefined()
219 })
220​
221 it('carries runId, dir and attach from the resolved durability', () => {
222 const runs = new InMemoryRunStore()
223 const durability = resolvedDurability({
224 runs,
225 durability: {
226 adapter: fakeLog(),
227 journal: '/var/j',
228 attach: true,
229 pollIntervalMs: 10,
230 attachWaitMs: 250,
231 },
232 })
233 expect(journalOptionsFor(durability, 'jopt-attach')).toEqual({
234 runId: 'jopt-attach',
235 dir: '/var/j',
236 attach: true,
237 pollIntervalMs: 10,
238 // Only on an attach: the run record is what tells `awaitAttachableJournal`
239 // "not written yet" from "will never be written".
240 runs,
241 attachWaitMs: 250,
242 })
243 })
244​
245 it('omits runs on a NON-attach run, where journal absence proves nothing', () => {
246 // A fresh run's journal is created by its own `journaledCommand` spawn
247 // moments after this option object is built, so gating on its absence would
248 // fail every new run. Not carrying the store makes that impossible.
249 const durability = resolvedDurability({
250 runs: new InMemoryRunStore(),
251 durability: { adapter: fakeLog(), attach: false, attachWaitMs: 250 },
252 })
253 const options = journalOptionsFor(durability, 'jopt-fresh')
254 expect(Object.keys(options ?? {})).not.toContain('runs')
255 expect(Object.keys(options ?? {})).not.toContain('attachWaitMs')
256 })
257​
258 it('always supplies dir, even though JournalOptions.dir is optional', () => {
259 // A successor host recomputes the journal path from these options. Leaving
260 // `dir` out would make it re-derive the default independently, so the two
261 // hosts would agree only by coincidence.
262 const durability = resolvedDurability({
263 runs: new InMemoryRunStore(),
264 durability: { adapter: fakeLog() },
265 })
266 const options = journalOptionsFor(durability, 'jopt-dir')
267 expect(options?.dir).toBe(DEFAULT_JOURNAL_DIR)
268 expect(Object.keys(options ?? {})).toContain('dir')
269 })
270​
271 it('omits pollIntervalMs when unset, rather than passing undefined through', () => {
272 const durability = resolvedDurability({
273 runs: new InMemoryRunStore(),
274 durability: { adapter: fakeLog() },
275 })
276 const options = journalOptionsFor(durability, 'jopt-default')
277 expect(options).toEqual({
278 runId: 'jopt-default',
279 dir: DEFAULT_JOURNAL_DIR,
280 attach: false,
281 })
282 expect(Object.keys(options ?? {})).not.toContain('pollIntervalMs')
283 })
284})
285​
286describe('alignedIfAttaching', () => {
287 it('passes the stream through untouched when not attaching', async () => {
288 // A log with entries in it: proof that a NON-attach run does not align,
289 // which matters because a fresh run's own chunks would otherwise be
290 // classified as "already stored" and silently suppressed.
291 const adapter = fakeLog([text('m1', 'a')])
292 // `fakeLog` COPIES its seed, so assert against the log itself — asserting
293 // against the array passed in would be vacuous.
294 expect(await adapter.snapshot()).toEqual([
295 { offset: 'o:0', chunk: text('m1', 'a') },
296 ])
297 const durability = resolvedDurability({
298 runs: new InMemoryRunStore(),
299 durability: { adapter },
300 })
301 const source = fromChunkValues([text('m1', 'a'), text('m1', 'b')])
302 const wrapped = alignedIfAttaching(source, durability)
303 // Delivery first: without the `attach` guard, `text('m1', 'a')` matches the
304 // seeded entry and is SUPPRESSED — silent data loss, not a slow path.
305 expect(await collectChunks(wrapped)).toEqual([
306 text('m1', 'a'),
307 text('m1', 'b'),
308 ])
309 // Identity, not just equality: nothing wraps a non-attach stream at all.
310 expect(wrapped).toBe(source)
311 })
312​
313 it('passes the stream through untouched when the run is not durable at all', async () => {
314 const source = fromChunkValues([text('m1', 'a')])
315 const wrapped = alignedIfAttaching(source, undefined)
316 expect(wrapped).toBe(source)
317 expect(await collectChunks(wrapped)).toEqual([text('m1', 'a')])
318 })
319​
320 it('suppresses the stored prefix when attaching', async () => {
321 const adapter = fakeLog([text('m1', 'a')])
322 expect(await adapter.snapshot()).toHaveLength(1)
323 const durability = resolvedDurability({
324 runs: new InMemoryRunStore(),
325 durability: { adapter, attach: true },
326 })
327 expect(
328 await collectChunks(
329 alignedIfAttaching(
330 fromChunkValues([text('m1', 'a'), text('m1', 'b')]),
331 durability,
332 ),
333 ),
334 ).toEqual([text('m1', 'b')])
335 })
336​
337 it('tolerates a bridged CUSTOM chunk in the stored log when attaching', async () => {
338 // Without `isOutOfBand: isBridgeCustomChunk` this replay diverges at the
339 // bridged entry, so a bridged-tool run could never be taken over.
340 const adapter = fakeLog([text('m1', 'a'), bridged('code_mode:console')])
341 expect(await adapter.snapshot()).toHaveLength(2)
342 const durability = resolvedDurability({
343 runs: new InMemoryRunStore(),
344 durability: { adapter, attach: true },
345 })
346 expect(
347 await collectChunks(
348 alignedIfAttaching(
349 fromChunkValues([text('m1', 'a'), text('m1', 'b')]),
350 durability,
351 ),
352 ),
353 ).toEqual([text('m1', 'b')])
354 })
355​
356 it('forwards the logger so the alignment summary is observable', async () => {
357 const adapter = fakeLog([text('m1', 'a')])
358 const durability = resolvedDurability({
359 runs: new InMemoryRunStore(),
360 durability: { adapter, attach: true },
361 })
362 const { logger, calls } = captureLogger()
363 await collectChunks(
364 alignedIfAttaching(
365 fromChunkValues([text('m1', 'a'), text('m1', 'b')]),
366 durability,
367 logger,
368 ),
369 )
370 expect(calls.some((call) => call.msg.includes('journal alignment'))).toBe(
371 true,
372 )
373 })
374})