Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/4257-bounded-ui-sync.md
Original file line number Diff line number Diff line change
@@ -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.
21 changes: 19 additions & 2 deletions docs/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions docs/integration-contract/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

<a id="bounded-ui-sync-additive-4257"></a>

### 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.

<a id="typed-status-software-identity-additive-598"></a>

### Typed status software identity (additive, #598)
Expand Down
2 changes: 1 addition & 1 deletion packages/ui-server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1187,7 +1187,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise<BrainUi
for (const path of INDEX_READ_ROUTES) app.use(path, indexReadBarrier(indexBatch));
app.route(
"/api",
createBrainRoutes({ syncingRoots: new Set(), brain, brainPath: config.brainPath, exec: config.exec, keyterms, brainCliMinimum, log: brainLog, boundary })
createBrainRoutes({ syncingRoots: new Map(), activity: activity.store, brain, brainPath: config.brainPath, exec: config.exec, keyterms, brainCliMinimum, log: brainLog, boundary })
);
app.route("/api", createSessionProfileRoutes(sessionProfiles));
app.route("/api", createSessionRoutes({ registry, db, labels: host.labels !== null, prepareHistory: (id, messages) => host.prepareHistory(id, messages),
Expand Down
11 changes: 9 additions & 2 deletions packages/ui-server/src/brain/host-boundary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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") },
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 ?? "");
Expand Down
6 changes: 5 additions & 1 deletion packages/ui-server/src/brain/sync-mirror.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof prepareNativeWorkerStartupView>[1]; command: MaintenanceCommand; mirror: string; transportEnv?: MaintenanceCommand["env"]; signal?: AbortSignal; timeoutMs?: number }): Promise<ExecutionResult> {
export async function runMirrorSync(input: { log?: import("@opentelemetry/api-logs").Logger; folderPaths?: readonly string[]; nativeManager?: Parameters<typeof prepareNativeWorkerStartupView>[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<ExecutionResult> {
// 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 });
Expand All @@ -162,6 +164,8 @@ async function executeMirrorSync(input: Parameters<typeof runMirrorSync>[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);
Expand Down
Loading
Loading