Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { EventType, memoryStream } from '@tanstack/ai'
3import {
4 DEFAULT_MAX_OUT_OF_BAND_SKIP,
5 JournalReplayDivergedError,
6 JournalReplayThreadIdMismatchError,
7 alignToStoredLog,
8 isBridgeCustomChunk,
9} from '../src/align'
10import {
11 chunkFingerprint,
12 chunkFingerprintIgnoringThreadId,
13 chunkThreadId,
14} from '../src/chunk-identity'
15import type { StreamChunk, StreamDurability } from '@tanstack/ai'
16
17/**
18 * `memoryStream` keys its log map by runId at MODULE scope, so a reused runId
19 * silently inherits another test's entries. Every case below gets its own.
20 */
21function producerRequest(runId: string): Request {
22 return new Request(`http://test.local/api/chat?runId=${runId}`, {
23 method: 'POST',
24 })
25}
26
27function textChunk(messageId: string, delta: string): StreamChunk {
28 return {
29 type: EventType.TEXT_MESSAGE_CONTENT,
30 messageId,
31 delta,
32 timestamp: 1,
33 }
34}
35
36async function* fromChunks(
37 chunks: Array<StreamChunk>,
38): AsyncIterable<StreamChunk> {
39 for (const chunk of chunks) {
40 await Promise.resolve()
41 yield chunk
42 }
43}
44
45function bridgedChunk(name: string): StreamChunk {
46 return { type: EventType.CUSTOM, name, value: {}, timestamp: 1 }
47}
48
49/**
50 * A `StreamDurability` that only answers `snapshot()`. Everything that would
51 * mutate or tail the log rejects, so the shape of the fixture itself proves
52 * alignment never appends, never closes, and never `read`s.
53 */
54function storedLog(chunks: Array<StreamChunk>): StreamDurability {
55 return {
56 resumeFrom: () => null,
57 append: () => Promise.reject(new Error('alignToStoredLog must not append')),
58 read: () => {
59 throw new Error('alignToStoredLog must use snapshot(), never read()')
60 },
61 close: () => Promise.reject(new Error('alignToStoredLog must not close')),
62 snapshot: () =>
63 Promise.resolve(
64 chunks.map((chunk, index) => ({ offset: `o:${index}`, chunk })),
65 ),
66 }
67}
68
69async function collectChunks(
70 it: AsyncIterable<StreamChunk>,
71): Promise<Array<StreamChunk>> {
72 const out: Array<StreamChunk> = []
73 for await (const chunk of it) out.push(chunk)
74 return out
75}
76
77async function collectDeltas(
78 it: AsyncIterable<StreamChunk>,
79): Promise<Array<string>> {
80 const out: Array<string> = []
81 for await (const chunk of it) {
82 if (chunk.type === EventType.TEXT_MESSAGE_CONTENT) out.push(chunk.delta)
83 }
84 return out
85}
86
87describe('alignToStoredLog', () => {
88 it('passes everything through when the log is empty (a fresh run)', async () => {
89 const durability = memoryStream(producerRequest('align-fresh'))
90 const replay = fromChunks([textChunk('m1', 'a'), textChunk('m1', 'b')])
91 expect(
92 await collectDeltas(alignToStoredLog(replay, { durability })),
93 ).toEqual(['a', 'b'])
94 })
95
96 it('suppresses the stored prefix and yields only the remainder', async () => {
97 const durability = memoryStream(producerRequest('align-partial'))
98 await durability.append([textChunk('m1', 'a'), textChunk('m1', 'b')])
99
100 const replay = fromChunks([
101 textChunk('m1', 'a'),
102 textChunk('m1', 'b'),
103 textChunk('m1', 'c'),
104 textChunk('m1', 'd'),
105 ])
106 expect(
107 await collectDeltas(alignToStoredLog(replay, { durability })),
108 ).toEqual(['c', 'd'])
109 })
110
111 it('yields nothing when the log already holds the whole replay', async () => {
112 const durability = memoryStream(producerRequest('align-complete'))
113 await durability.append([textChunk('m1', 'a'), textChunk('m1', 'b')])
114 const replay = fromChunks([textChunk('m1', 'a'), textChunk('m1', 'b')])
115 expect(
116 await collectDeltas(alignToStoredLog(replay, { durability })),
117 ).toEqual([])
118 })
119
120 it('matches on the fingerprint, not identity or JSON text: timestamp drift and key reordering still align', async () => {
121 // The journal round-trips every chunk through NDJSON, which preserves
122 // neither object identity nor key order, and `timestamp` is wall-clock and
123 // unreproducible. A comparison by reference or by `JSON.stringify` would
124 // report a divergence here.
125 const durability = memoryStream(producerRequest('align-fingerprint'))
126 await durability.append([
127 {
128 type: EventType.TEXT_MESSAGE_CONTENT,
129 messageId: 'm1',
130 delta: 'a',
131 timestamp: 1,
132 },
133 ])
134 const replay = fromChunks([
135 {
136 delta: 'a',
137 timestamp: 999_999,
138 messageId: 'm1',
139 type: EventType.TEXT_MESSAGE_CONTENT,
140 },
141 textChunk('m1', 'b'),
142 ])
143 expect(
144 await collectDeltas(alignToStoredLog(replay, { durability })),
145 ).toEqual(['b'])
146 })
147
148 it('throws JournalReplayDivergedError when the very first chunk differs', async () => {
149 const durability = memoryStream(producerRequest('align-diverge-0'))
150 await durability.append([textChunk('m1', 'a'), textChunk('m1', 'b')])
151
152 // A nondeterministic messageId is exactly what this must catch.
153 const replay = fromChunks([textChunk('m2', 'a'), textChunk('m1', 'b')])
154 let caught: unknown
155 try {
156 await collectDeltas(alignToStoredLog(replay, { durability }))
157 } catch (error) {
158 caught = error
159 }
160 expect(caught).toBeInstanceOf(JournalReplayDivergedError)
161 if (caught instanceof JournalReplayDivergedError) {
162 expect(caught.index).toBe(0)
163 expect(caught.stored).toContain('"messageId":"m1"')
164 expect(caught.replayed).toContain('"messageId":"m2"')
165 }
166 })
167
168 it('throws mid-prefix, reporting the diverging index and both fingerprints', async () => {
169 const durability = memoryStream(producerRequest('align-diverge-mid'))
170 await durability.append([
171 textChunk('m1', 'a'),
172 textChunk('m1', 'b'),
173 textChunk('m1', 'c'),
174 ])
175 const replay = fromChunks([
176 textChunk('m1', 'a'),
177 textChunk('m1', 'X'),
178 textChunk('m1', 'c'),
179 ])
180 let caught: unknown
181 try {
182 await collectDeltas(alignToStoredLog(replay, { durability }))
183 } catch (error) {
184 caught = error
185 }
186 expect(caught).toBeInstanceOf(JournalReplayDivergedError)
187 if (caught instanceof JournalReplayDivergedError) {
188 expect(caught.index).toBe(1)
189 expect(caught.stored).toContain('"delta":"b"')
190 expect(caught.replayed).toContain('"delta":"X"')
191 }
192 })
193
194 it('yields nothing before it throws on a divergence, so no chunk escapes the mismatch', async () => {
195 const durability = memoryStream(producerRequest('align-diverge-no-yield'))
196 await durability.append([textChunk('m1', 'a'), textChunk('m1', 'b')])
197 const replay = fromChunks([
198 textChunk('m1', 'a'),
199 textChunk('m1', 'X'),
200 textChunk('m1', 'c'),
201 ])
202 const seen: Array<string> = []
203 await expect(async () => {
204 for await (const chunk of alignToStoredLog(replay, { durability })) {
205 if (chunk.type === EventType.TEXT_MESSAGE_CONTENT)
206 seen.push(chunk.delta)
207 }
208 }).rejects.toThrow(JournalReplayDivergedError)
209 expect(seen).toEqual([])
210 })
211
212 it('throws when the replay is SHORTER than the log rather than silently truncating', async () => {
213 // A shorter replay means the journal lost bytes a previous host translated.
214 // Continuing would produce a run whose log claims events the journal cannot
215 // account for.
216 const durability = memoryStream(producerRequest('align-short'))
217 await durability.append([textChunk('m1', 'a'), textChunk('m1', 'b')])
218 const replay = fromChunks([textChunk('m1', 'a')])
219 await expect(
220 collectDeltas(alignToStoredLog(replay, { durability })),
221 ).rejects.toThrow(/shorter than the stored log/)
222 })
223
224 it('throws when the replay is empty but the log is not', async () => {
225 const durability = memoryStream(producerRequest('align-empty-replay'))
226 await durability.append([textChunk('m1', 'a')])
227 await expect(
228 collectDeltas(alignToStoredLog(fromChunks([]), { durability })),
229 ).rejects.toThrow(/shorter than the stored log/)
230 })
231
232 it('reads a still-OPEN log and terminates (the takeover case: the host that would have closed it died)', async () => {
233 const durability = memoryStream(producerRequest('align-open-log'), {
234 firstChunkDeadlineMs: 10_000,
235 })
236 await durability.append([textChunk('m1', 'a')])
237
238 // Prove the log really is open: a tailing `read` does NOT return here,
239 // which is precisely why alignment must use `snapshot()` instead.
240 const controller = new AbortController()
241 const tail = (async () => {
242 for await (const _entry of durability.read('-1', controller.signal)) {
243 // drain
244 }
245 })()
246 const raced = await Promise.race([
247 tail.then(() => 'read-returned'),
248 new Promise<string>((resolve) =>
249 setTimeout(() => resolve('still-tailing'), 50),
250 ),
251 ])
252 expect(raced).toBe('still-tailing')
253
254 // The alignment itself must complete against that same open log. The
255 // explicit per-test timeout turns a non-terminating implementation into a
256 // fast failure rather than a hung suite.
257 const replay = fromChunks([textChunk('m1', 'a'), textChunk('m1', 'b')])
258 expect(
259 await collectDeltas(alignToStoredLog(replay, { durability })),
260 ).toEqual(['b'])
261
262 controller.abort()
263 await tail
264 }, 2_000)
265
266 it('reads the stored prefix exactly once, before consuming any replay chunk', async () => {
267 const durability = memoryStream(producerRequest('align-once'))
268 await durability.append([textChunk('m1', 'a')])
269
270 let pulled = 0
271 let snapshots = 0
272 let pulledAtFirstSnapshot = -1
273 const counted: StreamDurability = {
274 ...durability,
275 snapshot: () => {
276 if (snapshots === 0) pulledAtFirstSnapshot = pulled
277 snapshots += 1
278 return durability.snapshot()
279 },
280 }
281
282 async function* counting(): AsyncIterable<StreamChunk> {
283 for (const chunk of [
284 textChunk('m1', 'a'),
285 textChunk('m1', 'b'),
286 textChunk('m1', 'c'),
287 ]) {
288 pulled += 1
289 yield chunk
290 }
291 }
292
293 expect(
294 await collectDeltas(
295 alignToStoredLog(counting(), { durability: counted }),
296 ),
297 ).toEqual(['b', 'c'])
298 expect(snapshots).toBe(1)
299 expect(pulledAtFirstSnapshot).toBe(0)
300 expect(pulled).toBe(3)
301 })
302})
303
304describe('alignToStoredLog — out-of-band tolerance', () => {
305 it('by DEFAULT still throws on a stored chunk the replay does not produce', async () => {
306 // The strict behavior is the default so a non-bridged determinism
307 // regression stays loud. Opting into tolerance is an explicit act.
308 const log = storedLog([
309 textChunk('m1', 'a'),
310 bridgedChunk('code_mode:console'),
311 ])
312 await expect(
313 collectChunks(
314 alignToStoredLog(fromChunks([textChunk('m1', 'a')]), {
315 durability: log,
316 }),
317 ),
318 ).rejects.toThrow(/shorter than the stored log/)
319 })
320
321 it('skips a stored out-of-band chunk and keeps aligning after it', async () => {
322 const log = storedLog([
323 textChunk('m1', 'a'),
324 bridgedChunk('code_mode:console'),
325 textChunk('m1', 'b'),
326 ])
327 const out = await collectChunks(
328 alignToStoredLog(
329 fromChunks([
330 textChunk('m1', 'a'),
331 textChunk('m1', 'b'),
332 textChunk('m1', 'c'),
333 ]),
334 { durability: log, isOutOfBand: isBridgeCustomChunk },
335 ),
336 )
337 // Both stored translated chunks suppressed, the bridged one skipped, and
338 // only the genuinely-new chunk forwarded.
339 expect(out).toEqual([textChunk('m1', 'c')])
340 })
341
342 it('tolerates several consecutive out-of-band chunks', async () => {
343 const log = storedLog([
344 textChunk('m1', 'a'),
345 bridgedChunk('one'),
346 bridgedChunk('two'),
347 bridgedChunk('three'),
348 textChunk('m1', 'b'),
349 ])
350 const out = await collectChunks(
351 alignToStoredLog(
352 fromChunks([textChunk('m1', 'a'), textChunk('m1', 'b')]),
353 {
354 durability: log,
355 isOutOfBand: isBridgeCustomChunk,
356 },
357 ),
358 )
359 expect(out).toEqual([])
360 })
361
362 it('tolerates TRAILING out-of-band chunks with no replay counterpart', async () => {
363 // A bridged tool's last console line lands after the final translated chunk.
364 const log = storedLog([textChunk('m1', 'a'), bridgedChunk('last')])
365 const out = await collectChunks(
366 alignToStoredLog(fromChunks([textChunk('m1', 'a')]), {
367 durability: log,
368 isOutOfBand: isBridgeCustomChunk,
369 }),
370 )
371 expect(out).toEqual([])
372 })
373
374 it('still throws on a real divergence, even with tolerance enabled', async () => {
375 // A changed messageId is a determinism bug, not an out-of-band chunk, and
376 // must not be absorbed by the skip.
377 const log = storedLog([textChunk('m1', 'a')])
378 await expect(
379 collectChunks(
380 alignToStoredLog(fromChunks([textChunk('m2', 'a')]), {
381 durability: log,
382 isOutOfBand: isBridgeCustomChunk,
383 }),
384 ),
385 ).rejects.toBeInstanceOf(JournalReplayDivergedError)
386 })
387
388 it('throws once consecutive skips exceed maxOutOfBandSkip', async () => {
389 const log = storedLog([
390 ...Array.from({ length: 5 }, (_, i) => bridgedChunk(`n${i}`)),
391 textChunk('m1', 'a'),
392 ])
393 await expect(
394 collectChunks(
395 alignToStoredLog(fromChunks([textChunk('m1', 'a')]), {
396 durability: log,
397 isOutOfBand: isBridgeCustomChunk,
398 maxOutOfBandSkip: 3,
399 }),
400 ),
401 ).rejects.toBeInstanceOf(JournalReplayDivergedError)
402 })
403
404 it('resets the skip counter after a match, so a long run is not starved', async () => {
405 // 3 skips, a match, 3 more skips: fine at a bound of 3. A counter that never
406 // reset would reject this.
407 const log = storedLog([
408 bridgedChunk('a1'),
409 bridgedChunk('a2'),
410 bridgedChunk('a3'),
411 textChunk('m1', 'a'),
412 bridgedChunk('b1'),
413 bridgedChunk('b2'),
414 bridgedChunk('b3'),
415 textChunk('m1', 'b'),
416 ])
417 const out = await collectChunks(
418 alignToStoredLog(
419 fromChunks([textChunk('m1', 'a'), textChunk('m1', 'b')]),
420 {
421 durability: log,
422 isOutOfBand: isBridgeCustomChunk,
423 maxOutOfBandSkip: 3,
424 },
425 ),
426 )
427 expect(out).toEqual([])
428 })
429
430 it('defaults the bound to 64', () => {
431 expect(DEFAULT_MAX_OUT_OF_BAND_SKIP).toBe(64)
432 })
433})
434
435describe('isBridgeCustomChunk', () => {
436 it('matches a CUSTOM chunk and nothing else', () => {
437 expect(isBridgeCustomChunk(bridgedChunk('x'))).toBe(true)
438 expect(isBridgeCustomChunk(textChunk('m', 'd'))).toBe(false)
439 expect(
440 isBridgeCustomChunk({
441 type: EventType.RUN_STARTED,
442 runId: 'r1',
443 threadId: 't1',
444 timestamp: 1,
445 }),
446 ).toBe(false)
447 })
448})
449
450/**
451 * A `threadId`-only mismatch is a CONFIG mistake (the attach route did not pass
452 * the run record's `threadId`, so the adapter's `options.threadId ??
453 * this.generateId()` minted a new one), not a determinism regression. The two
454 * must not be collapsed: reporting a real divergence as a config mistake would
455 * send a reader to the wrong place just as surely as the reverse.
456 */
457function runStarted(runId: string, threadId: string): StreamChunk {
458 return { type: EventType.RUN_STARTED, runId, threadId, timestamp: 1 }
459}
460
461describe('alignToStoredLog: threadId-only divergence', () => {
462 it('reports a threadId-only mismatch as JournalReplayThreadIdMismatchError', async () => {
463 const durability = memoryStream(producerRequest('align-thread-only'))
464 await durability.append([runStarted('r1', 't-stored')])
465
466 // Identical in every other field — exactly what a takeover that forgot to
467 // pass `threadId` produces on its very first chunk.
468 const replay = fromChunks([runStarted('r1', 't-generated')])
469 const caught = await collectChunks(
470 alignToStoredLog(replay, { durability }),
471 ).then(
472 () => null,
473 (error: unknown) => error,
474 )
475 expect(caught).toBeInstanceOf(JournalReplayThreadIdMismatchError)
476 if (!(caught instanceof JournalReplayThreadIdMismatchError)) return
477 expect(caught.index).toBe(0)
478 expect(caught.storedThreadId).toBe('t-stored')
479 expect(caught.replayedThreadId).toBe('t-generated')
480 expect(caught.message).toContain('ONLY by threadId')
481 expect(caught.message).toContain('did NOT behave differently')
482 expect(caught.message).toContain('RunRecord.threadId')
483 })
484
485 it('stays a JournalReplayDivergedError, so existing consumers keep branching', async () => {
486 const durability = memoryStream(producerRequest('align-thread-subclass'))
487 await durability.append([runStarted('r1', 't-a')])
488 const replay = fromChunks([runStarted('r1', 't-b')])
489 await expect(
490 collectChunks(alignToStoredLog(replay, { durability })),
491 ).rejects.toBeInstanceOf(JournalReplayDivergedError)
492 })
493
494 it('reports a GENUINE content divergence as the general error, not a threadId hint', async () => {
495 const durability = memoryStream(producerRequest('align-thread-content'))
496 await durability.append([textChunk('m1', 'a')])
497 // Same threadId (absent on both), different delta: a real divergence.
498 const replay = fromChunks([textChunk('m1', 'X')])
499 const caught = await collectChunks(
500 alignToStoredLog(replay, { durability }),
501 ).then(
502 () => null,
503 (error: unknown) => error,
504 )
505 expect(caught).toBeInstanceOf(JournalReplayDivergedError)
506 expect(caught).not.toBeInstanceOf(JournalReplayThreadIdMismatchError)
507 if (!(caught instanceof JournalReplayDivergedError)) return
508 expect(caught.name).toBe('JournalReplayDivergedError')
509 expect(caught.message).not.toContain('threadId')
510 })
511
512 it('does NOT blame threadId when the threadId matches but content differs', async () => {
513 const durability = memoryStream(producerRequest('align-thread-same-id'))
514 await durability.append([runStarted('r1', 't-same')])
515 // Same threadId, different runId — a real divergence that happens to be on
516 // a chunk type that carries a threadId at all.
517 const replay = fromChunks([runStarted('r2', 't-same')])
518 const caught = await collectChunks(
519 alignToStoredLog(replay, { durability }),
520 ).then(
521 () => null,
522 (error: unknown) => error,
523 )
524 expect(caught).not.toBeInstanceOf(JournalReplayThreadIdMismatchError)
525 expect(caught).toBeInstanceOf(JournalReplayDivergedError)
526 })
527
528 it('does NOT blame threadId when BOTH the threadId and other fields moved', async () => {
529 // The whole point of the second, threadId-excluded comparison: a run that
530 // both diverged AND changed its threadId is still a determinism bug, and
531 // reporting it as a config mistake would hide that.
532 const durability = memoryStream(producerRequest('align-thread-and-content'))
533 await durability.append([runStarted('r1', 't-a')])
534 const replay = fromChunks([runStarted('r2', 't-b')])
535 const caught = await collectChunks(
536 alignToStoredLog(replay, { durability }),
537 ).then(
538 () => null,
539 (error: unknown) => error,
540 )
541 expect(caught).not.toBeInstanceOf(JournalReplayThreadIdMismatchError)
542 expect(caught).toBeInstanceOf(JournalReplayDivergedError)
543 })
544})
545
546describe('chunkFingerprintIgnoringThreadId', () => {
547 it('erases a top-level threadId difference and nothing else', () => {
548 expect(chunkFingerprintIgnoringThreadId(runStarted('r1', 't-a'))).toBe(
549 chunkFingerprintIgnoringThreadId(runStarted('r1', 't-b')),
550 )
551 expect(chunkFingerprint(runStarted('r1', 't-a'))).not.toBe(
552 chunkFingerprint(runStarted('r1', 't-b')),
553 )
554 expect(chunkFingerprintIgnoringThreadId(runStarted('r1', 't'))).not.toBe(
555 chunkFingerprintIgnoringThreadId(runStarted('r2', 't')),
556 )
557 })
558
559 it('keeps a NESTED threadId, which is content rather than routing metadata', () => {
560 const nested = (value: string): StreamChunk => ({
561 type: EventType.CUSTOM,
562 name: 'x',
563 value: { threadId: value },
564 metadata: { tanstack: { threadId: 't-outer' } },
565 timestamp: 1,
566 })
567 expect(chunkFingerprintIgnoringThreadId(nested('a'))).not.toBe(
568 chunkFingerprintIgnoringThreadId(nested('b')),
569 )
570 })
571})
572
573describe('chunkThreadId', () => {
574 it('reads a chunk threadId and answers undefined when there is none', () => {
575 expect(chunkThreadId(runStarted('r1', 't-1'))).toBe('t-1')
576 expect(chunkThreadId(textChunk('m1', 'a'))).toBeUndefined()
577 })
578})