Open History to see the last commit
1/**
2 * The gate that turns a HOPELESS attach into an error instead of an infinite
3 * wait.
4 *
5 * `journalFollowCommand` creates the journal before tailing it (`: >> file`),
6 * because `tail -f` on a missing path prints a diagnostic and EXITS rather than
7 * waiting — a defect that made a legitimate attach racing the driver's first
8 * write deliver zero lines. But creating the file has a cost: an attach for a
9 * `runId` that never had a journal creates an EMPTY one and tails it forever. No
10 * `{"__exit":N}` sentinel can ever arrive, so the caller waits indefinitely with
11 * no error, no timeout, and no log line — for what is the single most likely
12 * mistake on this path (a stale link, a typo, a run whose journal was cleaned up
13 * after completing).
14 *
15 * Absence of the journal alone cannot decide the question, which is exactly why
16 * `: >> file` exists: "not written YET" and "will never be written" look
17 * identical on the filesystem. The RUN RECORD is what distinguishes them, and it
18 * is authoritative — `runs.get(runId)` says whether the run exists at all,
19 * whether it is terminal, and (via `detachedSince`) whether anyone is expected
20 * to be driving it. So the policy is:
21 *
22 * | journal | record | decision |
23 * | --------- | ----------------------- | ------------------------------------- |
24 * | exists | (not consulted) | attach, under the reader's own bound |
25 * | absent | unknown (`null`) | fail fast, `'unknown-run'` |
26 * | absent | terminal | fail fast, `'terminal-run'` |
27 * | absent | running / interrupted | BOUNDED wait, then `'journal-timeout'`|
28 * | unusable | running / interrupted | BOUNDED wait, then `'journal-timeout'`|
29 *
30 * Four deliberate choices in that table:
31 *
32 * 1. **An existing journal short-circuits this gate**, before the store is read
33 * at all — because gating it would make a perfectly readable journal
34 * unreadable whenever a store lost its record. It does NOT mean the read is
35 * unbounded: this module used to justify the short-circuit with "a journal
36 * that exists either carries a sentinel or is still being appended to, neither
37 * hangs", and that trichotomy was FALSE. `journalFollowCommand`'s first act is
38 * `: >> file`, so the reader itself manufactures the third state — a file that
39 * exists, receives nothing, and can never receive a sentinel — and the same
40 * state is independently reachable by SIGKILL/OOM of the agent's shell before
41 * its `printf`. The bound for it lives where it belongs, on the read:
42 * `journal-reader.ts` fails a follow/poll that receives no bytes at all within
43 * {@link DEFAULT_ATTACH_JOURNAL_WAIT_MS} with `'journal-stalled'`.
44 * 2. **A terminal record with no journal fails rather than waiting.** Nothing
45 * will ever be appended: the run is over and `journalCleanupCommand` deletes a
46 * terminal run's files by design. Its transcript lives in the event log, which
47 * the resume response serves independently of this path.
48 * 3. **A live or detached record waits, but not forever.** A driver that has
49 * claimed the run and not yet written its first line is the normal case, not
50 * the unlucky one, so failing fast here would break the very race
51 * `journalFollowCommand` was fixed to tolerate. `detachedSince` does NOT
52 * change the decision — a detached run's journal is exactly what a successor
53 * is supposed to read, and a driver that died before its first write leaves an
54 * identical filesystem state — but it IS reported in the timeout message,
55 * since "detached with no journal after N ms" and "attached with no journal
56 * after N ms" point at different causes.
57 * 4. **An UNUSABLE probe falls through to the bounded wait; it does not skip the
58 * gate.** This module used to fail open here — `if (existence === 'unknown')
59 * return` — on the reasoning that a diagnostic gate must not break an attach
60 * that would otherwise have worked. That reasoning inverted the actual risk.
61 * Returning handed control to a reader whose very first act CREATES the
62 * journal (`journalFollowCommand`'s `: >> file`) and then tails it forever, so
63 * the fail-open path did not preserve a working attach — it manufactured the
64 * exact infinite wait this module exists to prevent. Worse, it was
65 * self-perpetuating: the file it created made `test -f` succeed from then on,
66 * so every LATER attach short-circuited at choice 1 and hung too, permanently,
67 * long after the transient probe failure had cleared. An unanswerable probe is
68 * precisely when a deadline matters most, so an unusable probe is re-polled
69 * (it may recover) and, failing that, times out. The store checks still run
70 * first and need no probe, so an unknown or terminal `runId` still fails fast.
71 */
72import { isTerminalRunStatus } from '@tanstack/ai'
73import { journalExistsCommand } from './journal'
74import type { JournalPaths } from './journal'
75import type { SandboxHandle } from './contracts'
76import type { InternalLogger } from '@tanstack/ai/adapter-internals'
77import type { RunRecord, RunStore } from '@tanstack/ai'
78
79/**
80 * How long an attach waits for a live run's journal to appear before failing.
81 *
82 * User-relevant, hence exported: this bounds how long an attach REQUEST can sit
83 * before it answers, so an application that fronts the attach route with its own
84 * timeout needs to know the number. Generous relative to the gap between a
85 * driver claiming a run and its first journal write (a `spawn` plus one line),
86 * and short relative to any sane HTTP timeout. Override per run with
87 * `SandboxDurabilityOptions.attachWaitMs`.
88 */
89export const DEFAULT_ATTACH_JOURNAL_WAIT_MS = 10_000
90
91/**
92 * How often the bounded wait re-probes for the journal. Not user-facing: it
93 * trades a `test -f` per interval for attach latency, and neither number is
94 * something an application tunes.
95 */
96export const DEFAULT_ATTACH_PROBE_INTERVAL_MS = 100
97
98/**
99 * Which of the three hopeless-attach cases was hit. Exported so a consumer can
100 * branch (a 404 for `'unknown-run'`, a 410 for `'terminal-run'`, a 504 for
101 * `'journal-timeout'`) instead of matching on message text.
102 */
103export type AttachUnavailableReason =
104 | 'unknown-run'
105 | 'terminal-run'
106 | 'journal-timeout'
107 /**
108 * The journal EXISTS but produced no bytes at all within the deadline, so no
109 * sentinel can be coming and the follow would tail an empty (or abandoned)
110 * file forever. Raised by `journal-reader.ts`, not by the preflight: the
111 * preflight cannot see this state, because `test -f` succeeds for it.
112 *
113 * A 504 at an attach route, exactly like `'journal-timeout'`, which is why it
114 * shares {@link JournalAttachUnavailableError} — but a distinct value, because
115 * the cause is different: `'journal-timeout'` means nobody created the
116 * journal, `'journal-stalled'` means somebody did and then stopped (a
117 * SIGKILLed agent shell, a destroyed sandbox, a reader that created the file
118 * itself on a fail-open path).
119 */
120 | 'journal-stalled'
121
122/**
123 * An attach cannot succeed, and waiting longer would not change that.
124 *
125 * One class with a {@link AttachUnavailableReason} discriminant rather than three
126 * classes: every consumer of this path handles all three cases at the same seam
127 * (the attach route), so one `instanceof` plus a `switch (error.reason)` is the
128 * shape that is actually written, while the message names the specific case for a
129 * human reading a log.
130 */
131export class JournalAttachUnavailableError extends Error {
132 constructor(
133 readonly runId: string,
134 readonly reason: AttachUnavailableReason,
135 detail: string,
136 ) {
137 super(`cannot attach to run ${runId}: ${detail}`)
138 this.name = 'JournalAttachUnavailableError'
139 }
140}
141
142/** Existence of the journal, or `'unknown'` when the probe itself failed. */
143type JournalExistence = 'yes' | 'no' | 'unknown'
144
145export interface AwaitAttachableJournalOptions {
146 /** The run's journal paths, as {@link journalPaths} derived them. */
147 paths: JournalPaths
148 /** Run id, for the store lookup and the error messages. */
149 runId: string
150 /**
151 * The authoritative run record store. Omitted only by a caller with no store
152 * wired, which loses the unknown/terminal classification but keeps the bound.
153 */
154 runs?: RunStore
155 /** Bounded wait. Defaults to {@link DEFAULT_ATTACH_JOURNAL_WAIT_MS}. */
156 waitMs?: number
157 /** Re-probe interval. Defaults to {@link DEFAULT_ATTACH_PROBE_INTERVAL_MS}. */
158 probeIntervalMs?: number
159 /**
160 * The consumer's abort. An aborted wait returns rather than throwing: the
161 * caller stopped caring, which is not a diagnosis about the run.
162 */
163 signal?: AbortSignal
164 logger?: InternalLogger
165}
166
167/**
168 * Shell `test -f`, never `handle.fs.exists` — `journal.ts` rule 3: on
169 * local-process the two resolve `/tmp` differently, so `fs.exists` would probe a
170 * path the journal was never written to and report `false` for every run.
171 */
172async function probeJournal(
173 handle: SandboxHandle,
174 options: AwaitAttachableJournalOptions,
175): Promise<JournalExistence> {
176 try {
177 const result = await handle.process.exec(
178 journalExistsCommand(options.paths),
179 )
180 return result.exitCode === 0 ? 'yes' : 'no'
181 } catch (error) {
182 options.logger?.provider(
183 `attach preflight: journal existence probe failed for run ${options.runId}; re-probing under the bounded wait rather than attaching blind`,
184 { runId: options.runId, error },
185 )
186 return 'unknown'
187 }
188}
189
190/**
191 * `null` means the store answered "no such run" — a real, actionable fact.
192 * `undefined` means there is no answer to be had (no store, or `get` threw), and
193 * the caller must not treat that as "unknown run".
194 */
195async function readRecord(
196 options: AwaitAttachableJournalOptions,
197): Promise<RunRecord | null | undefined> {
198 if (options.runs === undefined) return undefined
199 try {
200 return await options.runs.get(options.runId)
201 } catch (error) {
202 options.logger?.errors(
203 `attach preflight: reading the run record failed for run ${options.runId}`,
204 { runId: options.runId, error },
205 )
206 return undefined
207 }
208}
209
210function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
211 if (ms <= 0) return Promise.resolve()
212 return new Promise<void>((resolve) => {
213 const timer = setTimeout(finish, ms)
214 function finish(): void {
215 clearTimeout(timer)
216 signal?.removeEventListener('abort', finish)
217 resolve()
218 }
219 signal?.addEventListener('abort', finish, { once: true })
220 })
221}
222
223function describeRecord(record: RunRecord): string {
224 return record.detachedSince === undefined
225 ? `status '${record.status}' with a viewer attached`
226 : `status '${record.status}', detached since ${new Date(record.detachedSince).toISOString()}`
227}
228
229/**
230 * Resolve once the run's journal can be tailed, or reject with a
231 * {@link JournalAttachUnavailableError} explaining why it never will be.
232 *
233 * Call this BEFORE the first follow/poll read of an attach, never on a fresh
234 * run: a fresh run's journal is created by its own `journaledCommand` spawn,
235 * which has not happened yet, so gating it would fail every new run.
236 */
237export async function awaitAttachableJournal(
238 handle: SandboxHandle,
239 options: AwaitAttachableJournalOptions,
240): Promise<void> {
241 const existence = await probeJournal(handle, options)
242 if (existence === 'yes') return
243
244 const record = await readRecord(options)
245 if (record === null) {
246 throw new JournalAttachUnavailableError(
247 options.runId,
248 'unknown-run',
249 `no run record exists and the journal (${options.paths.journal}) has never been written, so nothing will ever be appended to it. ` +
250 `The runId is unknown to the RunStore — it is mistyped, from another deployment, or its record has been evicted.`,
251 )
252 }
253 if (record !== undefined && isTerminalRunStatus(record.status)) {
254 throw new JournalAttachUnavailableError(
255 options.runId,
256 'terminal-run',
257 `the run is already '${record.status}' and its journal (${options.paths.journal}) does not exist, so nothing will ever be appended to it. ` +
258 `A terminal run's transcript lives in its event log, not in a journal — serve the log instead of attaching.`,
259 )
260 }
261
262 // NOTE: no fail-open branch here. An `existence === 'unknown'` probe falls
263 // through into the bounded wait below — see choice 4 in the module doc for why
264 // returning was worse than timing out, not safer.
265 const waitMs = options.waitMs ?? DEFAULT_ATTACH_JOURNAL_WAIT_MS
266 const probeIntervalMs =
267 options.probeIntervalMs ?? DEFAULT_ATTACH_PROBE_INTERVAL_MS
268 const deadline = Date.now() + waitMs
269 let lastExistence: JournalExistence = existence
270 for (;;) {
271 const remaining = deadline - Date.now()
272 if (remaining <= 0) {
273 throw new JournalAttachUnavailableError(
274 options.runId,
275 'journal-timeout',
276 `the run record says ${record === undefined ? 'nothing (no run store is wired)' : describeRecord(record)}, ` +
277 (lastExistence === 'unknown'
278 ? `and its journal (${options.paths.journal}) could not be probed at all within ${waitMs}ms — every '${journalExistsCommand(options.paths)}' failed. ` +
279 `Attaching anyway would create that journal and tail it forever, so this fails instead. Check that the sandbox is still alive and that its exec transport works.`
280 : `but its journal (${options.paths.journal}) did not appear within ${waitMs}ms. ` +
281 `Either the driver died before writing its first line, or the journal directory does not match the one the agent was started with.`),
282 )
283 }
284 // The consumer gave up (client gone, lease lost). Returning hands control
285 // back to the reader, whose own AbortSignal handling ends the read — a
286 // caller's abort is not a diagnosis about the run.
287 if (options.signal?.aborted) return
288 await sleep(Math.min(probeIntervalMs, remaining), options.signal)
289 lastExistence = await probeJournal(handle, options)
290 if (lastExistence === 'yes') return
291 }
292}