Open History to see the last commit
1/**
2 * Determinism of the codex translator on the journaled path.
3 *
4 * WHAT THIS COVERS: `translateThreadEvents` mints message ids only through
5 * `ctx.genId` (used for `TOOL_CALL_RESULT.messageId`, both the resolved-item
6 * path and `synthesizeUnresolvedResults`). Replaying the exact same journal
7 * bytes through a fresh `createRunScopedIdGen(runId)` each time must produce
8 * an identical chunk sequence (compared via `chunkFingerprint`, which drops
9 * only the wall-clock `timestamp` field) — this is the load-bearing property
10 * `alignToStoredLog` (a later phase) depends on to recognize what a previous
11 * host already delivered and suppress it.
12 *
13 * WHAT THIS DOES NOT COVER: in the real adapter
14 * (`packages/ai-codex/src/adapters/text.ts`), `translateThreadEvents`'s
15 * output is not what gets delivered on its own — it is piped through
16 * `mergeChunkStreams(translated, channel.stream)`, where `channel.stream`
17 * carries CUSTOM events from the host-tool-bridge, produced by *live* tool
18 * execution. On a journal replay:
19 * 1. No live tools run, so those bridged events do not occur at all.
20 * 2. Even for the original run, where they interleave relative to the
21 * translated chunks is timing-dependent, not something recoverable
22 * from the journal.
23 * So a deterministic translator (proven here) does NOT imply the adapter's
24 * actually-delivered, post-merge stream is deterministic for any run that
25 * used bridged tools. This test only exercises `translateThreadEvents` in
26 * isolation and intentionally makes no claim about `mergeChunkStreams`
27 * output — that gap is left open for Phase 3 to scope, not fixed here.
28 */
29import { afterAll, describe, expect, it } from 'vitest'
30import * as fsp from 'node:fs/promises'
31import * as os from 'node:os'
32import * as path from 'node:path'
33import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
34import {
35 SandboxCapability,
36 chunkFingerprint,
37 createRunScopedIdGen,
38 journalPaths,
39 provideSandboxDurability,
40} from '@tanstack/ai-sandbox'
41import { InMemoryRunStore } from '@tanstack/ai'
42import { codexText } from '../src/index'
43import { translateThreadEvents } from '../src/stream/translate'
44import type { InternalLogger } from '@tanstack/ai/adapter-internals'
45import type {
46 CapabilityContext,
47 AdapterYieldChunk,
48 StreamDurability,
49} from '@tanstack/ai'
50import type { SandboxHandle } from '@tanstack/ai-sandbox'
51import type { CodexThreadEvent } from '../src/stream/sdk-types'
52
53/**
54 * Real codex thread-event shapes, copied from `tests/translate.test.ts` and
55 * `src/stream/sdk-types.ts` (not invented): a session start, a command
56 * execution that starts and completes (exercising the TOOL_CALL_RESULT path
57 * that calls `genId()`), an assistant message, and turn completion.
58 */
59const JOURNAL_EVENTS: Array<CodexThreadEvent> = [
60 { type: 'thread.started', thread_id: 'sess-1' },
61 { type: 'turn.started' },
62 {
63 type: 'item.started',
64 item: {
65 id: 'cmd-1',
66 type: 'command_execution',
67 command: 'ls',
68 status: 'in_progress',
69 },
70 },
71 {
72 type: 'item.completed',
73 item: {
74 id: 'cmd-1',
75 type: 'command_execution',
76 command: 'ls',
77 aggregated_output: 'file.txt\n',
78 exit_code: 0,
79 status: 'completed',
80 },
81 },
82 {
83 type: 'item.completed',
84 item: { id: 'item-1', type: 'agent_message', text: 'Done.' },
85 },
86 {
87 type: 'turn.completed',
88 usage: { input_tokens: 10, output_tokens: 5 },
89 },
90]
91
92async function* replay(): AsyncIterable<CodexThreadEvent> {
93 for (const event of JOURNAL_EVENTS) {
94 // Mirrors the async, one-event-at-a-time delivery a journal reader
95 // provides — not a synchronous array iteration.
96 await Promise.resolve()
97 yield event
98 }
99}
100
101async function fingerprintRun(genId: () => string): Promise<Array<string>> {
102 const out: Array<string> = []
103 const chunks: AsyncIterable<AdapterYieldChunk> = translateThreadEvents(
104 replay(),
105 {
106 model: 'gpt-5.1-codex',
107 runId: 'run-1',
108 threadId: 'thread-1',
109 genId,
110 },
111 )
112 for await (const chunk of chunks) out.push(chunkFingerprint(chunk))
113 return out
114}
115
116describe('codex translation determinism (journaled path)', () => {
117 it('produces the identical chunk sequence when the same journal is replayed twice', async () => {
118 // This is the load-bearing property of journal replay: without it,
119 // alignToStoredLog cannot recognize what a previous host already
120 // delivered, and a resume would duplicate or corrupt output (see the
121 // Phase 2 plan's "Reason 2" for why non-determinism kills the replay
122 // mechanism outright).
123 const first = await fingerprintRun(createRunScopedIdGen('run-1'))
124 const second = await fingerprintRun(createRunScopedIdGen('run-1'))
125 expect(first.length).toBeGreaterThan(0)
126 expect(second).toEqual(first)
127 })
128
129 it('diverges when genId is NOT run-scoped, proving the test has teeth', async () => {
130 const randomGenId = (): string =>
131 `${Math.random().toString(36)}-${Date.now()}`
132 const first = await fingerprintRun(randomGenId)
133 const second = await fingerprintRun(randomGenId)
134 expect(first).not.toEqual(second)
135 })
136})
137
138// --- Wiring check: the actual adapter call site (not just the translator) ---
139//
140// The two tests above exercise `translateThreadEvents` directly with a
141// generator we construct ourselves, so they cannot catch a regression at the
142// `chatStreamNdjson`/`chatStream` call site in `../src/adapters/text.ts`
143// (e.g. reverting `genId: createRunScopedIdGen(runId)` back to
144// `genId: () => this.generateId()`). This block runs the real adapter, via
145// the same `localProcessSandbox` harness `text-adapter.test.ts` uses, and
146// asserts:
147// 1. message ids follow the `${runId}-N` shape `createRunScopedIdGen`
148// produces — a shape `this.generateId()`
149// (`${name}-${Date.now()}-${random}`) never produces, and
150// 2. the sandbox journal file for this `runId` actually exists after the
151// run, proving `spawnNdjson` really was called with `journal: { runId }`
152// (not just that the adapter happened to mint run-scoped ids some other
153// way).
154
155const baseDir = path.join(
156 os.tmpdir(),
157 `tanstack-ai-codex-determinism-test-${Date.now()}`,
158)
159const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
160
161afterAll(async () => {
162 try {
163 await fsp.rm(baseDir, { recursive: true, force: true })
164 } catch {
165 // Windows can report EBUSY here when a child process handle briefly
166 // outlives `sbx.destroy()`; this is a cleanup nicety, not part of what
167 // the test verifies, so a failure here must not fail the suite.
168 }
169})
170
171// Stand-in for `codex exec --experimental-json` that additionally emits a
172// `command_execution` item start+completion — the shape that exercises
173// `genId()` via the TOOL_CALL_RESULT path in `translateThreadEvents`
174// (see `handleItemCompleted`'s `isToolItem` branch).
175const NATIVE_FAKE_CODEX = [
176 `import { writeFileSync } from 'node:fs'`,
177 `const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
178 `w({ type: 'thread.started', thread_id: 'sess-1' })`,
179 `w({ type: 'turn.started' })`,
180 `w({ type: 'item.started', item: { id: 'cmd-1', type: 'command_execution', command: 'ls', status: 'in_progress' } })`,
181 `w({ type: 'item.completed', item: { id: 'cmd-1', type: 'command_execution', command: 'ls', aggregated_output: 'file.txt\\n', exit_code: 0, status: 'completed' } })`,
182 `w({ type: 'item.completed', item: { id: 'item-1', type: 'agent_message', text: 'pong' } })`,
183 `w({ type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1 } })`,
184].join('\n')
185
186const noopLogger = {
187 request: () => {},
188 provider: () => {},
189 errors: () => {},
190 agentLoop: () => {},
191 warnings: () => {},
192 debug: () => {},
193} as unknown as InternalLogger
194
195/**
196 * Minimal in-memory `StreamDurability`, just enough to make the sandbox
197 * durability capability resolvable (`runs` + `durability.adapter` both
198 * present) so this test can exercise the JOURNALED path. Phase 3 gates
199 * journaling on that capability rather than on `runId` alone — see
200 * `resolveDurableRunId` / `journalOptionsFor` in `@tanstack/ai-sandbox`'s
201 * `durability.ts` — so a durability-less capability context (as this file
202 * wired before Phase 3) no longer journals at all, and this test would
203 * otherwise assert a run that never touches the journal.
204 */
205function fakeStreamDurability(): StreamDurability {
206 return {
207 resumeFrom: () => null,
208 append: (chunks) => Promise.resolve(chunks.map((_, i) => String(i))),
209 read: () => (async function* () {})(),
210 close: () => Promise.resolve(),
211 snapshot: () => Promise.resolve([]),
212 }
213}
214
215function capabilityContextWith(handle: SandboxHandle): CapabilityContext {
216 const [, provideSandbox] = SandboxCapability
217 const ctx = {
218 capabilities: { markProvided: () => {}, has: () => true },
219 } as unknown as CapabilityContext
220 provideSandbox(ctx, handle)
221 // Phase 3: journaling requires the resolved sandbox-durability capability,
222 // not merely a caller-supplied `runId`. Wire it directly (rather than via
223 // `withSandbox`'s `resolveSandboxDurability`, which is intentionally not
224 // exported outside the package) so this wiring test still exercises the
225 // journaled call site.
226 provideSandboxDurability(ctx, {
227 runs: new InMemoryRunStore(),
228 adapter: fakeStreamDurability(),
229 journalDir: '/tmp/tanstack-runs',
230 attach: false,
231 detachOnDisconnect: true,
232 })
233 return ctx
234}
235
236// `@tanstack/ai-sandbox`'s journal reader picks a "follow" strategy
237// (`tail -c +N -f journal | base64`, piped through a spawned `SpawnHandle`)
238// whenever `capabilities.backgroundProcesses && capabilities.killableProcesses`
239// — true for `local-process`. On this host that pipeline's downstream
240// `base64` fully buffers its stdout (it isn't a tty and `tail -f` never
241// closes its input), so nothing is ever flushed to the reader for a payload
242// under one buffer's worth — the read hangs forever even though the journal
243// file itself is complete and correct. This is independent of anything under
244// test here (confirmed by reproducing the same hang against the plain
245// `spawnNdjson` primitive and against the already-merged
246// `ai-grok-build/tests/translate-determinism.test.ts` reference test). The
247// bounded "poll" strategy (`tail -c +N journal | base64`, no `-f`) has no such
248// problem: each poll is a one-shot process that flushes its buffer on exit.
249// `journalReadStrategy` decides purely from `handle.capabilities`, so
250// reporting `killableProcesses: false` on the handle we hand the adapter
251// steers it onto the poll path without touching `@tanstack/ai-sandbox` or
252// the adapter itself — every other operation (fs, process.exec, destroy)
253// still goes through the real local-process sandbox unchanged.
254/**
255 * Force the bounded-poll read strategy, and record every command the adapter
256 * spawns so the journal wiring can be asserted from the command itself.
257 *
258 * Recording the command is the only durable way to prove `journal: { runId }`
259 * reached `spawnNdjson`: the journal is deleted once the run reaches its
260 * `{"__exit":N}` sentinel, so by the time this test can look, a correctly
261 * journaled run and an unjournaled one both leave no file behind.
262 */
263function pollStrategyHandle(handle: SandboxHandle): {
264 handle: SandboxHandle
265 spawned: Array<string>
266} {
267 const spawned: Array<string> = []
268 return {
269 spawned,
270 handle: {
271 ...handle,
272 capabilities: { ...handle.capabilities, killableProcesses: false },
273 process: {
274 ...handle.process,
275 spawn: (command, options) => {
276 spawned.push(command)
277 return handle.process.spawn(command, options)
278 },
279 exec: (command, options) => {
280 spawned.push(command)
281 return handle.process.exec(command, options)
282 },
283 },
284 },
285 }
286}
287
288async function collect(
289 stream: AsyncIterable<AdapterYieldChunk>,
290): Promise<Array<AdapterYieldChunk>> {
291 const out: Array<AdapterYieldChunk> = []
292 for await (const chunk of stream) out.push(chunk)
293 return out
294}
295
296describe('codex chatStream wiring (real adapter, journaled call site)', () => {
297 it('mints run-scoped message ids and actually journals under the supplied runId', async () => {
298 const sbx = await provider.create({})
299 await sbx.fs.write('/workspace/fake-codex.mjs', NATIVE_FAKE_CODEX)
300 const recorder = pollStrategyHandle(sbx)
301
302 // Unique per test run: `journalPaths`'s default directory
303 // (`/tmp/tanstack-runs`) is a REAL host path shared across every
304 // `local-process` sandbox instance and every test run (unlike the rest of
305 // the sandbox filesystem, it is not virtualized under this test's own
306 // `baseDir`/`afterAll` cleanup), and the journal file itself is opened
307 // `>>` (append-only) by design — see `journaledCommand` in
308 // `@tanstack/ai-sandbox`'s `journal.ts`. A fixed literal `runId` would
309 // collide with a previous run's leftover journal file (this file
310 // survives this test's own `afterAll`) and the read would stop at
311 // that STALE run's `__exit` sentinel, silently observing 0 of this run's
312 // events. A fresh id per invocation avoids the collision.
313 const runId = `run-wiring-check-${Date.now()}-${Math.random().toString(36).slice(2)}`
314 const adapter = codexText('gpt-5.5-codex', {
315 codexExecutable: 'node fake-codex.mjs',
316 })
317
318 const chunks = await collect(
319 adapter.chatStream({
320 threadId: 'thread-1',
321 model: 'gpt-5.5-codex',
322 messages: [{ role: 'user', content: 'say pong' }],
323 logger: noopLogger,
324 runId,
325 capabilities: capabilityContextWith(recorder.handle),
326 }),
327 )
328
329 // Only `TOOL_CALL_RESULT.messageId` comes from `genId()` — the
330 // `agent_message`/text chunks above carry the codex-native item id
331 // instead (see `handleItemCompleted` in `../src/stream/translate.ts`), so
332 // asserting run-scoping across every chunk with a `messageId` field would
333 // wrongly fail on those. `command_execution` in `NATIVE_FAKE_CODEX` is
334 // exactly what exercises the `genId()`-backed path.
335 const toolResultMessageIds = chunks
336 .filter((c) => c.type === 'TOOL_CALL_RESULT')
337 .map((c) => (c as { messageId?: unknown }).messageId)
338 .filter((id): id is string => typeof id === 'string')
339
340 expect(toolResultMessageIds.length).toBeGreaterThan(0)
341 for (const id of toolResultMessageIds) {
342 expect(id).toMatch(new RegExp(`^${runId}-\\d+$`))
343 }
344
345 // Prove `spawnNdjson` was actually invoked with `journal: { runId }`, not
346 // merely that the translator happened to receive a run-scoped generator.
347 //
348 // Asserted against the spawned COMMAND rather than the journal file: the
349 // journal is deleted once the run reaches its `{"__exit":N}` sentinel, so a
350 // post-run existence check cannot distinguish a journaled run from an
351 // unjournaled one. The command is unambiguous, and it is also the thing a
352 // regression would actually change.
353 const paths = journalPaths(runId)
354 const journaled = recorder.spawned.filter((command) =>
355 command.includes(paths.journal),
356 )
357 expect(journaled.length).toBeGreaterThan(0)
358 // The agent's own output is redirected into the journal, and the reader
359 // reads that same path back.
360 expect(journaled.some((command) => command.includes('>>'))).toBe(true)
361
362 // The journal is cleaned up by the reader on the terminal sentinel, so
363 // nothing is left for this test to remove.
364 await sbx.destroy()
365 })
366})