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 8bb9812427..57ab56feb5 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -622,10 +622,27 @@ 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'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 +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/docs/integration-contract/http.md b/docs/integration-contract/http.md index b20d6e1bc2..a27ea82c45 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -251,6 +251,26 @@ 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'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 }`. +- 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 0dba58ebf5..d31219f3a7 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1187,7 +1187,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise host.prepareHistory(id, messages), 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 518e295e56..c1bb92f760 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"; @@ -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. + */ +const SYNC_LAUNCH_TIMEOUT_MS = 120_000; +/** How long a sync's output may keep its pipes open after the process has exited. */ +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,88 @@ 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"); +} + +/** + * 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 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 +216,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,53 +256,88 @@ 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 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(); + // 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) { + 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, + 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(() => {}); 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(() => {}); + 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. - 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 = ""; - 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); - } + 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; - await stderrDone; + // A descendant that outlives the sync can hold its output pipes open + // (#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. + 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()); + // 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(); + }); + 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 stdout.cancel(); void stderr.cancel(); // Rebuild voice keyterms cache after a successful sync. if (exitCode === 0) { @@ -214,6 +359,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 +371,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..121321db24 100644 --- a/packages/ui-server/tests/host-version-requirements.test.ts +++ b/packages/ui-server/tests/host-version-requirements.test.ts @@ -1,5 +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"; @@ -112,12 +113,26 @@ 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"); 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..0d04f30aed --- /dev/null +++ b/packages/ui-server/tests/sync-launch-bound.test.ts @@ -0,0 +1,284 @@ +/** + * 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(() => {}); + execution.onExecute?.(); + 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 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 execution => { + calls++; + execution.onExecute?.(); + if (calls > 1) return fakeProcess([], 0); + // A descendant holds stdout open after the sync itself exited. + return { + // 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() {}, + }; + }, { 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 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 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; + 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 execution => (execution.onExecute?.(), { + 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-mirror.test.ts b/packages/ui-server/tests/sync-mirror.test.ts index 8a2fc11ae7..a2ab5c81c2 100644 --- a/packages/ui-server/tests/sync-mirror.test.ts +++ b/packages/ui-server/tests/sync-mirror.test.ts @@ -403,6 +403,28 @@ 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[] = []; + // 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(); } +}); + 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(); 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() {