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

durable-takeover.spec.ts

1,238 lines48.8 KB

1import { expect, test } from '@playwright/test'
2​
3/**
4 * Durable, detachable sandboxed runs over real HTTP.
5 *
6 * The five behaviors this phase added, each pinned here:
7 *
8 * 1. A takeover resumes a detached run and delivers the remainder with the
9 * delivered prefix suppressed — the log holds each chunk exactly once. Pinned
10 * both from a seeded precondition and from a REAL disconnect.
11 * 2. A plain disconnect does NOT terminalize the run: the record stays
12 * `'running'` with no `finishedAt` and no `error`, and gains `detachedSince`
13 * + `sandboxKey`.
14 * 3. An explicit cancel DOES tear down — in either band — destroying the
15 * sandbox and writing a terminal `'aborted'`.
16 * 4. Cancel and disconnect are distinguished even though the connection close is
17 * byte-identical.
18 * 5. A superseded driver corrupts nothing: it writes NOTHING to the log (not
19 * even an error chunk) and cannot mark the record terminal, while the winner
20 * completes normally.
21 * 6. The reaper handles the case every other test here leaves hanging — nobody
22 * ever comes back: it finalizes a run that reached its sentinel while
23 * detached (which is the only way that transcript is ever saved), expires one
24 * past its TTL, and leaves a still-producing one completely untouched.
25 * 7. A replay that stopped being deterministic fails the attach LOUDLY instead of
26 * delivering the prefix twice.
27 *
28 * Harness: `/api/durable-takeover`. Provider-free (no LLM), so it is exempt from
29 * the aimock policy like the other durability harness routes. The agent's
30 * journal advances only on an explicit `?action=tick`, so every disconnect
31 * happens at a known point in the stream — no timers, no sleeps.
32 *
33 * Every test mints its own `runId`, because shared run state has produced false
34 * passes on this feature before, and every wait is explicitly bounded: an attach
35 * against a run with no journal used to hang forever, and a hung test stalls CI
36 * instead of failing it.
37 */
38​
39/**
40 * Generous per-test budget, deliberately larger than every wait inside these
41 * tests. These specs share one dev server with the rest of the suite, and under
42 * full parallel load a correct run can be slow; each wait below has its own
43 * explicit, shorter deadline with a message that says what it was waiting for,
44 * so a real failure still reports itself instead of being cut off by the runner.
45 */
46test.beforeEach(() => {
47 test.setTimeout(60_000)
48})
49​
50const ROUTE = '/api/durable-takeover'
51​
52interface SseEvent {
53 id: string
54 data: Record<string, unknown>
56​
57interface RunRecordBody {
58 runId: string
59 threadId: string
60 status: string
61 startedAt: number
62 finishedAt?: number
63 error?: unknown
64 detachedSince?: number
65 sandboxKey?: string
66 cancelRequested?: boolean
67 driverEpoch?: number
69​
70interface StateBody {
71 record: RunRecordBody | null
72 attachDrives: number
73 attachChunks: number
74 attachDriveEnds: number
75 sandboxDestroyed: boolean
76 journal: {
77 lines: number
78 total: number
79 done: boolean
80 killed: boolean
81 } | null
82 /** Whether this run's journal file still exists in its sandbox. */
83 journalFile: boolean
84 /** The transcript `withPersistence.onFinish` saved for this run's thread. */
85 messages: Array<{ role: string; text: string }>
86 log: Array<{ type: string; delta?: string; message?: string }>
88​
89/** One run's line in a sweep summary (`ReapRunEntry`). */
90interface ReapEntry {
91 runId: string
92 outcome: string
93 status?: string
94 exitCode?: number
95 terminalizedAnyway?: boolean
97​
98interface ReapSummary {
99 considered: number
100 probed: number
101 outcomes: Record<string, number>
102 runs: Array<ReapEntry>
104​
105interface PruneSummary {
106 listed: number
107 runIds: number
108 deleted: Array<string>
109 kept: Array<{ runId?: string; names: Array<string>; reason: string }>
110 ageGate: string
111 failures: Array<unknown>
113​
114interface ReapBody {
115 reap: ReapSummary
116 prune: Array<{ sandboxKey: string; result: PruneSummary }>
118​
119/**
120 * The detached-run TTL, in milliseconds. The route passes this same value to
121 * `reapDetachedRuns` as `detachedRunTtlMs` — its only consumer, and the only
122 * place a TTL is read at all — so this is the cutoff the boundary cases below
123 * are constructed against. It is deliberately NOT also handed to `withSandbox`:
124 * that option does not exist, so a copy there would be inert.
125 */
126const DETACHED_RUN_TTL_MS = 5 * 60 * 1000
127​
128function baseUrl(): string {
129 const url = test.info().project.use.baseURL
130 if (typeof url !== 'string') {
131 throw new Error('durable-takeover: no baseURL configured for this project')
132 }
133 return url
135​
136function routeUrl(params: Record<string, string>): string {
137 const url = new URL(ROUTE, baseUrl())
138 for (const [key, value] of Object.entries(params)) {
139 url.searchParams.set(key, value)
140 }
141 return url.toString()
143​
144function uniqueRunId(label: string): string {
145 return `${label}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
147​
148/** Parse whole SSE blocks out of a decoded buffer, returning the remainder. */
149function drainBlocks(buffer: string): {
150 events: Array<SseEvent>
151 rest: string
152} {
153 const events: Array<SseEvent> = []
154 let rest = buffer
155 for (;;) {
156 const boundary = rest.indexOf('\n\n')
157 if (boundary === -1) break
158 const block = rest.slice(0, boundary)
159 rest = rest.slice(boundary + 2)
160 if (block.trim().length === 0) continue
161 const lines = block.split('\n')
162 const idLine = lines.find((line) => line.startsWith('id:'))
163 const dataLine = lines.find((line) => line.startsWith('data:'))
164 if (!dataLine) continue
165 const raw = dataLine.slice(dataLine.indexOf(':') + 1).trim()
166 const parsed: unknown = JSON.parse(raw)
167 if (typeof parsed !== 'object' || parsed === null) continue
168 events.push({
169 id: idLine ? idLine.slice(idLine.indexOf(':') + 1).trim() : '',
170 data: { ...parsed },
171 })
172 }
173 return { events, rest }
175​
176function eventType(event: SseEvent): string {
177 const type = event.data.type
178 return typeof type === 'string' ? type : '<untyped>'
180​
181function contentDeltas(events: Array<SseEvent>): Array<string> {
182 return events
183 .filter((event) => eventType(event) === 'TEXT_MESSAGE_CONTENT')
184 .map((event) => {
185 const delta = event.data.delta
186 return typeof delta === 'string' ? delta : ''
187 })
189​
190/**
191 * A live SSE reader over `fetch`, so a test can disconnect at a chosen point in
192 * the stream — which Playwright's `request` fixture cannot express.
193 *
194 * Every wait is bounded and every failure names what it was waiting for.
195 */
196class SseStream {
197 private buffer = ''
198 private readonly received: Array<SseEvent> = []
199 private reader: ReadableStreamDefaultReader<Uint8Array> | undefined =
200 undefined
201 private readonly decoder = new TextDecoder()
202 private ended = false
203​
204 private constructor(
205 response: Response,
206 private readonly controller: AbortController,
207 ) {
208 const body = response.body
209 if (!body) throw new Error('durable-takeover: response had no body')
210 this.reader = body.getReader()
211 }
212​
213 static async open(url: string, init: RequestInit = {}): Promise<SseStream> {
214 const controller = new AbortController()
215 const response = await fetch(url, {
216 method: 'POST',
217 ...init,
218 signal: controller.signal,
219 })
220 if (!response.ok) {
221 throw new Error(
222 `durable-takeover: ${url} responded ${response.status} ${await response.text()}`,
223 )
224 }
225 return new SseStream(response, controller)
226 }
227​
228 /** Read until `count` events have arrived, or fail after `timeoutMs`. */
229 async take(count: number, timeoutMs = 15_000): Promise<Array<SseEvent>> {
230 const deadline = Date.now() + timeoutMs
231 while (this.received.length < count && !this.ended) {
232 const remaining = deadline - Date.now()
233 if (remaining <= 0) {
234 throw new Error(
235 `durable-takeover: timed out after ${timeoutMs}ms waiting for ${count} SSE events; got ${this.received.length} (${this.received.map(eventType).join(', ')})`,
236 )
237 }
238 await this.pump(remaining)
239 }
240 if (this.received.length < count) {
241 throw new Error(
242 `durable-takeover: stream ended with ${this.received.length}/${count} events (${this.received.map(eventType).join(', ')})`,
243 )
244 }
245 return this.received.slice(0, count)
246 }
247​
248 /** Read until the stream ends, or fail after `timeoutMs`. */
249 async drain(timeoutMs = 20_000): Promise<Array<SseEvent>> {
250 const deadline = Date.now() + timeoutMs
251 while (!this.ended) {
252 const remaining = deadline - Date.now()
253 if (remaining <= 0) {
254 throw new Error(
255 `durable-takeover: timed out after ${timeoutMs}ms draining the stream; got ${this.received.length} events (${this.received.map(eventType).join(', ')})`,
256 )
257 }
258 await this.pump(remaining)
259 }
260 return this.received.slice()
261 }
262​
263 private async pump(timeoutMs: number): Promise<void> {
264 const reader = this.reader
265 if (!reader) {
266 this.ended = true
267 return
268 }
269 let timer: ReturnType<typeof setTimeout> | undefined
270 const timeout = new Promise<'timeout'>((resolve) => {
271 timer = setTimeout(() => resolve('timeout'), timeoutMs)
272 })
273 try {
274 const step = await Promise.race([reader.read(), timeout])
275 if (step === 'timeout') return
276 if (step.done) {
277 this.ended = true
278 return
279 }
280 this.buffer += this.decoder.decode(step.value, { stream: true })
281 const { events, rest } = drainBlocks(this.buffer)
282 this.buffer = rest
283 this.received.push(...events)
284 } finally {
285 if (timer !== undefined) clearTimeout(timer)
286 }
287 }
288​
289 /** Stop reading and release the socket. Not a server-observable disconnect. */
290 close(): void {
291 this.controller.abort()
292 this.reader = undefined
293 this.ended = true
294 }
296​
297/**
298 * The client disconnect.
299 *
300 * Injected server-side rather than produced by closing the test's own socket:
301 * a `fetch` abort does not propagate to the server through this app's dev
302 * server (verified — the run keeps producing and `withSandbox.onAbort` never
303 * runs), so a test cannot observe a real socket close from here. `?action=drop`
304 * aborts the run's own `AbortController` with NO reason, which is exactly what
305 * the transport does when the socket goes away, and the absence of a reason is
306 * the entire difference from a cancel. See `dropResponse` in the harness route.
307 */
308async function drop(runId: string, stream?: SseStream): Promise<void> {
309 const response = await fetch(routeUrl({ action: 'drop', runId }), {
310 method: 'POST',
311 })
312 expect(response.ok, 'drop should succeed').toBe(true)
313 const body: unknown = await response.json()
314 expect(
315 typeof body === 'object' &&
316 body !== null &&
317 Reflect.get(body, 'dropped') === true,
318 'drop should have found a live run to disconnect',
319 ).toBe(true)
320 stream?.close()
322​
323async function tick(runId: string, n = 1): Promise<void> {
324 const response = await fetch(
325 routeUrl({ action: 'tick', runId, n: String(n) }),
326 {
327 method: 'POST',
328 },
329 )
330 expect(response.ok, 'tick should succeed').toBe(true)
331 await response.json()
333​
334/**
335 * Construct the detached precondition, and answer with the sandbox key it was
336 * built under so a spec can address that sandbox's journal-sweep summary.
337 *
338 * `detachedSince` is injectable because the reaper's TTL boundary is
339 * `detachedSince <= now - ttl` and `?action=reap` injects `now`: with both sides
340 * supplied, "past the TTL" and "one millisecond inside it" are exact, with no
341 * fake clock and no dependence on how long a request took.
342 */
343async function seed(params: {
344 runId: string
345 threadId?: string
346 total?: number
347 lines?: number
348 detachedSince?: number
349}): Promise<string> {
350 const response = await fetch(
351 routeUrl({
352 action: 'seed',
353 runId: params.runId,
354 ...(params.threadId === undefined ? {} : { threadId: params.threadId }),
355 total: String(params.total ?? 6),
356 lines: String(params.lines ?? 2),
357 ...(params.detachedSince === undefined
358 ? {}
359 : { detachedSince: String(params.detachedSince) }),
360 }),
361 { method: 'POST' },
362 )
363 expect(response.ok, 'seed should succeed').toBe(true)
364 const body: unknown = await response.json()
365 const sandboxKey =
366 typeof body === 'object' && body !== null
367 ? Reflect.get(body, 'sandboxKey')
368 : undefined
369 if (typeof sandboxKey !== 'string') {
370 throw new Error('durable-takeover: seed did not answer with a sandboxKey')
371 }
372 return sandboxKey
374​
375/**
376 * Run ONE reaper sweep over exactly the runIds named, then the journal sweep.
377 *
378 * Several runIds in one call on purpose: every case below asserts both that the
379 * reaper acted on the run it should AND that it left a specifically-constructed
380 * run alone, and asserting both against the SAME sweep is what makes the second
381 * half mean something — a sweep that considered nothing satisfies every
382 * "untouched" assertion on its own.
383 */
384async function reap(params: {
385 runIds: Array<string>
386 now: number
387 runBudgetMs?: number
388}): Promise<ReapBody> {
389 const url = new URL(ROUTE, baseUrl())
390 url.searchParams.set('action', 'reap')
391 for (const runId of params.runIds) url.searchParams.append('runId', runId)
392 url.searchParams.set('now', String(params.now))
393 if (params.runBudgetMs !== undefined) {
394 url.searchParams.set('runBudgetMs', String(params.runBudgetMs))
395 }
396 const response = await fetch(url.toString(), { method: 'POST' })
397 expect(response.ok, `reap should succeed (${response.status})`).toBe(true)
398 const body: unknown = await response.json()
399 if (typeof body !== 'object' || body === null) {
400 throw new Error('durable-takeover: reap response was not an object')
401 }
402 return body as ReapBody
404​
405/** The sweep's line for one run, so a missing entry fails loudly. */
406function reapEntry(body: ReapBody, runId: string): ReapEntry {
407 const entry = body.reap.runs.find((candidate) => candidate.runId === runId)
408 if (entry === undefined) {
409 throw new Error(
410 `durable-takeover: the sweep has no entry for ${runId}; summary ${JSON.stringify(body.reap)}`,
411 )
412 }
413 return entry
415​
416/** The journal-sweep summary for one sandbox. */
417function pruneFor(body: ReapBody, sandboxKey: string): PruneSummary {
418 const entry = body.prune.find(
419 (candidate) => candidate.sandboxKey === sandboxKey,
420 )
421 if (entry === undefined) {
422 throw new Error(
423 `durable-takeover: no journal sweep for sandbox ${sandboxKey}; got ${body.prune.map((p) => p.sandboxKey).join(', ')}`,
424 )
425 }
426 return entry.result
428​
429async function cancel(
430 runId: string,
431 band: 'both' | 'durable' | 'inprocess',
432): Promise<void> {
433 const response = await fetch(routeUrl({ action: 'cancel', runId, band }), {
434 method: 'POST',
435 })
436 expect(response.status, 'cancel should be 204').toBe(204)
438​
439async function state(runId: string): Promise<StateBody> {
440 const response = await fetch(routeUrl({ action: 'state', runId }))
441 expect(response.ok, 'state should succeed').toBe(true)
442 const body: unknown = await response.json()
443 if (typeof body !== 'object' || body === null) {
444 throw new Error('durable-takeover: state response was not an object')
445 }
446 return body as StateBody
448​
449/** Poll `state` until `predicate` holds, with an explicit bound. */
450async function stateUntil(
451 runId: string,
452 what: string,
453 predicate: (body: StateBody) => boolean,
454 timeoutMs = 15_000,
455): Promise<StateBody> {
456 const deadline = Date.now() + timeoutMs
457 let last: StateBody | undefined
458 for (;;) {
459 last = await state(runId)
460 if (predicate(last)) return last
461 if (Date.now() > deadline) {
462 throw new Error(
463 `durable-takeover: timed out after ${timeoutMs}ms waiting for ${what}; last state ${JSON.stringify(last)}`,
464 )
465 }
466 await new Promise((resolve) => setTimeout(resolve, 100))
467 }
469​
470/** The full, correct chunk sequence for a six-line run. */
471const FULL_SEQUENCE = [
472 'RUN_STARTED',
473 'TEXT_MESSAGE_START',
474 'TEXT_MESSAGE_CONTENT',
475 'TEXT_MESSAGE_CONTENT',
476 'TEXT_MESSAGE_CONTENT',
477 'TEXT_MESSAGE_CONTENT',
478 'TEXT_MESSAGE_CONTENT',
479 'TEXT_MESSAGE_CONTENT',
480 'TEXT_MESSAGE_END',
481 'RUN_FINISHED',
483​
484/** The full, correct chunk sequence for a TWO-line run. */
485const TWO_LINE_SEQUENCE = [
486 'RUN_STARTED',
487 'TEXT_MESSAGE_START',
488 'TEXT_MESSAGE_CONTENT',
489 'TEXT_MESSAGE_CONTENT',
490 'TEXT_MESSAGE_END',
491 'RUN_FINISHED',
493​
494/** What a previous host had already delivered when it went away: two lines. */
495const DELIVERED_PREFIX = [
496 'RUN_STARTED',
497 'TEXT_MESSAGE_START',
498 'TEXT_MESSAGE_CONTENT',
499 'TEXT_MESSAGE_CONTENT',
501​
502/**
503 * The leave-alone half of a sweep, asserted as one whole.
504 *
505 * Every field here is one the reaper could have moved and must not have:
506 * `pipeToRunLog` is total, so entering it AT ALL writes a terminal status, closes
507 * the log and — on the expiry path — records a cancel. `detachedSince` is the
508 * sharpest of them: it is both this run's TTL evidence and the field the next
509 * sweep selects on, so a sweep that refreshed or cleared it would make the run
510 * either immortal or invisible, and neither shows up in a status assertion.
511 */
512function expectUntouched(before: StateBody, after: StateBody): void {
513 expect(after.record?.status, 'an untouched run stays running').toBe('running')
514 expect(after.record?.cancelRequested).toBeUndefined()
515 expect(after.record?.finishedAt).toBeUndefined()
516 expect(after.record?.error).toBeUndefined()
517 expect(
518 after.record?.detachedSince,
519 'detachedSince must be the very same instant, not a refreshed one',
520 ).toBe(before.record?.detachedSince)
521 // Not even the claim was taken: the leave-alone path returns before
522 // `withRunClaim`, so the epoch cannot have moved.
523 expect(after.record?.driverEpoch).toBe(before.record?.driverEpoch)
524 // Nothing appended and nothing closed.
525 expect(after.log.map((entry) => entry.type)).toEqual(
526 before.log.map((entry) => entry.type),
527 )
528 expect(after.log.map((entry) => entry.delta)).toEqual(
529 before.log.map((entry) => entry.delta),
530 )
531 // No transcript was saved: `withPersistence.onFinish` never ran.
532 expect(after.messages).toEqual([])
533 // The agent is still alive in a sandbox that is still up.
534 expect(after.sandboxDestroyed).toBe(false)
535 expect(after.journal?.killed).toBe(false)
536 expect(after.journal?.lines).toBe(before.journal?.lines)
537 // And its journal — the only copy of the bytes a successor would replay — is
538 // still on disk.
539 expect(after.journalFile).toBe(true)
541​
542/**
543 * What the sweep reports for a run it expired while its agent was STILL WORKING.
544 *
545 * `'expired'`, which is what the TTL path is FOR. It read `'budget-exceeded'`
546 * while two defects stacked. Nothing polls `RunRecord.cancelRequested` to abort a
547 * live drive — `wasCancelRequested` has exactly one reader, `withSandbox`'s
548 * `onAbort`, which runs only once something else has already aborted — so
549 * `ReapOptions.runBudgetMs` is the only thing that ends this drive; and `reap.ts`
550 * used to label ANY budget expiry the anomaly it only is on the finalization path,
551 * where the probe already said the agent was done. On the expiry path the budget is
552 * the designed stop, so `'expired'` is now reported and the anomaly is reserved for
553 * the case that really is one.
554 */
555const EXPIRED_LIVE_OUTCOME = 'expired'
556​
557/**
558 * The acted-on half of an expiry: the run is terminal, the sandbox is gone, and
559 * nothing was invented about what the agent produced.
560 *
561 * The terminal STATUS is `'aborted'`, pinned exactly. It used to be `'completed'`
562 * — `pipeToRunLog` checked its abort signal only per chunk, so a signal-aware
563 * producer that ended its stream made the loop exit normally and the success path
564 * ran — which meant a run the reaper had force-expired, and whose sandbox it had
565 * just destroyed, was recorded as having completed successfully. `not.toBe(
566 * 'running')` is the assertion that let that through: `'completed'` is terminal
567 * too. The two facts below are the other half of the same guard, against the
568 * danger in terminalizing a live run at all: no synthesized chunk in the log, and
569 * no invented assistant turn in the transcript.
570 */
571async function expectExpiredAndTornDown(runId: string): Promise<StateBody> {
572 const after = await stateUntil(
573 runId,
574 'the expired run to reach a terminal status',
575 (body) => body.record?.finishedAt !== undefined,
576 )
577 // Recorded BEFORE the drive, which is what makes the teardown an explicit
578 // cancel that DESTROYS the sandbox rather than a second detach that re-arms
579 // `detachedSince` and leaves the run to be swept forever.
580 expect(after.record?.cancelRequested).toBe(true)
581 // The agent was mid-sentence when the reaper stopped it. Anything but
582 // `'aborted'` here is a transcript that claims something that did not happen.
583 expect(after.record?.status).toBe('aborted')
584 expect(typeof after.record?.finishedAt).toBe('number')
585 // The cost leak is closed: the agent cannot keep burning tokens in a sandbox
586 // nobody is reading.
587 expect(after.sandboxDestroyed).toBe(true)
588 expect(after.journal?.killed).toBe(true)
589 // The log holds what was really delivered and nothing else — no synthetic
590 // terminal, no error chunk.
591 expect(after.log.map((entry) => entry.type)).toEqual(DELIVERED_PREFIX)
592 expect(after.log.filter((entry) => entry.type === 'RUN_ERROR')).toEqual([])
593 // And no assistant turn was invented for output the agent never finished.
594 expect(
595 after.messages.filter((message) => message.role === 'assistant'),
596 ).toEqual([])
597 return after
599​
600// ---------------------------------------------------------------------------
601// 1. Takeover
602// ---------------------------------------------------------------------------
603​
604test.describe('durable runs — takeover', () => {
605 test('an attach takes the detached run over and delivers the remainder exactly once', async () => {
606 const runId = uniqueRunId('takeover')
607 // The takeover precondition: a running record, a detached marker, an agent
608 // that has written 2 of 6 lines, and an OPEN log holding the 4 chunks a
609 // previous host already delivered.
610 await seed({ runId, total: 6, lines: 2 })
611​
612 const attach = await SseStream.open(routeUrl({ runId, offset: '-1' }), {
613 method: 'GET',
614 })
615​
616 // The replayed prefix arrives first, from the log.
617 const prefix = await attach.take(4)
618 expect(prefix.map(eventType)).toEqual([
619 'RUN_STARTED',
620 'TEXT_MESSAGE_START',
621 'TEXT_MESSAGE_CONTENT',
622 'TEXT_MESSAGE_CONTENT',
623 ])
624 expect(contentDeltas(prefix)).toEqual(['1', '2'])
625​
626 // The driver has claimed the run and is tailing the journal. Let the agent
627 // finish; the remaining four lines must arrive on THIS connection.
628 await stateUntil(
629 runId,
630 'the takeover to claim the run (driverEpoch)',
631 (body) => (body.record?.driverEpoch ?? 0) >= 1,
632 )
633 await tick(runId, 4)
634​
635 const delivered = await attach.drain()
636​
637 // THE assertion: the delivered sequence is exactly the run's chunk sequence.
638 // A takeover that replayed the journal without aligning would deliver
639 // '1','2','1','2','3'… and the user would see the prefix twice.
640 expect(delivered.map(eventType)).toEqual(FULL_SEQUENCE)
641 expect(contentDeltas(delivered)).toEqual(['1', '2', '3', '4', '5', '6'])
642 // Offsets are opaque, but each event must carry its own — no reuse.
643 const offsets = delivered.map((event) => event.id)
644 expect(new Set(offsets).size).toBe(offsets.length)
645​
646 // The record: the detached clock stopped and the run completed for real.
647 const after = await stateUntil(
648 runId,
649 'the taken-over run to reach a terminal status',
650 (body) => body.record?.status === 'completed',
651 )
652 expect(after.record?.detachedSince).toBeUndefined()
653 expect(after.record?.error).toBeUndefined()
654 // The log itself holds each chunk once — nothing was appended twice.
655 expect(after.log.map((entry) => entry.type)).toEqual(FULL_SEQUENCE)
656 })
657​
658 /**
659 * The disconnect→takeover path end to end, which is what the docs promise:
660 * a run streaming mid-flight, the tab goes away, the stream continues.
661 *
662 * This case was `test.fail()` while core's durable delivery sink terminalized
663 * EVERY abort — it appended a synthetic `RUN_ERROR` ("Request aborted") and
664 * called `durability.close()` unconditionally, so a detached run's log ended at
665 * that error. A later attach's replay stopped at the prefix, and the stored
666 * `RUN_ERROR` was a chunk the journal replay could not reproduce, so
667 * `alignToStoredLog` diverged and `pipeToRunLog` recorded the healthy detached
668 * run as `'failed'`.
669 *
670 * The sink now consults the run's own detach verdict
671 * (`RunDetachedCapability`, published by `withSandbox`'s detach branch and
672 * carried to the transport on the stream itself), so a plain disconnect of a
673 * detachable run leaves the log OPEN. Both halves of the assertion below are
674 * load bearing: the remainder must arrive on the attach's socket, AND the
675 * record must not be `'failed'`.
676 */
677 test('a real disconnect, then an attach, continues the stream', async () => {
678 const runId = uniqueRunId('disconnect-takeover')
679 const run = await SseStream.open(routeUrl({ runId, total: '6' }))
680 await tick(runId, 2)
681 // Five events now lead with the run-accepted marker: CUSTOM, RUN_STARTED,
682 // TEXT_MESSAGE_START, '1', '2'.
683 const before = await run.take(5)
684 expect(contentDeltas(before)).toEqual(['1', '2'])
685 await drop(runId, run)
686​
687 await stateUntil(
688 runId,
689 'the run to be marked detached',
690 (body) => typeof body.record?.detachedSince === 'number',
691 )
692​
693 const attach = await SseStream.open(routeUrl({ runId, offset: '-1' }), {
694 method: 'GET',
695 })
696 await stateUntil(
697 runId,
698 'the takeover to claim the detached run (driverEpoch)',
699 (body) => (body.record?.driverEpoch ?? 0) >= 1,
700 )
701 await tick(runId, 4)
702 const delivered = await attach.drain()
703​
704 // The from-start attach replays the run-accepted marker the producer
705 // appended, then the full run.
706 expect(delivered.map(eventType)).toEqual(['CUSTOM', ...FULL_SEQUENCE])
707 expect(contentDeltas(delivered)).toEqual(['1', '2', '3', '4', '5', '6'])
708​
709 // The run completed for real — NOT recorded as failed by a diverged replay.
710 const after = await stateUntil(
711 runId,
712 'the taken-over run to reach a terminal status',
713 (body) => body.record?.status === 'completed',
714 )
715 expect(after.record?.status).not.toBe('failed')
716 expect(after.record?.error).toBeUndefined()
717 expect(after.record?.detachedSince).toBeUndefined()
718 // And the log holds each chunk exactly once (marker included), with no
719 // stored RUN_ERROR.
720 expect(after.log.map((entry) => entry.type)).toEqual([
721 'CUSTOM',
722 ...FULL_SEQUENCE,
723 ])
724 })
725})
726​
727// ---------------------------------------------------------------------------
728// 2. A plain disconnect is not a terminal event
729// ---------------------------------------------------------------------------
730​
731test.describe('durable runs — disconnect', () => {
732 test('a plain disconnect does not terminalize the run', async () => {
733 const runId = uniqueRunId('detach')
734 const run = await SseStream.open(routeUrl({ runId, total: '6' }))
735 await tick(runId, 2)
736 expect(contentDeltas(await run.take(5))).toEqual(['1', '2'])
737​
738 await drop(runId, run)
739​
740 const body = await stateUntil(
741 runId,
742 'the run to be marked detached',
743 (record) => typeof record.record?.detachedSince === 'number',
744 )
745 // withPersistence writes NOTHING on this branch: the run is still going.
746 expect(body.record?.status).toBe('running')
747 expect(body.record?.finishedAt).toBeUndefined()
748 expect(body.record?.error).toBeUndefined()
749 // withSandbox records the two facts a later attach and the reaper need.
750 expect(typeof body.record?.detachedSince).toBe('number')
751 expect(typeof body.record?.sandboxKey).toBe('string')
752 // And the sandbox is still up, so the agent keeps working.
753 expect(body.sandboxDestroyed).toBe(false)
754 expect(body.journal?.killed).toBe(false)
755​
756 // Proof the agent really did outlive the connection: it can still advance.
757 await tick(runId, 1)
758 const advanced = await state(runId)
759 expect(advanced.journal?.lines).toBe(3)
760 expect(advanced.journal?.killed).toBe(false)
761 })
762})
763​
764// ---------------------------------------------------------------------------
765// 3. An explicit cancel tears down — in either band
766// ---------------------------------------------------------------------------
767​
768test.describe('durable runs — cancel', () => {
769 for (const band of ['durable', 'inprocess'] as const) {
770 test(`an explicit cancel in the ${band} band destroys the sandbox and ends the run`, async () => {
771 const runId = uniqueRunId(`cancel-${band}`)
772 const run = await SseStream.open(routeUrl({ runId, total: '6' }))
773 await tick(runId, 2)
774 expect(contentDeltas(await run.take(5))).toEqual(['1', '2'])
775​
776 await cancel(runId, band)
777 if (band === 'durable') {
778 // The durable band records intent only — `requestRunCancel` deliberately
779 // writes no status. The teardown happens on the run's next teardown,
780 // which for a remote driver is its own disconnect, and here is this
781 // client going away.
782 await drop(runId, run)
783 } else {
784 // The in-process band already aborted the run's controller with
785 // RUN_CANCEL_REASON, so the teardown has begun; nothing else to do.
786 run.close()
787 }
788​
789 const body = await stateUntil(
790 runId,
791 'the cancelled run to reach a terminal status',
792 (record) => record.record?.status === 'aborted',
793 )
794 expect(body.record?.status).toBe('aborted')
795 expect(typeof body.record?.finishedAt).toBe('number')
796 // A cancel is not a detach: the sandbox goes, always.
797 expect(body.sandboxDestroyed).toBe(true)
798 expect(body.journal?.killed).toBe(true)
799 // The agent is dead, so the journal cannot advance any further.
800 const linesAtCancel = body.journal?.lines
801 await tick(runId, 2)
802 expect((await state(runId)).journal?.lines).toBe(linesAtCancel)
803 })
804 }
805​
806 // ------------------------------------------------------------------------
807 // 4. The two are distinguished, though the close is identical
808 // ------------------------------------------------------------------------
809​
810 test('cancel and disconnect diverge even though the connection close is identical', async () => {
811 // Two runs, the SAME client-side action on both — drop the connection. The
812 // only difference is that one had a cancel recorded out of band first.
813 const dropped = uniqueRunId('diverge-dropped')
814 const cancelled = uniqueRunId('diverge-cancelled')
815​
816 const droppedRun = await SseStream.open(routeUrl({ runId: dropped }))
817 const cancelledRun = await SseStream.open(routeUrl({ runId: cancelled }))
818 await tick(dropped, 2)
819 await tick(cancelled, 2)
820 await droppedRun.take(4)
821 await cancelledRun.take(4)
822​
823 // Out of band, and only for one of them.
824 await cancel(cancelled, 'durable')
825​
826 // Byte-identical connection close from here: the SAME plain abort, with no
827 // reason, on both runs.
828 await drop(dropped, droppedRun)
829 await drop(cancelled, cancelledRun)
830​
831 // Waits for each teardown to have SETTLED either way — detached or terminal —
832 // rather than for the outcome under test. Waiting for the expected outcome
833 // would turn a wrong verdict into a timeout; this way a wrong verdict lands
834 // on the divergence assertions below, which say what actually went wrong.
835 const settled = (body: StateBody): boolean =>
836 typeof body.record?.detachedSince === 'number' ||
837 body.record?.finishedAt !== undefined
838 const droppedState = await stateUntil(
839 dropped,
840 "the dropped run's teardown to settle",
841 settled,
842 )
843 const cancelledState = await stateUntil(
844 cancelled,
845 "the cancelled run's teardown to settle",
846 settled,
847 )
848​
849 // The divergence, asserted as a divergence and not as two isolated facts.
850 expect(droppedState.record?.status).toBe('running')
851 expect(cancelledState.record?.status).toBe('aborted')
852 expect(droppedState.record?.status).not.toBe(cancelledState.record?.status)
853 expect(droppedState.sandboxDestroyed).toBe(false)
854 expect(cancelledState.sandboxDestroyed).toBe(true)
855 expect(droppedState.journal?.killed).toBe(false)
856 expect(cancelledState.journal?.killed).toBe(true)
857 expect(droppedState.record?.finishedAt).toBeUndefined()
858 expect(typeof cancelledState.record?.finishedAt).toBe('number')
859 })
860})
861​
862// ---------------------------------------------------------------------------
863// 5. A superseded driver corrupts nothing
864// ---------------------------------------------------------------------------
865​
866test.describe('durable runs — single-writer fencing', () => {
867 test('a superseded driver writes nothing to the log and cannot mark the run terminal', async () => {
868 const runId = uniqueRunId('fence')
869 await seed({ runId, total: 6, lines: 2 })
870​
871 // `locks=permissive` models a lease-less lock so the two drives actually
872 // OVERLAP. `InMemoryLockStore` serializes them inside one process, which
873 // would make the fence unobservable (see the harness route's comment and
874 // `packages/ai-sandbox/src/claim.ts`).
875 const first = await SseStream.open(
876 routeUrl({ runId, offset: '-1', locks: 'permissive' }),
877 { method: 'GET' },
878 )
879 const loser = await stateUntil(
880 runId,
881 'the first driver to claim the run and replay the stored prefix',
882 // Four produced chunks means this driver is PAST `awaitLogQuiescence` and
883 // past `alignToStoredLog`'s one eager snapshot. That precondition is what
884 // makes this a test of the EPOCH fence (layer 2) specifically: superseded
885 // before the snapshot, the loser is stopped by quiescence (layer 3)
886 // instead, and the test would pass with the epoch fence removed —
887 // verified, so this wait is load bearing.
888 (body) => (body.record?.driverEpoch ?? 0) >= 1 && body.attachChunks >= 4,
889 )
890 expect(loser.record?.driverEpoch).toBe(1)
891​
892 // A second attach supersedes it. The journal has produced nothing new yet,
893 // so neither driver has appended: the loser's first append will come AFTER
894 // it has been superseded, which is the case being fenced.
895 const second = await SseStream.open(
896 routeUrl({ runId, offset: '-1', locks: 'permissive' }),
897 { method: 'GET' },
898 )
899 await stateUntil(
900 runId,
901 'the second driver to supersede the first',
902 (body) => (body.record?.driverEpoch ?? 0) >= 2,
903 )
904​
905 await tick(runId, 4)
906​
907 // Deliberately NOT asserted on the winner's socket: the loser's teardown
908 // calls `durability.close()`, which is UNFENCED on purpose (a fenced close
909 // would wedge the record at 'running' with every tailer parked forever), so
910 // a live reader can be terminalized early by the loser. The authoritative
911 // facts are the log and the record, and that is what is asserted.
912 await stateUntil(
913 runId,
914 'the winning driver to complete the run',
915 (record) => record.record?.status === 'completed',
916 )
917​
918 // Then LET THE LOSER FINISH, and wait for a FACT rather than a duration:
919 // both drives must have produced their full ten-chunk sequence. Asserting the
920 // instant the winner completes makes this test pass even with the fence
921 // removed, because the loser's refused writes are still in flight —
922 // verified: with `fenceDurability` stubbed out, the loser's duplicate
923 // '3','4','5','6' + terminal land AFTER the winner's completion. The point of
924 // the test is what the loser could NOT do, so it has to have tried first.
925 await stateUntil(
926 runId,
927 'both drivers to finish producing their remainder',
928 (record) => record.attachDriveEnds >= 2,
929 )
930 // A short settle after BOTH drives stopped producing, so any append the
931 // loser had in flight has landed before the log is judged.
932 await new Promise((resolve) => setTimeout(resolve, 500))
933 const body = await state(runId)
934​
935 // Two drivers really did drive, and both really did produce the remainder.
936 // Without this, "the log has no duplicates" is also satisfied by a second
937 // driver that never ran — a false pass.
938 expect(body.attachDrives).toBe(2)
939​
940 // The winner completed normally...
941 expect(body.record?.status).toBe('completed')
942 expect(body.record?.error).toBeUndefined()
943 // ...and the loser wrote NOTHING: no duplicated chunk, and no error chunk
944 // either. A fence on the log alone would leave a `RUN_ERROR` here; a fence
945 // on the record alone would leave duplicated deltas.
946 expect(body.log.map((entry) => entry.type)).toEqual(FULL_SEQUENCE)
947 expect(body.log.filter((entry) => entry.type === 'RUN_ERROR')).toEqual([])
948 expect(
949 body.log
950 .filter((entry) => entry.type === 'TEXT_MESSAGE_CONTENT')
951 .map((entry) => entry.delta),
952 ).toEqual(['1', '2', '3', '4', '5', '6'])
953​
954 first.close()
955 second.close()
956 })
957})
958​
959// ---------------------------------------------------------------------------
960// 6. The reaper: nobody came back
961// ---------------------------------------------------------------------------
962​
963/**
964 * A detached run whose viewer never returns is the case every other test here
965 * leaves hanging: the takeover tests all end with somebody attaching. Nothing in
966 * the library drives such a run — `reapDetachedRuns` is a plain function an
967 * application calls from a cron — so these cases call it over real HTTP and assert
968 * what it did to the store, the log, the saved transcript, the sandbox and the
969 * journal directory.
970 *
971 * EVERY case sweeps TWO runs in ONE pass and asserts both halves. That is not
972 * symmetry for its own sake: a sweep whose candidate list came back empty
973 * satisfies every "the reaper did not touch this run" assertion by doing nothing
974 * at all, so the acted-on half — plus `considered` — is what makes the untouched
975 * half evidence rather than decoration.
976 *
977 * `now` is injected on `?action=reap` and `detachedSince` on `?action=seed`, so
978 * both sides of the reaper's `detachedSince <= now - ttl` are supplied by the
979 * test. No fake clock, and no dependence on how long a request took.
980 */
981test.describe('durable runs — the reaper', () => {
982 test('finalizes a run that reached its sentinel while detached, and leaves a still-producing one alone', async () => {
983 const finished = uniqueRunId('reap-finalized')
984 const producing = uniqueRunId('reap-producing')
985 const now = Date.now()
986​
987 const finishedSandbox = await seed({
988 runId: finished,
989 total: 6,
990 lines: 2,
991 detachedSince: now,
992 })
993 // Same detached instant, same delivered prefix; the ONLY difference is the
994 // tick below, which carries one agent to its sentinel and leaves the other
995 // mid-flight.
996 const producingSandbox = await seed({
997 runId: producing,
998 total: 6,
999 lines: 2,
1000 detachedSince: now,
1001 })
1002 // The agent kept working after the viewer left and reached `{"__exit":0}`
1003 // with nobody reading its output — so four of its six lines were never
1004 // delivered and its transcript was never saved. This is the state only the
1005 // reaper resolves.
1006 await tick(finished, 4)
1007 const before = await state(producing)
1008​
1009 const body = await reap({ runIds: [finished, producing], now })
1010​
1011 // Both runs really were candidates, and both were probed: neither is past
1012 // the TTL, so the out-of-band exit probe is what separated them.
1013 expect(body.reap.considered).toBe(2)
1014 expect(body.reap.probed).toBe(2)
1015 expect(body.reap.outcomes.finalized).toBe(1)
1016 expect(body.reap.outcomes.producing).toBe(1)
1017 expect(body.reap.outcomes.expired).toBe(0)
1018 expect(reapEntry(body, finished).outcome).toBe('finalized')
1019 expect(reapEntry(body, finished).status).toBe('completed')
1020 expect(reapEntry(body, finished).exitCode).toBe(0)
1021 expect(reapEntry(body, producing).outcome).toBe('producing')
1022​
1023 // `withPersistence.onFinish` runs in the drive's teardown, which the sweep's
1024 // own response does not wait for, so this waits for the FACT rather than for a
1025 // duration. A run that never lands its transcript fails here with the whole
1026 // state dumped, which is the outcome under test.
1027 const after = await stateUntil(
1028 finished,
1029 'the finalized run to save its transcript',
1030 (record) =>
1031 record.messages.some((message) => message.role === 'assistant'),
1033 expect(after.record?.status).toBe('completed')
1034 expect(typeof after.record?.finishedAt).toBe('number')
1035 expect(after.record?.error).toBeUndefined()
1036 // The four undelivered lines arrived and the two already-stored ones did NOT
1037 // arrive twice: alignment suppressed them. Asserted as the exact sequence,
1038 // because a duplicated delta is what a failed alignment produces and a
1039 // substring check cannot see it.
1040 expect(after.log.map((entry) => entry.type)).toEqual(FULL_SEQUENCE)
1041 expect(
1042 after.log
1043 .filter((entry) => entry.type === 'TEXT_MESSAGE_CONTENT')
1044 .map((entry) => entry.delta),
1045 ).toEqual(['1', '2', '3', '4', '5', '6'])
1046​
1047 // THE point of the `'finalized'` outcome. `withPersistence.onFinish` is what
1048 // saves a thread's history, and a run that completes while detached has
1049 // nobody to run it — so until something drives it to terminal the
1050 // conversation never lands at all. This is that transcript, and the
1051 // still-producing run's empty one (asserted below) is the control.
1052 //
1053 // It holds the REMAINDER, not the whole message: alignment suppresses the
1054 // delivered prefix inside the adapter, so `withPersistence`'s accumulator
1055 // never sees '1','2' — the delivery log is the complete record, the saved
1056 // message is not. That is a property of every takeover, not of the reaper,
1057 // and it is pinned here because it is invisible in the log assertion above.
1058 expect(
1059 after.messages.map((message) => `${message.role}:${message.text}`),
1060 ).toEqual(['user:go', 'assistant:123456'])
1061​
1062 // The journal sweep runs after the reaper, so the finalized run's journal is
1063 // deletable — the delivery log is the record now — while the live one's is
1064 // the only copy of the bytes a successor would replay and must survive.
1065 expect(pruneFor(body, finishedSandbox).deleted).toEqual([finished])
1066 expect(after.journalFile).toBe(false)
1067 expect(pruneFor(body, producingSandbox).deleted).toEqual([])
1068 expect(
1069 pruneFor(body, producingSandbox).kept.map((entry) => entry.reason),
1070 ).toEqual(['non-terminal'])
1071 expect(pruneFor(body, producingSandbox).ageGate).toBe('listed')
1072​
1073 const untouched = await state(producing)
1074 expectUntouched(before, untouched)
1075 expect(untouched.log.map((entry) => entry.type)).toEqual(DELIVERED_PREFIX)
1076 })
1077​
1078 test('expires a still-producing detached run past its TTL, and leaves a fresher one alone', async () => {
1079 const expired = uniqueRunId('reap-expired')
1080 const fresh = uniqueRunId('reap-fresh')
1081 const now = Date.now()
1082​
1083 // Identical runs — same total, same delivered prefix, same still-working
1084 // agent. The ONLY difference is when the viewer left.
1085 await seed({
1086 runId: expired,
1087 total: 6,
1088 lines: 2,
1089 detachedSince: now - 10 * 60 * 1000,
1090 })
1091 await seed({ runId: fresh, total: 6, lines: 2, detachedSince: now })
1092 const before = await state(fresh)
1093​
1094 // A still-producing agent cannot be stopped by the cancel the reaper records:
1095 // nothing in the library polls `RunRecord.cancelRequested` to abort a live
1096 // drive, so `runBudgetMs` is the only thing that ends this one. Kept short so
1097 // the sweep returns promptly; the value is a server-side bound, not a sleep in
1098 // the test.
1099 const body = await reap({
1100 runIds: [expired, fresh],
1101 now,
1102 runBudgetMs: 500,
1103 })
1104​
1105 expect(body.reap.considered).toBe(2)
1106 // Only the fresher run was probed. An expired run needs no probe — its
1107 // outcome is terminal whether or not the agent finished — so `probed: 1` is
1108 // itself the proof that the two were classified differently.
1109 expect(body.reap.probed).toBe(1)
1110 expect(reapEntry(body, fresh).outcome).toBe('producing')
1111 expect(reapEntry(body, expired).outcome).toBe(EXPIRED_LIVE_OUTCOME)
1112 // `terminalizedAnyway` is reported on `'budget-exceeded'` only — it exists so
1113 // an operator reading the anomaly does not have to infer that the record still
1114 // reached terminal. On the expiry path the outcome itself already says so.
1115 expect(reapEntry(body, expired).terminalizedAnyway).toBeUndefined()
1116​
1117 await expectExpiredAndTornDown(expired)
1118 expectUntouched(before, await state(fresh))
1119 })
1120​
1121 test('the TTL cutoff is inclusive: a run exactly at it expires, one millisecond inside it is untouched', async () => {
1122 const atCutoff = uniqueRunId('reap-at-cutoff')
1123 const insideCutoff = uniqueRunId('reap-inside-cutoff')
1124 const now = Date.now()
1125​
1126 // One millisecond apart, either side of `now - ttl`.
1127 // `RunStore.listReclaimable` documents that cutoff as INCLUSIVE and the
1128 // reaper classifies expiry against the same one; the two disagreeing by a
1129 // millisecond would list a run as reclaimable and then call it fresh on
1130 // every sweep, forever.
1131 await seed({
1132 runId: atCutoff,
1133 total: 6,
1134 lines: 2,
1135 detachedSince: now - DETACHED_RUN_TTL_MS,
1136 })
1137 await seed({
1138 runId: insideCutoff,
1139 total: 6,
1140 lines: 2,
1141 detachedSince: now - DETACHED_RUN_TTL_MS + 1,
1142 })
1143 const before = await state(insideCutoff)
1144​
1145 const body = await reap({
1146 runIds: [atCutoff, insideCutoff],
1147 now,
1148 runBudgetMs: 500,
1149 })
1150​
1151 expect(body.reap.considered).toBe(2)
1152 // The whole assertion, in one number: exactly one of the two was treated as
1153 // expired, and it was not the one a millisecond inside the window.
1154 expect(body.reap.probed).toBe(1)
1155 expect(reapEntry(body, insideCutoff).outcome).toBe('producing')
1156 expect(reapEntry(body, atCutoff).outcome).toBe(EXPIRED_LIVE_OUTCOME)
1157​
1158 await expectExpiredAndTornDown(atCutoff)
1159 expectUntouched(before, await state(insideCutoff))
1160 })
1162​
1163// ---------------------------------------------------------------------------
1164// 7. Replay divergence is loud
1165// ---------------------------------------------------------------------------
1166​
1167/**
1168 * Determinism is a PRECONDITION of the takeover, not a property of it: a resumed
1169 * journal read is idempotent only because `createRunScopedIdGen` makes
1170 * re-translation reproduce the same ids. `alignToStoredLog` verifies that on every
1171 * attach and throws `JournalReplayDivergedError` on the first mismatch, and the
1172 * alternative to throwing is a delivered stream whose prefix and suffix disagree
1173 * about message identity — a duplicated `TEXT_MESSAGE_START`, and a client that
1174 * renders two messages for one.
1176 * `?nondeterministic=1` makes the attaching translator mint a message id that is
1177 * not run-scoped, leaving the stored prefix exactly as the previous host wrote it.
1178 * The control run below is the same seed WITHOUT the flag, so the two differ in
1179 * that one respect and nothing else.
1180 */
1181test.describe('durable runs — replay divergence', () => {
1182 test('a non-deterministic replay fails the attach loudly instead of duplicating the prefix', async () => {
1183 const diverged = uniqueRunId('diverge-replay')
1184 const aligned = uniqueRunId('aligned-replay')
1185 await seed({ runId: diverged, total: 2, lines: 2 })
1186 await seed({ runId: aligned, total: 2, lines: 2 })
1187​
1188 const bad = await SseStream.open(
1189 routeUrl({ runId: diverged, offset: '-1', nondeterministic: '1' }),
1190 { method: 'GET' },
1192 const delivered = await bad.drain()
1193​
1194 // The stored prefix replays, and then the run ENDS in an error — it does not
1195 // continue with a second TEXT_MESSAGE_START under a new id, and it does not
1196 // re-deliver '1','2'.
1197 expect(delivered.map(eventType)).toEqual([...DELIVERED_PREFIX, 'RUN_ERROR'])
1198 expect(contentDeltas(delivered)).toEqual(['1', '2'])
1199 const failure = delivered.at(-1)
1200 expect(typeof failure?.data.message).toBe('string')
1201 expect(String(failure?.data.message)).toContain(
1202 'journal replay diverged at index 1',
1204​
1205 const after = await stateUntil(
1206 diverged,
1207 'the diverged run to be recorded as failed',
1208 (record) => record.record?.status === 'failed',
1210 expect(after.log.map((entry) => entry.type)).toEqual([
1211 ...DELIVERED_PREFIX,
1212 'RUN_ERROR',
1213 ])
1214 // No assistant turn was saved from a stream the guard refused to trust — the
1215 // stored prefix stays the only record of what was delivered.
1216 expect(
1217 after.messages.filter((message) => message.role === 'assistant'),
1218 ).toEqual([])
1219​
1220 // The control: the identical seed, attached WITHOUT the flag, aligns and
1221 // completes. Without this the test above also passes if an attach can never
1222 // succeed at all.
1223 const good = await SseStream.open(
1224 routeUrl({ runId: aligned, offset: '-1' }),
1225 { method: 'GET' },
1227 expect((await good.drain()).map(eventType)).toEqual(TWO_LINE_SEQUENCE)
1228 const control = await stateUntil(
1229 aligned,
1230 'the aligned run to complete',
1231 (record) => record.record?.status === 'completed',
1233 expect(control.log.map((entry) => entry.type)).toEqual(TWO_LINE_SEQUENCE)
1234 expect(control.log.filter((entry) => entry.type === 'RUN_ERROR')).toEqual(
1235 [],
1237 })