Open History to see the last commit
1/**
2 * Replay-from-zero with log alignment: the mechanism that makes a resumed
3 * journal read idempotent.
4 *
5 * A host translates journal bytes 0..1000 and appends the resulting chunks, then
6 * dies. A successor re-reads the journal **from byte 0** and re-translates it,
7 * producing the same chunks again. This transform reads what is already in the
8 * event log, verifies that the replay reproduces it, suppresses that prefix, and
9 * passes only the remainder downstream to be appended.
10 *
11 * Why this shape rather than the offset-upsert the design sketched:
12 *
13 * - `StreamDurability.append` does not accept caller-supplied offsets, and
14 * `UpsertableStreamDurability.upsert` is deliberately **not** used here:
15 * `memoryStream.upsert` rejects any offset it did not mint itself, and
16 * `durableStream` has no `upsert` at all (its offsets embed a
17 * backend-assigned cursor). The journal path therefore only ever *appends*,
18 * and this function's whole job is deciding where that append starts. Do not
19 * "simplify" it into an `upsert` — the recommended production adapter cannot
20 * accept one.
21 * - Even if it could, re-translation is only reproducible because
22 * `createRunScopedIdGen` makes it so. The dedupe boundary therefore has to be
23 * *derived from the log*, not tracked beside it — which also means there is no
24 * window in which a checkpoint and the log can disagree, because the log is
25 * the checkpoint.
26 * - The log stays append-only with strictly increasing offsets. That is what
27 * `durableStream`'s backend enforces and what the client's offset de-dup
28 * (`ai-client`'s `seen` set) relies on — the client is NOT tolerant of a
29 * duplicated text or tool-argument delta.
30 *
31 * Divergence is a bug, not a condition to recover from, so it throws.
32 */
33import { EventType } from '@tanstack/ai'
34import {
35 chunkFingerprint,
36 chunkFingerprintIgnoringThreadId,
37 chunkThreadId,
38} from './chunk-identity'
39import type { InternalLogger } from '@tanstack/ai/adapter-internals'
40import type { StreamChunk, StreamDurability } from '@tanstack/ai'
41
42/**
43 * Default bound on consecutive stored chunks alignment will skip as out-of-band.
44 *
45 * A bound is what keeps this a tolerance rather than a search. Unbounded, a
46 * genuine determinism regression would make alignment scan forward through the
47 * whole log looking for a fingerprint that happens to match, suppress
48 * everything it passed, and deliver a stream whose prefix and suffix disagree —
49 * the exact failure {@link JournalReplayDivergedError} exists to prevent. 64 is
50 * well above any realistic burst of bridged console events between two
51 * translated chunks and well below a log length where a false match becomes
52 * plausible.
53 */
54export const DEFAULT_MAX_OUT_OF_BAND_SKIP = 64
55
56/**
57 * The out-of-band predicate for the harness adapters.
58 *
59 * `ai-codex` and `ai-claude-code` splice `createBridgeEventChannel`'s stream
60 * into their translated output with `mergeChunkStreams`. That channel is the
61 * only producer on the path and it emits exclusively `EventType.CUSTOM` chunks
62 * (`bridge-events.ts:53-63`), fired by LIVE bridged-tool execution. A replay
63 * runs no tools, so those chunks exist in the log and not in the replay.
64 *
65 * Structural rather than a list of event names on purpose: a new bridged tool
66 * inventing a new `name` must not silently reintroduce the divergence.
67 */
68export function isBridgeCustomChunk(chunk: StreamChunk): boolean {
69 return chunk.type === EventType.CUSTOM
70}
71
72/**
73 * The replay produced a different chunk than the log already holds at that
74 * index. Means translation stopped being deterministic — a `genId` that is not
75 * run-scoped, a translator that consults the clock, or a journal that was
76 * rewritten. Fail loud: suppressing the mismatch would deliver a stream whose
77 * prefix and suffix disagree about message identity.
78 */
79export class JournalReplayDivergedError extends Error {
80 constructor(
81 readonly index: number,
82 readonly stored: string,
83 readonly replayed: string,
84 ) {
85 super(
86 `journal replay diverged at index ${index}: stored ${stored} but replayed ${replayed}`,
87 )
88 this.name = 'JournalReplayDivergedError'
89 }
90}
91
92/**
93 * The replay reproduced the stored chunk EXACTLY except for its `threadId`.
94 *
95 * A distinct diagnosis because the cause and the fix are entirely different from
96 * a real divergence. The adapters resolve `threadId` as
97 * `options.threadId ?? this.generateId()`, and that id lands in every emitted
98 * chunk — so an attach route that drives a run without passing the run record's
99 * `threadId` mints a fresh one, and the very first chunk (`RUN_STARTED`) fails
100 * alignment. The agent behaved identically; only the id moved. Reported as a
101 * generic divergence, that sends the reader hunting for non-determinism in the
102 * translator, which is the wrong place entirely.
103 *
104 * A SUBCLASS of {@link JournalReplayDivergedError}, deliberately: this is still a
105 * divergence and still fatal, so a consumer already branching on the general
106 * class keeps working. The two are not collapsed — a genuine content divergence
107 * throws the base class, so `instanceof JournalReplayThreadIdMismatchError`
108 * separates a config mistake from a determinism bug in exactly one check.
109 */
110export class JournalReplayThreadIdMismatchError extends JournalReplayDivergedError {
111 constructor(
112 index: number,
113 stored: string,
114 replayed: string,
115 readonly storedThreadId: string | undefined,
116 readonly replayedThreadId: string | undefined,
117 ) {
118 super(index, stored, replayed)
119 this.name = 'JournalReplayThreadIdMismatchError'
120 this.message =
121 `journal replay diverged at index ${index} ONLY by threadId: stored ${JSON.stringify(storedThreadId)} but replayed ${JSON.stringify(replayedThreadId)}. ` +
122 `Every other field of the chunk is identical, so the agent did NOT behave differently — the attaching run generated a new threadId instead of reusing the run record's. ` +
123 `Pass the run record's threadId (RunRecord.threadId, which sandboxRunDriver hands to drive({ runId, threadId, signal })) into chat() on the attach route; ` +
124 `without it the adapter falls back to generateId() and every chunk carries an id the stored log cannot match.`
125 }
126}
127
128/**
129 * Classify a mismatch before throwing.
130 *
131 * The `threadId`-only case is recognized by comparing the two chunks a SECOND
132 * time with `threadId` excluded: equal there and unequal under the real
133 * fingerprint means `threadId` is the only field that moved. Cheap, because it
134 * runs only on the failure path, and precise, because it is derived from the same
135 * fingerprint function rather than a hand-written field diff.
136 */
137function divergenceError(
138 index: number,
139 storedChunk: StreamChunk,
140 replayedChunk: StreamChunk,
141 stored: string,
142 replayed: string,
143): JournalReplayDivergedError {
144 const storedThreadId = chunkThreadId(storedChunk)
145 const replayedThreadId = chunkThreadId(replayedChunk)
146 if (
147 storedThreadId !== replayedThreadId &&
148 chunkFingerprintIgnoringThreadId(storedChunk) ===
149 chunkFingerprintIgnoringThreadId(replayedChunk)
150 ) {
151 return new JournalReplayThreadIdMismatchError(
152 index,
153 stored,
154 replayed,
155 storedThreadId,
156 replayedThreadId,
157 )
158 }
159 return new JournalReplayDivergedError(index, stored, replayed)
160}
161
162export interface AlignToStoredLogOptions<TOffset extends string = string> {
163 /**
164 * The run's event log. Read from the beginning; never written here.
165 *
166 * Generic in the offset type, defaulted to `string`, for the same reason
167 * {@link RunDeps} is: a branded-cursor backend's `StreamDurability<TOffset>`
168 * is not assignable to `StreamDurability<string>`.
169 *
170 * Narrowed to `snapshot` — the only member this transform touches, as the
171 * function docs below spell out — so the capability-bus view of a log
172 * (`SandboxDurabilityLog`, which omits the offset-invariant `read`) can be
173 * passed straight through by `alignedIfAttaching`. A full `StreamDurability`
174 * still satisfies it, so no existing caller changes.
175 */
176 durability: Pick<StreamDurability<TOffset>, 'snapshot'>
177 /** Optional sink for the alignment summary. */
178 logger?: InternalLogger
179 /**
180 * Recognizes a stored chunk that the replay CANNOT reproduce, so alignment
181 * skips it instead of throwing.
182 *
183 * Absent by default, which keeps strict positional comparison: any stored
184 * chunk the replay does not produce is a determinism bug and fails loudly.
185 * Pass {@link isBridgeCustomChunk} on the harness attach path, where the
186 * previous host spliced live bridged-tool events into the log.
187 *
188 * The predicate is applied to the STORED chunk, never to the replayed one. A
189 * skipped entry is suppressed, not re-appended, so the client's view is
190 * unchanged: it already received that chunk under its own offset.
191 */
192 isOutOfBand?: (chunk: StreamChunk) => boolean
193 /**
194 * Maximum CONSECUTIVE stored chunks that may be skipped as out-of-band before
195 * alignment gives up. Reset by every match. Defaults to
196 * {@link DEFAULT_MAX_OUT_OF_BAND_SKIP}. Ignored when `isOutOfBand` is absent.
197 */
198 maxOutOfBandSkip?: number
199}
200
201/**
202 * Suppress the chunks already present in the event log and yield the rest.
203 *
204 * The stored prefix is read exactly once, eagerly, before the first replay
205 * chunk is pulled. Both halves of that matter:
206 *
207 * - **Exactly once**, because a second read mid-stream would race the appends
208 * the caller is making downstream of this transform and could classify a
209 * chunk this very run just appended as an already-stored one, dropping it.
210 * - **Via `snapshot()`, never `read()`**. `read` *tails*: it returns only when
211 * the log is terminalized with `close()` or the caller aborts. A takeover's
212 * log is open by definition — the host that would have closed it is the host
213 * that died — so `for await (… of read('-1'))` would never finish, and on an
214 * empty log `memoryStream` rejects a from-start join outright once its
215 * first-chunk deadline elapses. `snapshot()` is the bounded read: it resolves
216 * with what is stored right now, including while the log is still open, and
217 * resolves to `[]` for a run with nothing stored.
218 */
219export async function* alignToStoredLog<TOffset extends string = string>(
220 chunks: AsyncIterable<StreamChunk>,
221 options: AlignToStoredLogOptions<TOffset>,
222): AsyncIterable<StreamChunk> {
223 const entries = await options.durability.snapshot()
224 const stored = entries.map((entry) => chunkFingerprint(entry.chunk))
225
226 const isOutOfBand = options.isOutOfBand
227 const maxSkip = options.maxOutOfBandSkip ?? DEFAULT_MAX_OUT_OF_BAND_SKIP
228
229 let cursor = 0
230 let suppressed = 0
231 let skipped = 0
232 let forwarded = 0
233
234 for await (const chunk of chunks) {
235 // Past the end of the stored log: everything from here is new.
236 if (cursor >= stored.length) {
237 forwarded += 1
238 yield chunk
239 continue
240 }
241
242 const actual = chunkFingerprint(chunk)
243 let consecutiveSkips = 0
244 for (;;) {
245 // `entries` and `stored` are the same length by construction; both are
246 // bound because the predicate needs the CHUNK while the comparison needs
247 // its fingerprint.
248 const entry = entries[cursor]
249 const expected = stored[cursor]
250 if (entry === undefined || expected === undefined) {
251 forwarded += 1
252 yield chunk
253 break
254 }
255 if (expected === actual) {
256 cursor += 1
257 suppressed += 1
258 break
259 }
260 // Mismatch. Only a stored chunk the replay provably cannot reproduce may
261 // be skipped, and only `maxSkip` of them in a row.
262 if (isOutOfBand === undefined || !isOutOfBand(entry.chunk)) {
263 throw divergenceError(cursor, entry.chunk, chunk, expected, actual)
264 }
265 if (consecutiveSkips >= maxSkip) {
266 throw divergenceError(cursor, entry.chunk, chunk, expected, actual)
267 }
268 cursor += 1
269 consecutiveSkips += 1
270 skipped += 1
271 }
272 }
273
274 // Trailing stored entries. Out-of-band ones are expected (a bridged tool's
275 // last event lands after the final translated chunk); anything else means the
276 // journal no longer accounts for chunks the log already delivered, which
277 // nothing downstream can repair.
278 while (cursor < stored.length) {
279 const entry = entries[cursor]
280 if (
281 entry === undefined ||
282 isOutOfBand === undefined ||
283 !isOutOfBand(entry.chunk)
284 ) {
285 throw new Error(
286 `journal replay is shorter than the stored log: ${stored.length - cursor} stored chunk(s) from index ${cursor} were not reproduced`,
287 )
288 }
289 cursor += 1
290 skipped += 1
291 }
292
293 options.logger?.provider(
294 `journal alignment: suppressed ${suppressed} stored chunk(s), skipped ${skipped} out-of-band, forwarded ${forwarded}`,
295 { suppressed, skipped, forwarded },
296 )
297}