From 5620b7acc3bf558a9f1f82e92e64c00726cb6bb7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 12:28:26 +0000 Subject: [PATCH 1/9] CONTRACT: fix(ui-server): bound a UI sync's launch and record its outcome in Activity (#4257) A probe or launch that never settled held the brain's admission entry until restart, so every later Sync got 409 with nothing running. The start is now bounded (refused as `launch_timeout`, a late launch is killed), output pipes held open past the process's exit get a short grace, the 409 names how long the hold has lasted (`heldMs`), and each UI sync is an Activity run with its exit status and last error lines plus a `ui sync failed` log line. Co-Authored-By: Claude Opus 5.5 --- .changeset/4257-bounded-ui-sync.md | 5 + docs/http-api.md | 20 +- packages/ui-server/src/app.ts | 2 +- packages/ui-server/src/routes/brain.ts | 196 ++++++++++++++---- .../tests/host-version-requirements.test.ts | 13 ++ .../ui-server/tests/sync-launch-bound.test.ts | 194 +++++++++++++++++ .../ui-server/tests/sync-reservation.test.ts | 4 +- 7 files changed, 386 insertions(+), 48 deletions(-) create mode 100644 .changeset/4257-bounded-ui-sync.md create mode 100644 packages/ui-server/tests/sync-launch-bound.test.ts diff --git a/.changeset/4257-bounded-ui-sync.md b/.changeset/4257-bounded-ui-sync.md new file mode 100644 index 0000000000..61f6e82569 --- /dev/null +++ b/.changeset/4257-bounded-ui-sync.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +A UI sync can no longer hold the brain as "already running" until the server restarts (#4257). Everything between accepting `POST /api/brain/sync` and the sync process starting (the CLI probe, the writer gate and the worker launch) is bounded at 120 seconds. Past it the stream ends with `{ type: "done", success: false, reason: "launch_timeout" }` and the next sync is accepted. A process that exits while a descendant keeps its output open releases the brain after a 10-second grace. A 409 now says how long the current sync has held the brain (`heldMs`, also in the message). Each UI sync is recorded as an Activity run (`jobName: "ui-sync"`) with its exit status and last error lines, and a failure is logged as `ui sync failed`, so the reason survives a disconnected browser. diff --git a/docs/http-api.md b/docs/http-api.md index 0490e30f89..8cf285874f 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -618,10 +618,26 @@ with `type: "done", success: false`; transport termination without done is an incomplete result, not success. One HTTP sync per canonical brain root is admitted across app instances; -concurrent attempts get 409 `{ error }` before SSE starts. The route invokes +concurrent attempts get 409 `{ error, heldMs }` before SSE starts, where +`heldMs` (additive, #4257) is how long the admitted sync has held the root and +the error text names it in seconds. The route invokes `brain sync --human`. Disconnecting the reader stops delivery but **does not cancel sync or release its reservation**; output continues draining until the -child exits. Successful sync attempts voice keyterm rebuild; a rebuild failure +child exits. + +**Bounded start (additive, #4257).** Everything between admission and the +sync process starting (the CLI version probe, the writer gate and the worker +launch) is bounded at 120 seconds. Past it the stream ends with +`{ type: "done", success: false, reason: "launch_timeout", text }`, the +reservation is released, nothing has run, and a launch that settles later is +killed. `reason` is present only on this refusal. After the child exits, its +output pipes get 10 seconds to close; a descendant holding them open no longer +holds the reservation. Each admitted sync is also an Activity run (root span +kind and origin `cron`, `jobName: "ui-sync"`, attributed to the requesting +principal) whose terminal outcome carries the exit status and the last +non-empty output lines, with the combined output tail as its `job_output` +event, so a result survives a disconnected reader. A failure also logs +`ui sync failed` with the same text on the `brain` logger. Successful sync attempts voice keyterm rebuild; a rebuild failure is progress text and does not turn successful sync into failure. A degraded rebuild (no usable core peer, or an index core cannot read) is reported as progress text and not cached. A canonical diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index eca09a8ba6..7e7b92d10b 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1183,7 +1183,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise host.prepareHistory(id, messages), diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index 518e295e56..b067c43e67 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -13,10 +13,36 @@ import { import { realpathSync } from "fs"; import { readJsonBody } from "../middleware/body-limit.js"; import { requireJson } from "../middleware/origin.js"; +import type { AppEnv } from "../app-env.js"; +import type { AwaitableActivityStore } from "../activity/store.js"; +import { observeWrite } from "../activity/store-writes.js"; + +/** + * How long a UI sync may take from admission until its process has started + * (#4257): the CLI probe, the writer gate and the worker launch. Past it the + * sync is refused by name and the brain is free again; a sync that has + * started is never bounded here. + */ +export const SYNC_LAUNCH_TIMEOUT_MS = 120_000; +/** How long a sync's output may keep its pipes open after the process has exited. */ +export const SYNC_OUTPUT_GRACE_MS = 10_000; +/** Combined output kept on a UI sync's Activity run, as a cron job keeps its own. */ +const SYNC_OUTPUT_TAIL_CHARS = 8_000; +/** Non-empty output lines named in a failed UI sync's run reason and log line. */ +const SYNC_ERROR_LINES = 5; interface BrainRoutesDeps { - /** App-owned admission state; the host boundary still coordinates repository writers. */ - syncingRoots?: Set; + /** + * App-owned admission state, each admitted canonical root with when it was + * admitted; the host boundary still coordinates repository writers. + */ + syncingRoots?: Map; + /** @internal The launch bound; {@link SYNC_LAUNCH_TIMEOUT_MS} when omitted. */ + syncLaunchTimeoutMs?: number; + /** @internal The output grace after exit; {@link SYNC_OUTPUT_GRACE_MS} when omitted. */ + syncOutputGraceMs?: number; + /** Where each UI sync records its run (#4257), as scheduled syncs do. Fail-open. */ + activity?: AwaitableActivityStore; brainCliMinimum?: string; log?: Logger; brain: BrainClient; @@ -28,13 +54,55 @@ interface BrainRoutesDeps { exec: ExecWrapperConfig; } -export function createBrainRoutes(deps: BrainRoutesDeps): Hono { +class SyncLaunchTimeout extends Error { + constructor(ms: number) { + super(`Sync did not start within ${Math.round(ms / 1000)} s (the brain's writer may be busy, or the sync worker did not start). Nothing ran; try again.`); + } +} + +/** The last few non-empty lines of a sync's output: what a failure says. */ +function lastLines(output: string, count: number): string { + return output.split("\n").map(line => line.trim()).filter(Boolean).slice(-count).join("\n"); +} + +export function createBrainRoutes(deps: BrainRoutesDeps): Hono { const { brain, brainPath, keyterms } = deps; - const syncingRoots = deps.syncingRoots ?? new Set(); + const syncingRoots = deps.syncingRoots ?? new Map(); + const launchTimeoutMs = deps.syncLaunchTimeoutMs ?? SYNC_LAUNCH_TIMEOUT_MS; + const outputGraceMs = deps.syncOutputGraceMs ?? SYNC_OUTPUT_GRACE_MS; const boundary = deps.boundary ?? createHostBoundary({ brainPath, exec: deps.exec }); let indexing: Promise | null = null; + /** + * A UI sync's Activity run (#4257), so its outcome outlives the stream: a + * reader that disconnected is exactly the one who did not see the result. + * Recording is fail-open and never stops the sync it observes. + */ + function startSyncRun(principalId: string | undefined) { + const store = deps.activity; + const unavailable = (error: unknown) => deps.log?.emit({ severityText: "WARN", body: "ui sync activity unavailable", + attributes: { error: error instanceof Error ? error.message : String(error) } }); + const runId = `ui-sync-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, spanId = `${runId}:root`; + let started = false; + if (store) { + try { + observeWrite(store.startSpan({ spanId, runId, name: "cron ui-sync", kind: "cron", origin: "cron", jobName: "ui-sync", principalId }), unavailable); + started = true; + } catch (error) { unavailable(error); } + } + return { + end(failure: string | undefined, output: string) { + if (failure !== undefined) deps.log?.emit({ severityText: "ERROR", body: "ui sync failed", attributes: { error: failure.slice(0, 2_000) } }); + if (!store || !started) return; + try { + if (output) observeWrite(store.appendEvent(spanId, "job_output", output, undefined, SYNC_OUTPUT_TAIL_CHARS), unavailable); + observeWrite(store.endSpan(spanId, failure === undefined ? { outcome: "success" } : { outcome: "error", reason: failure }), unavailable); + observeWrite(store.rollupRun(runId), unavailable); + } catch (error) { unavailable(error); } + }, + }; + } - return new Hono() + return new Hono() .get("/brain/search", async (c) => { const q = c.req.query("q"); if (!q) { @@ -115,20 +183,29 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { // brain sync spawns a nested Claude Code process that can take minutes. const syncRoot = realpathSync(brainPath); - if (syncingRoots.has(syncRoot)) { - return c.json({ error: "A sync is already running. Wait for it to finish before retrying." }, 409); + const since = syncingRoots.get(syncRoot); + if (since !== undefined) { + const heldMs = Math.max(0, Date.now() - since); + return c.json({ error: `A sync is already running (it has held the brain for ${Math.floor(heldMs / 1000)} s). Wait for it to finish before retrying.`, heldMs }, 409); } - syncingRoots.add(syncRoot); + syncingRoots.set(syncRoot, Date.now()); + const run = startSyncRun(c.get("principal")?.id); return streamSSE(c, async (stream) => { let keepalive: ReturnType | undefined; let disconnected = false; + let output = ""; + let failure: string | undefined; stream.onAbort(() => { disconnected = true; }); const send = (data: { type: string; text?: string; success?: boolean; - }) => disconnected ? Promise.resolve() : stream.writeSSE({ data: JSON.stringify(data) }) - .catch(() => { disconnected = true; }); + reason?: string; + }) => { + if (data.type === "progress" && data.text) output = (output + data.text + "\n").slice(-SYNC_OUTPUT_TAIL_CHARS); + return disconnected ? Promise.resolve() : stream.writeSSE({ data: JSON.stringify(data) }) + .catch(() => { disconnected = true; }); + }; try { await send({ type: "start", text: "Starting brain sync..." }); @@ -146,21 +223,40 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { // bash as positional args rather than interpolated into the script, so a // BRAIN_PATH containing spaces or shell metacharacters stays inert. const command = brain.cliCommand(); - if (deps.brainCliMinimum !== undefined) { - await probeBrainCliVersion(brainPath, deps.log ?? { emit() {}, enabled: () => false }, { exec: deps.exec, minimumVersion: deps.brainCliMinimum, phase: "streaming sync invocation", command, boundary }); - } - const [cliBin, ...cliArgs] = command; - // Through the host boundary (#1648): a credentialed maintenance worker - // holding the writer gate exclusively while the boundary holds. - const proc = await boundary.launch({ - // `--human`: stdout is a pipe, which would make it the JSON - // result (#290); this route streams the readable report. - argv: ["bash", "-c", '"$0" "$@" 2>&1', cliBin!, ...cliArgs, "sync", "--human"], - env: subprocessEnv("brainCli", { NO_COLOR: "1" }), - ...brainCommandClass(["sync"]), - purpose: "brain sync", - sync: true, + // Everything before the process starts is bounded (#4257): a probe or + // launch that never settles must not hold the brain until a restart. + const launching = new AbortController(); + let timedOut = false; + let timer: ReturnType | undefined; + const bound = new Promise((_, reject) => { + timer = setTimeout(() => { timedOut = true; launching.abort(); reject(new SyncLaunchTimeout(launchTimeoutMs)); }, launchTimeoutMs); }); + const start = (async () => { + if (deps.brainCliMinimum !== undefined) { + await probeBrainCliVersion(brainPath, deps.log ?? { emit() {}, enabled: () => false }, { exec: deps.exec, minimumVersion: deps.brainCliMinimum, phase: "streaming sync invocation", command, boundary, signal: launching.signal }); + } + launching.signal.throwIfAborted(); + const [cliBin, ...cliArgs] = command; + // Through the host boundary (#1648): a credentialed maintenance worker + // holding the writer gate exclusively while the boundary holds. + const proc = await boundary.launch({ + // `--human`: stdout is a pipe, which would make it the JSON + // result (#290); this route streams the readable report. + argv: ["bash", "-c", '"$0" "$@" 2>&1', cliBin!, ...cliArgs, "sync", "--human"], + env: subprocessEnv("brainCli", { NO_COLOR: "1" }), + ...brainCommandClass(["sync"]), + purpose: "brain sync", + sync: true, + signal: launching.signal, + }); + // A launch that settles after its bound was already refused: stop it. + if (timedOut) { proc.kill("SIGTERM"); void proc.exited.catch(() => {}); } + return proc; + })(); + start.catch(() => {}); + let proc: Awaited; + try { proc = await Promise.race([start, bound]); } + finally { clearTimeout(timer); } // Keep draining even when the SSE reader disconnects. The repository // stays reserved until the actual sync process has exited. @@ -171,28 +267,36 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { const reader = proc.stdout.getReader(); const decoder = new TextDecoder(); let buffer = ""; - try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - buffer += decoder.decode(value, { stream: true }); - const lines = buffer.split("\n"); - buffer = lines.pop() || ""; - for (const line of lines) { - if (line.trim()) { - await send({ type: "progress", text: line }); + const drained = (async () => { + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split("\n"); + buffer = lines.pop() || ""; + for (const line of lines) { + if (line.trim()) { + await send({ type: "progress", text: line }); + } } } - } - if (buffer.trim()) { - await send({ type: "progress", text: buffer }); - } - } catch {} finally { - clearInterval(keepalive); - } + if (buffer.trim()) { + await send({ type: "progress", text: buffer }); + } + } catch {} + })(); const exitCode = await proc.exited; - await stderrDone; + // A descendant that outlives the sync can hold its output pipes open + // (#4257): once the process has exited, its output gets a short grace + // period and the brain is released whether or not the pipes closed. + let grace: ReturnType | undefined; + const graceOver = new Promise(resolve => { grace = setTimeout(resolve, outputGraceMs); }); + await Promise.race([Promise.all([drained, stderrDone]), graceOver]); + clearTimeout(grace); + clearInterval(keepalive); + await reader.cancel().catch(() => {}); // Rebuild voice keyterms cache after a successful sync. if (exitCode === 0) { @@ -214,6 +318,9 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { }`, }); } + } else { + const tail = lastLines(output, SYNC_ERROR_LINES); + failure = `Sync failed (exit ${exitCode})${tail ? `: ${tail}` : ""}`; } await send({ @@ -223,10 +330,13 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { exitCode === 0 ? "Sync completed" : `Sync failed (exit ${exitCode})`, }); } catch (error) { - await send({ type: "done", success: false, text: error instanceof Error ? error.message : "Sync failed" }); + const text = error instanceof Error ? error.message : "Sync failed"; + failure = text; + await send({ type: "done", success: false, text, ...(error instanceof SyncLaunchTimeout ? { reason: "launch_timeout" } : {}) }); } finally { clearInterval(keepalive); syncingRoots.delete(syncRoot); + run.end(failure, output); } }); }) diff --git a/packages/ui-server/tests/host-version-requirements.test.ts b/packages/ui-server/tests/host-version-requirements.test.ts index 64e3189c33..45dc6d106e 100644 --- a/packages/ui-server/tests/host-version-requirements.test.ts +++ b/packages/ui-server/tests/host-version-requirements.test.ts @@ -1,3 +1,4 @@ +import { Database } from "bun:sqlite"; import { afterEach, describe, expect, spyOn, test } from "bun:test"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -118,6 +119,18 @@ describe("host version requirements at app startup", () => { const response = await app.fetch(new Request("http://localhost/api/brain/sync", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })); expect(await response.text()).toContain("incompatible"); expect(f.invocations().filter(args => args[0] === "sync")).toEqual([]); + // The refused UI sync is an Activity run with its failure, and a log line (#4257). + type Run = { outcome: string | null; outcome_reason: string | null }; + const read = () => { + const db = new Database(f.config.dbPath, { readonly: true }); + try { return db.query("SELECT outcome, outcome_reason FROM activity_spans WHERE job_name = 'ui-sync' AND parent_span_id IS NULL").get() as Run | null; } + finally { db.close(); } + }; + let run = read(); + for (const deadline = Date.now() + 5_000; !run?.outcome && Date.now() < deadline; run = read()) await Bun.sleep(10); + expect(run, "APP_UI_SYNC_RUN").toMatchObject({ outcome: "error" }); + expect(run!.outcome_reason ?? "").toContain("incompatible"); + expect(f.observability.logs.find({ scope: "brain", body: "ui sync failed" }), "APP_UI_SYNC_LOGGED").toHaveLength(1); } finally { await app.close(); } }); }); diff --git a/packages/ui-server/tests/sync-launch-bound.test.ts b/packages/ui-server/tests/sync-launch-bound.test.ts new file mode 100644 index 0000000000..53ead61dc4 --- /dev/null +++ b/packages/ui-server/tests/sync-launch-bound.test.ts @@ -0,0 +1,194 @@ +/** + * A UI sync's admission is bounded and its outcome survives the client + * (#4257). A launch that never settles used to hold the brain's + * `syncingRoots` entry until the server restarted, so every later Sync got + * 409 with no process running; and a sync whose reader had disconnected left + * its failure only in the closed stream. + */ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { Logger, LogRecord } from "@opentelemetry/api-logs"; +import { createBrainRoutes } from "../src/routes/brain"; +import { createActivityStore } from "../src/activity/store.js"; +import { createUiDb } from "../src/db/client.js"; +import type { BrainClient } from "../src/brain/client"; +import type { HostBoundary, StreamingExecution } from "../src/brain/host-boundary"; +import type { KeytermSettings } from "../src/voice/keyterm-builder"; + +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); + +function brainRoot() { + const root = mkdtempSync(join(tmpdir(), "odysseus-sync-bound-")); + roots.push(root); + return root; +} + +/** Read an SSE body to its end, or give up after `ms` with what arrived. */ +async function readFor(response: Response, ms: number): Promise<{ text: string; ended: boolean }> { + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + let text = ""; + const deadline = Date.now() + ms; + while (Date.now() < deadline) { + const next = await Promise.race([reader.read(), Bun.sleep(Math.max(1, deadline - Date.now())).then(() => null)]); + if (next === null) break; + if (next.done) return { text, ended: true }; + text += decoder.decode(next.value, { stream: true }); + } + await reader.cancel().catch(() => {}); + return { text, ended: false }; +} + +const frames = (text: string) => text.split("\n").filter(line => line.startsWith("data: ")).map(line => JSON.parse(line.slice(6)) as Record); + +/** A child process stand-in whose output and exit the test controls. */ +function fakeProcess(lines: string[], exitCode: number) { + let killed: string | undefined; + const encoder = new TextEncoder(); + const proc: StreamingExecution & { killedWith(): string | undefined } = { + stdout: new ReadableStream({ start(controller) { for (const line of lines) controller.enqueue(encoder.encode(`${line}\n`)); controller.close(); } }), + stderr: new ReadableStream({ start(controller) { controller.close(); } }), + exited: Promise.resolve(exitCode), + signalCode: null, + kill(signal) { killed = signal ?? "SIGTERM"; }, + killedWith: () => killed, + }; + return proc; +} + +function routes(root: string, launch: HostBoundary["launch"], extra: Partial[0]> = {}) { + return createBrainRoutes({ + brainPath: root, + brain: { cliCommand: () => [process.execPath, "sync.ts"] } as BrainClient, + keyterms: { brainPath: root } as KeytermSettings, exec: {}, + boundary: { launch } as HostBoundary, + ...extra, + }); +} + +describe("bounded sync launch (#4257)", () => { + test("a launch that never settles ends with a named refusal and frees the brain for the next sync", async () => { + const root = brainRoot(); + const signals: (AbortSignal | undefined)[] = []; + let calls = 0; + const app = routes(root, async execution => { + calls++; + signals.push(execution.signal); + if (calls === 1) return new Promise(() => {}); + return fakeProcess(["Synced Ithaca"], 0); + }, { syncLaunchTimeoutMs: 50 }); + + const first = await app.request("/brain/sync", { method: "POST" }); + expect(first.status).toBe(200); + const stalled = await readFor(first, 2_000); + expect(stalled.ended, "STALLED_STREAM_ENDS").toBe(true); + const done = frames(stalled.text).find(frame => frame.type === "done"); + expect(done, "STALLED_DONE_FRAME").toMatchObject({ type: "done", success: false, reason: "launch_timeout" }); + expect(String(done!.text)).toContain("did not start"); + expect(signals[0]?.aborted, "STALLED_LAUNCH_ABORTED").toBe(true); + + const next = await app.request("/brain/sync", { method: "POST" }); + expect(next.status, "NEXT_SYNC_ADMITTED").toBe(200); + expect(frames((await readFor(next, 2_000)).text).at(-1)).toMatchObject({ type: "done", success: true }); + }); + + test("a launch that settles after its bound has its process killed", async () => { + const root = brainRoot(); + let settle!: (proc: StreamingExecution) => void; + const late = fakeProcess([], 0); + const app = routes(root, () => new Promise(resolve => { settle = resolve; }), { syncLaunchTimeoutMs: 20 }); + const response = await app.request("/brain/sync", { method: "POST" }); + expect(frames((await readFor(response, 2_000)).text).at(-1)).toMatchObject({ reason: "launch_timeout" }); + settle(late); + await Bun.sleep(10); + expect(late.killedWith(), "LATE_PROCESS_KILLED").toBe("SIGTERM"); + }); + + test("a sync whose process exited while its output pipe stays open still releases the brain", async () => { + const root = brainRoot(); + const encoder = new TextEncoder(); + let calls = 0; + const app = routes(root, async () => { + calls++; + if (calls > 1) return fakeProcess([], 0); + // A descendant holds stdout open after the sync itself exited. + return { + stdout: new ReadableStream({ start(controller) { controller.enqueue(encoder.encode("Pulled Ithaca\n")); } }), + stderr: new ReadableStream({ start(controller) { controller.close(); } }), + exited: Promise.resolve(0), signalCode: null, kill() {}, + }; + }, { syncOutputGraceMs: 30 }); + const first = await readFor(await app.request("/brain/sync", { method: "POST" }), 2_000); + expect(first.ended, "HELD_PIPE_STREAM_ENDS").toBe(true); + expect(frames(first.text).at(-1)).toMatchObject({ type: "done", success: true }); + expect(first.text).toContain("Pulled Ithaca"); + expect((await app.request("/brain/sync", { method: "POST" })).status, "HELD_PIPE_NEXT_ADMITTED").toBe(200); + }); + + test("a 409 names how long the current sync has held the brain", async () => { + const root = brainRoot(); + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + const app = routes(root, async () => { await held; return fakeProcess([], 0); }); + const first = await app.request("/brain/sync", { method: "POST" }); + await Bun.sleep(30); + const busy = await app.request("/brain/sync", { method: "POST" }); + expect(busy.status).toBe(409); + const body = await busy.json() as { error: string; heldMs: number }; + expect(body.heldMs, "BUSY_HELD_MS").toBeGreaterThanOrEqual(25); + expect(body.error).toMatch(/already running .*held the brain for \d+ s/); + release(); + await readFor(first, 2_000); + }); + + test("a sync whose reader disconnected records its exit and last error lines in Activity and logs the failure", async () => { + const root = brainRoot(); + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); + const records: LogRecord[] = []; + const log = { emit: (record: LogRecord) => { records.push(record); }, enabled: () => true } as unknown as Logger; + let finish!: () => void; + const gate = new Promise(resolve => { finish = resolve; }); + const encoder = new TextEncoder(); + let exit!: (code: number) => void; + const exited = new Promise(resolve => { exit = resolve; }); + const app = routes(root, async () => ({ + stdout: new ReadableStream({ async start(controller) { + controller.enqueue(encoder.encode("Pulling the Ithaca remote\n")); + await gate; + controller.enqueue(encoder.encode("error: maintenance output cannot change protected input context/policies/governance.md\n")); + controller.close(); + exit(1); + } }), + stderr: new ReadableStream({ start(controller) { controller.close(); } }), + exited, signalCode: null, kill() {}, + }), { activity: store, log }); + + const response = await app.request("/brain/sync", { method: "POST" }); + await readFor(response, 100); + finish(); + await exited; + const deadline = Date.now() + 2_000; + let root_: ReturnType[number] | undefined; + let ended = null as ReturnType; + while (Date.now() < deadline) { + root_ = store.changesSince(0).flatMap(change => change.kind === "span" ? [change.span] : []).find(span => span.jobName === "ui-sync"); + ended = root_ ? store.getSpan(root_.spanId) : null; + if (ended?.endedAt) break; + await Bun.sleep(10); + } + expect(ended, "UI_SYNC_RUN_RECORDED").toMatchObject({ jobName: "ui-sync", outcome: "error" }); + expect(ended!.outcomeReason ?? "", "UI_SYNC_RUN_REASON").toContain("cannot change protected input context/policies/governance.md"); + expect(ended!.outcomeReason ?? "").toContain("exit 1"); + const output = store.snapshotRun(ended!.runId)!.events.find(event => event.eventType === "job_output"); + expect(JSON.stringify(output?.payload), "UI_SYNC_OUTPUT_TAIL").toContain("Pulling the Ithaca remote"); + const failure = records.find(record => record.body === "ui sync failed"); + expect(failure, "UI_SYNC_FAILURE_LOGGED").toBeDefined(); + expect(String(failure!.attributes?.error)).toContain("cannot change protected input context/policies/governance.md"); + } finally { db.close(); } + }); +}); diff --git a/packages/ui-server/tests/sync-reservation.test.ts b/packages/ui-server/tests/sync-reservation.test.ts index c8fb8d9829..803f06989a 100644 --- a/packages/ui-server/tests/sync-reservation.test.ts +++ b/packages/ui-server/tests/sync-reservation.test.ts @@ -35,7 +35,7 @@ describe("sync reservation", () => { appendFileSync(${JSON.stringify(events)}, 'end\\n'); process.exit(1);`); symlinkSync(root, link); const boundary = createHostBoundary({ brainPath: root, exec: {} }); - const syncingRoots = new Set(); + const syncingRoots = new Map(); const route = (brainPath: string) => createBrainRoutes({ syncingRoots, brainPath, brain: { cliCommand: () => [process.execPath, script] } as BrainClient, keyterms: { brainPath } as KeytermSettings, exec: {}, @@ -97,7 +97,7 @@ test("independent apps do not share sync admission (#1364)", async () => { const boundary = createHostBoundary({ brainPath: root, exec: {} }); let calls = 0; const route = () => createBrainRoutes({ - syncingRoots: new Set(), brainPath: root, + syncingRoots: new Map(), brainPath: root, brain: { cliCommand: () => [process.execPath, "sync.ts"] } as BrainClient, keyterms: { brainPath: root } as KeytermSettings, exec: {}, boundary: { ...boundary, async launch() { From c7af79a0068a296bb0332cc76cbd5d8f5cd9cff9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 12:29:04 +0000 Subject: [PATCH 2/9] fix(ui-server): keep the sync bounds module-private (#4257) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/routes/brain.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index b067c43e67..a1507ee9c1 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -23,9 +23,9 @@ import { observeWrite } from "../activity/store-writes.js"; * sync is refused by name and the brain is free again; a sync that has * started is never bounded here. */ -export const SYNC_LAUNCH_TIMEOUT_MS = 120_000; +const SYNC_LAUNCH_TIMEOUT_MS = 120_000; /** How long a sync's output may keep its pipes open after the process has exited. */ -export const SYNC_OUTPUT_GRACE_MS = 10_000; +const SYNC_OUTPUT_GRACE_MS = 10_000; /** Combined output kept on a UI sync's Activity run, as a cron job keeps its own. */ const SYNC_OUTPUT_TAIL_CHARS = 8_000; /** Non-empty output lines named in a failed UI sync's run reason and log line. */ From 5867f40ae3d34b59c3dce7eb4a0e101f478ec6e1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 12:34:41 +0000 Subject: [PATCH 3/9] test(ui-server): MUTATION, reverted next commit: drop the UI sync Activity wiring to show the app test fails (#4257) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/app.ts | 2 +- packages/ui-server/tests/host-version-requirements.test.ts | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 7e7b92d10b..9773f29394 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1183,7 +1183,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise host.prepareHistory(id, messages), diff --git a/packages/ui-server/tests/host-version-requirements.test.ts b/packages/ui-server/tests/host-version-requirements.test.ts index 45dc6d106e..121321db24 100644 --- a/packages/ui-server/tests/host-version-requirements.test.ts +++ b/packages/ui-server/tests/host-version-requirements.test.ts @@ -1,6 +1,6 @@ import { Database } from "bun:sqlite"; import { afterEach, describe, expect, spyOn, test } from "bun:test"; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { type HostVersionRequirements } from "../src/app"; @@ -113,6 +113,8 @@ describe("host version requirements at app startup", () => { }); test("a replaced CLI is also refused before streaming sync's independent launch", async () => { const f = fixture(); + // The Odysseus fixture corpus as the brain, so the UI sync runs against a real brain (#4257). + cpSync(join(import.meta.dir, "../../core/fixtures/corpus"), f.root, { recursive: true }); const app = await createApp({ ...f, versionRequirements: { brainCli: "0.40.0" } }); try { f.install("0.39.0"); From 12829ec10820712ad72773913f99616e610ee290 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 13:26:15 +0000 Subject: [PATCH 4/9] CONTRACT: fix(ui-server): restore the UI sync Activity wiring and record the contract entry (#4257) Restores the wiring the previous commit removed as a mutation (its hosted run failed APP_UI_SYNC_RUN as expected), and adds the authoritative contract entry for the additive sync fields. Co-Authored-By: Claude Opus 5.5 --- docs/integration-contract/http.md | 19 +++++++++++++++++++ packages/ui-server/src/app.ts | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index b20d6e1bc2..867ac07b7b 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -251,6 +251,25 @@ Disconnect does not establish cancellation: the server continues draining and reserves the canonical repository until its child exits, as specified in [the HTTP sync contract](../http-api.md#corpus-queries-capture-and-sync). + + +### Bounded UI sync start, hold duration and Activity run (additive, #4257) + +`POST /api/brain/sync` keeps its admission, SSE frames and disconnect rules. +Three additions ([HTTP reference](../http-api.md#corpus-queries-capture-and-sync)): + +- A concurrent attempt's 409 body is `{ error, heldMs }`, where `heldMs` is how + long the admitted sync has held the canonical root. +- The time from admission until the sync process starts is bounded at 120 + seconds. Past it the stream ends with `{ type: "done", success: false, + reason: "launch_timeout", text }`, the reservation is released and nothing + has run. `reason` is present only on this refusal. `brainSync()` keeps + mapping it to `{ success: false, message }`. +- Each admitted UI sync is an Activity run with root span kind and origin + `cron` and `jobName: "ui-sync"`, attributed to the requesting principal. Its + terminal outcome carries the exit status and last output lines, and its + `job_output` event carries the output tail. + ### Typed status software identity (additive, #598) diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 9773f29394..7e7b92d10b 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1183,7 +1183,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise host.prepareHistory(id, messages), From 01b630b4dac07fafb48f3038485b8b5b27920cda Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 13:33:37 +0000 Subject: [PATCH 5/9] CONTRACT: fix(ui-server): bound a hosted sync until its first worker starts (#4257) A hosted sync's launch returns before its mirror lock, native startup view and origin probe, so the launch bound ended too early. The boundary now reports the start through onExecute (after the origin probe for a mirror sync), the route bounds until that start, and a returned launch that never starts is killed at the bound. Co-Authored-By: Claude Opus 5.5 --- docs/http-api.md | 5 ++-- docs/integration-contract/http.md | 5 ++-- packages/ui-server/src/brain/host-boundary.ts | 11 +++++-- packages/ui-server/src/brain/sync-mirror.ts | 6 +++- packages/ui-server/src/routes/brain.ts | 20 +++++++++++-- .../ui-server/tests/sync-launch-bound.test.ts | 29 +++++++++++++++++-- packages/ui-server/tests/sync-mirror.test.ts | 19 ++++++++++++ 7 files changed, 83 insertions(+), 12 deletions(-) diff --git a/docs/http-api.md b/docs/http-api.md index 8cf285874f..394b9bf763 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -626,8 +626,9 @@ cancel sync or release its reservation**; output continues draining until the child exits. **Bounded start (additive, #4257).** Everything between admission and the -sync process starting (the CLI version probe, the writer gate and the worker -launch) is bounded at 120 seconds. Past it the stream ends with +sync's first worker starting (the CLI version probe, the writer gate, the +worker launch and, on a hosted install, the mirror lock, startup view and +origin probe) is bounded at 120 seconds. Past it the stream ends with `{ type: "done", success: false, reason: "launch_timeout", text }`, the reservation is released, nothing has run, and a launch that settles later is killed. `reason` is present only on this refusal. After the child exits, its diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 867ac07b7b..a27ea82c45 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -260,8 +260,9 @@ Three additions ([HTTP reference](../http-api.md#corpus-queries-capture-and-sync - A concurrent attempt's 409 body is `{ error, heldMs }`, where `heldMs` is how long the admitted sync has held the canonical root. -- The time from admission until the sync process starts is bounded at 120 - seconds. Past it the stream ends with `{ type: "done", success: false, +- The time from admission until the sync's first worker starts (on a hosted + install, after the mirror lock, startup view and origin probe) is bounded at + 120 seconds. Past it the stream ends with `{ type: "done", success: false, reason: "launch_timeout", text }`, the reservation is released and nothing has run. `reason` is present only on this refusal. `brainSync()` keeps mapping it to `{ success: false, message }`. diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 874fe8af29..e2bed21be8 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -72,7 +72,12 @@ export interface BrainExecution { timeoutMs?: number; /** @internal Storage owner operations recheck authority after admission/preparation. */ assertAuthorized?: () => void; - /** @internal Distinguish pre-launch owner refusal from an interrupted effect. */ + /** + * @internal Distinguish pre-launch owner refusal from an interrupted effect. + * `launch` calls it once the command's process has started; for a hosted + * sync, once its mirror lock, startup view and origin probe are done and its + * first worker starts, so a caller can bound everything before it (#4257). + */ onExecute?: () => void; /** @internal Combined output bound for an explicitly bounded operation. */ outputBytes?: number; @@ -690,6 +695,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { await admitHost(hold); stillHostFallback(execution.signal); const proc = hostSpawn(execution); + execution.onExecute?.(); const admitted = credential; return retainExecutionAdmission({ stdout: proc.stdout, stderr: proc.stderr, exited: proc.exited, get signalCode() { return proc.signalCode; }, kill: (signal?: NodeJS.Signals) => killWrapped(proc, exec, signal ?? "SIGTERM") }, @@ -718,7 +724,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { const onAbort = () => abort.abort(execution.signal?.reason); execution.signal?.addEventListener("abort", onAbort, { once: true }); const exited = runMirrorSync({ log: options.log, nativeManager: options.nativeManager, folderPaths: hold?.folderPaths, command: selectedCommand, transportEnv: execution.env, mirror: selectedMirror, signal: abort.signal, - ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }).then(result => { + ...(execution.onExecute ? { onExecute: execution.onExecute } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }).then(result => { stdout.write(result.stdout); stderr.write(result.stderr); return result.exitCode; }, error => { stderr.write(error instanceof Error ? error.message : String(error)); return 1; }) .finally(async () => { @@ -749,6 +755,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { await prepareMaintenanceWorker(maintenance, execution.signal); execution.signal?.throwIfAborted(); worker = await launchMaintenanceWorkerAsync(maintenance); + execution.onExecute?.(); } catch (error) { await relay?.stop(); try { await outputs?.cleanup(); } finally { try { await view?.cleanup(); } finally { try { releaseOutput(); } finally { try { credential?.release(); } finally { hold?.release(); } } } } throw error; } void worker.input(execution.stdin ?? ""); diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index fed6750790..dc914bb98e 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -148,7 +148,9 @@ async function runLocalSync(command: MaintenanceCommand & { signal?: AbortSignal } /** Full deterministic sync with the same local merge behavior; remote races repeat its existing re-pull flow. */ -export async function runMirrorSync(input: { log?: import("@opentelemetry/api-logs").Logger; folderPaths?: readonly string[]; nativeManager?: Parameters[1]; command: MaintenanceCommand; mirror: string; transportEnv?: MaintenanceCommand["env"]; signal?: AbortSignal; timeoutMs?: number }): Promise { +export async function runMirrorSync(input: { log?: import("@opentelemetry/api-logs").Logger; folderPaths?: readonly string[]; nativeManager?: Parameters[1]; command: MaintenanceCommand; mirror: string; transportEnv?: MaintenanceCommand["env"]; signal?: AbortSignal; timeoutMs?: number; + /** Called once the sync's first worker is about to start: after the mirror lock, the startup view and the origin probe (#4257). */ + onExecute?: () => void }): Promise { // Standalone embedders have no attached database gate. Their private // mirror still serializes every local/transport phase in this process. return mirrorLocks.withLock(input.mirror, () => executeMirrorSync(input), { signal: input.signal }); @@ -162,6 +164,8 @@ async function executeMirrorSync(input: Parameters[0]): Pr let remote: string | null; try { input.signal?.throwIfAborted(); remote = await origin({ ...command, startupView: originView }); } finally { await originView.cleanup(); } + input.signal?.throwIfAborted(); + input.onExecute?.(); if (remote === null) return runLocalSync({ ...command, credentials: false, ...(input.signal ? { signal: input.signal } : {}), ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}) }, input.nativeManager, input.folderPaths, input.log); prepareMirror(mirror, brain); diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index a1507ee9c1..47e83f2d2c 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -1,7 +1,7 @@ import { Hono } from "hono"; import { streamSSE } from "hono/streaming"; import { probeBrainCliVersion, type BrainClient } from "../brain/client.js"; -import { brainCommandClass, createHostBoundary, type HostBoundary } from "../brain/host-boundary.js"; +import { brainCommandClass, createHostBoundary, type HostBoundary, type StreamingExecution } from "../brain/host-boundary.js"; import type { Logger } from "@opentelemetry/api-logs"; import { subprocessEnv } from "../config/env.js"; import type { ExecWrapperConfig } from "@schlessera/brain-ui-sdk/server"; @@ -226,10 +226,18 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { // Everything before the process starts is bounded (#4257): a probe or // launch that never settles must not hold the brain until a restart. const launching = new AbortController(); + let markStarted!: () => void; + const started = new Promise(resolve => { markStarted = resolve; }); let timedOut = false; let timer: ReturnType | undefined; + let launched: StreamingExecution | undefined; const bound = new Promise((_, reject) => { - timer = setTimeout(() => { timedOut = true; launching.abort(); reject(new SyncLaunchTimeout(launchTimeoutMs)); }, launchTimeoutMs); + timer = setTimeout(() => { + timedOut = true; launching.abort(); + // A launch that returned but never started its work is stopped now. + if (launched) { launched.kill("SIGTERM"); void launched.exited.catch(() => {}); } + reject(new SyncLaunchTimeout(launchTimeoutMs)); + }, launchTimeoutMs); }); const start = (async () => { if (deps.brainCliMinimum !== undefined) { @@ -248,9 +256,15 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { purpose: "brain sync", sync: true, signal: launching.signal, + onExecute: () => markStarted(), }); + launched = proc; // A launch that settles after its bound was already refused: stop it. - if (timedOut) { proc.kill("SIGTERM"); void proc.exited.catch(() => {}); } + if (timedOut) { proc.kill("SIGTERM"); void proc.exited.catch(() => {}); return proc; } + // A hosted sync's launch returns before its mirror lock, startup + // view and origin probe: the bound holds until its first worker + // starts, or the attempt ends before one does. + await Promise.race([started, proc.exited.then(() => {}, () => {})]); return proc; })(); start.catch(() => {}); diff --git a/packages/ui-server/tests/sync-launch-bound.test.ts b/packages/ui-server/tests/sync-launch-bound.test.ts index 53ead61dc4..b4d3b7a524 100644 --- a/packages/ui-server/tests/sync-launch-bound.test.ts +++ b/packages/ui-server/tests/sync-launch-bound.test.ts @@ -78,6 +78,7 @@ describe("bounded sync launch (#4257)", () => { calls++; signals.push(execution.signal); if (calls === 1) return new Promise(() => {}); + execution.onExecute?.(); return fakeProcess(["Synced Ithaca"], 0); }, { syncLaunchTimeoutMs: 50 }); @@ -107,12 +108,36 @@ describe("bounded sync launch (#4257)", () => { expect(late.killedWith(), "LATE_PROCESS_KILLED").toBe("SIGTERM"); }); + test("a hosted launch that returns before its first worker starts is bounded until that start", async () => { + const root = brainRoot(); + // A hosted sync's launch returns at once; its mirror lock, startup view and + // origin probe follow inside the returned process. Here they never finish. + const pending = { ...fakeProcess([], 0), exited: new Promise(() => {}) }; + let killed: string | undefined; + pending.kill = signal => { killed = signal ?? "SIGTERM"; }; + let calls = 0; + const app = routes(root, async execution => { + calls++; + if (calls === 1) return pending; + execution.onExecute?.(); + return fakeProcess(["Synced Ithaca"], 0); + }, { syncLaunchTimeoutMs: 50 }); + const first = await readFor(await app.request("/brain/sync", { method: "POST" }), 2_000); + expect(first.ended, "PRESTART_STREAM_ENDS").toBe(true); + expect(frames(first.text).at(-1), "PRESTART_REFUSED").toMatchObject({ type: "done", success: false, reason: "launch_timeout" }); + expect(killed, "PRESTART_KILLED").toBe("SIGTERM"); + const next = await app.request("/brain/sync", { method: "POST" }); + expect(next.status, "PRESTART_NEXT_ADMITTED").toBe(200); + expect(frames((await readFor(next, 2_000)).text).at(-1)).toMatchObject({ type: "done", success: true }); + }); + test("a sync whose process exited while its output pipe stays open still releases the brain", async () => { const root = brainRoot(); const encoder = new TextEncoder(); let calls = 0; - const app = routes(root, async () => { + const app = routes(root, async execution => { calls++; + execution.onExecute?.(); if (calls > 1) return fakeProcess([], 0); // A descendant holds stdout open after the sync itself exited. return { @@ -156,7 +181,7 @@ describe("bounded sync launch (#4257)", () => { const encoder = new TextEncoder(); let exit!: (code: number) => void; const exited = new Promise(resolve => { exit = resolve; }); - const app = routes(root, async () => ({ + const app = routes(root, async execution => (execution.onExecute?.(), { stdout: new ReadableStream({ async start(controller) { controller.enqueue(encoder.encode("Pulling the Ithaca remote\n")); await gate; diff --git a/packages/ui-server/tests/sync-mirror.test.ts b/packages/ui-server/tests/sync-mirror.test.ts index 8a2fc11ae7..9b77b06fa2 100644 --- a/packages/ui-server/tests/sync-mirror.test.ts +++ b/packages/ui-server/tests/sync-mirror.test.ts @@ -403,6 +403,25 @@ for (const output of ["stdout", "stderr"] as const) { }); } +test("a hosted sync launch reports its start only once its first worker starts, after the origin probe (#4257)", async () => { + const f = fixture(); + const db = createUiDb(f.dbPath); + const execution = createHostExecution({ brainPath: f.brain, nativeManager: f.nativeManager, dbPath: f.dbPath, exec: {} }); + try { + execution.attach(db); + const events: string[] = []; + const sentinel = join(f.brain, "started.sentinel"); + const worker = await execution.boundary.launch({ argv: ["/bin/sh", "-c", 'printf started > "$1"', "probe", sentinel], + env: { PATH: "/usr/bin:/bin" }, credentials: false, gate: "exclusive", sync: true, purpose: "start-reporting sync", + onExecute: () => { events.push(existsSync(sentinel) ? "after-worker" : "started"); } }); + // The launch returned with the mirror sync still preparing: nothing has started yet. + events.push("launched"); + void new Response(worker.stdout).text().catch(() => {}); void new Response(worker.stderr).text().catch(() => {}); + expect(await worker.exited, "START_SYNC_EXIT").toBe(0); + expect(events, "START_REPORTED_ONCE_AFTER_LAUNCH_BEFORE_WORKER").toEqual(["launched", "started"]); + } finally { db.close(); } +}); + test("an in-memory host uses its private temporary mirror for a real sync", async () => { if (await privateMaintenanceTest(import.meta.path, "an in-memory host uses its private temporary mirror for a real sync", 120_000)) return; const f = fixture(); From d6cced97aacdb1906283ac11aa85c9d8cb008ef7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 13:38:57 +0000 Subject: [PATCH 6/9] fix(ui-server): release a UI sync's reservation without waiting for its output cancel (#4257) The host boundary's admission-retaining stream drains to EOF on cancel, so awaiting it held the reservation while a descendant kept the pipe open. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/routes/brain.ts | 5 ++++- packages/ui-server/tests/sync-launch-bound.test.ts | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index 47e83f2d2c..9f4c6d256c 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -310,7 +310,10 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { await Promise.race([Promise.all([drained, stderrDone]), graceOver]); clearTimeout(grace); clearInterval(keepalive); - await reader.cancel().catch(() => {}); + // Never awaited: a boundary's cancel can itself drain to EOF, keeping + // the writer gate until the descendant lets go (the next sync waits on + // that gate within its own launch bound), but not this reservation. + void reader.cancel().catch(() => {}); // Rebuild voice keyterms cache after a successful sync. if (exitCode === 0) { diff --git a/packages/ui-server/tests/sync-launch-bound.test.ts b/packages/ui-server/tests/sync-launch-bound.test.ts index b4d3b7a524..6fd107d12d 100644 --- a/packages/ui-server/tests/sync-launch-bound.test.ts +++ b/packages/ui-server/tests/sync-launch-bound.test.ts @@ -141,7 +141,8 @@ describe("bounded sync launch (#4257)", () => { if (calls > 1) return fakeProcess([], 0); // A descendant holds stdout open after the sync itself exited. return { - stdout: new ReadableStream({ start(controller) { controller.enqueue(encoder.encode("Pulled Ithaca\n")); } }), + // Its cancel drains to EOF, as the host boundary's admission-retaining stream does. + stdout: new ReadableStream({ start(controller) { controller.enqueue(encoder.encode("Pulled Ithaca\n")); }, cancel: () => new Promise(() => {}) }), stderr: new ReadableStream({ start(controller) { controller.close(); } }), exited: Promise.resolve(0), signalCode: null, kill() {}, }; From 7a8cc533a7b8153a678ce83860f4f6eabacf1e0b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 13:51:17 +0000 Subject: [PATCH 7/9] test(ui-server): the hosted start-report test runs a worker that writes nothing (#4257) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/sync-mirror.test.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/packages/ui-server/tests/sync-mirror.test.ts b/packages/ui-server/tests/sync-mirror.test.ts index 9b77b06fa2..d221d594ea 100644 --- a/packages/ui-server/tests/sync-mirror.test.ts +++ b/packages/ui-server/tests/sync-mirror.test.ts @@ -410,15 +410,14 @@ test("a hosted sync launch reports its start only once its first worker starts, try { execution.attach(db); const events: string[] = []; - const sentinel = join(f.brain, "started.sentinel"); - const worker = await execution.boundary.launch({ argv: ["/bin/sh", "-c", 'printf started > "$1"', "probe", sentinel], - env: { PATH: "/usr/bin:/bin" }, credentials: false, gate: "exclusive", sync: true, purpose: "start-reporting sync", - onExecute: () => { events.push(existsSync(sentinel) ? "after-worker" : "started"); } }); + const worker = await execution.boundary.launch({ argv: ["/bin/true"], env: { PATH: "/usr/bin:/bin" }, credentials: false, + gate: "exclusive", sync: true, purpose: "start-reporting sync", onExecute: () => { events.push("started"); } }); // The launch returned with the mirror sync still preparing: nothing has started yet. events.push("launched"); - void new Response(worker.stdout).text().catch(() => {}); void new Response(worker.stderr).text().catch(() => {}); - expect(await worker.exited, "START_SYNC_EXIT").toBe(0); - expect(events, "START_REPORTED_ONCE_AFTER_LAUNCH_BEFORE_WORKER").toEqual(["launched", "started"]); + void new Response(worker.stdout).text().catch(() => {}); + const stderr = new Response(worker.stderr).text().catch(() => ""); + expect(await worker.exited, `START_SYNC_EXIT: ${await stderr}`).toBe(0); + expect(events, "START_REPORTED_ONCE_AFTER_LAUNCH").toEqual(["launched", "started"]); } finally { db.close(); } }); From f0bcdc5db569528cf6462f1935d896729d7830eb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 14:05:34 +0000 Subject: [PATCH 8/9] fix(ui-server): count the output grace only while a pipe sits open and idle; pin the start report (#4257) A slow reader draining a hosted sync's buffered output lost its last lines when the grace ran on wall-clock time after exit. The grace now counts only time every unfinished pipe spends blocked on a read. Tests now pin that a started sync outlives the launch bound and that the hosted start is reported before the worker runs. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/routes/brain.ts | 87 ++++++++++++------- .../ui-server/tests/sync-launch-bound.test.ts | 39 +++++++++ packages/ui-server/tests/sync-mirror.test.ts | 8 +- 3 files changed, 99 insertions(+), 35 deletions(-) diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index 9f4c6d256c..005422a58a 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -65,6 +65,39 @@ function lastLines(output: string, count: number): string { return output.split("\n").map(line => line.trim()).filter(Boolean).slice(-count).join("\n"); } +/** + * Read a stream line by line, handing each non-empty line to `line` in order. + * `idleSince` is when the current read started while it waits for data with + * nothing pending, null while a line is being handled: it tells a pipe held + * open apart from output still being delivered. + */ +function drainLines(stream: ReadableStream, line: (text: string) => unknown) { + const reader = stream.getReader(); + const decoder = new TextDecoder(); + let buffer = "", waiting: number | null = null, finished = false; + const done = (async () => { + try { + while (true) { + waiting = Date.now(); + const { done, value } = await reader.read(); + waiting = null; + if (done) break; + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split("\n"); + buffer = lines.pop() || ""; + for (const text of lines) if (text.trim()) await line(text); + } + if (buffer.trim()) await line(buffer); + } catch {} finally { waiting = null; finished = true; } + })(); + return { + done, + finished: () => finished, + idleSince: () => waiting, + cancel: () => reader.cancel().catch(() => {}), + }; +} + export function createBrainRoutes(deps: BrainRoutesDeps): Hono { const { brain, brainPath, keyterms } = deps; const syncingRoots = deps.syncingRoots ?? new Map(); @@ -274,46 +307,34 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { // Keep draining even when the SSE reader disconnects. The repository // stays reserved until the actual sync process has exited. - const stderrDone = new Response(proc.stderr).text().then(async text => { - if (text.trim()) await send({ type: "progress", text: text.trim() }); - return text; - }).catch(() => ""); - const reader = proc.stdout.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - const drained = (async () => { - try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - buffer += decoder.decode(value, { stream: true }); - const lines = buffer.split("\n"); - buffer = lines.pop() || ""; - for (const line of lines) { - if (line.trim()) { - await send({ type: "progress", text: line }); - } - } - } - if (buffer.trim()) { - await send({ type: "progress", text: buffer }); - } - } catch {} - })(); + const stdout = drainLines(proc.stdout, line => send({ type: "progress", text: line })); + // stderr is sent as one block once it ends, as before. + let stderrText = ""; + const stderr = drainLines(proc.stderr, line => { stderrText += `${line}\n`; }); + const stderrDone = stderr.done.then(() => stderrText.trim() ? send({ type: "progress", text: stderrText.trim() }) : undefined); const exitCode = await proc.exited; // A descendant that outlives the sync can hold its output pipes open - // (#4257): once the process has exited, its output gets a short grace - // period and the brain is released whether or not the pipes closed. - let grace: ReturnType | undefined; - const graceOver = new Promise(resolve => { grace = setTimeout(resolve, outputGraceMs); }); - await Promise.race([Promise.all([drained, stderrDone]), graceOver]); - clearTimeout(grace); + // (#4257). Once the process has exited, the brain is released when + // every unfinished pipe has sat open with nothing to read for the + // grace period. Time spent delivering output to a slow reader never + // counts, so nothing the sync wrote is cut off. + await new Promise(resolve => { + let timer: ReturnType | undefined; + const finish = () => { clearTimeout(timer); resolve(); }; + void Promise.all([stdout.done, stderrDone]).then(finish, finish); + const check = () => { + const idle = [stdout, stderr].filter(pipe => !pipe.finished()).map(pipe => pipe.idleSince()); + if (idle.length && idle.every(since => since !== null && Date.now() - since >= outputGraceMs)) return finish(); + timer = setTimeout(check, Math.max(1, Math.min(250, outputGraceMs))); + }; + check(); + }); clearInterval(keepalive); // Never awaited: a boundary's cancel can itself drain to EOF, keeping // the writer gate until the descendant lets go (the next sync waits on // that gate within its own launch bound), but not this reservation. - void reader.cancel().catch(() => {}); + void stdout.cancel(); void stderr.cancel(); // Rebuild voice keyterms cache after a successful sync. if (exitCode === 0) { diff --git a/packages/ui-server/tests/sync-launch-bound.test.ts b/packages/ui-server/tests/sync-launch-bound.test.ts index 6fd107d12d..5ceb97cf75 100644 --- a/packages/ui-server/tests/sync-launch-bound.test.ts +++ b/packages/ui-server/tests/sync-launch-bound.test.ts @@ -154,6 +154,45 @@ describe("bounded sync launch (#4257)", () => { expect((await app.request("/brain/sync", { method: "POST" })).status, "HELD_PIPE_NEXT_ADMITTED").toBe(200); }); + test("a sync that has started is never bounded: it runs past the launch bound and is not killed", async () => { + const root = brainRoot(); + let killed: string | undefined; + const app = routes(root, async execution => { + execution.onExecute?.(); + return { ...fakeProcess(["Merged Ithaca"], 0), exited: Bun.sleep(150).then(() => 0), kill(signal?: NodeJS.Signals) { killed = signal ?? "SIGTERM"; } }; + }, { syncLaunchTimeoutMs: 30 }); + const result = await readFor(await app.request("/brain/sync", { method: "POST" }), 2_000); + expect(frames(result.text).at(-1), "STARTED_SYNC_COMPLETES").toMatchObject({ type: "done", success: true }); + expect(killed, "STARTED_SYNC_NOT_KILLED").toBeUndefined(); + }); + + test("a reader that drains slowly after exit still gets every line, and Activity keeps the last error", async () => { + const root = brainRoot(); + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); + const lines = Array.from({ length: 40 }, (_, i) => `Ithaca ledger line ${i} ${"ยท".repeat(2_000)}`); + const app = routes(root, async execution => { + execution.onExecute?.(); + return fakeProcess([...lines, "error: final refusal from Ithaca"], 1); + }, { syncOutputGraceMs: 20, activity: store }); + const response = await app.request("/brain/sync", { method: "POST" }); + // The reader is slow: nothing is read for well past the grace period. + await Bun.sleep(200); + const all = await readFor(response, 5_000); + expect(all.ended).toBe(true); + expect(all.text, "SLOW_READER_GETS_FINAL_LINE").toContain("error: final refusal from Ithaca"); + const deadline = Date.now() + 2_000; + let ended: ReturnType = null; + while (Date.now() < deadline && !ended?.endedAt) { + const span = store.changesSince(0).flatMap(change => change.kind === "span" ? [change.span] : []).find(span => span.jobName === "ui-sync"); + ended = span ? store.getSpan(span.spanId) : null; + await Bun.sleep(10); + } + expect(ended?.outcomeReason ?? "", "SLOW_READER_ACTIVITY_KEEPS_FINAL_LINE").toContain("final refusal from Ithaca"); + } finally { db.close(); } + }); + test("a 409 names how long the current sync has held the brain", async () => { const root = brainRoot(); let release!: () => void; diff --git a/packages/ui-server/tests/sync-mirror.test.ts b/packages/ui-server/tests/sync-mirror.test.ts index d221d594ea..a2ab5c81c2 100644 --- a/packages/ui-server/tests/sync-mirror.test.ts +++ b/packages/ui-server/tests/sync-mirror.test.ts @@ -410,13 +410,17 @@ test("a hosted sync launch reports its start only once its first worker starts, try { execution.attach(db); const events: string[] = []; - const worker = await execution.boundary.launch({ argv: ["/bin/true"], env: { PATH: "/usr/bin:/bin" }, credentials: false, - gate: "exclusive", sync: true, purpose: "start-reporting sync", onExecute: () => { events.push("started"); } }); + // The worker runs for two seconds: a start reported before it runs comes + // long before the exit, one reported at the end of the sync does not. + let startedAt = 0; + const worker = await execution.boundary.launch({ argv: ["/bin/sh", "-c", "sleep 2"], env: { PATH: "/usr/bin:/bin" }, credentials: false, + gate: "exclusive", sync: true, purpose: "start-reporting sync", onExecute: () => { startedAt = performance.now(); events.push("started"); } }); // The launch returned with the mirror sync still preparing: nothing has started yet. events.push("launched"); void new Response(worker.stdout).text().catch(() => {}); const stderr = new Response(worker.stderr).text().catch(() => ""); expect(await worker.exited, `START_SYNC_EXIT: ${await stderr}`).toBe(0); + expect(performance.now() - startedAt, "START_REPORTED_BEFORE_WORKER_RUNS").toBeGreaterThanOrEqual(1_500); expect(events, "START_REPORTED_ONCE_AFTER_LAUNCH").toEqual(["launched", "started"]); } finally { db.close(); } }); From 0686c841fce4fd0abfe23faf3e2063860f5d508c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 14:10:39 +0000 Subject: [PATCH 9/9] fix(ui-server): count a pipe's idle grace from the sync's exit (#4257) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/routes/brain.ts | 5 +++- .../ui-server/tests/sync-launch-bound.test.ts | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index 005422a58a..c1bb92f760 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -319,13 +319,16 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { // every unfinished pipe has sat open with nothing to read for the // grace period. Time spent delivering output to a slow reader never // counts, so nothing the sync wrote is cut off. + const exitedAt = Date.now(); await new Promise(resolve => { let timer: ReturnType | undefined; const finish = () => { clearTimeout(timer); resolve(); }; void Promise.all([stdout.done, stderrDone]).then(finish, finish); const check = () => { const idle = [stdout, stderr].filter(pipe => !pipe.finished()).map(pipe => pipe.idleSince()); - if (idle.length && idle.every(since => since !== null && Date.now() - since >= outputGraceMs)) return finish(); + // Idle time counts from the exit at the earliest: a read that began + // during a silent stretch before it says nothing about the pipe. + if (idle.length && idle.every(since => since !== null && Date.now() - Math.max(since, exitedAt) >= outputGraceMs)) return finish(); timer = setTimeout(check, Math.max(1, Math.min(250, outputGraceMs))); }; check(); diff --git a/packages/ui-server/tests/sync-launch-bound.test.ts b/packages/ui-server/tests/sync-launch-bound.test.ts index 5ceb97cf75..0d04f30aed 100644 --- a/packages/ui-server/tests/sync-launch-bound.test.ts +++ b/packages/ui-server/tests/sync-launch-bound.test.ts @@ -193,6 +193,31 @@ describe("bounded sync launch (#4257)", () => { } finally { db.close(); } }); + test("a sync silent past the grace before it exits still delivers the lines it writes at exit", async () => { + const root = brainRoot(); + const encoder = new TextEncoder(); + const app = routes(root, async execution => { + execution.onExecute?.(); + let exit!: (code: number) => void; + const exited = new Promise(resolve => { exit = resolve; }); + return { + stdout: new ReadableStream({ async start(controller) { + controller.enqueue(encoder.encode("Pulling Ithaca\n")); + // Silent for longer than the grace, then the process exits just before its last write arrives. + await Bun.sleep(80); + exit(1); + await Bun.sleep(5); + controller.enqueue(encoder.encode("error: final refusal after silence\n")); + controller.close(); + } }), + stderr: new ReadableStream({ start(controller) { controller.close(); } }), + exited, signalCode: null, kill() {}, + }; + }, { syncOutputGraceMs: 20 }); + const all = await readFor(await app.request("/brain/sync", { method: "POST" }), 2_000); + expect(all.text, "SILENT_SYNC_FINAL_LINE_KEPT").toContain("error: final refusal after silence"); + }); + test("a 409 names how long the current sync has held the brain", async () => { const root = brainRoot(); let release!: () => void;