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

api.durable-takeover.ts

1,095 lines40.9 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 EventType,
4 RUN_CANCEL_REASON,
5 chat,
6 memoryStream,
7 requestRunCancel,
8 resumeServerSentEventsResponse,
9 toServerSentEventsResponse,
10} from '@tanstack/ai'
11import { InMemoryLockStore, withLocks } from '@tanstack/ai/locks'
12import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
13import {
14 InMemorySandboxInstanceStore,
15 alignedIfAttaching,
16 createRunScopedIdGen,
17 defineSandbox,
18 defineWorkspace,
19 exitSentinelLine,
20 getSandboxDurability,
21 journalPaths,
22 probeRunExit,
23 pruneJournals,
24 reapDetachedRuns,
25 resolveDurableRunId,
26 sandboxReclaimer,
27 sandboxRunDriver,
28 withSandbox,
29} from '@tanstack/ai-sandbox'
30import type {
31 AnyTextAdapter,
32 ModelMessage,
33 RunRecord,
34 StreamChunk,
35} from '@tanstack/ai'
36import type { LockStore } from '@tanstack/ai/locks'
37import type {
38 PruneJournalsResult,
39 ReapResult,
40 RunExitProbe,
41 SandboxHandle,
42 SandboxProvider,
43 SandboxRunDurability,
44} from '@tanstack/ai-sandbox'
45​
46/**
47 * Durable, detachable sandboxed runs over real HTTP: detach on disconnect,
48 * takeover, out-of-band cancel vs. plain disconnect, and the single-writer
49 * epoch fence.
50 *
51 * WHAT IS REAL AND WHAT IS A STAND-IN. Everything that decides the behaviors
52 * under test is production code — `withSandbox`'s durability resolution and its
53 * detach-vs-destroy `onAbort` branch, `withPersistence`'s
54 * `DetachableRunCapability` branch, `requestRunCancel` / `wasCancelRequested` /
55 * `RUN_CANCEL_REASON`, `resolveDurableRunId`, `alignedIfAttaching`
56 * (`alignToStoredLog`), `sandboxRunDriver`'s claim and BOTH its fences, core's
57 * `startRunDriver`, and — for the sweep — `reapDetachedRuns`, `probeRunExit`,
58 * `pruneJournals` and `sandboxReclaimer`. Two things are stand-ins:
59 *
60 * - **The sandbox provider** is a fake handle (no container). It records every
61 * `destroy` per sandbox key, which is how "an explicit cancel tears the
62 * sandbox down" is asserted.
63 * - **The agent's journal** is a counter instead of an NDJSON file inside the
64 * sandbox. The substitution keeps the property the journal exists for: the
65 * agent's output lives OUTSIDE the request, so it survives the client
66 * disconnect and a later attach re-reads it from the first line. The counter
67 * advances only on an explicit `?action=tick`, so a test controls exactly
68 * where mid-stream it disconnects — no timers, no sleeps, no flake. The
69 * counter is ALSO projected as a real NDJSON file in a fake journal directory
70 * (see `journalDirs`), because `probeRunExit` and `pruneJournals` read that
71 * directory through `handle.process.exec` and parse its stdout — so those two
72 * run for real rather than being stubbed.
73 *
74 * Provider-free (no LLM in the loop), so this route is exempt from the aimock
75 * policy, like the other durability harness routes.
76 *
77 * Actions, all keyed by a caller-supplied `runId` that must be unique per test:
78 *
79 * - `POST ?runId&threadId&total` — start a fresh durable run over SSE.
80 * - `POST ?action=tick&runId&n` — advance the agent's journal by `n` lines.
81 * - `POST ?action=drop&runId` — the client disconnect (see `dropResponse`).
82 * - `POST ?action=seed&runId&threadId&total&lines&detachedSince` — construct the
83 * takeover PRECONDITION directly: a running record, a detached marker, a live
84 * agent, and an OPEN log holding the prefix a previous host delivered. See
85 * "Why seeding exists" below.
86 * - `GET ?runId&offset=-1` — attach: replay the log AND take the run over.
87 * - `POST ?action=cancel&runId&band=both|durable|inprocess` — out-of-band cancel.
88 * - `POST ?action=reap&runId…&now&runBudgetMs` — one reaper sweep, scoped to the
89 * runIds named (repeat `runId`), plus one journal-directory sweep per sandbox
90 * those runs live in. See {@link reapResponse}.
91 * - `GET ?action=state&runId` — the observable server state, as JSON.
92 *
93 * Any request may add `?nondeterministic=1` alongside its `runId` to make that
94 * run's translator mint a message id that is NOT run-scoped — see
95 * {@link nondeterministicRuns}.
96 *
97 * WHY SEEDING EXISTS. A takeover's documented precondition is "record still
98 * `running`, delivery log OPEN and holding what was already delivered, agent
99 * still working". `?action=seed` writes exactly that, with the same translator a
100 * live host would have used, so the takeover machinery can be exercised in
101 * isolation from whatever produced the prefix — no disconnect timing, no
102 * dependence on the producing host at all.
103 *
104 * A real `?action=drop` now produces the same precondition (core's delivery sink
105 * leaves a DETACHED run's log open — see `RunDetachedCapability`), and the spec
106 * pins the disconnect→takeover path end to end as well. Seeding is kept because
107 * the two prove different things: seeding proves a takeover can pick up a prefix
108 * it did not produce, which is the cross-host case a single-process test cannot
109 * otherwise reach.
110 */
111​
112// ---------------------------------------------------------------------------
113// The fake agent's journal: output that outlives the request that started it.
114// ---------------------------------------------------------------------------
115​
116interface FakeJournal {
117 /** Lines written so far. Advanced only by `?action=tick`. */
118 lines: number
119 /** Line count at which the agent finishes and seals the journal. */
120 total: number
121 done: boolean
122 /** Set when this run's sandbox is destroyed — the agent dies with it. */
123 killed: boolean
124 /** The sandbox this run's agent lives in, so a destroy is attributable. */
125 sandboxKey: string
127​
128const journals = new Map<string, FakeJournal>()
129​
130// ---------------------------------------------------------------------------
131// The fake sandbox's journal DIRECTORY.
132//
133// The counter above is what the harness adapter tails. This is the same journal
134// as a FILE, because two pieces of production code under test read the journal
135// directory through `handle.process.exec` and parse its stdout —
136// `probeRunExit` (`tail -c -N … | base64`) and `pruneJournals`
137// (`ls -1`, `stat -c '%Y %n'`, `rm -f`). Stubbing either of them out would leave
138// the reaper's "did the agent finish?" decision and the sweep's keep/delete
139// decision untested, so `exec` answers that shell text instead (see
140// `execJournalCommand`). The file's CONTENT is derived from the run's
141// `FakeJournal` on demand, so `?action=tick` moves the counter and the file
142// together and they can never disagree.
143// ---------------------------------------------------------------------------
144​
145/** One file in a sandbox's journal directory. */
146interface JournalFile {
147 /** The run whose `FakeJournal` supplies this file's bytes. */
148 runId: string
149 mtimeMs: number
151​
152/** Per sandbox key, the journal filenames that currently exist in it. */
153const journalDirs = new Map<string, Map<string, JournalFile>>()
154​
155function journalDirFor(sandboxKey: string): Map<string, JournalFile> {
156 const existing = journalDirs.get(sandboxKey)
157 if (existing !== undefined) return existing
158 const created = new Map<string, JournalFile>()
159 journalDirs.set(sandboxKey, created)
160 return created
162​
163function baseName(path: string): string {
164 return path.slice(path.lastIndexOf('/') + 1)
166​
167/**
168 * Register a run's journal and its `.err` sidecar under its sandbox, with the
169 * names `journalPaths` derives — the SAME function `pruneJournals` uses to build
170 * the `rm`, so a name this harness invents can never diverge from one the sweep
171 * targets.
172 */
173function createJournalFiles(runId: string, sandboxKey: string): void {
174 const paths = journalPaths(runId)
175 const dir = journalDirFor(sandboxKey)
176 const mtimeMs = Date.now()
177 dir.set(baseName(paths.journal), { runId, mtimeMs })
178 dir.set(baseName(paths.stderr), { runId, mtimeMs })
180​
181/** Whether a run's journal file still exists — i.e. a sweep has not deleted it. */
182function journalFileExists(runId: string, sandboxKey: string): boolean {
183 return journalDirFor(sandboxKey).has(baseName(journalPaths(runId).journal))
185​
186/**
187 * The run's journal as NDJSON, exactly as `journaledCommand` would have written
188 * it: one line per journal line, then the real `{"__exit":N,"__nonce":"…"}`
189 * sentinel once the agent is done — built with {@link exitSentinelLine}, the
190 * SAME helper `journaledCommand`'s `printf` and the reader are asserted against
191 * byte-for-byte, so this harness cannot drift onto a shape `parseJournalExit`
192 * refuses. `parseJournalExit` reads the sentinel and nothing else, so the line
193 * payloads only have to be valid JSON that does not carry the sentinel key.
194 */
195function journalContent(runId: string): string {
196 const journal = journals.get(runId)
197 if (journal === undefined) return ''
198 let text = ''
199 for (let line = 1; line <= journal.lines; line += 1) {
200 text += `{"line":${line}}\n`
201 }
202 if (journal.done) text += `${exitSentinelLine(journalPaths(runId), 0)}\n`
203 return text
205​
206/** Every single-quoted word in a command, as `journal.ts` quotes its paths. */
207function quotedWords(command: string): Array<string> {
208 return [...command.matchAll(/'([^']*)'/g)].map((match) => match[1] ?? '')
210​
211/**
212 * Answer the four journal-directory commands `journal.ts` composes, for ONE
213 * sandbox's directory. Anything else answers empty, as the rest of this fake
214 * handle does.
215 *
216 * The `tail` arm's missing-file answer is load bearing: the real command ends
217 * `2>/dev/null | base64`, so a journal that is not there contributes no bytes and
218 * the pipe emits the base64 of nothing — which `parseJournalExit` reads as "no
219 * sentinel", i.e. `'producing'`. Answering an error string instead would let a
220 * pruned journal read as a finished agent.
221 */
222function execJournalCommand(
223 sandboxKey: string,
224 command: string,
225): { stdout: string; stderr: string; exitCode: number } {
226 const dir = journalDirFor(sandboxKey)
227 const words = quotedWords(command)
228 const ok = (stdout: string) => ({ stdout, stderr: '', exitCode: 0 })
229​
230 if (command.startsWith('ls -1 ')) return ok([...dir.keys()].join('\n'))
231​
232 if (command.startsWith(`stat -c '%Y %n' `)) {
233 // `words[0]` is the quoted FORMAT (`%Y %n`); the directory is the next word.
234 const root = words[1] ?? ''
235 // The directory itself FIRST: `parseJournalMtimeListing` treats that line as
236 // its self-witness and answers `unavailable` without it.
237 const lines = [`${Math.floor(Date.now() / 1000)} ${root}`]
238 for (const [name, file] of dir) {
239 lines.push(`${Math.floor(file.mtimeMs / 1000)} ${root}/${name}`)
240 }
241 return ok(lines.join('\n'))
242 }
243​
244 if (command.startsWith('rm -f ')) {
245 for (const word of words) dir.delete(baseName(word))
246 return ok('')
247 }
248​
249 if (command.startsWith('tail -c -')) {
250 const file = dir.get(baseName(words[0] ?? ''))
251 return ok(file === undefined ? '' : btoa(journalContent(file.runId)))
252 }
253​
254 return ok('')
256​
257/** Sandbox keys passed to `provider.destroy`, in order. */
258const destroyedSandboxes: Array<string> = []
259​
260/** Runs this process is currently driving (the in-process cancel band). */
261const driving = new Map<string, AbortController>()
262​
263/**
264 * Per-run bookkeeping for ATTACHING drives: how many reached the adapter, how
265 * many chunks they produced, and how many have finished producing.
266 *
267 * Exposed on `?action=state` because the fencing test needs both halves. Without
268 * `attachDrives`, "the log has no duplicates" is also satisfied by a second
269 * driver that never ran. Without `attachDriveEnds`, the test can assert before
270 * the LOSER has had its chance to write, which passes even with the fence
271 * removed — verified, so this is load bearing, not decoration.
272 */
273const attachDrives = new Map<string, number>()
274const attachChunks = new Map<string, number>()
275const attachDriveEnds = new Map<string, number>()
276​
277function bump(map: Map<string, number>, key: string): void {
278 map.set(key, (map.get(key) ?? 0) + 1)
280​
281const persistence = memoryPersistence()
282const { runs } = persistence.stores
283​
284/**
285 * Explicit instance map, so `sandboxReclaimer` can resolve the provider sandbox
286 * behind a terminal run. `withSandbox` falls back to a private in-memory store
287 * when this is omitted, and `reclaimSandbox` cannot see that one — a reaper wired
288 * without it reports `'no-sandbox-key'`/`'not-found'` forever and every sandbox
289 * leaks. Same store on every `withSandbox` call here, so the key one branch wrote
290 * is the key another reads.
291 */
292const instances = new InMemorySandboxInstanceStore()
293​
294/**
295 * The detached-run TTL. `reapDetachedRuns` is its ONE consumer: the reaper's
296 * inclusive `detachedSince <= now - ttl` cutoff is the only thing that decides
297 * expiry, so this single value is what the boundary cases in the spec are
298 * constructed against.
299 *
300 * There is deliberately no second, duration-string spelling passed to
301 * `withSandbox`. `withSandbox`'s durability options carry no TTL — a
302 * `detachedRunTtl` there was parsed and read by nothing, so it could silently
303 * disagree with the value below while looking authoritative.
304 */
305const DETACHED_RUN_TTL_MS = 5 * 60 * 1000
306​
307/** The ordinary wiring: one lock store, serializing claims in this process. */
308const serializingLocks = new InMemoryLockStore()
309​
310/**
311 * A lock that grants every request immediately and never reports a loss.
312 *
313 * `InMemoryLockStore` SERIALIZES claims inside one process, so a second attach
314 * waits for the first to finish and the two drivers are never concurrent —
315 * which means the fence can never be observed there.
316 * `packages/ai-sandbox/src/claim.ts` says exactly that: within one process only
317 * layer 2, the `driverEpoch` fence, is provable. This models a lease-less lock
318 * so the two drives overlap and layer 2 does the work.
319 */
320const permissiveLocks: LockStore = {
321 withLock: (_key, fn) => fn(new AbortController().signal),
323​
324function locksFor(url: URL): LockStore {
325 return url.searchParams.get('locks') === 'permissive'
326 ? permissiveLocks
327 : serializingLocks
329​
330function startAgent(
331 runId: string,
332 threadId: string,
333 total: number,
334): FakeJournal {
335 const existing = journals.get(runId)
336 if (existing) return existing
337 const journal: FakeJournal = {
338 lines: 0,
339 total,
340 done: false,
341 killed: false,
342 sandboxKey: sandbox.key({ threadId, runId }),
343 }
344 journals.set(runId, journal)
345 // The reader creates the journal file before it writes a line — see
346 // `journalFollowCommand`'s `: >> file` — so the file exists from run start.
347 createJournalFiles(runId, journal.sandboxKey)
348 return journal
350​
351function tickAgent(runId: string, n: number): FakeJournal | undefined {
352 const journal = journals.get(runId)
353 if (!journal || journal.killed) return journal
354 journal.lines = Math.min(journal.total, journal.lines + n)
355 if (journal.lines >= journal.total) journal.done = true
356 return journal
358​
359const JOURNAL_STALL_MS = 20_000
360const JOURNAL_POLL_MS = 20
361​
362function sleep(ms: number): Promise<void> {
363 return new Promise((resolve) => setTimeout(resolve, ms))
365​
366/**
367 * Follow the journal, yielding each line index as it appears.
368 *
369 * Bounded on purpose: a tail that parks forever turns a broken attach into a
370 * hung CI job instead of a failing test. Ends WITHOUT a terminal when the
371 * consumer's signal aborts, so a disconnect never synthesizes a completion.
372 */
373async function* tailJournal(
374 runId: string,
375 signal: AbortSignal | undefined,
376): AsyncIterable<number> {
377 const journal = journals.get(runId)
378 if (!journal) {
379 throw new Error(`durable-takeover: no journal for run ${runId}`)
380 }
381 let delivered = 0
382 let waited = 0
383 for (;;) {
384 while (delivered < journal.lines) {
385 delivered += 1
386 yield delivered
387 }
388 if (journal.done || journal.killed) return
389 if (signal?.aborted) return
390 await sleep(JOURNAL_POLL_MS)
391 waited += JOURNAL_POLL_MS
392 if (waited > JOURNAL_STALL_MS) {
393 throw new Error(
394 `durable-takeover: journal for run ${runId} stalled at ${delivered}/${journal.total} lines`,
395 )
396 }
397 }
399​
400// ---------------------------------------------------------------------------
401// The translator. Deterministic by construction, which is what makes alignment
402// possible: ids come from `createRunScopedIdGen`, never a clock or randomness,
403// so re-translating the same journal from line 1 reproduces byte-identical
404// chunks. `timestamp` is the one wall-clock field, and `chunkFingerprint`
405// excludes exactly that.
406//
407// The individual builders are shared with `?action=seed`, so a seeded prefix and
408// a live replay cannot drift apart in shape.
409// ---------------------------------------------------------------------------
410​
411/**
412 * Runs whose translator must mint a message id that is NOT run-scoped.
413 *
414 * The determinism above is a PRECONDITION of the takeover, not a property of it:
415 * `alignToStoredLog` compares the replay's chunks to the stored ones by
416 * fingerprint and throws `JournalReplayDivergedError` on the first mismatch. That
417 * guard is the only thing standing between a translator that quietly stopped
418 * being deterministic and a delivered stream whose prefix and suffix disagree
419 * about message identity, so it needs a way to be provoked at the HTTP boundary
420 * rather than only in a unit test. `?nondeterministic=1` is that way: the stored
421 * prefix keeps the run-scoped id (`deliveredPrefix` is unchanged, exactly as a
422 * previous host wrote it) while the replay mints a fresh one, so alignment
423 * diverges at the `TEXT_MESSAGE_START` and the error must surface on the attach's
424 * socket instead of being swallowed.
425 */
426const nondeterministicRuns = new Set<string>()
427​
428/** The translated message id: run-scoped, unless this run opted out. */
429function messageIdFor(runId: string): string {
430 if (nondeterministicRuns.has(runId)) return `nd-${crypto.randomUUID()}`
431 return createRunScopedIdGen(runId)()
433​
434function runStartedChunk(runId: string, threadId: string): StreamChunk {
435 return { type: EventType.RUN_STARTED, runId, threadId, timestamp: Date.now() }
437​
438function messageStartChunk(messageId: string): StreamChunk {
439 return {
440 type: EventType.TEXT_MESSAGE_START,
441 messageId,
442 role: 'assistant',
443 timestamp: Date.now(),
444 }
446​
447/** Every delta up to and including `line`, concatenated. */
448function accumulatedContent(line: number): string {
449 let text = ''
450 for (let n = 1; n <= line; n += 1) text += String(n)
451 return text
453​
454function contentChunk(messageId: string, line: number): StreamChunk {
455 return {
456 type: EventType.TEXT_MESSAGE_CONTENT,
457 messageId,
458 delta: String(line),
459 // `content` is the text accumulated SO FAR, as the real adapters emit it —
460 // not a second copy of the delta. It matters because that field is what the
461 // message a run saves is assembled from, so emitting the delta here made
462 // every saved transcript one chunk long. Derived from `line` alone, so a
463 // replay reproduces it byte for byte and alignment still holds. The
464 // AG-UI 1.0 event type has no `content`, so it rides in a spread.
465 ...{ content: accumulatedContent(line) },
466 timestamp: Date.now(),
467 }
469​
470function messageEndChunk(messageId: string): StreamChunk {
471 return {
472 type: EventType.TEXT_MESSAGE_END,
473 messageId,
474 timestamp: Date.now(),
475 }
477​
478function runFinishedChunk(runId: string, threadId: string): StreamChunk {
479 return {
480 type: EventType.RUN_FINISHED,
481 runId,
482 threadId,
483 finishReason: 'stop',
484 timestamp: Date.now(),
485 }
487​
488async function* translate(
489 runId: string,
490 threadId: string,
491 lines: AsyncIterable<number>,
492): AsyncIterable<StreamChunk> {
493 const messageId = messageIdFor(runId)
494 yield runStartedChunk(runId, threadId)
495 yield messageStartChunk(messageId)
496 for await (const line of lines) yield contentChunk(messageId, line)
497 yield messageEndChunk(messageId)
498 yield runFinishedChunk(runId, threadId)
500​
501/** The chunks a previous host would have delivered for `lines` journal lines. */
502function deliveredPrefix(
503 runId: string,
504 threadId: string,
505 lines: number,
506): Array<StreamChunk> {
507 const genId = createRunScopedIdGen(runId)
508 const messageId = genId()
509 const chunks: Array<StreamChunk> = [
510 runStartedChunk(runId, threadId),
511 messageStartChunk(messageId),
512 ]
513 for (let line = 1; line <= lines; line += 1) {
514 chunks.push(contentChunk(messageId, line))
515 }
516 return chunks
518​
519/** The subset of a text adapter's stream options this harness reads. */
520interface HarnessStreamOptions {
521 runId?: string
522 threadId?: string
523 capabilities?: Parameters<typeof getSandboxDurability>[0]
524 abortController?: AbortController
525 /**
526 * How `chat()` actually hands an adapter the run's abort signal: it builds
527 * `{ signal }` from the caller's `abortController` and passes it as `request`,
528 * never the controller itself. The real harness adapters read both, in this
529 * order, and so must this one — reading only `abortController` leaves the
530 * journal tail blind to the abort and the run deadlocks.
531 */
532 request?: Request | RequestInit
534​
535function abortSignalFor(
536 options: HarnessStreamOptions,
537): AbortSignal | undefined {
538 return options.abortController?.signal ?? options.request?.signal ?? undefined
540​
541/**
542 * A journaling harness adapter, wired the way the real ones are: read the
543 * resolved durability off the capability bus, resolve the durable `runId` with
544 * `resolveDurableRunId`, and wrap the FINAL translated sequence in
545 * `alignedIfAttaching` so alignment runs on an attach and only on an attach.
546 */
547const harnessAdapter: AnyTextAdapter = {
548 kind: 'text',
549 name: 'fake-harness',
550 model: 'fake-harness-model',
551 '~types': {},
552 chatStream: (options: HarnessStreamOptions): AsyncIterable<StreamChunk> => {
553 const durability: SandboxRunDurability | undefined = options.capabilities
554 ? getSandboxDurability(options.capabilities, { optional: true })
555 : undefined
556 const runId = resolveDurableRunId(options.runId, {
557 durable: durability !== undefined,
558 adapter: 'fake-harness',
559 fallback: () => crypto.randomUUID(),
560 })
561 const threadId = options.threadId ?? runId
562 // An attach must never start a second agent: it tails the journal the first
563 // one is still writing. Only a fresh run spawns.
564 if (durability?.attach !== true) startAgent(runId, threadId, 6)
565 else bump(attachDrives, runId)
566 const counted = durability?.attach === true
567 return alignedIfAttaching(
568 (async function* () {
569 try {
570 for await (const chunk of translate(
571 runId,
572 threadId,
573 tailJournal(runId, abortSignalFor(options)),
574 )) {
575 if (counted) bump(attachChunks, runId)
576 yield chunk
577 }
578 } finally {
579 if (counted) bump(attachDriveEnds, runId)
580 }
581 })(),
582 durability,
583 )
584 },
585 structuredOutput: () => Promise.resolve({ data: {}, rawText: '{}' }),
586} as unknown as AnyTextAdapter
587​
588// ---------------------------------------------------------------------------
589// Fake sandbox provider. Records destroys per key; a destroy kills that
590// sandbox's agent, because closing an agent's IO stream does NOT stop it — the
591// reason a cancel destroys the sandbox at all.
592// ---------------------------------------------------------------------------
593​
594function fakeHandle(id: string): SandboxHandle {
595 return {
596 id,
597 provider: 'fake',
598 capabilities: {
599 fs: true,
600 exec: true,
601 env: true,
602 ports: false,
603 backgroundProcesses: false,
604 writableStdin: false,
605 killableProcesses: false,
606 snapshots: false,
607 networkPolicy: false,
608 durableFilesystem: false,
609 fork: false,
610 },
611 fs: {
612 read: () => Promise.resolve(''),
613 readBytes: () => Promise.resolve(new Uint8Array()),
614 write: () => Promise.resolve(),
615 list: () => Promise.resolve([]),
616 mkdir: () => Promise.resolve(),
617 remove: () => Promise.resolve(),
618 rename: () => Promise.resolve(),
619 exists: () => Promise.resolve(false),
620 },
621 git: {
622 clone: () => Promise.resolve(),
623 status: () => Promise.resolve(''),
624 add: () => Promise.resolve(),
625 commit: () => Promise.resolve(),
626 push: () => Promise.resolve(),
627 pull: () => Promise.resolve(),
628 branch: () => Promise.resolve('main'),
629 },
630 process: {
631 // `id` IS the sandbox key (`ensure` passes `create({ id: key })`), so this
632 // handle reads and writes exactly its own sandbox's journal directory.
633 exec: (command: string) =>
634 Promise.resolve(execJournalCommand(id, command)),
635 spawn: () => Promise.reject(new Error('not supported')),
636 },
637 ports: { connect: () => Promise.reject(new Error('not supported')) },
638 env: { set: () => Promise.resolve() },
639 destroy: () => Promise.resolve(),
640 }
642​
643const provider: SandboxProvider = {
644 name: 'fake',
645 capabilities: () => fakeHandle('probe').capabilities,
646 create: (input) => Promise.resolve(fakeHandle(input.id ?? 'fake-sandbox')),
647 resume: (input) => Promise.resolve(fakeHandle(input.id)),
648 destroy: (input) => {
649 destroyedSandboxes.push(input.id)
650 // Scoped to this sandbox's own runs: the suite runs fully parallel, so
651 // killing every live journal would poison other tests.
652 for (const journal of journals.values()) {
653 if (journal.sandboxKey === input.id) journal.killed = true
654 }
655 return Promise.resolve()
656 },
658​
659const sandbox = defineSandbox({
660 id: 'durable-takeover',
661 provider,
662 workspace: defineWorkspace({ source: { type: 'none' } }),
663 fileEvents: false,
664})
665​
666// ---------------------------------------------------------------------------
667// Handlers
668// ---------------------------------------------------------------------------
669​
670function requiredParam(url: URL, key: string): string {
671 const value = url.searchParams.get(key)
672 if (value === null || value.length === 0) {
673 throw new Error(`durable-takeover: ${key} is required`)
674 }
675 return value
677​
678function intParam(url: URL, key: string, fallback: number): number {
679 const raw = url.searchParams.get(key)
680 const parsed = raw === null ? Number.NaN : Number.parseInt(raw, 10)
681 return Number.isFinite(parsed) ? parsed : fallback
683​
684/** A `memoryStream` bound to one run, independent of the current request. */
685function logFor(runId: string) {
686 return memoryStream(
687 new Request(
688 `http://durable-takeover.local/?runId=${encodeURIComponent(runId)}`,
689 { method: 'POST' },
690 ),
691 )
693​
694/** Mirror the driver's abort signal onto a controller `chat()` can take. */
695function controllerFor(signal: AbortSignal): AbortController {
696 const controller = new AbortController()
697 const abort = (): void => controller.abort(signal.reason)
698 if (signal.aborted) abort()
699 else signal.addEventListener('abort', abort, { once: true })
700 return controller
702​
703interface StateBody {
704 record: RunRecord | null
705 /** Attaching drives that reached the adapter for this run. */
706 attachDrives: number
707 /** Chunks those drives produced in total (pre-alignment). */
708 attachChunks: number
709 /** Attaching drives that have finished producing. */
710 attachDriveEnds: number
711 /** Whether THIS run's sandbox has been destroyed. */
712 sandboxDestroyed: boolean
713 journal: FakeJournal | null
714 /**
715 * Whether this run's journal FILE still exists in its sandbox.
716 *
717 * The reaper's counterpart sweep, `pruneJournals`, decides per run whether the
718 * journal may be deleted, and its whole risk is deleting one it must keep — the
719 * journal is the only copy of the bytes a successor replays. Without this the
720 * sweep's summary is the only witness, and a summary that says `deleted: [x]`
721 * cannot show that `y`'s bytes are still there.
722 */
723 journalFile: boolean
724 /**
725 * The transcript `withPersistence.onFinish` saved for this run's thread.
726 *
727 * This is what makes the reaper's `'finalized'` outcome worth anything: a run
728 * that reached its sentinel while detached has nobody driving it, so nothing
729 * calls `onFinish` and the conversation NEVER lands — the whole point of
730 * finalizing it is that the transcript appears here afterwards.
731 */
732 messages: Array<{ role: string; text: string }>
733 /** The run's delivery log, reduced to what the assertions read. */
734 log: Array<{ type: string; delta?: string; message?: string }>
736​
737/** Flatten a stored message to its text, so a spec can assert on it. */
738function messageText(message: ModelMessage): string {
739 const content: unknown = message.content
740 if (typeof content === 'string') return content
741 if (!Array.isArray(content)) return ''
742 return content
743 .map((part: unknown) => {
744 if (typeof part !== 'object' || part === null) return ''
745 if (Reflect.get(part, 'type') !== 'text') return ''
746 const content: unknown = Reflect.get(part, 'content')
747 return typeof content === 'string' ? content : ''
748 })
749 .join('')
751​
752async function stateResponse(url: URL): Promise<Response> {
753 const runId = requiredParam(url, 'runId')
754 const snapshot = await logFor(runId).snapshot()
755 const journal = journals.get(runId) ?? null
756 const record = await runs.get(runId)
757 const threadId = record?.threadId ?? `thread-${runId}`
758 const stored = await persistence.stores.messages.loadThread(threadId)
759 const body: StateBody = {
760 record,
761 attachDrives: attachDrives.get(runId) ?? 0,
762 attachChunks: attachChunks.get(runId) ?? 0,
763 attachDriveEnds: attachDriveEnds.get(runId) ?? 0,
764 sandboxDestroyed:
765 journal !== null && destroyedSandboxes.includes(journal.sandboxKey),
766 journal,
767 journalFile:
768 journal !== null && journalFileExists(runId, journal.sandboxKey),
769 messages: stored.map((message) => ({
770 role: message.role,
771 text: messageText(message),
772 })),
773 log: snapshot.map((entry) => {
774 const delta: unknown = Reflect.get(entry.chunk, 'delta')
775 const message: unknown = Reflect.get(entry.chunk, 'message')
776 return {
777 type: entry.chunk.type,
778 ...(typeof delta === 'string' ? { delta } : {}),
779 ...(typeof message === 'string' ? { message } : {}),
780 }
781 }),
782 }
783 return Response.json(body)
785​
786/**
787 * Drop the run's connection: abort its `AbortController` with NO reason.
788 *
789 * This is the disconnect, injected at the seam a real one reaches. It has to be
790 * injected because a client `fetch` abort does not propagate to the server
791 * through this app's dev server — the request keeps running — so a test cannot
792 * produce a server-observable disconnect by closing its own socket.
793 *
794 * Faithful where it matters: `chat()`'s abort hooks and the delivery sink share
795 * this one controller, so aborting it is exactly what the transport does when
796 * the socket goes away, and the abort carries no reason — which is the ENTIRE
797 * difference from `?action=cancel`'s in-process band, and precisely the
798 * "identical connection close, different out-of-band intent" the feature
799 * distinguishes.
800 */
801function dropResponse(url: URL): Response {
802 const runId = requiredParam(url, 'runId')
803 const controller = driving.get(runId)
804 controller?.abort()
805 return Response.json({ dropped: controller !== undefined })
807​
808async function cancelResponse(url: URL): Promise<Response> {
809 const runId = requiredParam(url, 'runId')
810 const band = url.searchParams.get('band') ?? 'both'
811 // Band 1 (durable): the only channel that reaches a run driven elsewhere.
812 if (band === 'both' || band === 'durable') {
813 await requestRunCancel(runs, runId)
814 }
815 // Band 2 (in-process): stops a co-located driver immediately.
816 if (band === 'both' || band === 'inprocess') {
817 driving.get(runId)?.abort(RUN_CANCEL_REASON)
818 }
819 return new Response(null, { status: 204 })
821​
822/**
823 * Construct a takeover precondition: running record, detached marker, live
824 * agent, and an OPEN log holding the prefix a previous host delivered.
825 */
826async function seedResponse(url: URL): Promise<Response> {
827 const runId = requiredParam(url, 'runId')
828 const threadId = url.searchParams.get('threadId') ?? `thread-${runId}`
829 const total = intParam(url, 'total', 6)
830 const lines = intParam(url, 'lines', 2)
831​
832 // `detachedSince` is INJECTABLE because it is the field the reaper's TTL
833 // boundary is computed from. With `now` injected on `?action=reap` too, both
834 // sides of `detachedSince <= now - ttl` are supplied by the test, so a spec can
835 // land a run exactly ON the inclusive cutoff and one millisecond inside it with
836 // no fake clock anywhere and no dependence on how long the request took.
837 const detachedSince = intParam(url, 'detachedSince', Date.now())
838​
839 const journal = startAgent(runId, threadId, total)
840 tickAgent(runId, lines)
841 await runs.createOrResume({ runId, threadId, startedAt: Date.now() })
842 await runs.update(runId, {
843 detachedSince,
844 sandboxKey: journal.sandboxKey,
845 })
846 // Appended, never closed: the host that would have closed the log is the host
847 // that died.
848 await logFor(runId).append(deliveredPrefix(runId, threadId, lines))
849 return Response.json({ seeded: lines, sandboxKey: journal.sandboxKey })
851​
852function startResponse(url: URL): Response {
853 const runId = requiredParam(url, 'runId')
854 const threadId = url.searchParams.get('threadId') ?? `thread-${runId}`
855 startAgent(runId, threadId, intParam(url, 'total', 6))
856​
857 const log = logFor(runId)
858 // ONE controller for the run and its delivery, so a client disconnect reaches
859 // `chat()`'s abort hooks. Without it `withSandbox.onAbort` never runs and
860 // nothing detaches — see the note in the spec.
861 const abortController = new AbortController()
862 driving.set(runId, abortController)
863​
864 const stream = chat({
865 adapter: harnessAdapter,
866 messages: [{ role: 'user', content: 'go' }],
867 runId,
868 threadId,
869 abortController,
870 middleware: [
871 withPersistence(persistence),
872 withLocks(locksFor(url)),
873 withSandbox(sandbox, {
874 runs,
875 instances,
876 durability: { adapter: log },
877 }),
878 ],
879 })
880​
881 // `batch: 1` so every chunk reaches the client (and the log) as it is
882 // produced: a test that disconnects mid-stream needs the prefix to be real.
883 return toServerSentEventsResponse(stream, {
884 durability: { adapter: log, batch: 1 },
885 abortController,
886 })
888​
889/**
890 * Drive an already-detached run: tail the EXISTING journal instead of starting a
891 * second agent, and align against the stored log.
892 *
893 * Shared by the attach route and the reaper on purpose. `sandboxRunDriver.drive`
894 * and `ReapOptions.drive` take the same `{ runId, threadId, signal }`, and the
895 * reaper's contract is that it drives a run the SAME way a viewer would — so a
896 * second, subtly different producer here would let the reaper specs pass against
897 * behavior the takeover specs never see.
898 */
899function driveDetachedRun(
900 input: { runId: string; threadId: string; signal: AbortSignal },
901 locks: LockStore,
902): AsyncIterable<StreamChunk> {
903 const abortController = controllerFor(input.signal)
904 driving.set(input.runId, abortController)
905 return chat({
906 adapter: harnessAdapter,
907 messages: [{ role: 'user', content: 'go' }],
908 runId: input.runId,
909 threadId: input.threadId,
910 abortController,
911 middleware: [
912 withPersistence(persistence),
913 withLocks(locks),
914 withSandbox(sandbox, {
915 runs,
916 instances,
917 durability: { adapter: logFor(input.runId), attach: true },
918 }),
919 ],
920 })
922​
923function attachResponse(request: Request, url: URL): Response {
924 const locks = locksFor(url)
925 const runId = requiredParam(url, 'runId')
926 return resumeServerSentEventsResponse({
927 adapter: memoryStream(request),
928 driver: sandboxRunDriver({
929 request,
930 runs,
931 locks,
932 durability: (driven) => logFor(driven),
933 // Default is 5s; the journal only advances on an explicit tick, so a short
934 // window keeps the suite fast without weakening what it proves.
935 fenceQuietMs: intParam(url, 'fenceQuietMs', 50),
936 drive: (input) => driveDetachedRun(input, locks),
937 }),
938 headers: { 'X-Run-Id': runId },
939 })
941​
942// ---------------------------------------------------------------------------
943// The reaper sweep.
944// ---------------------------------------------------------------------------
945​
946/**
947 * The run store the reaper is allowed to SELECT from, narrowed to the runIds the
948 * request named.
949 *
950 * `reapDetachedRuns` sweeps every detached run `listReclaimable` surfaces, and
951 * this suite is `fullyParallel` over one shared store — an unscoped sweep would
952 * cancel and drive other tests' detached runs, and a future `now` would expire
953 * them all. Narrowing the CANDIDATE LIST and nothing else keeps a sweep an
954 * assertion about the runs one test constructed, which is also why the spec
955 * asserts `considered`: a sweep over an empty candidate list satisfies every "the
956 * reaper did not touch this" assertion, and that exact false pass is what the
957 * leave-alone halves exist to rule out.
958 */
959function runsScopedTo(runIds: Array<string>): typeof runs {
960 return {
961 createOrResume: (input) => runs.createOrResume(input),
962 update: (runId, patch) => runs.update(runId, patch),
963 get: (runId) => runs.get(runId),
964 findActiveRun: (threadId) => runs.findActiveRun(threadId),
965 listReclaimable: async (opts) => {
966 const listed = (await runs.listReclaimable?.(opts)) ?? []
967 return listed.filter((record) => runIds.includes(record.runId))
968 },
969 }
971​
972/**
973 * The out-of-band exit probe, wired to the REAL {@link probeRunExit} against this
974 * run's own sandbox handle.
975 *
976 * `ReapOptions.hasFinished` is injected precisely so this is the application's
977 * job: the delivery log stops growing when the viewer leaves while the journal
978 * keeps growing, and only the application can turn a `sandboxKey` into a handle.
979 * A run with no `sandboxKey` therefore answers `'unknown'` — never `'finished'`,
980 * which would have the reaper drive a live run.
981 */
982function probeFor(record: RunRecord): Promise<RunExitProbe> {
983 const sandboxKey = record.sandboxKey
984 if (sandboxKey === undefined) return Promise.resolve({ state: 'unknown' })
985 return probeRunExit({ handle: fakeHandle(sandboxKey), runId: record.runId })
987​
988interface ReapBody {
989 reap: ReapResult
990 /** One journal-directory sweep per sandbox the named runs live in. */
991 prune: Array<{ sandboxKey: string; result: PruneJournalsResult }>
993​
994/**
995 * One reaper sweep plus the journal sweep that follows it, over the runIds the
996 * request named (repeat `runId` to sweep several in ONE pass).
997 *
998 * `now` is injected rather than read, which is what makes the TTL boundary
999 * deterministic without a fake clock anywhere: `ReapOptions.now` and
1000 * `detachedRunTtlMs` are explicit parameters, and `?action=seed` injects
1001 * `detachedSince`, so a spec supplies both sides of `detachedSince <= now - ttl`.
1003 * `pruneJournals` runs AFTER the sweep and per sandbox, because it asks the store
1004 * whether each journal's run is terminal — the sweep is what makes a finalized
1005 * run's answer `terminal`, so running it first would report every journal as
1006 * `'non-terminal'` and prove nothing.
1007 */
1008async function reapResponse(url: URL): Promise<Response> {
1009 const runIds = url.searchParams.getAll('runId').filter((id) => id.length > 0)
1010 if (runIds.length === 0) {
1011 throw new Error('durable-takeover: reap requires at least one runId')
1013 const now = intParam(url, 'now', Date.now())
1014 const locks = locksFor(url)
1015 const rawBudget = url.searchParams.get('runBudgetMs')
1016​
1017 const reap = await reapDetachedRuns({
1018 runs: runsScopedTo(runIds),
1019 locks,
1020 durability: (runId) => logFor(runId),
1021 hasFinished: probeFor,
1022 drive: (input) => driveDetachedRun(input, locks),
1023 now,
1024 detachedRunTtlMs: DETACHED_RUN_TTL_MS,
1025 ...(rawBudget === null
1026 ? {}
1027 : { runBudgetMs: intParam(url, 'runBudgetMs', 0) }),
1028 fenceQuietMs: intParam(url, 'fenceQuietMs', 50),
1029 reclaim: sandboxReclaimer({ provider, instances }),
1030 })
1031​
1032 const sandboxKeys = [
1033 ...new Set(
1034 runIds
1035 .map((runId) => journals.get(runId)?.sandboxKey)
1036 .filter((key): key is string => key !== undefined),
1037 ),
1039 const prune: ReapBody['prune'] = []
1040 for (const sandboxKey of sandboxKeys) {
1041 prune.push({
1042 sandboxKey,
1043 result: await pruneJournals({
1044 handle: fakeHandle(sandboxKey),
1045 runs,
1046 now,
1047 }),
1048 })
1050​
1051 const body: ReapBody = { reap, prune }
1052 return Response.json(body)
1054​
1055/**
1056 * Opt a run's translator out of determinism for the rest of the process. Read on
1057 * every request so it can be set by the attach that must diverge, and never
1058 * cleared: every spec mints a unique `runId`.
1059 */
1060function applyTranslatorFlags(url: URL): void {
1061 if (url.searchParams.get('nondeterministic') !== '1') return
1062 const runId = url.searchParams.get('runId')
1063 if (runId !== null && runId.length > 0) nondeterministicRuns.add(runId)
1065​
1066export const Route = createFileRoute('/api/durable-takeover')({
1067 server: {
1068 handlers: {
1069 POST: async ({ request }) => {
1070 const url = new URL(request.url)
1071 applyTranslatorFlags(url)
1072 const action = url.searchParams.get('action')
1073 if (action === 'reap') return reapResponse(url)
1074 if (action === 'tick') {
1075 const runId = requiredParam(url, 'runId')
1076 return Response.json({
1077 journal: tickAgent(runId, intParam(url, 'n', 1)) ?? null,
1078 })
1080 if (action === 'drop') return dropResponse(url)
1081 if (action === 'cancel') return cancelResponse(url)
1082 if (action === 'seed') return seedResponse(url)
1083 return startResponse(url)
1084 },
1085 GET: async ({ request }) => {
1086 const url = new URL(request.url)
1087 applyTranslatorFlags(url)
1088 if (url.searchParams.get('action') === 'state') {
1089 return stateResponse(url)
1091 return attachResponse(request, url)
1092 },
1093 },
1094 },