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

chunk-identity.ts

185 lines7.6 KB

1/**
2 * Deterministic chunk identity — the prerequisite that makes journal replay
3 * exact.
4 *
5 * The design premise is that re-translating a journal prefix reproduces the
6 * chunks a previous host already delivered, so a successor can recognize and
7 * skip them (see `align.ts`, a later task). Two things in the default path
8 * break that premise:
9 *
10 * 1. `ChatAdapter.generateId()` — `packages/ai/src/activities/chat/adapter.ts:227`,
11 * read directly for this task — is:
12 *
13 * ```ts
14 * protected generateId(): string {
15 * return `${this.name}-${Date.now()}-${Math.random().toString(36).substring(7)}`
16 * }
17 * ```
18 *
19 * and every harness translator mints message ids through it (wired as
20 * `genId` in the Grok Build, Claude Code, and Codex text adapters). Both
21 * `Date.now()` and `Math.random()` are non-reproducible: replaying the same
22 * journal bytes through a second `generateId()` call produces a different
23 * id every time, so "same bytes ⇒ same chunks" is false on the journaled
24 * path today. {@link createRunScopedIdGen} replaces it with a run-scoped
25 * counter that has neither a clock nor randomness, so two generators built
26 * from the same `runId` always produce the same sequence.
27 * 2. Chunks also carry `timestamp: Date.now()`, which cannot be reproduced at
28 * all, deterministic id or not. {@link chunkFingerprint} therefore excludes
29 * exactly that field — nothing downstream keys on a chunk's timestamp, so
30 * leaving it wall-clock is safe, but every other field must participate in
31 * the comparison or a real divergence would go undetected.
32 * 3. Adapter yields still carry leftover TanStack extras (`content`, `args`,
33 * `finishReason`). The durability log stores spec chunks. Fingerprints keep
34 * only AG-UI spec keys and drop `metadata.tanstack`, so a live adapter yield
35 * matches the stored spec chunk.
36 */
37import type { StreamChunk } from '@tanstack/ai'
38import {
39 isSpecTopLevelKey,
40 tanstackMetadata,
41} from '@tanstack/ai/adapter-internals'
42​
43/**
44 * A deterministic id generator scoped to one run.
45 *
46 * Passed as the harness translators' `genId`, so translating the same journal
47 * prefix twice mints the same message ids. The counter is per-generator, so a
48 * replay must create a fresh one and start from the journal's first byte —
49 * which is exactly what the alignment step (a later task) assumes.
50 *
51 * No clock, no `Math.random`, no crypto: `next` is the only state, and it is
52 * seeded fresh for every call to this factory.
53 */
54export function createRunScopedIdGen(runId: string): () => string {
55 let next = 0
56 return () => {
57 const id = `${runId}-${next}`
58 next += 1
59 return id
60 }
62​
63/**
64 * Fields excluded from a fingerprint because they are wall-clock and therefore
65 * unreproducible. Kept as an explicit set so adding one is a deliberate,
66 * reviewable act rather than a silent loosening of the comparison.
67 */
68const VOLATILE_FIELDS: ReadonlySet<string> = new Set(['timestamp'])
69​
70/**
71 * The conversation id every chunk carries. Excluded from
72 * {@link chunkFingerprintIgnoringThreadId} — and ONLY from that variant — so
73 * alignment can tell an id-only mismatch from a real content divergence.
74 */
75const THREAD_ID_FIELD = 'threadId'
76​
77const VOLATILE_AND_THREAD_ID: ReadonlySet<string> = new Set([
78 ...VOLATILE_FIELDS,
79 THREAD_ID_FIELD,
80])
81​
82/**
83 * `dropped` applies at the TOP LEVEL only (nested calls pass `undefined`).
84 * A `threadId` nested inside, say, a tool call's arguments is real content and
85 * must keep participating in the comparison.
86 */
87function stableStringify(
88 value: unknown,
89 dropped: ReadonlySet<string> | undefined,
90): string {
91 if (value === null) return 'null'
92 if (Array.isArray(value)) {
93 return `[${value.map((item) => stableStringify(item, undefined)).join(',')}]`
94 }
95 if (typeof value === 'object') {
96 const record: Record<string, unknown> = value as Record<string, unknown>
97 const keys = Object.keys(record)
98 .filter((key) => dropped === undefined || !dropped.has(key))
99 .sort()
100 const parts = keys.map((key) => {
101 const entry = record[key]
102 const encoded =
103 entry === undefined
104 ? '"__undefined__"'
105 : stableStringify(entry, undefined)
106 return `${JSON.stringify(key)}:${encoded}`
107 })
108 return `{${parts.join(',')}}`
109 }
110 const encoded = JSON.stringify(value)
111 return encoded === undefined ? 'null' : encoded
113​
114/**
115 * A stable, order-independent identity for a chunk, excluding wall-clock
116 * fields. Used to recognize the chunks a previous host already appended.
117 *
118 * - **Key-order independent**: object keys are sorted before stringifying, so
119 * a JSON round trip through the journal (which does not preserve key order)
120 * cannot spuriously diverge.
121 * - **Recurses into nested arrays and objects**: tool-call arguments are
122 * nested, and a shallow fingerprint would miss a changed argument.
123 * - **Excludes `timestamp` and leftover adapter extras.** Spec keys
124 * participate, including `undefined` values. `metadata.tanstack` is dropped
125 * so stored spec chunks match live adapter yields.
126 * - **Distinguishes present-but-`undefined` from absent**: `undefined` is
127 * encoded as the sentinel string `"__undefined__"` rather than dropped, so
128 * `{a: undefined}` and `{}` do not collide. A translator emitting an
129 * explicit `undefined` is a different chunk shape and must fingerprint
130 * differently.
131 */
132function fingerprintableChunk(chunk: StreamChunk): Record<string, unknown> {
133 const out: Record<string, unknown> = {}
134 for (const [key, value] of Object.entries(chunk)) {
135 if (key === 'timestamp') continue
136 if (!isSpecTopLevelKey(chunk.type, key)) continue
137 if (key === 'metadata' && value != null && typeof value === 'object') {
138 const rest: Record<string, unknown> = {}
139 for (const [metaKey, metaValue] of Object.entries(value)) {
140 if (metaKey === 'tanstack') continue
141 rest[metaKey] = metaValue
142 }
143 if (Object.keys(rest).length === 0) continue
144 out.metadata = rest
145 continue
146 }
147 out[key] = value
148 }
149 return out
151​
152export function chunkFingerprint(chunk: StreamChunk): string {
153 return stableStringify(fingerprintableChunk(chunk), VOLATILE_FIELDS)
155​
156/**
157 * {@link chunkFingerprint} with the chunk's own `threadId` also excluded.
158 *
159 * NOT an alternative identity — never use it to decide that two chunks are the
160 * same. Its single purpose is DIAGNOSIS: when a replay diverges from the stored
161 * log, comparing both fingerprints answers "did the agent behave differently, or
162 * did only the conversation id move?". Two chunks that match here but not under
163 * {@link chunkFingerprint} differ in `threadId` and nothing else, which is a
164 * misconfigured attach route rather than a determinism regression (see
165 * `JournalReplayThreadIdMismatchError` in `align.ts`).
166 */
167export function chunkFingerprintIgnoringThreadId(chunk: StreamChunk): string {
168 return stableStringify(fingerprintableChunk(chunk), VOLATILE_AND_THREAD_ID)
170​
171/**
172 * A chunk's own `threadId`, or `undefined` when it carries none.
173 *
174 * Reads the field structurally rather than narrowing on `chunk.type`: nearly
175 * every member of the `StreamChunk` union declares `threadId?: string`, and an
176 * exhaustive switch would have to be revisited for each new member while adding
177 * nothing — a chunk with no `threadId` is exactly the `undefined` case.
178 */
179export function chunkThreadId(chunk: StreamChunk): string | undefined {
180 const record: Record<string, unknown> = chunk as Record<string, unknown>
181 const value = record[THREAD_ID_FIELD]
182 if (typeof value === 'string') return value
183 const nested = tanstackMetadata(chunk)?.threadId
184 return typeof nested === 'string' ? nested : undefined