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

align.ts

296 lines12.5 KB

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
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 }
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 caller's `threadId` lands in every emitted chunk — so
97 * an attach route that passes a different `threadId` than the run record's
98 * fails alignment at the very first chunk (`RUN_STARTED`). The agent behaved
99 * identically; only the id moved. Reported as a
100 * generic divergence, that sends the reader hunting for non-determinism in the
101 * translator, which is the wrong place entirely.
102 *
103 * A SUBCLASS of {@link JournalReplayDivergedError}, deliberately: this is still a
104 * divergence and still fatal, so a consumer already branching on the general
105 * class keeps working. The two are not collapsed — a genuine content divergence
106 * throws the base class, so `instanceof JournalReplayThreadIdMismatchError`
107 * separates a config mistake from a determinism bug in exactly one check.
108 */
109export class JournalReplayThreadIdMismatchError extends JournalReplayDivergedError {
110 constructor(
111 index: number,
112 stored: string,
113 replayed: string,
114 readonly storedThreadId: string | undefined,
115 readonly replayedThreadId: string | undefined,
116 ) {
117 super(index, stored, replayed)
118 this.name = 'JournalReplayThreadIdMismatchError'
119 this.message =
120 `journal replay diverged at index ${index} ONLY by threadId: stored ${JSON.stringify(storedThreadId)} but replayed ${JSON.stringify(replayedThreadId)}. ` +
121 `Every other field of the chunk is identical, so the agent did NOT behave differently — the attaching run used a different threadId than the run record's. ` +
122 `Pass the run record's threadId (RunRecord.threadId, which sandboxRunDriver hands to drive({ runId, threadId, signal })) into chat() on the attach route; ` +
123 `with any other id, every chunk carries an id the stored log cannot match.`
124 }
126​
127/**
128 * Classify a mismatch before throwing.
129 *
130 * The `threadId`-only case is recognized by comparing the two chunks a SECOND
131 * time with `threadId` excluded: equal there and unequal under the real
132 * fingerprint means `threadId` is the only field that moved. Cheap, because it
133 * runs only on the failure path, and precise, because it is derived from the same
134 * fingerprint function rather than a hand-written field diff.
135 */
136function divergenceError(
137 index: number,
138 storedChunk: StreamChunk,
139 replayedChunk: StreamChunk,
140 stored: string,
141 replayed: string,
142): JournalReplayDivergedError {
143 const storedThreadId = chunkThreadId(storedChunk)
144 const replayedThreadId = chunkThreadId(replayedChunk)
145 if (
146 storedThreadId !== replayedThreadId &&
147 chunkFingerprintIgnoringThreadId(storedChunk) ===
148 chunkFingerprintIgnoringThreadId(replayedChunk)
149 ) {
150 return new JournalReplayThreadIdMismatchError(
151 index,
152 stored,
153 replayed,
154 storedThreadId,
155 replayedThreadId,
156 )
157 }
158 return new JournalReplayDivergedError(index, stored, replayed)
160​
161export interface AlignToStoredLogOptions<TOffset extends string = string> {
162 /**
163 * The run's event log. Read from the beginning; never written here.
164 *
165 * Generic in the offset type, defaulted to `string`, for the same reason
166 * {@link RunDeps} is: a branded-cursor backend's `StreamDurability<TOffset>`
167 * is not assignable to `StreamDurability<string>`.
168 *
169 * Narrowed to `snapshot` — the only member this transform touches, as the
170 * function docs below spell out — so the capability-bus view of a log
171 * (`SandboxDurabilityLog`, which omits the offset-invariant `read`) can be
172 * passed straight through by `alignedIfAttaching`. A full `StreamDurability`
173 * still satisfies it, so no existing caller changes.
174 */
175 durability: Pick<StreamDurability<TOffset>, 'snapshot'>
176 /** Optional sink for the alignment summary. */
177 logger?: InternalLogger
178 /**
179 * Recognizes a stored chunk that the replay CANNOT reproduce, so alignment
180 * skips it instead of throwing.
181 *
182 * Absent by default, which keeps strict positional comparison: any stored
183 * chunk the replay does not produce is a determinism bug and fails loudly.
184 * Pass {@link isBridgeCustomChunk} on the harness attach path, where the
185 * previous host spliced live bridged-tool events into the log.
186 *
187 * The predicate is applied to the STORED chunk, never to the replayed one. A
188 * skipped entry is suppressed, not re-appended, so the client's view is
189 * unchanged: it already received that chunk under its own offset.
190 */
191 isOutOfBand?: (chunk: StreamChunk) => boolean
192 /**
193 * Maximum CONSECUTIVE stored chunks that may be skipped as out-of-band before
194 * alignment gives up. Reset by every match. Defaults to
195 * {@link DEFAULT_MAX_OUT_OF_BAND_SKIP}. Ignored when `isOutOfBand` is absent.
196 */
197 maxOutOfBandSkip?: number
199​
200/**
201 * Suppress the chunks already present in the event log and yield the rest.
202 *
203 * The stored prefix is read exactly once, eagerly, before the first replay
204 * chunk is pulled. Both halves of that matter:
205 *
206 * - **Exactly once**, because a second read mid-stream would race the appends
207 * the caller is making downstream of this transform and could classify a
208 * chunk this very run just appended as an already-stored one, dropping it.
209 * - **Via `snapshot()`, never `read()`**. `read` *tails*: it returns only when
210 * the log is terminalized with `close()` or the caller aborts. A takeover's
211 * log is open by definition — the host that would have closed it is the host
212 * that died — so `for await (… of read('-1'))` would never finish, and on an
213 * empty log `memoryStream` rejects a from-start join outright once its
214 * first-chunk deadline elapses. `snapshot()` is the bounded read: it resolves
215 * with what is stored right now, including while the log is still open, and
216 * resolves to `[]` for a run with nothing stored.
217 */
218export async function* alignToStoredLog<TOffset extends string = string>(
219 chunks: AsyncIterable<StreamChunk>,
220 options: AlignToStoredLogOptions<TOffset>,
221): AsyncIterable<StreamChunk> {
222 const entries = await options.durability.snapshot()
223 const stored = entries.map((entry) => chunkFingerprint(entry.chunk))
224​
225 const isOutOfBand = options.isOutOfBand
226 const maxSkip = options.maxOutOfBandSkip ?? DEFAULT_MAX_OUT_OF_BAND_SKIP
227​
228 let cursor = 0
229 let suppressed = 0
230 let skipped = 0
231 let forwarded = 0
232​
233 for await (const chunk of chunks) {
234 // Past the end of the stored log: everything from here is new.
235 if (cursor >= stored.length) {
236 forwarded += 1
237 yield chunk
238 continue
239 }
240​
241 const actual = chunkFingerprint(chunk)
242 let consecutiveSkips = 0
243 for (;;) {
244 // `entries` and `stored` are the same length by construction; both are
245 // bound because the predicate needs the CHUNK while the comparison needs
246 // its fingerprint.
247 const entry = entries[cursor]
248 const expected = stored[cursor]
249 if (entry === undefined || expected === undefined) {
250 forwarded += 1
251 yield chunk
252 break
253 }
254 if (expected === actual) {
255 cursor += 1
256 suppressed += 1
257 break
258 }
259 // Mismatch. Only a stored chunk the replay provably cannot reproduce may
260 // be skipped, and only `maxSkip` of them in a row.
261 if (isOutOfBand === undefined || !isOutOfBand(entry.chunk)) {
262 throw divergenceError(cursor, entry.chunk, chunk, expected, actual)
263 }
264 if (consecutiveSkips >= maxSkip) {
265 throw divergenceError(cursor, entry.chunk, chunk, expected, actual)
266 }
267 cursor += 1
268 consecutiveSkips += 1
269 skipped += 1
270 }
271 }
272​
273 // Trailing stored entries. Out-of-band ones are expected (a bridged tool's
274 // last event lands after the final translated chunk); anything else means the
275 // journal no longer accounts for chunks the log already delivered, which
276 // nothing downstream can repair.
277 while (cursor < stored.length) {
278 const entry = entries[cursor]
279 if (
280 entry === undefined ||
281 isOutOfBand === undefined ||
282 !isOutOfBand(entry.chunk)
283 ) {
284 throw new Error(
285 `journal replay is shorter than the stored log: ${stored.length - cursor} stored chunk(s) from index ${cursor} were not reproduced`,
286 )
287 }
288 cursor += 1
289 skipped += 1
290 }
291​
292 options.logger?.provider(
293 `journal alignment: suppressed ${suppressed} stored chunk(s), skipped ${skipped} out-of-band, forwarded ${forwarded}`,
294 { suppressed, skipped, forwarded },
295 )