From f74459256ad628ad1cdef82f1f1f4800e22beef9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:19:47 +0000 Subject: [PATCH 01/13] fix(ui-server): defer eligible result holds until inference dispatch --- .changeset/tidy-ithaca-freeze.md | 6 + docs/decisions/governed-writable-workers.md | 46 +++- packages/ui-sdk/src/server/egress-proxy.ts | 10 +- packages/ui-sdk/src/server/inference-relay.ts | 9 +- .../inference-diagnostic-isolation.test.ts | 1 + .../src/brain/deferred-observation.ts | 35 +++ packages/ui-server/src/brain/turn-egress.ts | 27 ++- packages/ui-server/src/brain/turn-journal.ts | 80 ++++++- packages/ui-server/src/brain/turn-scope.ts | 22 +- .../src/ws/session-run/backend-entry.ts | 1 + .../tests/deferred-freeze-runtime.test.ts | 62 +++++ .../ui-server/tests/deferred-freeze.test.ts | 217 ++++++++++++++++++ .../tests/helpers/deferred-freeze-fixture.ts | 60 +++++ 13 files changed, 559 insertions(+), 17 deletions(-) create mode 100644 .changeset/tidy-ithaca-freeze.md create mode 100644 packages/ui-server/src/brain/deferred-observation.ts create mode 100644 packages/ui-server/tests/deferred-freeze-runtime.test.ts create mode 100644 packages/ui-server/tests/deferred-freeze.test.ts create mode 100644 packages/ui-server/tests/helpers/deferred-freeze-fixture.ts diff --git a/.changeset/tidy-ithaca-freeze.md b/.changeset/tidy-ithaca-freeze.md new file mode 100644 index 0000000000..03f681dc3f --- /dev/null +++ b/.changeset/tidy-ithaca-freeze.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-server": patch +"@schlessera/brain-ui-sdk": patch +--- + +Overlap eligible per-tool journal observations with the next model request. Confirm the worker stop at full-request dispatch, retain every observation and its durability, and withhold the response until the observation and scope pause have committed. Unknown or concurrent work retains the immediate hold. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index ddeb05dc29..00a5e2e928 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1631,15 +1631,53 @@ from worker transcripts, and no extension of the observed-shell guarantee. > the scope-limit bound stay; no coalescing, overshoot relaxation or durability > change. +**Amendment (maintainer, 2026-11-20), Option A — deferred freeze (#4292).** +Keep a synchronous observation at every write-capable or unproven result. The +hold may be taken when the turn's relay has fully accepted the next inference +request and is about to dispatch it, instead of when the result is handled, +provided the stop is confirmed before dispatch. The upstream response then +overlaps the unchanged hold. A missing or ambiguous request, a pending sibling +call, an unknown writer or an interruption takes the immediate path. Each +required observation, its attribution, its durability and its terminal +accounting are preserved. One inference request may therefore be sent before +the observation's scope verdict is known. + +The implementation arms only one result boundary, with one 50 ms fallback +from that result. Dispatch, the deadline, a new tool or worker, another hold, +the periodic tick, finish, abort and shutdown claim that same boundary +synchronously; another result never coalesces with it +(`deferredObservation`, `packages/ui-server/src/brain/deferred-observation.ts:4-21`). Eligibility requires a +single active turn and worker, no pending calls globally, no peer unproven +producer, and no in-flight relay request at the result. Only a streaming +Messages request whose final assistant call and sole final user tool result +match that boundary can overlap. Token counts, tool-free titles, parallel +arrivals, unsupported request shapes and unknown transport state keep the +prior-verdict fence (`followsToolResult`, +`packages/ui-server/src/brain/deferred-observation.ts:24-36`). Admission still +checks both fences and the session binding. + +A synchronous control receipt, independent of diagnostic hold/timing marks, +confirms every stopped worker before upstream dispatch. A failed or legacy +void stop acknowledgement refuses dispatch and retains a partial journal +cause. The relay also holds response headers and body until the observation +and its scope writes commit. A scope refusal discards the in-flight upstream +response and records the connection as refused; the scope receipt remains +paused and the worker stays stopped for the existing authorized decision. +Files changed, observed turn bytes, index capacity, wall minutes and free +space can be discovered by this deferred observation after one request has +left. The tool-call cap is still checked at launch. No cap, credential, +recording or authority failure authorizes another request. These host facts +never enter provider history. + **Where the next request waited.** The bridge never awaits an observation: it starts one per result and carries on (`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:273`). The wait is the observation's hold. `held` takes it synchronously, before it queues the capture -(`function held`, `packages/ui-server/src/brain/turn-journal.ts:292-313`), +(`function held`, `packages/ui-server/src/brain/turn-journal.ts:320-364`), and the scope monitor's hold freezes every active turn's productive workers -until the capture completes (`before() {`, -`packages/ui-server/src/brain/turn-scope.ts:193-201`). Pi's agent loop runs in +until the capture completes (`before(hold?: JournalHold)`, +`packages/ui-server/src/brain/turn-scope.ts:255-272`). Pi's agent loop runs in its worker, so a frozen worker cannot send its next provider request until the resume. On the native fixture the gap between a result and the next request tracked the hold, not the bridge call. @@ -1648,7 +1686,7 @@ tracked the hold, not the bridge call. proven read-only, no other call of an active turn is still running, and no active turn has run a call whose effects may outlast it (`toolEnded(turnId: string, toolUseId: string)`, -`packages/ui-server/src/brain/turn-journal.ts:605-612`). Admission, turn end, +`packages/ui-server/src/brain/turn-journal.ts:681-703`). Admission, turn end, the 15-second timer, scope-limit observations, approved policy writes and removal coverage observe exactly as before. diff --git a/packages/ui-sdk/src/server/egress-proxy.ts b/packages/ui-sdk/src/server/egress-proxy.ts index ad264bc2d0..182fb7d330 100644 --- a/packages/ui-sdk/src/server/egress-proxy.ts +++ b/packages/ui-sdk/src/server/egress-proxy.ts @@ -365,7 +365,12 @@ export async function startEgressProxy(options: EgressProxyOptions) { if (finalReason === "taint_not_allowed") try { cause = options.taint?.cause?.(); } catch { /* The message names no cause. */ } return describeRefusal(finalReason, host, matches(host, options.deny), cause); }; - return { observeUsage, mark, finish, charge, admit, commit, refusal, signal: controller.signal, outcome: () => finalOutcome, reason: () => finalReason, pinned: () => pinned }; + // The concrete host turn wraps these only for per-result observation. + // Admission's own commit must never stop a partially transmitted request. + return { observeUsage, mark, finish, charge, admit, commit, + prepareDispatch: async (_body: Uint8Array) => true, + dispatch: () => commit(), responseReady: async () => true, + refusal, signal: controller.signal, outcome: () => finalOutcome, reason: () => finalReason, pinned: () => pinned }; } server.on("connect", (request, client, head) => { client.on("error", () => {}); @@ -471,7 +476,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { }; options.signal?.addEventListener("abort", stop, { once: true }); if (options.signal?.aborted) stop(); - return { dir, socketPath, stop, inferenceInFlight: () => inferenceControllers.size > 0, usedBytes: () => usedBytes, remainingBytes: () => Math.max(0, options.maxBytes - usedBytes), + return { dir, socketPath, stop, inferenceInFlight: () => inferenceControllers.size > 0, inferenceCount: () => inferenceControllers.size, usedBytes: () => usedBytes, remainingBytes: () => Math.max(0, options.maxBytes - usedBytes), /** The existing inference relay shares this turn's admission, counter and audit. */ inference(method: string, target: URL, signal: AbortSignal) { return relayedOperation(method, target, signal, "inference"); }, /** @@ -496,6 +501,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { signal.addEventListener("abort", abort, { once: true }); if (signal.aborted) abort(); return { observeUsage: op.observeUsage, mark: op.mark, charge: op.charge, signal: op.signal, outcome: op.outcome, refusal: op.refusal, reason: op.reason, + prepareDispatch: op.prepareDispatch, dispatch: op.dispatch, responseReady: op.responseReady, admit: async () => !op.signal.aborted && await op.admit() && (relay === "inference" || op.commit()), /** The concrete relay calls this again after its own final async waits. */ commit: op.commit, diff --git a/packages/ui-sdk/src/server/inference-relay.ts b/packages/ui-sdk/src/server/inference-relay.ts index 11100ab2b8..e6f28931b4 100644 --- a/packages/ui-sdk/src/server/inference-relay.ts +++ b/packages/ui-sdk/src/server/inference-relay.ts @@ -200,7 +200,8 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe // Body/credential waits may have crossed an input-recording failure. // Re-enter the concrete host admission at the last dispatch boundary. if(operation&&!await operation.admit())return denied("inference_admission_refused"); - if(operation&&!operation.commit())return denied("inference_admission_refused"); + if (operation && !await operation.prepareDispatch(body)) return denied("inference_admission_refused"); + if(operation&&!operation.dispatch())return denied("inference_admission_refused"); let response: Response; try { // Never follow a redirect: the upstream must not choose another host. @@ -212,6 +213,12 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe signal.aborted ? "Inference request cancelled" : "Inference upstream unreachable"); } mark("headersMs"); + // Even an immediate/large upstream answer cannot cross the result's + // durable observation boundary. This is control flow, never timing. + if (operation && !await operation.responseReady()) { + await response.body?.cancel().catch(() => {}); + return denied("deferred_observation_refused"); + } if (response.status >= 300 && response.status < 400) { operation?.finish("failed", "upstream_redirected"); await response.body?.cancel().catch(() => {}); diff --git a/packages/ui-sdk/tests/inference-diagnostic-isolation.test.ts b/packages/ui-sdk/tests/inference-diagnostic-isolation.test.ts index fac6dfd89b..8d3d013546 100644 --- a/packages/ui-sdk/tests/inference-diagnostic-isolation.test.ts +++ b/packages/ui-sdk/tests/inference-diagnostic-isolation.test.ts @@ -26,6 +26,7 @@ for (const point of points) test(`throwing relay diagnostic ${point} preserves d }) : undefined; const relay = startInferenceRelay({ upstream: upstream.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { inference() { return { + async prepareDispatch() { return true; }, dispatch() { return true; }, async responseReady() { return true; }, async admit() { return true; }, commit() { return true; }, charge() { return true; }, signal: controller.signal, outcome() { return outcome; }, reason() { return undefined; }, refusal() { return undefined; }, finish(value) { outcome = value; }, diff --git a/packages/ui-server/src/brain/deferred-observation.ts b/packages/ui-server/src/brain/deferred-observation.ts new file mode 100644 index 0000000000..d3d494d42f --- /dev/null +++ b/packages/ui-server/src/brain/deferred-observation.ts @@ -0,0 +1,35 @@ +/** One result boundary, claimed synchronously by dispatch or an interruption. */ +export const DEFERRED_OBSERVATION_MS = 50; + +export function deferredObservation(start: (confirmed?: { stopped: boolean }) => Promise) { + const done = Promise.withResolvers(); + let claimed = false; + const timer = setTimeout(() => claim(), DEFERRED_OBSERVATION_MS); + timer.unref?.(); + // A result's caller owns the error. The deadline must never reject unhandled. + void done.promise.catch(() => {}); + function claim(confirmed?: { stopped: boolean }): Promise { + if (!claimed) { + claimed = true; + clearTimeout(timer); + try { void start(confirmed).then(done.resolve, done.reject); } + catch (error) { done.reject(error); } + } + return done.promise; + } + return { done: done.promise, claim }; +} + +/** Exact single-call Messages continuation. Unknown protocols keep the prior verdict fence. */ +export function followsToolResult(path: string, body: Uint8Array, toolUseId: string): boolean { + if (path !== "/v1/messages") return false; + try { + const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body)); + if (value.stream !== true || !Array.isArray(value.tools) || !value.tools.length || !Array.isArray(value.messages)) return false; + const [assistant, user] = value.messages.slice(-2); + if (assistant?.role !== "assistant" || user?.role !== "user" || !Array.isArray(assistant.content) || !Array.isArray(user.content)) return false; + const calls = assistant.content.filter((block: { type?: string }) => block?.type === "tool_use"); + return calls.length === 1 && calls[0].id === toolUseId && user.content.length === 1 + && user.content[0]?.type === "tool_result" && user.content[0].tool_use_id === toolUseId; + } catch { return false; } +} diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index 7832e6f4f2..e854f4ef71 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -12,6 +12,8 @@ import { settleTurnSessionBinding } from "../ws/bridge-session-binding.js"; import { isMarkedUntrusted } from "../files/untrusted-marks.js"; import { createTurnExtraction } from "./turn-extraction.js"; import type { ExtractionJudge } from "../governance/extraction-judge.js"; +import type { TurnJournal } from "./turn-journal.js"; +import type { TurnScope } from "./turn-scope.js"; type Classification = Extract["classification"]; const GITHUB_API_HOSTS = ["api.github.com", "uploads.github.com"] as const; @@ -85,6 +87,8 @@ export function createOutwardCalls() { } export async function prepareTurnEgress(options: { + journal?: TurnJournal; + scope?: TurnScope; policy: EffectiveGovernancePolicy; policyHash?:string|null; bridge: BackendBridge; controller: AbortController; turnId: string; sessionId: () => string | null; model: () => string | null; profile: "governed" | "strict"; origin: "interactive" | "voice"; @@ -263,6 +267,8 @@ export async function prepareTurnEgress(options: { }, }); const original = options.bridge; + const releaseJournalRelay = options.journal && options.scope ? options.journal.relayStarted(options.turnId, + { inFlight: proxy.inferenceCount, eligible: () => options.scope!.canDefer(options.turnId) }, options.controller.signal) : undefined; /** The bridge the backend receives, so its classifications and results open and close each call. */ const bridge: BackendBridge = { ...original, emit(message) { calls.emitted(message); extraction?.emitted(message); original.emit(message); }, @@ -281,7 +287,25 @@ export async function prepareTurnEgress(options: { } const relayOperation = (kind: "inference" | "relayed", method: string, target: URL, signal: AbortSignal) => { const operation = proxy[kind](method, target, signal); - return settleOperation(operation); + const settledOperation = settleOperation(operation); + if (kind !== "inference" || !options.journal || !options.scope) return settledOperation; + let observation: Promise | undefined; + return { ...settledOperation, + async prepareDispatch(body: Uint8Array) { + try { return await options.journal!.prepareInference(options.turnId, target.pathname, body) && options.scope!.responseAllowed(options.turnId); } + catch { return false; } + }, + dispatch() { + if (!operation.commit()) return false; + const receipt = options.journal!.dispatchInference(options.turnId); + observation = receipt.ready; + return receipt.stopped; + }, + async responseReady() { + try { await observation; return !operation.signal.aborted && options.scope!.responseAllowed(options.turnId); } + catch { return false; } + }, + }; }; const settleOperation = (operation: ReturnType) => { return { ...operation, async admit() { @@ -303,6 +327,7 @@ export async function prepareTurnEgress(options: { } }; }; return { ...proxy, bridge, recordingFailure: () => recordingFailure, settled, + stop() { releaseJournalRelay?.(); proxy.stop(); }, inference: (method: string, target: URL, signal: AbortSignal) => relayOperation("inference", method, target, signal), relayed: (method: string, target: URL, signal: AbortSignal) => relayOperation("relayed", method, target, signal), managedReference: (target: URL, signal: AbortSignal) => settleOperation(proxy.managedReference(target, signal)) }; diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index e02f66fe37..613c908ac8 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -1,3 +1,4 @@ +import { deferredObservation, followsToolResult } from "./deferred-observation.js"; import type { ActivityTurnHold } from "@schlessera/brain-ui-sdk/protocol"; /** Concrete host journal: observations, durable ownership and completed-turn collection. */ import type { JournalRecoveryStatus } from "@schlessera/brain-ui-sdk/protocol"; @@ -105,6 +106,8 @@ export interface TurnJournalOptions { } /** Internal shared interval; scope records each turn's control acknowledgements. */ export interface JournalHold { + /** Control receipt required for speculative inference dispatch; never diagnostic. */ + requireConfirmedStop?: boolean; records: Map; stoppedTurns: Set; paths: Map>; @@ -288,7 +291,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { catch (error) { if (!(error instanceof JournalCapacityError) || !await collectOne()) throw error; } } } - const periodicObservers = new Set<{ before(hold?: JournalHold): void; after(completed: boolean, hold?: JournalHold): void }>(); + const periodicObservers = new Set<{ before(hold?: JournalHold): void; after(completed: boolean, hold?: JournalHold): void; settled?(): Promise }>(); const evidence = new Map void; inference: () => boolean }>(); let currentHold: JournalHold | undefined; const observers = new Set<(turnId: string, facts: { changedPaths: number; observedBytes: number; workspacePaths: number; indexBytes?: number | null; partial: boolean; observationChangedPaths?: number; observationToolUseId?: string }) => void>(); @@ -303,13 +306,22 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const calls = new Map(); const lasting = new Set(); const callKey = (turnId: string, toolUseId: string) => JSON.stringify([turnId, toolUseId]); + const relays = new Map(); + let deferred: { turnId: string; toolUseId: string; observation: ReturnType } | undefined; + function flushDeferred(): Promise { + const pending = deferred; + if (!pending) return Promise.resolve(); + deferred = undefined; + return pending.observation.claim(); + } let holds = 0; let observationFailures = 0; /** `trace` also times the hold itself; `lifecycle` sees every step but that one. */ function held(operation: (timing?: PhaseTimer) => Promise, admission = false, trace?: PhaseTimer, lifecycle?: PhaseTimer, - cause: { kind: ActivityTurnHold["cause"]; turnId: string | null; toolUseId?: string; hold?: ActivityTurnHold } = { kind: "scope", turnId: null }): Promise { + cause: { kind: ActivityTurnHold["cause"]; turnId: string | null; toolUseId?: string; hold?: ActivityTurnHold } = { kind: "scope", turnId: null }, confirmed?: { stopped: boolean }): Promise { + void flushDeferred().catch(() => {}); const holdId = cause.hold?.holdId ?? crypto.randomUUID(), requestedAt = Date.now(); - const interval: JournalHold = { records: new Map(), stoppedTurns: new Set(), paths: new Map(), + const interval: JournalHold = { ...(confirmed ? { requireConfirmedStop: true } : {}), records: new Map(), stoppedTurns: new Set(), paths: new Map(), inferenceInFlight: id => diagnostic(() => evidence.get(id)?.inference() ?? false) ?? null, participant(id) { const previous = interval.records.get(id); if (previous) return previous; @@ -331,12 +343,15 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { let acquired = 0; try { for (const holder of holders) { acquired++; holder.before(interval); } } catch (error) { holds--; for (const holder of holders.slice(0, acquired)) holder.after(false, interval); return Promise.reject(error); } + if (confirmed) confirmed.stopped = holders.length > 0; return serialize(async () => { waited?.(); currentHold = interval; let completed = false; const failedBefore = observationFailures; - try { const result = await operation(timing); completed = true; return result; } + try { const result = await operation(timing); + for (const holder of holders) await holder.settled?.(); + completed = true; return result; } finally { // A cancelled/refused new admission made no worker writes. Existing // participants resume when their shared observation itself succeeded, @@ -350,6 +365,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { } /** The turn is partial at once; its durable marker commits after. */ async function fail(turnId: string, error: unknown) { + void flushDeferred().catch(() => {}); const reason = error instanceof JournalCapacityError ? "journal_capacity" : "journal_unavailable"; failures.set(turnId, reason); // Admission preallocates this fixed-size terminal slot. It never needs a @@ -573,7 +589,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { evidence(turnId: string, record?: (hold: ActivityTurnHold) => void, inference: () => boolean = () => false) { if (record) evidence.set(turnId, { record, inference }); else evidence.delete(turnId); }, - onObservation(observer: (turnId: string, facts: { changedPaths: number; observedBytes: number; workspacePaths: number; indexBytes?: number | null; partial: boolean; observationChangedPaths?: number; observationToolUseId?: string }) => void, periodic?: { before(hold?: JournalHold): void; after(completed: boolean, hold?: JournalHold): void }) { + onObservation(observer: (turnId: string, facts: { changedPaths: number; observedBytes: number; workspacePaths: number; indexBytes?: number | null; partial: boolean; observationChangedPaths?: number; observationToolUseId?: string }) => void, periodic?: { before(hold?: JournalHold): void; after(completed: boolean, hold?: JournalHold): void; settled?(): Promise }) { observers.add(observer); if (periodic) periodicObservers.add(periodic); return () => { if (periodic) periodicObservers.delete(periodic); return observers.delete(observer); }; }, @@ -645,6 +661,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { * or another name, makes that call unproven. */ toolStarted(turnId: string, toolUseId: string, name: string, start: boolean): void { + void flushDeferred().catch(() => {}); if (!active.has(turnId)) return; const key = callKey(turnId, toolUseId), call = calls.get(key); if (!call) { calls.set(key, { turnId, name, started: start }); return; } @@ -662,12 +679,60 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { * may outlast it. A call that could write is observed after its own result. */ toolEnded(turnId: string, toolUseId: string): Promise { + void flushDeferred().catch(() => {}); const key = callKey(turnId, toolUseId), call = calls.get(key); calls.delete(key); const effect = call ? toolObservation(call.name, call.path) : "unproven"; if (effect === "unproven" && active.has(turnId)) lasting.add(turnId); if (effect === "read" && !lasting.size && !calls.size) return Promise.resolve(); - return held(timing => observe(false, timing), false, traceFor("tool", turnId, toolUseId), undefined, { kind: "tool", turnId, toolUseId }); + const start = (confirmed?: { stopped: boolean }) => held(timing => observe(false, timing), false, + traceFor("tool", turnId, toolUseId), undefined, { kind: "tool", turnId, toolUseId }, confirmed); + const relay = relays.get(turnId); + // A sibling, parent, peer producer or unknown transport keeps the immediate schedule. + if (!closing && !holds && active.size === 1 && active.has(turnId) && call?.started && call.name !== null + && !calls.size && ![...lasting].some(id => id !== turnId) && relay?.eligible() && relay.inFlight() === 0) { + const pending = { turnId, toolUseId, observation: deferredObservation(confirmed => { + if (deferred === pending) deferred = undefined; + return start(confirmed).catch(async error => { + await fail(turnId, error); + throw error; + }); + }) }; + deferred = pending; + return pending.observation.done; + } + return start(); + }, + /** Concrete turn relay lifecycle; absence always uses immediate observations. */ + relayStarted(turnId: string, transport: { inFlight(): number; eligible(): boolean }, signal: AbortSignal) { + void flushDeferred().catch(() => {}); + relays.set(turnId, transport); + const abort = () => { void flushDeferred().catch(() => {}); if (relays.get(turnId) === transport) relays.delete(turnId); }; + signal.addEventListener("abort", abort, { once: true }); + if (signal.aborted) abort(); + return () => { signal.removeEventListener("abort", abort); abort(); }; + }, + flushDeferred, + /** Fully read request only. Ambiguous traffic keeps the prior-verdict boundary. */ + async prepareInference(turnId: string, path: string, body: Uint8Array): Promise { + const relay = relays.get(turnId); + if (deferred?.turnId === turnId && relay?.eligible() && relay.inFlight() === 1 + && followsToolResult(path, body, deferred.toolUseId)) return true; + await flushDeferred(); + await tail; + return !failures.has(turnId); + }, + /** No await between the confirmed stop and the relay's fetch. */ + dispatchInference(turnId: string): { stopped: boolean; ready: Promise } { + const pending = deferred; + if (pending?.turnId !== turnId) return { stopped: !holds && !failures.has(turnId), ready: tail.then(() => {}) }; + deferred = undefined; + const confirmed = { stopped: false }; + const relay = relays.get(turnId); + // Parallel arrivals after arming invalidate the one-request attribution. + if (!relay?.eligible() || relay.inFlight() !== 1) return { stopped: false, ready: pending.observation.claim() }; + const ready = pending.observation.claim(confirmed); + return { stopped: confirmed.stopped, ready }; }, /** * Cover one managed worktree (#2430) for an active turn before any of its @@ -709,6 +774,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { for (const root of retiredWorktrees) await root.releasesSettled(); }, async idle(): Promise { + await flushDeferred(); let waiting: Promise; do { waiting = tail; await waiting; } while (waiting !== tail); // Background worktree cleanup (#3825) is not awaited here: every turn's @@ -955,7 +1021,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { /** @internal Runs one idle maintenance pass now; settles once it has (#3355). */ maintain, async close() { - closing = true; clearInterval(idleTimer); shutdown.abort(new Error("turn journal closed")); + closing = true; void flushDeferred().catch(() => {}); clearInterval(idleTimer); shutdown.abort(new Error("turn journal closed")); clearTimeout(worktreeRetryTimer); worktreeRetryTimer = undefined; clearInterval(scopeTimer); try { await tail; await worktreeRetry; await Promise.allSettled([...unserialized]); await dropWorktrees(); await capture.close(); } diff --git a/packages/ui-server/src/brain/turn-scope.ts b/packages/ui-server/src/brain/turn-scope.ts index c753798add..02e399870f 100644 --- a/packages/ui-server/src/brain/turn-scope.ts +++ b/packages/ui-server/src/brain/turn-scope.ts @@ -257,12 +257,20 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour if (observationHolds++ > 0) { timing(() => recordStops(hold)); return; } observationFailed = false; for (const [turnId, turn] of active) { - if (!turn.current() || turn.summary.receipts.some(receipt => receipt.state === "paused")) continue; + if (turn.summary.receipts.some(receipt => receipt.state === "paused")) continue; const held: Worker[] = []; periodicHeld.set(turnId, { turn, workers: held }); - for (const worker of turn.workers) { held.push(worker); freeze(worker); } + if (hold?.requireConfirmedStop && !turn.workers.size) throw new Error("Deferred observation has no worker to stop"); + for (const worker of turn.workers) { + held.push(worker); + freeze(worker); + if (hold?.requireConfirmedStop && !confirmed(worker)) throw new Error("Deferred worker stop was not confirmed"); + } if (hold) timing(() => recordStop(hold, turnId, held.filter(confirmed))); } }, + async settled() { + for (const id of active.keys()) for (let tail = tails.get(id); tail; tail = tails.get(id)) await tail; + }, after(completed: boolean, hold?: JournalHold) { if (hold) intervals.delete(hold); observationFailed ||= !completed; @@ -317,6 +325,7 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour }); }, workerStarted(turnId: string, worker: Worker) { + void options.journal.flushDeferred?.().catch(() => {}); const turn = active.get(turnId); if (!turn || !turn.current()) { worker.kill("SIGKILL"); return; } turn.workers.add(worker); void worker.exited.finally(() => { turn.workers.delete(worker); confirmedStops.delete(worker); }).catch(() => {}); @@ -336,6 +345,15 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour const turn = active.get(turnId); if (!turn || turn.calls.has(toolUseId)) return; turn.calls.add(toolUseId); turn.summary.calls = turn.calls.size; check(turnId, turn, { toolUseId }); }, + canDefer(turnId: string): boolean { + const turn = active.get(turnId); + return !!turn && turn.current() && !turn.unrecorded && turn.workers.size === 1 && !observationHolds + && !turn.summary.receipts.some(receipt => receipt.state === "paused"); + }, + responseAllowed(turnId: string): boolean { + const turn = active.get(turnId); + return !!turn && turn.current() && !turn.unrecorded && !turn.summary.receipts.some(receipt => receipt.state === "paused"); + }, isPaused(turnId: string) { return active.get(turnId)?.summary.receipts.some(receipt => receipt.state === "paused") ?? false; }, /** * Settles once every scope write the turn made before the decision has diff --git a/packages/ui-server/src/ws/session-run/backend-entry.ts b/packages/ui-server/src/ws/session-run/backend-entry.ts index debd116ddc..df58527e43 100644 --- a/packages/ui-server/src/ws/session-run/backend-entry.ts +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -178,6 +178,7 @@ export async function prepareRelayedEgress(run: TurnRun, bridge: BackendBridge, ...(governedHold.typeFolders ? { typeFolders: governedHold.typeFolders } : {}), budgets: host.budgets, observe: observeAttempt, stopped: () => abortController.signal.aborted ? "The turn was stopped." : (stops.budget as Error | undefined)?.message ?? null }); held.turnEgress = await prepareTurnEgress({ policy: governedHold.policy.policy, bridge, controller: abortController, + ...(host.journal && host.scope ? { journal: host.journal, scope: host.scope } : {}), turnId: turn.turnId, sessionId: () => turn.sessionId ?? null, model: () => run.mainModel, profile: heldProfile(run), origin,policyHash:governedHold.policy.hash, brainPath: host.brainPath, // A record's commit failure stops the turn, as a synchronous one did (#2850). diff --git a/packages/ui-server/tests/deferred-freeze-runtime.test.ts b/packages/ui-server/tests/deferred-freeze-runtime.test.ts new file mode 100644 index 0000000000..cdccff7c17 --- /dev/null +++ b/packages/ui-server/tests/deferred-freeze-runtime.test.ts @@ -0,0 +1,62 @@ +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { startInferenceRelay } from "@schlessera/brain-ui-sdk/internal"; +import { fixture, body } from "./helpers/deferred-freeze-fixture"; +import { watchdogMs } from "../../../scripts/test-deadlines"; + +// A real stopped reader and a response above the socket buffer are the failure +// mode: controlled time and a fake worker cannot exercise kernel backpressure. +// Ten seconds is the issue's observation window, not a readiness sleep. +test("a real stopped worker receives an 8 MiB stream only after its ten-second observation commits", async () => { + const child = Bun.spawn([process.execPath, "-e", ` + import { request } from "node:http"; + const reader = Bun.stdin.stream().getReader(); + const { value } = await reader.read(); + const { socketPath, body } = JSON.parse(new TextDecoder().decode(value)); + const req = request({ socketPath, path: "/v1/messages", method: "POST" }, res => { + let bytes = 0; res.on("data", chunk => bytes += chunk.length); + res.on("end", () => { console.log(JSON.stringify({ status: res.statusCode, bytes })); process.exit(0); }); + }); req.on("error", error => { console.error(String(error)); process.exit(1); }); req.end(body); + `], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + let stopped = false, committed = false; + const freeze = () => { + child.kill("SIGSTOP"); + const deadline = performance.now() + watchdogMs(5000); + for (;;) { + const state = readFileSync(`/proc/${child.pid}/stat`, "utf8").replace(/^.*\) /s, "")[0]; + if (state === "T") { stopped = true; return true; } + if (performance.now() > deadline) throw new Error("Owned worker did not stop"); + Bun.sleepSync(1); + } + }; + const f = await fixture(100, { freeze, resume() { expect(committed, "PROCESS_CANNOT_RESUME_BEFORE_COMMIT").toBe(true); child.kill("SIGCONT"); stopped = false; return true; }, kill(signal) { child.kill(signal); return true; }, exited: child.exited }); + const checkpoint = f.native.manager.checkpoint, dispatched = Promise.withResolvers(); + let produced = 0; + const total = 8 * 1024 * 1024; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { + expect(stopped, "REAL_PROCESS_STOP_CONFIRMED_BEFORE_UPSTREAM").toBe(true); dispatched.resolve(); + return new Response(new ReadableStream({ pull(controller) { + if (produced === total) controller.close(); + else { const chunk = new Uint8Array(64 * 1024).fill(73); produced += chunk.length; controller.enqueue(chunk); } + } })); + } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); + try { + let captureStarted = 0; + f.native.manager.checkpoint = async (...args) => { + captureStarted = performance.now(); await Bun.sleep(10_000); + return checkpoint(...args); + }; + f.journal.onObservation(() => { committed = true; }); + const observed = f.result(); + child.stdin.write(JSON.stringify({ socketPath: relay.socketPath, body: body() })); child.stdin.end(); + await dispatched.promise; + expect(stopped).toBe(true); + await observed; + expect(performance.now() - captureStarted, "TEN_SECOND_OBSERVATION_WAS_EXERCISED").toBeGreaterThanOrEqual(10_000); + expect(await child.exited).toBe(0); + expect(JSON.parse(await new Response(child.stdout).text())).toEqual({ status: 200, bytes: total }); + expect(await new Response(child.stderr).text()).toBe(""); + expect(produced).toBe(total); + } finally { child.kill("SIGKILL"); await child.exited; f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } +}, watchdogMs(60_000)); diff --git a/packages/ui-server/tests/deferred-freeze.test.ts b/packages/ui-server/tests/deferred-freeze.test.ts new file mode 100644 index 0000000000..cca4c5ec13 --- /dev/null +++ b/packages/ui-server/tests/deferred-freeze.test.ts @@ -0,0 +1,217 @@ +import { expect, test } from "bun:test"; +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { startInferenceRelay } from "@schlessera/brain-ui-sdk/internal"; +import { body, fixture, send } from "./helpers/deferred-freeze-fixture"; + +test("eligible result leaves the worker running until full request dispatch; response waits for committed observation", async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(), dispatched = Promise.withResolvers(); + const checkpoint = f.native.manager.checkpoint; + let upstream = 0, delivered = false; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; expect(f.frozen, "STOP_CONFIRMED_BEFORE_DISPATCH").toBe(true); dispatched.resolve(); return new Response("Ithaca"); } }); + const responseBoundary = Promise.withResolvers(); + let responseGateSettled = false; + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { + inference(...args) { + const operation = f.proxy.inference(...args); + return { ...operation, responseReady() { + const ready = operation.responseReady(); + void ready.then(() => { responseGateSettled = true; }); + responseBoundary.resolve(); return ready; + } }; + }, + } }); + try { + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + writeFileSync(join(f.brain, "note.md"), "Penelope"); + const observed = f.result(); + expect(f.frozen, "ELIGIBLE_RESULT_DEFERS_HOLD").toBe(false); + const response = send(relay.socketPath).then(value => { delivered = true; return value; }); + void response.catch(() => {}); + await entered.promise; await dispatched.promise; await responseBoundary.promise; + await Promise.resolve(); + expect(responseGateSettled, "RESPONSE_CANNOT_PRECEDE_OBSERVATION_COMMIT").toBe(false); + expect(delivered).toBe(false); + expect(upstream).toBe(1); + release.resolve(); await observed; + expect(await response).toEqual({ status: 200, bytes: 6 }); + expect(f.journal.details("ithaca", "voyage")!.changes.map(change => change.path)).toEqual(["note.md"]); + expect(f.frozen).toBe(false); + } finally { release.resolve(); f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } +}); + +for (const boundary of ["deadline", "new tool", "new worker", "periodic", "abort", "finish", "shutdown"] as const) { + test(`${boundary} claims an armed result exactly once and retains its observation`, async () => { + const f = await fixture(); let observations = 0; + const unsubscribe = f.journal.onObservation(() => { observations++; }); + try { + const observed = f.result(); + expect(f.frozen, "ARMED_BOUNDARY_RUNS_UNTIL_CLAIM").toBe(false); + expect(f.deadlines).toHaveLength(1); + let terminal: Promise | undefined; + if (boundary === "deadline") f.fireDeadline(); + else if (boundary === "new tool") f.journal.toolStarted("voyage", "sail", "Read", true); + else if (boundary === "new worker") f.scope.workerStarted("voyage", { freeze: () => true, resume: () => true, kill: () => true, exited: new Promise(() => {}) }); + else if (boundary === "periodic") { f.tick(); terminal = f.journal.idle(); } + else if (boundary === "abort") f.controller.abort(); + else if (boundary === "finish") terminal = f.journal.finish("voyage"); + else terminal = f.journal.close(); + expect(f.frozen, "INTERRUPTION_SYNCHRONOUSLY_TAKES_HOLD").toBe(true); + await observed; await terminal; + expect(observations, "RESULT_IS_NEVER_COALESCED_WITH_ANOTHER_BOUNDARY").toBe(boundary === "periodic" || boundary === "finish" ? 2 : 1); + expect(f.deadlines.filter(item => !item.cancelled)).toHaveLength(0); + } finally { unsubscribe(); await f.close(); } + }); +} + +for (const uncertainty of ["sibling", "subagent parent", "second session", "unknown call", "request in flight"] as const) { + test(`${uncertainty} keeps the synchronous per-result hold`, async () => { + const f = await fixture(); + let operation: ReturnType | undefined; + try { + if (uncertainty === "sibling" || uncertainty === "subagent parent") f.journal.toolStarted("voyage", "other", uncertainty === "sibling" ? "Read" : "Agent", true); + if (uncertainty === "second session") await f.journal.begin("pylos", { sessionId: null, actor: "interactive", model: null, profile: "governed", policyHash: null }, () => {}); + if (uncertainty === "request in flight") operation = f.proxy.inference("POST", new URL("http://127.0.0.1/v1/messages"), new AbortController().signal); + const observed = uncertainty === "unknown call" ? f.journal.toolEnded("voyage", "unknown") : f.result(); + expect(f.frozen, "UNKNOWN_EVIDENCE_USES_IMMEDIATE_HOLD").toBe(true); + expect(f.deadlines).toHaveLength(0); + await observed; + } finally { operation?.finish("cancelled"); await f.close(); } + }); +} + +for (const requestKind of ["token count", "title", "wrong result", "parallel results", "retry without result", "invalid JSON"] as const) { + test(`${requestKind} commits the immediate observation before dispatch`, async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const checkpoint = f.native.manager.checkpoint; + let upstream = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages", "/v1/messages/count_tokens"], credentials: {}, egress: f.proxy }); + try { + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + const observed = f.result(); + const value = JSON.parse(body()); + if (requestKind === "title") delete value.tools; + if (requestKind === "parallel results") value.messages.at(-1).content.push({ type: "tool_result", tool_use_id: "sail", content: "Ithaca" }); + if (requestKind === "retry without result") value.messages.pop(); + const content = requestKind === "invalid JSON" ? "{" : requestKind === "wrong result" ? body("sail") : JSON.stringify(value); + const response = send(relay.socketPath, content, requestKind === "token count" ? "/v1/messages/count_tokens" : "/v1/messages"); + await entered.promise; + expect(upstream, "AMBIGUOUS_REQUEST_CANNOT_OVERTAKE_VERDICT").toBe(0); + release.resolve(); await observed; + expect((await response).status).toBe(200); + expect(upstream).toBe(1); + } finally { release.resolve(); f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } + }); +} + +for (const ack of [false, undefined] as const) { + test(`a ${String(ack)} stop receipt refuses speculative dispatch`, async () => { + const f = await fixture(); let upstream = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); + try { + f.ack(ack); + const observed = f.result(); + const refusedObservation = observed.then(() => false, () => true); + expect((await send(relay.socketPath)).status, "UNCONFIRMED_STOP_REFUSES_DISPATCH").toBe(403); + expect(await refusedObservation).toBe(true); + expect(upstream).toBe(0); + expect(f.controller.signal.aborted).toBe(true); + expect(f.journal.summary("voyage").state, "FAILED_STOP_IS_DURABLY_PARTIAL").toBe("partial"); + } finally { relay.stop(); origin.stop(true); await f.close(); } + }); +} + +test("a deferred cap commits its pause and refusal before any response body reaches the worker", async () => { + const f = await fixture(1); let upstream = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("must stay withheld"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); + try { + writeFileSync(join(f.brain, "note.md"), "Penelope"); + const observed = f.result(); + const response = await send(relay.socketPath); await observed; + expect(upstream, "ONE_REQUEST_MAY_PRECEDE_SCOPE_VERDICT").toBe(1); + expect(response.status, "CAP_REFUSES_THE_IN_FLIGHT_RESPONSE").toBe(403); + expect(f.frozen).toBe(true); + const row = f.db.query("SELECT summary FROM turn_scope WHERE turn_id='voyage'").get() as { summary: string }; + expect(JSON.parse(row.summary).receipts).toMatchObject([{ dimension: "files_changed", state: "paused", frozen: true }]); + expect(f.resumes).toBe(0); + } finally { relay.stop(); origin.stop(true); await f.close(); } +}); + +test("a second result gets a separate observation rather than replacing the armed boundary", async () => { + const f = await fixture(); let observations = 0; + f.journal.onObservation(() => { observations++; }); + try { + const first = f.result("loom"), second = f.result("sail"); + expect(f.frozen).toBe(true); + await first; await second; + expect(observations, "BOTH_RESULT_BOUNDARIES_COMMIT").toBe(2); + expect(f.deadlines).toHaveLength(1); + } finally { await f.close(); } +}); + +test("receiving headers or a partial request body cannot stop the sending worker", async () => { + const f = await fixture(), admitted = Promise.withResolvers(); + let upstream = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { + inference(...args) { const operation = f.proxy.inference(...args); return { ...operation, async admit() { const allowed = await operation.admit(); admitted.resolve(); return allowed; } }; }, + } }); + let outgoing: ReturnType | undefined; + try { + const observed = f.result(); + const { request } = await import("node:http"); + const completed = new Promise((resolve, reject) => { + outgoing = request({ socketPath: relay.socketPath, path: "/v1/messages", method: "POST" }, response => { + response.resume(); response.on("error", reject); response.on("end", () => resolve(response.statusCode!)); + }); outgoing.on("error", reject); outgoing.write(body().slice(0, 10)); + }); + await admitted.promise; + expect(f.frozen, "PARTIAL_REQUEST_MUST_REMAIN_WRITABLE").toBe(false); + expect(upstream).toBe(0); + outgoing!.end(body().slice(10)); + expect(await completed).toBe(200); await observed; + expect(upstream).toBe(1); + } finally { outgoing?.destroy(); relay.stop(); origin.stop(true); await f.close(); } +}); + +test("a fallback during the final admission waits for the verdict and forwards without retry", async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const checkpoint = f.native.manager.checkpoint; let upstream = 0, fences = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { + inference(...args) { const operation = f.proxy.inference(...args); return { ...operation, async admit() { + if (++fences === 2) f.fireDeadline(); + return operation.admit(); + } }; }, + } }); + try { + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + const observed = f.result(), response = send(relay.socketPath); void response.catch(() => {}); + await entered.promise; + expect(upstream, "FALLBACK_RETAINS_PRIOR_VERDICT_FENCE").toBe(0); + release.resolve(); await observed; + expect((await response).status, "FALLBACK_NEEDS_NO_PROVIDER_RETRY").toBe(200); + expect(upstream).toBe(1); expect(fences).toBe(2); + } finally { release.resolve(); f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } +}); + +test("a parallel arrival after arming returns to the immediate observation path", async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const checkpoint = f.native.manager.checkpoint; let upstream = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); + let parallel: ReturnType | undefined; + try { + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + const observed = f.result(); + parallel = f.proxy.inference("POST", new URL("/v1/messages", origin.url), new AbortController().signal); + const response = send(relay.socketPath); void response.catch(() => {}); + await entered.promise; + expect(upstream, "PARALLEL_REQUESTS_DO_NOT_SPECULATE").toBe(0); + release.resolve(); await observed; + expect((await response).status).toBe(200); expect(upstream).toBe(1); + } finally { release.resolve(); parallel?.finish("cancelled"); f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } +}); diff --git a/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts b/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts new file mode 100644 index 0000000000..fbf39b7176 --- /dev/null +++ b/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts @@ -0,0 +1,60 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { resolveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { request } from "node:http"; +import { createUiDb } from "../../src/db/client"; +import { createTurnJournal } from "../../src/brain/turn-journal"; +import { createTurnScope } from "../../src/brain/turn-scope"; +import { prepareTurnEgress } from "../../src/brain/turn-egress"; +import { registeredInterval } from "./registered-interval"; +import { createNativeJournalFixture } from "./native-journal-fixture"; + +export const body = (id = "loom") => JSON.stringify({ model: "odysseus", stream: true, tools: [{ name: "Write" }], messages: [ + { role: "assistant", content: [{ type: "tool_use", id, name: "Write", input: {} }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: id, content: "Ithaca" }] }, +] }); +export async function fixture(cap = 100, realWorker?: Parameters["workerStarted"]>[1]) { + const root = mkdtempSync(join(tmpdir(), "odysseus-deferred-")), brain = join(root, "brain"), path = join(root, "ui.db"); + mkdirSync(brain); writeFileSync(join(brain, "note.md"), "Odysseus"); + const native = createNativeJournalFixture(brain, root), db = createUiDb(path), controller = new AbortController(); + const journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: brain, dbPath: path, objectsRoot: join(root, "objects") }); + const scope = createTurnScope(db, { brainPath: brain, journal, connected: () => true, changed() {}, space: () => ({ total: 100e9, free: 90e9 }) }); + db.query("INSERT INTO sessions(id,title,created_at,last_active_at) VALUES ('ithaca','Voyage',0,0)").run(); + const policy = resolveGovernancePolicy({ schema_version: 1, scope: { max_files_changed: cap } }); + const interval = registeredInterval(); + await journal.begin("voyage", { sessionId: "ithaca", actor: "interactive", model: null, profile: "governed", policyHash: null }, error => controller.abort(error)); + interval.finishRegistration(); + await scope.begin("voyage", { sessionId: "ithaca", principalId: "captain", origin: "interactive", profile: "governed", policy, source: "policy", hardTimeoutMs: 1e6, current: () => !controller.signal.aborted, stop: reason => controller.abort(new Error(reason)) }); + let frozen = false, stops = 0, resumes = 0, ack: boolean | void = true; + const worker = { freeze() { frozen = true; stops++; return ack; }, resume() { frozen = false; resumes++; return true; }, kill() { frozen = true; return true; }, exited: new Promise(() => {}) }; + scope.workerStarted("voyage", realWorker ?? worker); + const proxy = await prepareTurnEgress({ policy, controller, turnId: "voyage", sessionId: () => "ithaca", model: () => null, + profile: "governed", origin: "interactive", journal, scope, + bridge: { emit() {}, requestPermission: async () => ({ behavior: "deny" }) } as unknown as BackendBridge }); + const descriptor = Object.getOwnPropertyDescriptor(globalThis, "setTimeout")!; + const clearDescriptor = Object.getOwnPropertyDescriptor(globalThis, "clearTimeout")!; + const realSet = setTimeout, realClear = clearTimeout; + const deadlines: { callback: () => void; handle: ReturnType; cancelled: boolean }[] = []; + Object.defineProperty(globalThis, "setTimeout", { ...descriptor, value: (callback: () => void, ms?: number, ...args: unknown[]) => { + if (ms !== 50) return realSet(callback, ms, ...args); + const handle = { unref() {} } as ReturnType; + deadlines.push({ callback, handle, cancelled: false }); return handle; + } }); + Object.defineProperty(globalThis, "clearTimeout", { ...clearDescriptor, value: (handle: ReturnType) => { + const item = deadlines.find(item => item.handle === handle); + if (item) item.cancelled = true; else realClear(handle); + } }); + const restore = () => { interval.restore(); Object.defineProperty(globalThis, "setTimeout", descriptor); Object.defineProperty(globalThis, "clearTimeout", clearDescriptor); }; + const result = (id = "loom") => { journal.toolStarted("voyage", id, "Write", true); return journal.toolEnded("voyage", id); }; + return { tick() { interval.advanceTo(15000); }, deadlines, fireDeadline() { const item = deadlines.find(item => !item.cancelled)!; item.cancelled = true; item.callback(); }, root, brain, db, native, journal, scope, proxy, controller, result, get frozen() { return frozen; }, get stops() { return stops; }, get resumes() { return resumes; }, ack(value: boolean | void) { ack = value; }, + async close() { try { controller.abort(); proxy.stop(); await proxy.settled(); await journal.idle(); scope.close(); await journal.close(); await native.close(); db.close(); rmSync(root, { recursive: true, force: true }); } finally { restore(); } } }; +} +export function send(socketPath: string, content = body(), path = "/v1/messages") { + return new Promise<{ status: number; bytes: number }>((resolve, reject) => { + const outgoing = request({ socketPath, path, method: "POST", headers: { "content-type": "application/json" } }, incoming => { + let bytes = 0; incoming.on("data", chunk => { bytes += chunk.length; }); incoming.on("end", () => resolve({ status: incoming.statusCode!, bytes })); incoming.on("error", reject); + }); outgoing.on("error", reject); outgoing.end(content); + }); +} From ec7b6366f7fdcad8f458c35627df3c15458c487a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:19:58 +0000 Subject: [PATCH 02/13] test(ui-server): measure inference admission joins on the native fixture --- experiments/admission-join.test.ts | 20 +++++++++ scripts/native-proof/README.md | 10 +++++ scripts/native-proof/admission-join.ts | 55 ++++++++++++++++++++++++ scripts/native-proof/hosted-app-child.ts | 9 +++- scripts/native-proof/hosted-app.test.ts | 5 +++ 5 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 experiments/admission-join.test.ts create mode 100644 scripts/native-proof/admission-join.ts diff --git a/experiments/admission-join.test.ts b/experiments/admission-join.test.ts new file mode 100644 index 0000000000..9687db4638 --- /dev/null +++ b/experiments/admission-join.test.ts @@ -0,0 +1,20 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { measureAdmissionJoin } from "../scripts/native-proof/admission-join"; + +test("admission measurement retains both fences and every hold/delay cell with real FULL writes", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-admission-measure-")); + try { + const measured = await measureAdmissionJoin(root, 1); + expect(measured.rows.map(row => [row.hold, row.delayMs, row.queuedCommits, row.fences])).toEqual([ + ["drained", 10, 20, 2], ["drained", 50, 20, 2], ["drained", 500, 20, 2], + ["removed", 10, 20, 2], ["removed", 50, 20, 2], ["removed", 500, 20, 2], + ]); + for (const row of measured.rows) { + expect(row.admitMs).toBeGreaterThanOrEqual(0); + expect(row.credentialToDispatchMs).toBeGreaterThanOrEqual(0); + } + } finally { rmSync(root, { recursive: true, force: true }); } +}); diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index 7ac4c68e6f..45e2f289ae 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -58,6 +58,16 @@ phases and steps per scenario, and the host load before and after are in `observation-timing.json`. It is a measurement, not part of the default qualification. +The timing run also writes `admission-join.json` (#4293): five samples at +10, 50 and 500 ms after a synthetic result, each with the audit queue drained +and with the hold removed. Twenty prior inference records load the actual +FULL writer; each sample retains `admitMs`, credential-to-dispatch elapsed +time and the two admission fences. This isolates the join with a real Unix +relay and write worker. It does not measure Claude runtime request assembly: +the existing Claude hosted fixture uses a mock query. Standalone local +measurement uses `bun scripts/native-proof/admission-join.ts `; +its filesystem is the directory supplied, and it makes no native-storage claim. + `--tree=large` adds deterministic empty workspace/dependency files and tiny content-addressed journal objects before the app starts. Defaults: `--workspace-entries=80000 --dependency-entries=19000 --journal-objects=30000 diff --git a/scripts/native-proof/admission-join.ts b/scripts/native-proof/admission-join.ts new file mode 100644 index 0000000000..d3817db842 --- /dev/null +++ b/scripts/native-proof/admission-join.ts @@ -0,0 +1,55 @@ +/** Offline measurement of both inference fences with real FULL audit writes. */ +import { mkdtempSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { resolveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { startInferenceRelay, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; +import { createUiDb } from "../../packages/ui-server/src/db/client.js"; +import { openSqliteWriter } from "../../packages/ui-server/src/db/write-worker.js"; +import { createGovernanceWrites } from "../../packages/ui-server/src/governance/event-writes.js"; +import { prepareTurnEgress } from "../../packages/ui-server/src/brain/turn-egress.js"; +import { request } from "node:http"; + +export async function measureAdmissionJoin(directory: string, samples = 5) { + const root = mkdtempSync(join(directory, "admission-join-")), db = createUiDb(join(root, "ui.db")); + const writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); + const rows: { hold: "drained" | "removed"; delayMs: number; sample: number; queuedCommits: number; admitMs: number; credentialToDispatchMs: number; fences: number }[] = []; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { await req.arrayBuffer(); return new Response("Ithaca"); } }); + try { + for (const hold of ["drained", "removed"] as const) for (const delayMs of [10, 50, 500]) for (let sample = 0; sample < samples; sample++) { + const controller = new AbortController(), records: EgressRecord[] = []; + let fences = 0; + const proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1 }), controller, + turnId: `voyage-${hold}-${delayMs}-${sample}`, sessionId: () => null, model: () => "odysseus", origin: "interactive", profile: "governed", + bridge: { emit() {}, requestPermission: async () => ({ behavior: "deny" }) } as unknown as BackendBridge, + record(event) { if (event.kind === "egress_connection") records.push(event.payload); return writes.record(event); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { + inference(...args) { const operation = proxy.inference(...args); return { ...operation, async admit() { fences++; return operation.admit(); } }; }, + } }); + try { + // Twenty prior completed inference audit rows queue twenty separate + // FULL commits. No fake writer latency or durability setting is used. + for (let i = 0; i < 20; i++) proxy.inference("POST", new URL("/v1/messages", origin.url), controller.signal).finish("completed"); + const resultAt = performance.now(); + if (hold === "drained") await proxy.settled(); + await Bun.sleep(Math.max(0, delayMs - (performance.now() - resultAt))); + const status = await new Promise((resolve, reject) => { + const outgoing = request({ socketPath: relay.socketPath, path: "/v1/messages", method: "POST" }, response => { + response.resume(); response.on("error", reject); response.on("end", () => resolve(response.statusCode!)); + }); outgoing.on("error", reject); outgoing.end('{"model":"odysseus","messages":[]}'); + }); + await proxy.settled(); + const measured = records.at(-1)!; + if (status !== 200 || fences !== 2 || measured.admitMs === undefined || measured.dispatchMs === undefined || measured.credentialMs === undefined) throw Error("Admission join measurement missing a successful request, two fences or marks"); + rows.push({ hold, delayMs, sample, queuedCommits: 20, admitMs: measured.admitMs, credentialToDispatchMs: measured.dispatchMs - measured.credentialMs, fences }); + } finally { relay.stop(); controller.abort(); proxy.stop(); await proxy.settled(); } + } + return { coverage: "real FULL writer and Unix relay; synthetic twenty-record queue; no native worker or runtime assembly claim", rows }; + } finally { origin.stop(true); await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); } +} + +if (import.meta.main) { + const directory = process.argv[2]; + if (!directory) throw Error("Usage: admission-join.ts "); + console.log(JSON.stringify(await measureAdmissionJoin(directory), null, 2)); +} diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index eaf40b13fe..7d31df5bef 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -333,9 +333,14 @@ try { const replayBegin = app.wsHost.failureReplay.begin.bind(app.wsHost.failureReplay); app.wsHost.failureReplay.begin = async (...args: any[]) => { const answer = await replayBegin(...args), finish = answer.finish.bind(answer); answer.finish = async (...values: any[]) => { const start = performance.now(); event("failure_replay_finish_start"); try { return await finish(...values); } finally { event("failure_replay_finish_end", { elapsedMs: performance.now() - start }); } }; return answer; }; const principal = createPrincipal(app.db, { authMethod: "password", label: "Odysseus admission", ttlSeconds: 3600 }); - let pathMatrix: Promise | undefined; + let pathMatrix: Promise | undefined, admissionJoin: Promise | undefined; server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request: Request, server: any) { // Fixture-only endpoint; no product route or provider request is added. + if (OBSERVATION_TIMING && new URL(request.url).pathname === "/__native_admission_join") { + const { measureAdmissionJoin } = await import("./admission-join.js"); + admissionJoin ??= measureAdmissionJoin(dir!); + try { return Response.json(await admissionJoin); } catch (error) { return Response.json({ error: String(error) }, { status: 500 }); } + } if (OBSERVATION_TIMING && new URL(request.url).pathname === "/__native_observation_path_matrix") { const { observationPathMatrix } = await import("./observation-path-matrix.js"); pathMatrix ??= observationPathMatrix(brain!, app.wsHost.journal, app.wsHost.governedTurns, event, app.wsHost.scope, principal.id, app.db); @@ -355,7 +360,7 @@ try { let closing = false; process.on("SIGTERM", async () => { if (closing) return; closing = true; - try { server.stop(true); await pathMatrix; await app.close(); inference?.close(); egressOrigin.stop(true); event("fixture_warnings",{messages:observability.logs.records().map((log:any)=>({severity:log.severityText,body:log.body}))}); event("closed"); process.exit(0); } + try { server.stop(true); await pathMatrix; await admissionJoin; await app.close(); inference?.close(); egressOrigin.stop(true); event("fixture_warnings",{messages:observability.logs.records().map((log:any)=>({severity:log.severityText,body:log.body}))}); event("closed"); process.exit(0); } catch (error) { event("close_error", { error: String(error) }); process.exit(1); } }); } catch (error) { diff --git a/scripts/native-proof/hosted-app.test.ts b/scripts/native-proof/hosted-app.test.ts index 17eede687f..3dcebbddf4 100644 --- a/scripts/native-proof/hosted-app.test.ts +++ b/scripts/native-proof/hosted-app.test.ts @@ -485,6 +485,11 @@ print(json.dumps(result))`; }; const steps = [...new Set(warm.flatMap(row => Object.keys(row?.steps ?? {})))]; const stepMedians = Object.fromEntries(steps.map(name => [name, median(warm.map(row => row?.steps[name]).filter((n): n is number => typeof n === "number"))])); + const admissionJoinResponse = await fetch(`http://127.0.0.1:${ready.port}/__native_admission_join`); + const admissionJoin = await admissionJoinResponse.json(); + expect(admissionJoinResponse.status, "ADMISSION_JOIN_MEASURED").toBe(200); + expect(admissionJoin.rows, "ADMISSION_JOIN_ALL_DELAYS_AND_HOLD_MODES").toHaveLength(30); + writeFileSync(join(ARTIFACTS, "admission-join.json"), JSON.stringify(admissionJoin, null, 2)); writeFileSync(join(ARTIFACTS, "observation-holds.json"), JSON.stringify(lifecycles().map(record => ({ turnId: record.turnId, holds: record.holds ?? [], closing: (record.openSubPhases ?? []).filter((step: any) => step.phase === "closing"), recorderSettledAt: record.recorderSettledAt ?? null, idleEmittedAt: record.idleEmittedAt ?? null })), null, 2)); const pathCells = [0, 1, 20, 200].map(changedPaths => { From 2b5ef5df4bdea956e7def02e3d1b2ead755ed191 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:20:58 +0000 Subject: [PATCH 03/13] test(ui-server): retain separate admission fence durations --- experiments/admission-join.test.ts | 2 ++ scripts/native-proof/admission-join.ts | 18 +++++++++++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/experiments/admission-join.test.ts b/experiments/admission-join.test.ts index 9687db4638..8733936dc6 100644 --- a/experiments/admission-join.test.ts +++ b/experiments/admission-join.test.ts @@ -13,6 +13,8 @@ test("admission measurement retains both fences and every hold/delay cell with r ["removed", 10, 20, 2], ["removed", 50, 20, 2], ["removed", 500, 20, 2], ]); for (const row of measured.rows) { + expect(row.admissionFencesMs).toHaveLength(2); + expect(row.requestAfterResultMs).toBeGreaterThanOrEqual(0); expect(row.admitMs).toBeGreaterThanOrEqual(0); expect(row.credentialToDispatchMs).toBeGreaterThanOrEqual(0); } diff --git a/scripts/native-proof/admission-join.ts b/scripts/native-proof/admission-join.ts index d3817db842..1e69bde71c 100644 --- a/scripts/native-proof/admission-join.ts +++ b/scripts/native-proof/admission-join.ts @@ -13,24 +13,32 @@ import { request } from "node:http"; export async function measureAdmissionJoin(directory: string, samples = 5) { const root = mkdtempSync(join(directory, "admission-join-")), db = createUiDb(join(root, "ui.db")); const writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); - const rows: { hold: "drained" | "removed"; delayMs: number; sample: number; queuedCommits: number; admitMs: number; credentialToDispatchMs: number; fences: number }[] = []; + const rows: { hold: "drained" | "removed"; delayMs: number; sample: number; queuedCommits: number; admitMs: number; credentialToDispatchMs: number; fences: number; admissionFencesMs: number[]; requestAfterResultMs: number }[] = []; const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { await req.arrayBuffer(); return new Response("Ithaca"); } }); try { for (const hold of ["drained", "removed"] as const) for (const delayMs of [10, 50, 500]) for (let sample = 0; sample < samples; sample++) { const controller = new AbortController(), records: EgressRecord[] = []; - let fences = 0; + let fences = 0, resultAt = 0, requestReceivedAt = 0; + const admissionFencesMs: number[] = []; const proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1 }), controller, turnId: `voyage-${hold}-${delayMs}-${sample}`, sessionId: () => null, model: () => "odysseus", origin: "interactive", profile: "governed", bridge: { emit() {}, requestPermission: async () => ({ behavior: "deny" }) } as unknown as BackendBridge, record(event) { if (event.kind === "egress_connection") records.push(event.payload); return writes.record(event); } }); const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { - inference(...args) { const operation = proxy.inference(...args); return { ...operation, async admit() { fences++; return operation.admit(); } }; }, + inference(...args) { + requestReceivedAt = performance.now(); + const operation = proxy.inference(...args); + return { ...operation, async admit() { + fences++; const start = performance.now(); + try { return await operation.admit(); } finally { admissionFencesMs.push(performance.now() - start); } + } }; + }, } }); try { // Twenty prior completed inference audit rows queue twenty separate // FULL commits. No fake writer latency or durability setting is used. for (let i = 0; i < 20; i++) proxy.inference("POST", new URL("/v1/messages", origin.url), controller.signal).finish("completed"); - const resultAt = performance.now(); + resultAt = performance.now(); if (hold === "drained") await proxy.settled(); await Bun.sleep(Math.max(0, delayMs - (performance.now() - resultAt))); const status = await new Promise((resolve, reject) => { @@ -41,7 +49,7 @@ export async function measureAdmissionJoin(directory: string, samples = 5) { await proxy.settled(); const measured = records.at(-1)!; if (status !== 200 || fences !== 2 || measured.admitMs === undefined || measured.dispatchMs === undefined || measured.credentialMs === undefined) throw Error("Admission join measurement missing a successful request, two fences or marks"); - rows.push({ hold, delayMs, sample, queuedCommits: 20, admitMs: measured.admitMs, credentialToDispatchMs: measured.dispatchMs - measured.credentialMs, fences }); + rows.push({ hold, delayMs, sample, queuedCommits: 20, admitMs: measured.admitMs, credentialToDispatchMs: measured.dispatchMs - measured.credentialMs, fences, admissionFencesMs, requestAfterResultMs: requestReceivedAt - resultAt }); } finally { relay.stop(); controller.abort(); proxy.stop(); await proxy.settled(); } } return { coverage: "real FULL writer and Unix relay; synthetic twenty-record queue; no native worker or runtime assembly claim", rows }; From 1fb3675c0bec4528ad64ae33f30502d581711309 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:23:07 +0000 Subject: [PATCH 04/13] test(ui-server): prove deferred scope refusals await durable storage --- .../ui-server/tests/deferred-freeze.test.ts | 32 +++++++++++++++++++ .../tests/helpers/deferred-freeze-fixture.ts | 15 ++++++--- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/packages/ui-server/tests/deferred-freeze.test.ts b/packages/ui-server/tests/deferred-freeze.test.ts index cca4c5ec13..63f66a9d86 100644 --- a/packages/ui-server/tests/deferred-freeze.test.ts +++ b/packages/ui-server/tests/deferred-freeze.test.ts @@ -215,3 +215,35 @@ test("a parallel arrival after arming returns to the immediate observation path" expect((await response).status).toBe(200); expect(upstream).toBe(1); } finally { release.resolve(); parallel?.finish("cancelled"); f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } }); + +test("a deferred scope refusal waits for its offloop FULL pause record before answering the relay", async () => { + const f = await fixture(1, undefined, true); + const heldWriter = await import("./fixtures/held-publication-writer"); + const channel = f.writer!.channel(heldWriter, {}); await channel.ready; + const entered = new Int32Array(new SharedArrayBuffer(4)), release = new Int32Array(new SharedArrayBuffer(4)); + let held: Promise | undefined, responseGateSettled = false; + const boundary = Promise.withResolvers(); + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("Ithaca") }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { + inference(...args) { const operation = f.proxy.inference(...args); return { ...operation, responseReady() { + const ready = operation.responseReady(); void ready.then(() => { responseGateSettled = true; }); boundary.resolve(); return ready; + } }; }, + } }); + try { + // Insert an actual held FULL transaction ahead of the scope observer's + // save. The journal version is durable, but the cap pause is not yet. + f.beforeScope(() => { held ??= channel.call("hold", entered, release); }); + writeFileSync(join(f.brain, "note.md"), "Penelope"); + const observed = f.result(), response = send(relay.socketPath); void response.catch(() => {}); + const waiting = Atomics.waitAsync(entered, 0, 0); if (waiting.async) await waiting.value; + expect(Atomics.load(entered, 0)).toBe(1); + await boundary.promise; await Promise.resolve(); + expect(responseGateSettled, "SCOPE_REFUSAL_CANNOT_PRECEDE_FULL_COMMIT").toBe(false); + const prior = f.db.query("SELECT summary FROM turn_scope WHERE turn_id='voyage'").get() as { summary: string }; + expect(JSON.parse(prior.summary).receipts, "HELD_PAUSE_IS_NOT_DURABLE_YET").toEqual([]); + Atomics.store(release, 0, 1); Atomics.notify(release, 0); await held; await observed; + expect((await response).status).toBe(403); + const saved = f.db.query("SELECT summary FROM turn_scope WHERE turn_id='voyage'").get() as { summary: string }; + expect(JSON.parse(saved.summary).receipts).toMatchObject([{ state: "paused", dimension: "files_changed" }]); + } finally { Atomics.store(release, 0, 1); Atomics.notify(release, 0); await held; f.beforeScope(() => {}); relay.stop(); origin.stop(true); await f.close(); } +}); diff --git a/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts b/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts index fbf39b7176..7b604bfd8b 100644 --- a/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts +++ b/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts @@ -4,6 +4,8 @@ import { join } from "node:path"; import { resolveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; import { request } from "node:http"; +import { openSqliteWriter } from "../../src/db/write-worker"; +import { journalDatabasePath } from "../../src/db/journal-database"; import { createUiDb } from "../../src/db/client"; import { createTurnJournal } from "../../src/brain/turn-journal"; import { createTurnScope } from "../../src/brain/turn-scope"; @@ -15,12 +17,15 @@ export const body = (id = "loom") => JSON.stringify({ model: "odysseus", stream: { role: "assistant", content: [{ type: "tool_use", id, name: "Write", input: {} }] }, { role: "user", content: [{ type: "tool_result", tool_use_id: id, content: "Ithaca" }] }, ] }); -export async function fixture(cap = 100, realWorker?: Parameters["workerStarted"]>[1]) { +export async function fixture(cap = 100, realWorker?: Parameters["workerStarted"]>[1], offloopScope = false) { const root = mkdtempSync(join(tmpdir(), "odysseus-deferred-")), brain = join(root, "brain"), path = join(root, "ui.db"); mkdirSync(brain); writeFileSync(join(brain, "note.md"), "Odysseus"); const native = createNativeJournalFixture(brain, root), db = createUiDb(path), controller = new AbortController(); - const journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: brain, dbPath: path, objectsRoot: join(root, "objects") }); - const scope = createTurnScope(db, { brainPath: brain, journal, connected: () => true, changed() {}, space: () => ({ total: 100e9, free: 90e9 }) }); + const writer = offloopScope ? openSqliteWriter(db, { attach: [{ schema: "journal", path: journalDatabasePath(path) }] }) : undefined; + const journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: brain, dbPath: path, objectsRoot: join(root, "objects"), ...(writer ? { writer } : {}) }); + let beforeScope = () => {}; + journal.onObservation(() => beforeScope()); + const scope = createTurnScope(db, { brainPath: brain, journal, ...(writer ? { writer } : {}), connected: () => true, changed() {}, space: () => ({ total: 100e9, free: 90e9 }) }); db.query("INSERT INTO sessions(id,title,created_at,last_active_at) VALUES ('ithaca','Voyage',0,0)").run(); const policy = resolveGovernancePolicy({ schema_version: 1, scope: { max_files_changed: cap } }); const interval = registeredInterval(); @@ -48,8 +53,8 @@ export async function fixture(cap = 100, realWorker?: Parameters { interval.restore(); Object.defineProperty(globalThis, "setTimeout", descriptor); Object.defineProperty(globalThis, "clearTimeout", clearDescriptor); }; const result = (id = "loom") => { journal.toolStarted("voyage", id, "Write", true); return journal.toolEnded("voyage", id); }; - return { tick() { interval.advanceTo(15000); }, deadlines, fireDeadline() { const item = deadlines.find(item => !item.cancelled)!; item.cancelled = true; item.callback(); }, root, brain, db, native, journal, scope, proxy, controller, result, get frozen() { return frozen; }, get stops() { return stops; }, get resumes() { return resumes; }, ack(value: boolean | void) { ack = value; }, - async close() { try { controller.abort(); proxy.stop(); await proxy.settled(); await journal.idle(); scope.close(); await journal.close(); await native.close(); db.close(); rmSync(root, { recursive: true, force: true }); } finally { restore(); } } }; + return { writer, beforeScope(fn: () => void) { beforeScope = fn; }, tick() { interval.advanceTo(15000); }, deadlines, fireDeadline() { const item = deadlines.find(item => !item.cancelled)!; item.cancelled = true; item.callback(); }, root, brain, db, native, journal, scope, proxy, controller, result, get frozen() { return frozen; }, get stops() { return stops; }, get resumes() { return resumes; }, ack(value: boolean | void) { ack = value; }, + async close() { try { controller.abort(); proxy.stop(); await proxy.settled(); await journal.idle(); scope.close(); await journal.close(); await writer?.close(); await native.close(); db.close(); rmSync(root, { recursive: true, force: true }); } finally { restore(); } } }; } export function send(socketPath: string, content = body(), path = "/v1/messages") { return new Promise<{ status: number; bytes: number }>((resolve, reject) => { From 3dd5ac81fc9344cbc49ba3bfb1569625831130d1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:26:30 +0000 Subject: [PATCH 05/13] fix(test): retain the typed inference audit payload in admission measurement --- scripts/native-proof/admission-join.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/native-proof/admission-join.ts b/scripts/native-proof/admission-join.ts index 1e69bde71c..f90d91302b 100644 --- a/scripts/native-proof/admission-join.ts +++ b/scripts/native-proof/admission-join.ts @@ -23,7 +23,7 @@ export async function measureAdmissionJoin(directory: string, samples = 5) { const proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1 }), controller, turnId: `voyage-${hold}-${delayMs}-${sample}`, sessionId: () => null, model: () => "odysseus", origin: "interactive", profile: "governed", bridge: { emit() {}, requestPermission: async () => ({ behavior: "deny" }) } as unknown as BackendBridge, - record(event) { if (event.kind === "egress_connection") records.push(event.payload); return writes.record(event); } }); + record(event) { if (event.kind === "egress_connection") records.push(event.payload as EgressRecord); return writes.record(event); } }); const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { inference(...args) { requestReceivedAt = performance.now(); From a04cb4dcb66ddb797a263a12c2c4b8c7a13a23c6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:27:40 +0000 Subject: [PATCH 06/13] fix(ui-server): keep the observation deadline module private --- packages/ui-server/src/brain/deferred-observation.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/src/brain/deferred-observation.ts b/packages/ui-server/src/brain/deferred-observation.ts index d3d494d42f..7fbb344843 100644 --- a/packages/ui-server/src/brain/deferred-observation.ts +++ b/packages/ui-server/src/brain/deferred-observation.ts @@ -1,5 +1,5 @@ /** One result boundary, claimed synchronously by dispatch or an interruption. */ -export const DEFERRED_OBSERVATION_MS = 50; +const DEFERRED_OBSERVATION_MS = 50; export function deferredObservation(start: (confirmed?: { stopped: boolean }) => Promise) { const done = Promise.withResolvers(); From e7385d7710a65b7e2e445c540bb889df40359918 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:36:27 +0000 Subject: [PATCH 07/13] fix(ui-server): keep deferred inference controls outside the public journal type --- docs/decisions/governed-writable-workers.md | 6 +- .../ui-server/src/brain/journal-inference.ts | 11 +++ packages/ui-server/src/brain/turn-egress.ts | 10 ++- packages/ui-server/src/brain/turn-journal.ts | 79 ++++++++++--------- packages/ui-server/src/brain/turn-scope.ts | 7 +- 5 files changed, 68 insertions(+), 45 deletions(-) create mode 100644 packages/ui-server/src/brain/journal-inference.ts diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 00a5e2e928..9ac33a9f93 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1674,10 +1674,10 @@ starts one per result and carries on (`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:273`). The wait is the observation's hold. `held` takes it synchronously, before it queues the capture -(`function held`, `packages/ui-server/src/brain/turn-journal.ts:320-364`), +(`function held`, `packages/ui-server/src/brain/turn-journal.ts:322-366`), and the scope monitor's hold freezes every active turn's productive workers until the capture completes (`before(hold?: JournalHold)`, -`packages/ui-server/src/brain/turn-scope.ts:255-272`). Pi's agent loop runs in +`packages/ui-server/src/brain/turn-scope.ts:256-273`). Pi's agent loop runs in its worker, so a frozen worker cannot send its next provider request until the resume. On the native fixture the gap between a result and the next request tracked the hold, not the bridge call. @@ -1686,7 +1686,7 @@ tracked the hold, not the bridge call. proven read-only, no other call of an active turn is still running, and no active turn has run a call whose effects may outlast it (`toolEnded(turnId: string, toolUseId: string)`, -`packages/ui-server/src/brain/turn-journal.ts:681-703`). Admission, turn end, +`packages/ui-server/src/brain/turn-journal.ts:717-742`). Admission, turn end, the 15-second timer, scope-limit observations, approved policy writes and removal coverage observe exactly as before. diff --git a/packages/ui-server/src/brain/journal-inference.ts b/packages/ui-server/src/brain/journal-inference.ts new file mode 100644 index 0000000000..eefbe0c22f --- /dev/null +++ b/packages/ui-server/src/brain/journal-inference.ts @@ -0,0 +1,11 @@ +/** Concrete journal/scope/relay wiring, outside the public WsHost.journal type. */ +interface JournalInference { + flushDeferred(): Promise; + relayStarted(turnId: string, transport: { inFlight(): number; eligible(): boolean }, signal: AbortSignal): () => void; + prepareInference(turnId: string, path: string, body: Uint8Array): Promise; + dispatchInference(turnId: string): { stopped: boolean; ready: Promise }; + settleScope?: () => Promise; +} +const journals = new WeakMap(); +export function retainJournalInference(journal: object, control: JournalInference): void { journals.set(journal, control); } +export function journalInference(journal: object): JournalInference | undefined { return journals.get(journal); } diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index e854f4ef71..c6c8fee14a 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -1,3 +1,4 @@ +import { journalInference } from "./journal-inference.js"; /** One admitted turn's concrete proxy, approval surface and durable records. */ import type { EffectiveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; import { startEgressProxy, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; @@ -267,7 +268,8 @@ export async function prepareTurnEgress(options: { }, }); const original = options.bridge; - const releaseJournalRelay = options.journal && options.scope ? options.journal.relayStarted(options.turnId, + const inference = options.journal && journalInference(options.journal); + const releaseJournalRelay = inference && options.scope ? inference.relayStarted(options.turnId, { inFlight: proxy.inferenceCount, eligible: () => options.scope!.canDefer(options.turnId) }, options.controller.signal) : undefined; /** The bridge the backend receives, so its classifications and results open and close each call. */ const bridge: BackendBridge = { ...original, @@ -288,16 +290,16 @@ export async function prepareTurnEgress(options: { const relayOperation = (kind: "inference" | "relayed", method: string, target: URL, signal: AbortSignal) => { const operation = proxy[kind](method, target, signal); const settledOperation = settleOperation(operation); - if (kind !== "inference" || !options.journal || !options.scope) return settledOperation; + if (kind !== "inference" || !inference || !options.scope) return settledOperation; let observation: Promise | undefined; return { ...settledOperation, async prepareDispatch(body: Uint8Array) { - try { return await options.journal!.prepareInference(options.turnId, target.pathname, body) && options.scope!.responseAllowed(options.turnId); } + try { return await inference.prepareInference(options.turnId, target.pathname, body) && options.scope!.responseAllowed(options.turnId); } catch { return false; } }, dispatch() { if (!operation.commit()) return false; - const receipt = options.journal!.dispatchInference(options.turnId); + const receipt = inference.dispatchInference(options.turnId); observation = receipt.ready; return receipt.stopped; }, diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index 613c908ac8..b6fb3e3774 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -1,3 +1,4 @@ +import { retainJournalInference } from "./journal-inference.js"; import { deferredObservation, followsToolResult } from "./deferred-observation.js"; import type { ActivityTurnHold } from "@schlessera/brain-ui-sdk/protocol"; /** Concrete host journal: observations, durable ownership and completed-turn collection. */ @@ -106,7 +107,7 @@ export interface TurnJournalOptions { } /** Internal shared interval; scope records each turn's control acknowledgements. */ export interface JournalHold { - /** Control receipt required for speculative inference dispatch; never diagnostic. */ + /** @internal Control receipt required for speculative inference dispatch; never diagnostic. */ requireConfirmedStop?: boolean; records: Map; stoppedTurns: Set; @@ -291,7 +292,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { catch (error) { if (!(error instanceof JournalCapacityError) || !await collectOne()) throw error; } } } - const periodicObservers = new Set<{ before(hold?: JournalHold): void; after(completed: boolean, hold?: JournalHold): void; settled?(): Promise }>(); + const periodicObservers = new Set<{ before(hold?: JournalHold): void; after(completed: boolean, hold?: JournalHold): void }>(); const evidence = new Map void; inference: () => boolean }>(); let currentHold: JournalHold | undefined; const observers = new Set<(turnId: string, facts: { changedPaths: number; observedBytes: number; workspacePaths: number; indexBytes?: number | null; partial: boolean; observationChangedPaths?: number; observationToolUseId?: string }) => void>(); @@ -308,6 +309,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const callKey = (turnId: string, toolUseId: string) => JSON.stringify([turnId, toolUseId]); const relays = new Map(); let deferred: { turnId: string; toolUseId: string; observation: ReturnType } | undefined; + /** @internal */ function flushDeferred(): Promise { const pending = deferred; if (!pending) return Promise.resolve(); @@ -350,7 +352,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { let completed = false; const failedBefore = observationFailures; try { const result = await operation(timing); - for (const holder of holders) await holder.settled?.(); + await inference.settleScope?.(); completed = true; return result; } finally { // A cancelled/refused new admission made no worker writes. Existing @@ -572,7 +574,41 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { throw failure; } } - return { + const inference: Parameters[1] = { + /** @internal Concrete turn relay lifecycle; absence always uses immediate observations. */ + relayStarted(turnId: string, transport: { inFlight(): number; eligible(): boolean }, signal: AbortSignal) { + void flushDeferred().catch(() => {}); + relays.set(turnId, transport); + const abort = () => { void flushDeferred().catch(() => {}); if (relays.get(turnId) === transport) relays.delete(turnId); }; + signal.addEventListener("abort", abort, { once: true }); + if (signal.aborted) abort(); + return () => { signal.removeEventListener("abort", abort); abort(); }; + }, + /** @internal */ + flushDeferred, + /** @internal Fully read request only. Ambiguous traffic keeps the prior-verdict boundary. */ + async prepareInference(turnId: string, path: string, body: Uint8Array): Promise { + const relay = relays.get(turnId); + if (deferred?.turnId === turnId && relay?.eligible() && relay.inFlight() === 1 + && followsToolResult(path, body, deferred.toolUseId)) return true; + await flushDeferred(); + await tail; + return !failures.has(turnId); + }, + /** @internal No await between the confirmed stop and the relay's fetch. */ + dispatchInference(turnId: string): { stopped: boolean; ready: Promise } { + const pending = deferred; + if (pending?.turnId !== turnId) return { stopped: !holds && !failures.has(turnId), ready: tail.then(() => {}) }; + deferred = undefined; + const confirmed = { stopped: false }; + const relay = relays.get(turnId); + // Parallel arrivals after arming invalidate the one-request attribution. + if (!relay?.eligible() || relay.inFlight() !== 1) return { stopped: false, ready: pending.observation.claim() }; + const ready = pending.observation.claim(confirmed); + return { stopped: confirmed.stopped, ready }; + }, + }; + const journal = { /** * @internal Host scope monitor consumes this same observation window. * `changedPaths` counts every changed path; `workspacePaths` counts paths @@ -589,7 +625,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { evidence(turnId: string, record?: (hold: ActivityTurnHold) => void, inference: () => boolean = () => false) { if (record) evidence.set(turnId, { record, inference }); else evidence.delete(turnId); }, - onObservation(observer: (turnId: string, facts: { changedPaths: number; observedBytes: number; workspacePaths: number; indexBytes?: number | null; partial: boolean; observationChangedPaths?: number; observationToolUseId?: string }) => void, periodic?: { before(hold?: JournalHold): void; after(completed: boolean, hold?: JournalHold): void; settled?(): Promise }) { + onObservation(observer: (turnId: string, facts: { changedPaths: number; observedBytes: number; workspacePaths: number; indexBytes?: number | null; partial: boolean; observationChangedPaths?: number; observationToolUseId?: string }) => void, periodic?: { before(hold?: JournalHold): void; after(completed: boolean, hold?: JournalHold): void }) { observers.add(observer); if (periodic) periodicObservers.add(periodic); return () => { if (periodic) periodicObservers.delete(periodic); return observers.delete(observer); }; }, @@ -703,37 +739,6 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { } return start(); }, - /** Concrete turn relay lifecycle; absence always uses immediate observations. */ - relayStarted(turnId: string, transport: { inFlight(): number; eligible(): boolean }, signal: AbortSignal) { - void flushDeferred().catch(() => {}); - relays.set(turnId, transport); - const abort = () => { void flushDeferred().catch(() => {}); if (relays.get(turnId) === transport) relays.delete(turnId); }; - signal.addEventListener("abort", abort, { once: true }); - if (signal.aborted) abort(); - return () => { signal.removeEventListener("abort", abort); abort(); }; - }, - flushDeferred, - /** Fully read request only. Ambiguous traffic keeps the prior-verdict boundary. */ - async prepareInference(turnId: string, path: string, body: Uint8Array): Promise { - const relay = relays.get(turnId); - if (deferred?.turnId === turnId && relay?.eligible() && relay.inFlight() === 1 - && followsToolResult(path, body, deferred.toolUseId)) return true; - await flushDeferred(); - await tail; - return !failures.has(turnId); - }, - /** No await between the confirmed stop and the relay's fetch. */ - dispatchInference(turnId: string): { stopped: boolean; ready: Promise } { - const pending = deferred; - if (pending?.turnId !== turnId) return { stopped: !holds && !failures.has(turnId), ready: tail.then(() => {}) }; - deferred = undefined; - const confirmed = { stopped: false }; - const relay = relays.get(turnId); - // Parallel arrivals after arming invalidate the one-request attribution. - if (!relay?.eligible() || relay.inFlight() !== 1) return { stopped: false, ready: pending.observation.claim() }; - const ready = pending.observation.claim(confirmed); - return { stopped: confirmed.stopped, ready }; - }, /** * Cover one managed worktree (#2430) for an active turn before any of its * workers can reach it: a baseline checkpoint and inventory of that root. @@ -1028,6 +1033,8 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { finally { await Promise.allSettled([...unserialized]); objects.close(); await ledger.close(); if (ownWriter) await writer.close(); } }, }; + retainJournalInference(journal, inference); + return journal; } export type TurnJournal = ReturnType; diff --git a/packages/ui-server/src/brain/turn-scope.ts b/packages/ui-server/src/brain/turn-scope.ts index 02e399870f..2fac2722a1 100644 --- a/packages/ui-server/src/brain/turn-scope.ts +++ b/packages/ui-server/src/brain/turn-scope.ts @@ -1,3 +1,4 @@ +import { journalInference } from "./journal-inference.js"; /** Concrete per-turn scope monitor; shared journal observations drive filesystem and lifetime checks. */ import type { Database } from "bun:sqlite"; import { randomUUID } from "node:crypto"; @@ -310,6 +311,8 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour turn.summary.coverage = facts.partial ? "partial" : "observed_versions"; turn.summary.observedAt = now(); check(turnId, turn, { toolUseId: facts.observationToolUseId, changedPaths: facts.observationChangedPaths }); }, periodic); + const inference = journalInference(options.journal); + if (inference) inference.settleScope = periodic.settled; return { begin(turnId: string, input: { sessionId: string | null; principalId: string; origin: Live["origin"]; profile: Live["profile"]; policy: EffectiveGovernancePolicy; source: Live["source"]; liveIndexWritable?: boolean; hardTimeoutMs: number; current: () => boolean; model?: () => string | null; stop: Live["stop"] }) { @@ -325,7 +328,7 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour }); }, workerStarted(turnId: string, worker: Worker) { - void options.journal.flushDeferred?.().catch(() => {}); + void journalInference(options.journal)?.flushDeferred().catch(() => {}); const turn = active.get(turnId); if (!turn || !turn.current()) { worker.kill("SIGKILL"); return; } turn.workers.add(worker); void worker.exited.finally(() => { turn.workers.delete(worker); confirmedStops.delete(worker); }).catch(() => {}); @@ -379,7 +382,7 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour scopeCapRecords.delete(turnId); return Promise.all([saved, ended]).then(results => results.every(Boolean)); }, - close() { unsubscribe(); for (const [id, turn] of active) { for (const worker of turn.workers) worker.kill("SIGKILL"); turn.stop("Host closed; the turn was interrupted."); this.finish(id); } }, + close() { unsubscribe(); if (inference?.settleScope === periodic.settled) delete inference.settleScope; for (const [id, turn] of active) { for (const worker of turn.workers) worker.kill("SIGKILL"); turn.stop("Host closed; the turn was interrupted."); this.finish(id); } }, }; /** A decision, synchronous from its read of the committed row through the writes it submits. */ function decideCommitted(msg: ClientScopeDecision): ServerScopeDecisionReceipt { From 236c501cd368c20410a8036da4ce24fc2aeb8cdb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 10:17:57 +0000 Subject: [PATCH 08/13] fix(ui-server): preserve immediate holds and latch deferred request verdicts --- .changeset/tidy-ithaca-freeze.md | 2 +- docs/decisions/governed-writable-workers.md | 69 +++--- experiments/admission-join.test.ts | 2 + packages/ui-sdk/src/server/egress-proxy.ts | 2 +- packages/ui-sdk/src/server/inference-relay.ts | 144 +++++++------ .../src/brain/deferred-observation.ts | 3 +- .../ui-server/src/brain/journal-inference.ts | 11 +- packages/ui-server/src/brain/turn-egress.ts | 17 +- packages/ui-server/src/brain/turn-journal.ts | 125 +++++++---- packages/ui-server/src/brain/turn-scope.ts | 8 +- .../tests/deferred-freeze-review.test.ts | 202 ++++++++++++++++++ .../tests/deferred-freeze-runtime.test.ts | 16 +- .../ui-server/tests/deferred-freeze.test.ts | 16 +- .../tests/helpers/deferred-freeze-fixture.ts | 16 +- scripts/native-proof/README.md | 8 +- scripts/native-proof/admission-join.ts | 56 +++-- scripts/native-proof/hosted-app-child.ts | 2 +- 17 files changed, 504 insertions(+), 195 deletions(-) create mode 100644 packages/ui-server/tests/deferred-freeze-review.test.ts diff --git a/.changeset/tidy-ithaca-freeze.md b/.changeset/tidy-ithaca-freeze.md index 03f681dc3f..775ef67723 100644 --- a/.changeset/tidy-ithaca-freeze.md +++ b/.changeset/tidy-ithaca-freeze.md @@ -3,4 +3,4 @@ "@schlessera/brain-ui-sdk": patch --- -Overlap eligible per-tool journal observations with the next model request. Confirm the worker stop at full-request dispatch, retain every observation and its durability, and withhold the response until the observation and scope pause have committed. Unknown or concurrent work retains the immediate hold. +Overlap eligible per-tool journal observations with the next model request. Confirm the worker stop at full-request dispatch, retain every observation and its durability, and withhold the response until the observation and scope pause have committed. Unknown, partial, unsupported or ambiguous work retains the immediate hold. Early refusals share the result observation gate, and each request retains its own cap verdict after Continue. Unconfirmed stops use the existing immediate schedule. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 9ac33a9f93..cca8d1b7e9 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1642,39 +1642,52 @@ required observation, its attribution, its durability and its terminal accounting are preserved. One inference request may therefore be sent before the observation's scope verdict is known. -The implementation arms only one result boundary, with one 50 ms fallback -from that result. Dispatch, the deadline, a new tool or worker, another hold, -the periodic tick, finish, abort and shutdown claim that same boundary -synchronously; another result never coalesces with it -(`deferredObservation`, `packages/ui-server/src/brain/deferred-observation.ts:4-21`). Eligibility requires a -single active turn and worker, no pending calls globally, no peer unproven -producer, and no in-flight relay request at the result. Only a streaming -Messages request whose final assistant call and sole final user tool result -match that boundary can overlap. Token counts, tool-free titles, parallel -arrivals, unsupported request shapes and unknown transport state keep the -prior-verdict fence (`followsToolResult`, -`packages/ui-server/src/brain/deferred-observation.ts:24-36`). Admission still -checks both fences and the session binding. - -A synchronous control receipt, independent of diagnostic hold/timing marks, -confirms every stopped worker before upstream dispatch. A failed or legacy -void stop acknowledgement refuses dispatch and retains a partial journal -cause. The relay also holds response headers and body until the observation -and its scope writes commit. A scope refusal discards the in-flight upstream -response and records the connection as refused; the scope receipt remains -paused and the worker stays stopped for the existing authorized decision. -Files changed, observed turn bytes, index capacity, wall minutes and free -space can be discovered by this deferred observation after one request has -left. The tool-call cap is still checked at launch. No cap, credential, -recording or authority failure authorizes another request. These host facts -never enter provider history. +The implementation arms one result boundary with one 50 ms fallback. Dispatch, +the elapsed deadline, a new tool or worker, another hold, the periodic tick, +finish, abort and shutdown claim that same boundary synchronously; another +result never coalesces with it (`deferredObservation`, +`packages/ui-server/src/brain/deferred-observation.ts:4-22`). One synchronous +predicate runs both when arming and at dispatch. Eligibility requires known +complete journal/scope coverage, a relay serving `/v1/messages`, a single active +turn and worker, no globally pending calls or peer unproven producer, and no +inference operation at the result. An ambiguous call identity or a second +inference operation after arming permanently selects the immediate schedule +for that turn, even after the call entry is deleted or the second request +closes. Operation creation supplies this evidence; an in-flight count cannot +recover uniqueness. Unsupported transports never arm. Expired deadlines take +the immediate path even before their timer callbacks run. + +Only a streaming Messages request whose final assistant call and sole final +user tool result match that boundary can overlap (`followsToolResult`, +`packages/ui-server/src/brain/deferred-observation.ts:25-37`). Token counts, +tool-free titles, unsupported shapes and unknown evidence keep the prior-verdict +fence. Both inference admission fences and the session-binding wait remain. + +A synchronous control receipt, independent of diagnostic timing marks, confirms +the stop before speculative dispatch. A false or legacy void acknowledgement +falls back to today's immediate held observation; it does not add a turn-abort +path. After that observation commits, ordinary admission may proceed as before. +Only a confirmed deferred stop waits for the scope writes to commit. Immediate, +periodic, finish and admission holds keep their existing schedule, and an +ordinary inference never joins unrelated work on the global journal queue. + +Every answer for a request associated with an armed or claimed result boundary +passes one observation gate, including admission, size, byte-cap and credential +refusals. Its observation verdict is latched for that request when the +observation commits. A cap discards the in-flight upstream response even if the +owner chooses Continue before upstream headers arrive; later requests use their +own verdict. The existing cap receipt and authorized continuation remain. +Files changed, observed turn bytes, index capacity, wall minutes and free space +may be discovered after one request has left. The tool-call cap stays checked at +launch. No existing egress, credential, recording or authority fence is removed. +These host facts never enter provider history. **Where the next request waited.** The bridge never awaits an observation: it starts one per result and carries on (`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:273`). The wait is the observation's hold. `held` takes it synchronously, before it queues the capture -(`function held`, `packages/ui-server/src/brain/turn-journal.ts:322-366`), +(`function held`, `packages/ui-server/src/brain/turn-journal.ts:341-385`), and the scope monitor's hold freezes every active turn's productive workers until the capture completes (`before(hold?: JournalHold)`, `packages/ui-server/src/brain/turn-scope.ts:256-273`). Pi's agent loop runs in @@ -1686,7 +1699,7 @@ tracked the hold, not the bridge call. proven read-only, no other call of an active turn is still running, and no active turn has run a call whose effects may outlast it (`toolEnded(turnId: string, toolUseId: string)`, -`packages/ui-server/src/brain/turn-journal.ts:717-742`). Admission, turn end, +`packages/ui-server/src/brain/turn-journal.ts:756-780`). Admission, turn end, the 15-second timer, scope-limit observations, approved policy writes and removal coverage observe exactly as before. diff --git a/experiments/admission-join.test.ts b/experiments/admission-join.test.ts index 8733936dc6..d7f593f682 100644 --- a/experiments/admission-join.test.ts +++ b/experiments/admission-join.test.ts @@ -8,11 +8,13 @@ test("admission measurement retains both fences and every hold/delay cell with r const root = mkdtempSync(join(tmpdir(), "odysseus-admission-measure-")); try { const measured = await measureAdmissionJoin(root, 1); + expect(measured.journalAttached).toBe(true); expect(measured.rows.map(row => [row.hold, row.delayMs, row.queuedCommits, row.fences])).toEqual([ ["drained", 10, 20, 2], ["drained", 50, 20, 2], ["drained", 500, 20, 2], ["removed", 10, 20, 2], ["removed", 50, 20, 2], ["removed", 500, 20, 2], ]); for (const row of measured.rows) { + expect(row.dispatchAfterResultMs).toBeGreaterThanOrEqual(row.requestAfterResultMs); expect(row.admissionFencesMs).toHaveLength(2); expect(row.requestAfterResultMs).toBeGreaterThanOrEqual(0); expect(row.admitMs).toBeGreaterThanOrEqual(0); diff --git a/packages/ui-sdk/src/server/egress-proxy.ts b/packages/ui-sdk/src/server/egress-proxy.ts index 182fb7d330..34ba78e43e 100644 --- a/packages/ui-sdk/src/server/egress-proxy.ts +++ b/packages/ui-sdk/src/server/egress-proxy.ts @@ -476,7 +476,7 @@ export async function startEgressProxy(options: EgressProxyOptions) { }; options.signal?.addEventListener("abort", stop, { once: true }); if (options.signal?.aborted) stop(); - return { dir, socketPath, stop, inferenceInFlight: () => inferenceControllers.size > 0, inferenceCount: () => inferenceControllers.size, usedBytes: () => usedBytes, remainingBytes: () => Math.max(0, options.maxBytes - usedBytes), + return { dir, socketPath, stop, inferenceInFlight: () => inferenceControllers.size > 0, usedBytes: () => usedBytes, remainingBytes: () => Math.max(0, options.maxBytes - usedBytes), /** The existing inference relay shares this turn's admission, counter and audit. */ inference(method: string, target: URL, signal: AbortSignal) { return relayedOperation(method, target, signal, "inference"); }, /** diff --git a/packages/ui-sdk/src/server/inference-relay.ts b/packages/ui-sdk/src/server/inference-relay.ts index e6f28931b4..917f7a87b5 100644 --- a/packages/ui-sdk/src/server/inference-relay.ts +++ b/packages/ui-sdk/src/server/inference-relay.ts @@ -35,7 +35,7 @@ export interface InferenceRelayOptions { /** Server-held headers, resolved for each dispatch after inbound credentials are removed. */ credentials: Readonly> | ((signal: AbortSignal, target: URL) => Promise>>); /** Concrete turn proxy: share its destination admission, application-byte ceiling and audit. */ - egress?: Pick>, "inference">; + egress?: Pick>, "inference"> & { inferenceRoutes?(paths: readonly string[]): void }; /** Called for every request, forwarded or refused. Values are never logged. */ observe?(event: InferenceRelayEvent): void; /** Host receipt of an authorized route, before egress admission or reading its body. Observability only. */ @@ -87,6 +87,7 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe } const base = upstream.pathname.replace(/\/+$/, ""); const routes = new Set(options.routes.map(route => `${base}${route}`)); + options.egress?.inferenceRoutes?.([...routes]); const validateCredentials = (credentials: Readonly>): void => { for (const [name, value] of Object.entries(credentials)) { if (!value || /[\r\n]/.test(value) || !/^[a-z0-9-]+$/i.test(name)) throw new Error("Invalid relay credential header"); @@ -124,14 +125,23 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe const operation = options.egress?.inference(request.method, target, request.signal); const mark = (name: InferenceTimingMark) => observeDiagnostic(() => operation?.mark(name)); const signal = operation ? AbortSignal.any([request.signal, operation.signal]) : request.signal; - const denied = (reason: string, status = 403): Response => { + // Every answer for this operation crosses the same result boundary, + // including failures before full-body dispatch preparation. + const answer = async (create: () => Response | Promise, discard?: () => Promise): Promise => { + if (operation && !await operation.responseReady()) { + await discard?.(); operation.finish("denied", "deferred_observation_refused"); + return refuse(request.method, path, 403, "Inference request refused", "deferred_observation_refused"); + } + return create(); + }; + const denied = (reason: string, status = 403): Promise => answer(() => { operation?.finish("denied", reason); return refuse(request.method, path, status, reason === "max_bytes_per_turn" ? "Inference egress limit exceeded" : "Inference request refused", operation?.reason?.() ?? reason); - }; + }); if (operation && !await operation.admit()) { const cancelled = request.signal.aborted || operation.outcome() === "cancelled"; operation.finish(cancelled ? "cancelled" : "denied", "inference_admission_refused"); - return refuse(request.method, path, cancelled ? 499 : 403, "Inference network admission refused", operation.reason?.()); + return answer(() => refuse(request.method, path, cancelled ? 499 : 403, "Inference network admission refused", operation.reason?.())); } mark("admitMs"); const declared = Number(request.headers.get("content-length") ?? "0"); @@ -158,7 +168,7 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe } } catch { operation?.finish("cancelled", "client_disconnected"); - return refuse(request.method, path, 499, "Inference request cancelled"); + return answer(() => refuse(request.method, path, 499, "Inference request cancelled")); } finally { signal.removeEventListener("abort", cancelBody); reader?.releaseLock(); } mark("bodyMs"); const body = new Uint8Array(length); @@ -169,7 +179,7 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe let credentials: Readonly>; if (signal.aborted) { operation?.finish("cancelled", "client_disconnected"); - return refuse(request.method, path, 499, "Inference request cancelled"); + return answer(() => refuse(request.method, path, 499, "Inference request cancelled")); } try { credentials = typeof options.credentials === "function" ? await options.credentials(signal, new URL(target)) : options.credentials; @@ -177,14 +187,15 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe mark("credentialMs"); if (signal.aborted) { operation?.finish("cancelled", "client_disconnected"); - return refuse(request.method, path, 499, "Inference request cancelled"); + return answer(() => refuse(request.method, path, 499, "Inference request cancelled")); } for (const [name, value] of Object.entries(credentials)) headers.set(name, value); } catch { // A resolver error may carry a provider reply, credential or host path. - operation?.finish(signal.aborted ? "cancelled" : "failed", "inference_credentials_unavailable"); - return refuse(request.method, path, signal.aborted ? 499 : 503, - signal.aborted ? "Inference request cancelled" : "Inference credentials unavailable"); + const cancelled = signal.aborted; + operation?.finish(cancelled ? "cancelled" : "failed", "inference_credentials_unavailable"); + return answer(() => refuse(request.method, path, cancelled ? 499 : 503, + cancelled ? "Inference request cancelled" : "Inference credentials unavailable")); } // HTTP application framing before provider TLS: never describe this as // measured TLS ciphertext/handshake bytes. Include every observable @@ -201,70 +212,71 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe // Re-enter the concrete host admission at the last dispatch boundary. if(operation&&!await operation.admit())return denied("inference_admission_refused"); if (operation && !await operation.prepareDispatch(body)) return denied("inference_admission_refused"); - if(operation&&!operation.dispatch())return denied("inference_admission_refused"); + if (operation && !operation.dispatch()) { + // An unconfirmed speculative stop falls back to the existing held + // observation. After it commits, base admission may proceed normally. + if (!await operation.responseReady() || !await operation.admit() || !operation.dispatch()) return denied("inference_admission_refused"); + } let response: Response; try { // Never follow a redirect: the upstream must not choose another host. mark("dispatchMs"); response = await fetch(target, { method: "POST", headers, body, redirect: "manual", signal }); } catch { - operation?.finish(signal.aborted ? "cancelled" : "failed", "upstream_unreachable"); - return refuse(request.method, path, signal.aborted ? 499 : 502, - signal.aborted ? "Inference request cancelled" : "Inference upstream unreachable"); + const cancelled = signal.aborted; + operation?.finish(cancelled ? "cancelled" : "failed", "upstream_unreachable"); + return answer(() => refuse(request.method, path, cancelled ? 499 : 502, + cancelled ? "Inference request cancelled" : "Inference upstream unreachable")); } mark("headersMs"); - // Even an immediate/large upstream answer cannot cross the result's - // durable observation boundary. This is control flow, never timing. - if (operation && !await operation.responseReady()) { - await response.body?.cancel().catch(() => {}); - return denied("deferred_observation_refused"); - } - if (response.status >= 300 && response.status < 400) { - operation?.finish("failed", "upstream_redirected"); - await response.body?.cancel().catch(() => {}); - return refuse(request.method, path, 502, "Inference upstream redirected; redirects are not followed"); - } - observeDiagnostic(() => options.observe?.({ method: request.method, path, outcome: "forwarded", status: response.status })); - const out = new Headers(); - for (const [name, value] of response.headers) if (!RESPONSE_STRIPPED.has(name.toLowerCase())) out.set(name, value); - if (operation && !operation.charge(headerBytes(`HTTP/1.1 ${response.status} ${response.statusText}`, response.headers))) { - operation.finish("denied", "max_bytes_per_turn"); - await response.body?.cancel().catch(() => {}); - return refuse(request.method, path, 403, "Inference egress limit exceeded"); - } - if (!operation) return new Response(response.body, { status: response.status, headers: out }); - if (!response.body) { - operation.finish("completed"); - return new Response(null, { status: response.status, headers: out }); - } - const upstreamReader = response.body.getReader(); - let observeUsage: ((chunk: Uint8Array) => void) | undefined; - observeDiagnostic(() => { observeUsage = inferenceUsageObserver(usage => observeDiagnostic(() => operation.observeUsage(usage))); }); - let firstReadAttempted = false; - let released = false; - const release = () => { if (!released) { released = true; upstreamReader.releaseLock(); } }; - const output = new ReadableStream({ - async pull(controller) { - try { - const next = await upstreamReader.read(); - if (!firstReadAttempted) { firstReadAttempted = true; mark("firstChunkMs"); } - if (next.done) { operation.finish("completed"); release(); controller.close(); } - else if (!operation.charge(next.value.byteLength + 16)) { - operation.finish("denied", "max_bytes_per_turn"); - await upstreamReader.cancel().catch(() => {}); release(); - controller.error(new Error("Inference egress limit exceeded")); - } else { controller.enqueue(next.value); observeDiagnostic(() => observeUsage?.(next.value)); } - } catch { - operation.finish(signal.aborted ? "cancelled" : "failed", "upstream_response_failed"); - release(); controller.error(new Error("Inference response interrupted")); - } - }, - async cancel() { - operation.finish("cancelled", "client_disconnected"); - await upstreamReader.cancel().catch(() => {}); release(); - }, - }); - return new Response(output, { status: response.status, headers: out }); + return answer(async () => { + if (response.status >= 300 && response.status < 400) { + operation?.finish("failed", "upstream_redirected"); + await response.body?.cancel().catch(() => {}); + return refuse(request.method, path, 502, "Inference upstream redirected; redirects are not followed"); + } + observeDiagnostic(() => options.observe?.({ method: request.method, path, outcome: "forwarded", status: response.status })); + const out = new Headers(); + for (const [name, value] of response.headers) if (!RESPONSE_STRIPPED.has(name.toLowerCase())) out.set(name, value); + if (operation && !operation.charge(headerBytes(`HTTP/1.1 ${response.status} ${response.statusText}`, response.headers))) { + operation.finish("denied", "max_bytes_per_turn"); + await response.body?.cancel().catch(() => {}); + return refuse(request.method, path, 403, "Inference egress limit exceeded"); + } + if (!operation) return new Response(response.body, { status: response.status, headers: out }); + if (!response.body) { + operation.finish("completed"); + return new Response(null, { status: response.status, headers: out }); + } + const upstreamReader = response.body.getReader(); + let observeUsage: ((chunk: Uint8Array) => void) | undefined; + observeDiagnostic(() => { observeUsage = inferenceUsageObserver(usage => observeDiagnostic(() => operation.observeUsage(usage))); }); + let firstReadAttempted = false; + let released = false; + const release = () => { if (!released) { released = true; upstreamReader.releaseLock(); } }; + const output = new ReadableStream({ + async pull(controller) { + try { + const next = await upstreamReader.read(); + if (!firstReadAttempted) { firstReadAttempted = true; mark("firstChunkMs"); } + if (next.done) { operation.finish("completed"); release(); controller.close(); } + else if (!operation.charge(next.value.byteLength + 16)) { + operation.finish("denied", "max_bytes_per_turn"); + await upstreamReader.cancel().catch(() => {}); release(); + controller.error(new Error("Inference egress limit exceeded")); + } else { controller.enqueue(next.value); observeDiagnostic(() => observeUsage?.(next.value)); } + } catch { + operation.finish(signal.aborted ? "cancelled" : "failed", "upstream_response_failed"); + release(); controller.error(new Error("Inference response interrupted")); + } + }, + async cancel() { + operation.finish("cancelled", "client_disconnected"); + await upstreamReader.cancel().catch(() => {}); release(); + }, + }); + return new Response(output, { status: response.status, headers: out }); + }, async () => { await response.body?.cancel().catch(() => {}); }); }, }); } catch (error) { rmSync(dir, { recursive: true, force: true }); throw error; } diff --git a/packages/ui-server/src/brain/deferred-observation.ts b/packages/ui-server/src/brain/deferred-observation.ts index 7fbb344843..73158901b5 100644 --- a/packages/ui-server/src/brain/deferred-observation.ts +++ b/packages/ui-server/src/brain/deferred-observation.ts @@ -2,6 +2,7 @@ const DEFERRED_OBSERVATION_MS = 50; export function deferredObservation(start: (confirmed?: { stopped: boolean }) => Promise) { + const deadline = performance.now() + DEFERRED_OBSERVATION_MS; const done = Promise.withResolvers(); let claimed = false; const timer = setTimeout(() => claim(), DEFERRED_OBSERVATION_MS); @@ -17,7 +18,7 @@ export function deferredObservation(start: (confirmed?: { stopped: boolean }) => } return done.promise; } - return { done: done.promise, claim }; + return { done: done.promise, claim, expired: () => performance.now() >= deadline }; } /** Exact single-call Messages continuation. Unknown protocols keep the prior verdict fence. */ diff --git a/packages/ui-server/src/brain/journal-inference.ts b/packages/ui-server/src/brain/journal-inference.ts index eefbe0c22f..28c81d3fde 100644 --- a/packages/ui-server/src/brain/journal-inference.ts +++ b/packages/ui-server/src/brain/journal-inference.ts @@ -1,9 +1,14 @@ /** Concrete journal/scope/relay wiring, outside the public WsHost.journal type. */ interface JournalInference { flushDeferred(): Promise; - relayStarted(turnId: string, transport: { inFlight(): number; eligible(): boolean }, signal: AbortSignal): () => void; - prepareInference(turnId: string, path: string, body: Uint8Array): Promise; - dispatchInference(turnId: string): { stopped: boolean; ready: Promise }; + relayStarted(turnId: string, transport: { eligible(): boolean; allowed(): boolean }, signal: AbortSignal): () => void; + routes(turnId: string, paths: readonly string[]): void; + requestStarted(turnId: string): { + prepare(path: string, body: Uint8Array): Promise; + dispatch(): boolean; + responseReady(): Promise; + close(): void; + }; settleScope?: () => Promise; } const journals = new WeakMap(); diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index c6c8fee14a..dd38c2a629 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -270,7 +270,7 @@ export async function prepareTurnEgress(options: { const original = options.bridge; const inference = options.journal && journalInference(options.journal); const releaseJournalRelay = inference && options.scope ? inference.relayStarted(options.turnId, - { inFlight: proxy.inferenceCount, eligible: () => options.scope!.canDefer(options.turnId) }, options.controller.signal) : undefined; + { eligible: () => options.scope!.canDefer(options.turnId), allowed: () => options.scope!.responseAllowed(options.turnId) }, options.controller.signal) : undefined; /** The bridge the backend receives, so its classifications and results open and close each call. */ const bridge: BackendBridge = { ...original, emit(message) { calls.emitted(message); extraction?.emitted(message); original.emit(message); }, @@ -291,21 +291,20 @@ export async function prepareTurnEgress(options: { const operation = proxy[kind](method, target, signal); const settledOperation = settleOperation(operation); if (kind !== "inference" || !inference || !options.scope) return settledOperation; - let observation: Promise | undefined; + const boundary = inference.requestStarted(options.turnId); + operation.signal.addEventListener("abort", boundary.close, { once: true }); + if (operation.signal.aborted) boundary.close(); return { ...settledOperation, async prepareDispatch(body: Uint8Array) { - try { return await inference.prepareInference(options.turnId, target.pathname, body) && options.scope!.responseAllowed(options.turnId); } + try { return await boundary.prepare(target.pathname, body); } catch { return false; } }, dispatch() { if (!operation.commit()) return false; - const receipt = inference.dispatchInference(options.turnId); - observation = receipt.ready; - return receipt.stopped; + return boundary.dispatch(); }, async responseReady() { - try { await observation; return !operation.signal.aborted && options.scope!.responseAllowed(options.turnId); } - catch { return false; } + return boundary.responseReady(); }, }; }; @@ -328,7 +327,7 @@ export async function prepareTurnEgress(options: { } finally { if (abort) operation.signal.removeEventListener("abort", abort); } } }; }; - return { ...proxy, bridge, recordingFailure: () => recordingFailure, settled, + return { ...proxy, inferenceRoutes(paths: readonly string[]) { inference?.routes(options.turnId, paths); }, bridge, recordingFailure: () => recordingFailure, settled, stop() { releaseJournalRelay?.(); proxy.stop(); }, inference: (method: string, target: URL, signal: AbortSignal) => relayOperation("inference", method, target, signal), relayed: (method: string, target: URL, signal: AbortSignal) => relayOperation("relayed", method, target, signal), diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index b6fb3e3774..53dcfc4e7d 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -307,14 +307,33 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const calls = new Map(); const lasting = new Set(); const callKey = (turnId: string, toolUseId: string) => JSON.stringify([turnId, toolUseId]); - const relays = new Map(); - let deferred: { turnId: string; toolUseId: string; observation: ReturnType } | undefined; + const relays = new Map; eligible(): boolean; allowed(): boolean }>(); + const immediateOnly = new Set(); + type Boundary = { turnId: string; toolUseId: string; generation: number; claimed: boolean; settled: boolean; observation: ReturnType; verdict: Promise }; + const claimed = new Map(); + let deferred: Boundary | undefined; /** @internal */ function flushDeferred(): Promise { const pending = deferred; if (!pending) return Promise.resolve(); - deferred = undefined; - return pending.observation.claim(); + return claimBoundary(pending); + } + function claimBoundary(boundary: Boundary, confirmed?: { stopped: boolean }): Promise { + if (deferred === boundary) deferred = undefined; + if (!boundary.claimed) { boundary.claimed = true; claimed.set(boundary.turnId, boundary); } + return boundary.observation.claim(confirmed); + } + /** One control predicate, used at arming and at the synchronous dispatch boundary. */ + function mayDefer(turnId: string, boundary?: Boundary, operation?: object): boolean { + const relay = relays.get(turnId); + if (failures.has(turnId) || summary(turnId).state !== "recording") immediateOnly.add(turnId); + if (!relay || !relay.messages || immediateOnly.has(turnId)) return false; + if (boundary && (boundary.observation.expired() || relay.generation !== boundary.generation + 1)) { + immediateOnly.add(turnId); return false; + } + return !closing && !holds && active.size === 1 && active.has(turnId) && !calls.size + && ![...lasting].some(id => id !== turnId) && relay.eligible() + && (operation ? relay.operations.size === 1 && relay.operations.has(operation) : relay.operations.size === 0); } let holds = 0; let observationFailures = 0; @@ -345,14 +364,14 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { let acquired = 0; try { for (const holder of holders) { acquired++; holder.before(interval); } } catch (error) { holds--; for (const holder of holders.slice(0, acquired)) holder.after(false, interval); return Promise.reject(error); } - if (confirmed) confirmed.stopped = holders.length > 0; + if (confirmed) confirmed.stopped = holders.length > 0 && interval.requireConfirmedStop === true; return serialize(async () => { waited?.(); currentHold = interval; let completed = false; const failedBefore = observationFailures; try { const result = await operation(timing); - await inference.settleScope?.(); + if (confirmed?.stopped) await inference.settleScope?.(); completed = true; return result; } finally { // A cancelled/refused new admission made no worker writes. Existing @@ -575,37 +594,57 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { } } const inference: Parameters[1] = { - /** @internal Concrete turn relay lifecycle; absence always uses immediate observations. */ - relayStarted(turnId: string, transport: { inFlight(): number; eligible(): boolean }, signal: AbortSignal) { + relayStarted(turnId, transport, signal) { void flushDeferred().catch(() => {}); - relays.set(turnId, transport); - const abort = () => { void flushDeferred().catch(() => {}); if (relays.get(turnId) === transport) relays.delete(turnId); }; + const relay = { ...transport, messages: false, generation: 0, operations: new Set() }; + relays.set(turnId, relay); + const abort = () => { void flushDeferred().catch(() => {}); if (relays.get(turnId) === relay) relays.delete(turnId); }; signal.addEventListener("abort", abort, { once: true }); if (signal.aborted) abort(); return () => { signal.removeEventListener("abort", abort); abort(); }; }, - /** @internal */ - flushDeferred, - /** @internal Fully read request only. Ambiguous traffic keeps the prior-verdict boundary. */ - async prepareInference(turnId: string, path: string, body: Uint8Array): Promise { - const relay = relays.get(turnId); - if (deferred?.turnId === turnId && relay?.eligible() && relay.inFlight() === 1 - && followsToolResult(path, body, deferred.toolUseId)) return true; - await flushDeferred(); - await tail; - return !failures.has(turnId); + routes(turnId, paths) { + const relay = relays.get(turnId); if (!relay) return; + relay.messages = paths.includes("/v1/messages"); + if (!relay.messages) { immediateOnly.add(turnId); void flushDeferred().catch(() => {}); } }, - /** @internal No await between the confirmed stop and the relay's fetch. */ - dispatchInference(turnId: string): { stopped: boolean; ready: Promise } { - const pending = deferred; - if (pending?.turnId !== turnId) return { stopped: !holds && !failures.has(turnId), ready: tail.then(() => {}) }; - deferred = undefined; - const confirmed = { stopped: false }; - const relay = relays.get(turnId); - // Parallel arrivals after arming invalidate the one-request attribution. - if (!relay?.eligible() || relay.inFlight() !== 1) return { stopped: false, ready: pending.observation.claim() }; - const ready = pending.observation.claim(confirmed); - return { stopped: confirmed.stopped, ready }; + flushDeferred, + requestStarted(turnId) { + const relay = relays.get(turnId), operation = {}; + const boundary = deferred?.turnId === turnId ? deferred : claimed.get(turnId); + if (relay) { + relay.operations.add(operation); relay.generation++; + if (boundary && relay.generation > boundary.generation + 1) { + immediateOnly.add(turnId); void claimBoundary(boundary).catch(() => {}); + } + } + let matched = false; + return { + async prepare(path, body) { + matched = !!boundary && mayDefer(turnId, boundary, operation) && followsToolResult(path, body, boundary.toolUseId); + if (matched && !boundary!.claimed) return true; + // Join only this request's result boundary, never unrelated journal work. + if (boundary) await claimBoundary(boundary); + return true; + }, + dispatch() { + if (!boundary) return true; + if (boundary.claimed) return boundary.settled; + if (!matched || !mayDefer(turnId, boundary, operation)) { + void claimBoundary(boundary).catch(() => {}); return false; + } + const confirmed = { stopped: false }; + void claimBoundary(boundary, confirmed).catch(() => {}); + if (!confirmed.stopped) immediateOnly.add(turnId); + return confirmed.stopped; + }, + async responseReady() { + if (!boundary) return true; + try { await claimBoundary(boundary); return await boundary.verdict; } + catch { return false; } + }, + close() { relay?.operations.delete(operation); }, + }; }, }; const journal = { @@ -701,7 +740,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { if (!active.has(turnId)) return; const key = callKey(turnId, toolUseId), call = calls.get(key); if (!call) { calls.set(key, { turnId, name, started: start }); return; } - if (call.name !== name || start && call.started) call.name = null; + if (call.name !== name || start && call.started) { call.name = null; immediateOnly.add(turnId); } call.started ||= start; }, /** @internal The backend's evidence of where the call actually ran (`StartTurnRequest.toolExecution`). */ @@ -723,17 +762,15 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { if (effect === "read" && !lasting.size && !calls.size) return Promise.resolve(); const start = (confirmed?: { stopped: boolean }) => held(timing => observe(false, timing), false, traceFor("tool", turnId, toolUseId), undefined, { kind: "tool", turnId, toolUseId }, confirmed); - const relay = relays.get(turnId); - // A sibling, parent, peer producer or unknown transport keeps the immediate schedule. - if (!closing && !holds && active.size === 1 && active.has(turnId) && call?.started && call.name !== null - && !calls.size && ![...lasting].some(id => id !== turnId) && relay?.eligible() && relay.inFlight() === 0) { - const pending = { turnId, toolUseId, observation: deferredObservation(confirmed => { - if (deferred === pending) deferred = undefined; - return start(confirmed).catch(async error => { - await fail(turnId, error); - throw error; - }); - }) }; + if (call?.started && call.name !== null && mayDefer(turnId)) { + const pending: Boundary = { turnId, toolUseId, generation: relays.get(turnId)!.generation, claimed: false, settled: false, + observation: deferredObservation(confirmed => { + if (deferred === pending) deferred = undefined; + pending.claimed = true; claimed.set(turnId, pending); + return start(confirmed); + }), verdict: Promise.resolve(false) }; + pending.verdict = pending.observation.done.then(() => { pending.settled = true; return relays.get(turnId)?.allowed() === true; }); + void pending.verdict.finally(() => { if (claimed.get(turnId) === pending) claimed.delete(turnId); }).catch(() => {}); deferred = pending; return pending.observation.done; } @@ -833,7 +870,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { if (!active.has(turnId)) { if (failedAdmissions.has(turnId)) await finalizeRefusedAdmission(turnId); return; } try { const end = bothTimers(lifecycle)?.("final_observation"); await observe(false, timing); end?.(); } finally { - active.delete(turnId); counters.delete(turnId); lasting.delete(turnId); + active.delete(turnId); counters.delete(turnId); lasting.delete(turnId); immediateOnly.delete(turnId); for (const [key, call] of calls) if (call.turnId === turnId) calls.delete(key); let step = [...worktrees.values()].some(root => root.turnId === turnId) ? timing?.("finish_worktrees") : undefined; if (await dropWorktrees(turnId)) step?.(); diff --git a/packages/ui-server/src/brain/turn-scope.ts b/packages/ui-server/src/brain/turn-scope.ts index 2fac2722a1..478a4babd3 100644 --- a/packages/ui-server/src/brain/turn-scope.ts +++ b/packages/ui-server/src/brain/turn-scope.ts @@ -258,13 +258,13 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour if (observationHolds++ > 0) { timing(() => recordStops(hold)); return; } observationFailed = false; for (const [turnId, turn] of active) { - if (turn.summary.receipts.some(receipt => receipt.state === "paused")) continue; + if (!turn.current() || turn.summary.receipts.some(receipt => receipt.state === "paused")) continue; const held: Worker[] = []; periodicHeld.set(turnId, { turn, workers: held }); - if (hold?.requireConfirmedStop && !turn.workers.size) throw new Error("Deferred observation has no worker to stop"); + if (hold?.requireConfirmedStop && !turn.workers.size) hold.requireConfirmedStop = false; for (const worker of turn.workers) { held.push(worker); freeze(worker); - if (hold?.requireConfirmedStop && !confirmed(worker)) throw new Error("Deferred worker stop was not confirmed"); + if (hold?.requireConfirmedStop && !confirmed(worker)) hold.requireConfirmedStop = false; } if (hold) timing(() => recordStop(hold, turnId, held.filter(confirmed))); } @@ -350,7 +350,7 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour }, canDefer(turnId: string): boolean { const turn = active.get(turnId); - return !!turn && turn.current() && !turn.unrecorded && turn.workers.size === 1 && !observationHolds + return !!turn && turn.current() && !turn.unrecorded && turn.summary.changedPaths !== null && turn.summary.observedBytes !== null && turn.workers.size === 1 && !observationHolds && !turn.summary.receipts.some(receipt => receipt.state === "paused"); }, responseAllowed(turnId: string): boolean { diff --git a/packages/ui-server/tests/deferred-freeze-review.test.ts b/packages/ui-server/tests/deferred-freeze-review.test.ts new file mode 100644 index 0000000000..5af36f9e90 --- /dev/null +++ b/packages/ui-server/tests/deferred-freeze-review.test.ts @@ -0,0 +1,202 @@ +import { expect, test } from "bun:test"; +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { startInferenceRelay } from "@schlessera/brain-ui-sdk/internal"; +import { MAX_INFERENCE_REQUEST_BYTES } from "../../ui-sdk/src/server/inference-relay"; +import { journalInference } from "../src/brain/journal-inference"; +import { body, fixture, send } from "./helpers/deferred-freeze-fixture"; + +for (const routes of [["/v1/responses"], ["/chat/completions"]]) test(`unsupported relay ${routes[0]} never arms (F13)`, async () => { + const f = await fixture(); + const relay = startInferenceRelay({ upstream: "http://127.0.0.1", routes, credentials: {}, egress: f.proxy }); + try { + const observed = f.result(); + expect(f.frozen, "UNSUPPORTED_RELAY_USES_IMMEDIATE_HOLD").toBe(true); await observed; + expect(f.deadlines).toHaveLength(0); + } finally { relay.stop(); await f.close(); } +}); + +test("an ambiguous call identity keeps later results immediate (F5)", async () => { + const f = await fixture(); + try { + f.journal.toolStarted("voyage", "twin", "Write", true); + f.journal.toolStarted("voyage", "twin", "Write", true); + await f.journal.toolEnded("voyage", "twin"); + const observed = f.result("sail"); + expect(f.frozen, "AMBIGUITY_LATCH_SURVIVES_CALL_ENTRY_DELETION").toBe(true); await observed; + } finally { await f.close(); } +}); + +for (const phase of ["arming", "dispatch"] as const) test(`partial coverage forbids deferral at ${phase} (F7)`, async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const checkpoint = f.native.manager.checkpoint; let upstream = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); + try { + if (phase === "arming") await f.journal.writeOperation([{ sql: "UPDATE turn_journal_turns SET state='partial' WHERE turn_id=?", params: ["voyage"] }]); + const observed = f.result(); + if (phase === "arming") { + expect(f.frozen, "PARTIAL_COVERAGE_NEVER_ARMS").toBe(true); await observed; + } else { + await f.journal.writeOperation([{ sql: "UPDATE turn_journal_turns SET state='partial' WHERE turn_id=?", params: ["voyage"] }]); + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + const operation = f.proxy.inference("POST", new URL("/v1/messages", origin.url), new AbortController().signal); + try { + let prepared = false; + const preparing = operation.prepareDispatch(Buffer.from(body())).then(value => { prepared = true; return value; }); + await new Promise(resolve => setImmediate(resolve)); + expect(prepared, "DISPATCH_RECHECKS_PARTIAL_COVERAGE").toBe(false); + await entered.promise; release.resolve(); await preparing; await observed; + } finally { operation.finish("cancelled"); } + + } + } finally { release.resolve(); f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } +}); + +test("a second inference arrival remains ambiguous after it disconnects (F11)", async () => { + const f = await fixture(); + let first: ReturnType | undefined, second: typeof first; + try { + const observed = f.result(); + first = f.proxy.inference("POST", new URL("http://127.0.0.1/v1/messages"), new AbortController().signal); + second = f.proxy.inference("POST", new URL("http://127.0.0.1/v1/messages"), new AbortController().signal); + second.finish("cancelled"); + expect(f.frozen, "SECOND_ARRIVAL_FLUSHES_SYNCHRONOUSLY").toBe(true); await observed; + first.finish("cancelled"); + const later = f.result("sail"); expect(f.frozen, "SECOND_ARRIVAL_LATCH_IS_STICKY").toBe(true); await later; + } finally { first?.finish("cancelled"); second?.finish("cancelled"); await f.close(); } +}); + +test("elapsed deadline takes the immediate path before its timer callback runs (D1)", async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const checkpoint = f.native.manager.checkpoint; let upstream = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); + try { + const observed = f.result(); f.elapseDeadline(51); + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + const operation = f.proxy.inference("POST", new URL("/v1/messages", origin.url), new AbortController().signal); + try { + let prepared = false; + const preparing = operation.prepareDispatch(Buffer.from(body())).then(value => { prepared = true; return value; }); + await new Promise(resolve => setImmediate(resolve)); + expect(prepared, "ELAPSED_DEADLINE_CANNOT_SPECULATE").toBe(false); + await entered.promise; release.resolve(); await preparing; await observed; + } finally { operation.finish("cancelled"); } + } finally { release.resolve(); f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } +}); + +for (const cause of ["credentials", "body size", "byte cap", "admission"] as const) test(`the ${cause} refusal joins its result observation (F2)`, async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const checkpoint = f.native.manager.checkpoint; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("Ithaca") }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: async () => { if (cause === "credentials") throw Error("fixture unavailable"); return {}; }, egress: { + ...f.proxy, inference(...args) { const operation = f.proxy.inference(...args); return { ...operation, + charge: cause === "byte cap" ? () => false : operation.charge, + admit: cause === "admission" ? async () => false : operation.admit, + }; }, + } }); + try { + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + const observed = f.result(); + const response = send(relay.socketPath, body(), "/v1/messages", cause === "body size" ? { "content-length": String(MAX_INFERENCE_REQUEST_BYTES + 1) } : {}); + void response.catch(() => {}); + const first = await Promise.race([entered.promise.then(() => "observation"), response.then(() => "reply")]); + expect(first, "ALL_RELAY_ANSWERS_JOIN_THE_RESULT_OBSERVATION").toBe("observation"); + release.resolve(); await observed; + expect((await response).status).toBe(cause === "credentials" ? 503 : cause === "body size" ? 413 : 403); + } finally { release.resolve(); f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } +}); + +test("Continue before headers cannot release the response of a capped observation (F1)", async () => { + const f = await fixture(1), headers = Promise.withResolvers(); + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch() { await headers.promise; return new Response("withhold"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); + try { + writeFileSync(join(f.brain, "note.md"), "Penelope"); + const observed = f.result(), response = send(relay.socketPath); void response.catch(() => {}); await observed; + const receipt = f.journal.summary("voyage").scope!.receipts.at(-1)!; + expect((await f.scope.decide({ type: "scope_decision", turnId: "voyage", sessionId: "ithaca", eventId: receipt.eventId, submissionId: "captain", action: "continue" }, true)).state).toBe("accepted"); + headers.resolve(); + expect((await response).status, "CAPPED_REQUEST_VERDICT_SURVIVES_CONTINUE").toBe(403); + expect((await send(relay.socketPath)).status, "LATER_REQUEST_DOES_NOT_INHERIT_THE_OLD_VERDICT").toBe(200); + } finally { headers.resolve(); relay.stop(); origin.stop(true); await f.close(); } +}); + +test("unrelated global journal work neither delays nor refuses an ordinary inference (F8, X2)", async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const checkpoint = f.native.manager.checkpoint; + let operation: ReturnType | undefined; + try { + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + const unrelated = f.journal.observe(); await entered.promise; + operation = f.proxy.inference("POST", new URL("http://127.0.0.1/v1/messages"), new AbortController().signal); + let prepared = false; + const preparing = operation.prepareDispatch(Buffer.from(body())).then(value => { prepared = true; return value; }); + await new Promise(resolve => setImmediate(resolve)); + expect(prepared, "ORDINARY_INFERENCE_DOES_NOT_JOIN_GLOBAL_TAIL").toBe(true); + expect(await preparing).toBe(true); + expect(operation.dispatch(), "ORDINARY_DISPATCH_RETAINS_BASE_COMMIT_BEHAVIOR").toBe(true); + release.resolve(); await unrelated; + } finally { release.resolve(); operation?.finish("cancelled"); f.native.manager.checkpoint = checkpoint; await f.close(); } +}); + +for (const kind of ["immediate", "periodic", "finish", "admission"] as const) test(`${kind} holds do not gain scope-settlement waits (F9)`, async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const control = journalInference(f.journal)!, settle = control.settleScope; + try { + control.settleScope = async () => { entered.resolve(); await release.promise; }; + let work: Promise; + if (kind === "immediate") { f.proxy.stop(); work = f.result(); } + else if (kind === "periodic") { f.tick(); work = f.journal.idle(); } + else if (kind === "finish") work = f.journal.finish("voyage"); + else work = f.journal.begin("pylos", { sessionId: null, actor: "interactive", model: null, profile: "governed", policyHash: null }, () => {}); + const first = await Promise.race([work.then(() => "complete"), entered.promise.then(() => "scope wait")]); + expect(first, "BASE_HOLD_SCHEDULE_HAS_NO_NEW_SCOPE_WAIT").toBe("complete"); + } finally { release.resolve(); control.settleScope = settle; await f.close(); } +}); + +test("periodic capture preserves the base skip for ended authority (X3)", async () => { + const f = await fixture(); + try { f.controller.abort(); await f.journal.observe(); expect(f.stops, "ENDED_AUTHORITY_IS_NOT_NEWLY_FROZEN").toBe(0); } + finally { await f.close(); } +}); + + +test("a non-deferred dispatch retains base commit behavior during another hold (X2)", async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const checkpoint = f.native.manager.checkpoint; + let operation: ReturnType | undefined; + try { + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + const unrelated = f.journal.observe(); await entered.promise; + operation = f.proxy.inference("POST", new URL("http://127.0.0.1/v1/messages"), new AbortController().signal); + expect(operation.dispatch(), "ORDINARY_DISPATCH_HAS_NO_NEW_HOLD_REFUSAL").toBe(true); + release.resolve(); await unrelated; + } finally { release.resolve(); operation?.finish("cancelled"); f.native.manager.checkpoint = checkpoint; await f.close(); } +}); + + +test("null scope measurements take the immediate path even with a recording journal (F7)", async () => { + const f = await fixture(); + try { + await f.journal.writeOperation([{ sql: "UPDATE turn_journal_turns SET state='partial' WHERE turn_id=?", params: ["voyage"] }]); + await f.journal.observe(); + await f.journal.writeOperation([{ sql: "UPDATE turn_journal_turns SET state='recording' WHERE turn_id=?", params: ["voyage"] }]); + const observed = f.result(); + expect(f.frozen, "UNKNOWN_SCOPE_MEASUREMENTS_USE_IMMEDIATE_HOLD").toBe(true); await observed; + } finally { await f.close(); } +}); + +test("the synchronous dispatch predicate rechecks coverage after preparation (D1)", async () => { + const f = await fixture(); + let operation: ReturnType | undefined; + try { + const observed = f.result(); + operation = f.proxy.inference("POST", new URL("http://127.0.0.1/v1/messages"), new AbortController().signal); + expect(await operation.prepareDispatch(Buffer.from(body()))).toBe(true); + await f.journal.writeOperation([{ sql: "UPDATE turn_journal_turns SET state='partial' WHERE turn_id=?", params: ["voyage"] }]); + expect(operation.dispatch(), "DISPATCH_HAS_THE_SAME_DEFERRAL_PREDICATE").toBe(false); + await observed; + } finally { operation?.finish("cancelled"); await f.close(); } +}); diff --git a/packages/ui-server/tests/deferred-freeze-runtime.test.ts b/packages/ui-server/tests/deferred-freeze-runtime.test.ts index cdccff7c17..aa1155be1c 100644 --- a/packages/ui-server/tests/deferred-freeze-runtime.test.ts +++ b/packages/ui-server/tests/deferred-freeze-runtime.test.ts @@ -8,6 +8,7 @@ import { watchdogMs } from "../../../scripts/test-deadlines"; // mode: controlled time and a fake worker cannot exercise kernel backpressure. // Ten seconds is the issue's observation window, not a readiness sleep. test("a real stopped worker receives an 8 MiB stream only after its ten-second observation commits", async () => { + const realNow = performance.now.bind(performance); const child = Bun.spawn([process.execPath, "-e", ` import { request } from "node:http"; const reader = Bun.stdin.stream().getReader(); @@ -18,18 +19,18 @@ test("a real stopped worker receives an 8 MiB stream only after its ten-second o res.on("end", () => { console.log(JSON.stringify({ status: res.statusCode, bytes })); process.exit(0); }); }); req.on("error", error => { console.error(String(error)); process.exit(1); }); req.end(body); `], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); - let stopped = false, committed = false; + let stopped = false, committed = false, earlyResume: unknown; const freeze = () => { child.kill("SIGSTOP"); - const deadline = performance.now() + watchdogMs(5000); + const deadline = realNow() + watchdogMs(5000); for (;;) { const state = readFileSync(`/proc/${child.pid}/stat`, "utf8").replace(/^.*\) /s, "")[0]; if (state === "T") { stopped = true; return true; } - if (performance.now() > deadline) throw new Error("Owned worker did not stop"); + if (realNow() > deadline) throw new Error("Owned worker did not stop"); Bun.sleepSync(1); } }; - const f = await fixture(100, { freeze, resume() { expect(committed, "PROCESS_CANNOT_RESUME_BEFORE_COMMIT").toBe(true); child.kill("SIGCONT"); stopped = false; return true; }, kill(signal) { child.kill(signal); return true; }, exited: child.exited }); + const f = await fixture(100, { freeze, resume() { try { expect(committed, "PROCESS_CANNOT_RESUME_BEFORE_COMMIT").toBe(true); } catch (error) { earlyResume = error; throw error; } child.kill("SIGCONT"); stopped = false; return true; }, kill(signal) { child.kill(signal); return true; }, exited: child.exited }); const checkpoint = f.native.manager.checkpoint, dispatched = Promise.withResolvers(); let produced = 0; const total = 8 * 1024 * 1024; @@ -44,16 +45,17 @@ test("a real stopped worker receives an 8 MiB stream only after its ten-second o try { let captureStarted = 0; f.native.manager.checkpoint = async (...args) => { - captureStarted = performance.now(); await Bun.sleep(10_000); + captureStarted = realNow(); await Bun.sleep(10_000); return checkpoint(...args); }; - f.journal.onObservation(() => { committed = true; }); + f.afterNativeCommit(() => { committed = true; }); const observed = f.result(); child.stdin.write(JSON.stringify({ socketPath: relay.socketPath, body: body() })); child.stdin.end(); await dispatched.promise; expect(stopped).toBe(true); await observed; - expect(performance.now() - captureStarted, "TEN_SECOND_OBSERVATION_WAS_EXERCISED").toBeGreaterThanOrEqual(10_000); + if (earlyResume) throw earlyResume; + expect(realNow() - captureStarted, "TEN_SECOND_OBSERVATION_WAS_EXERCISED").toBeGreaterThanOrEqual(10_000); expect(await child.exited).toBe(0); expect(JSON.parse(await new Response(child.stdout).text())).toEqual({ status: 200, bytes: total }); expect(await new Response(child.stderr).text()).toBe(""); diff --git a/packages/ui-server/tests/deferred-freeze.test.ts b/packages/ui-server/tests/deferred-freeze.test.ts index 63f66a9d86..130328e975 100644 --- a/packages/ui-server/tests/deferred-freeze.test.ts +++ b/packages/ui-server/tests/deferred-freeze.test.ts @@ -56,7 +56,7 @@ for (const boundary of ["deadline", "new tool", "new worker", "periodic", "abort else if (boundary === "abort") f.controller.abort(); else if (boundary === "finish") terminal = f.journal.finish("voyage"); else terminal = f.journal.close(); - expect(f.frozen, "INTERRUPTION_SYNCHRONOUSLY_TAKES_HOLD").toBe(true); + expect(f.frozen, "INTERRUPTION_RETAINS_BASE_HOLD_POLICY").toBe(boundary !== "abort"); await observed; await terminal; expect(observations, "RESULT_IS_NEVER_COALESCED_WITH_ANOTHER_BOUNDARY").toBe(boundary === "periodic" || boundary === "finish" ? 2 : 1); expect(f.deadlines.filter(item => !item.cancelled)).toHaveLength(0); @@ -106,19 +106,19 @@ for (const requestKind of ["token count", "title", "wrong result", "parallel res } for (const ack of [false, undefined] as const) { - test(`a ${String(ack)} stop receipt refuses speculative dispatch`, async () => { + test(`a ${String(ack)} stop receipt falls back to the base immediate hold`, async () => { const f = await fixture(); let upstream = 0; const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); try { f.ack(ack); const observed = f.result(); - const refusedObservation = observed.then(() => false, () => true); - expect((await send(relay.socketPath)).status, "UNCONFIRMED_STOP_REFUSES_DISPATCH").toBe(403); - expect(await refusedObservation).toBe(true); - expect(upstream).toBe(0); - expect(f.controller.signal.aborted).toBe(true); - expect(f.journal.summary("voyage").state, "FAILED_STOP_IS_DURABLY_PARTIAL").toBe("partial"); + let committed = false; void observed.then(() => { committed = true; }, () => {}); + expect((await send(relay.socketPath)).status, "UNCONFIRMED_STOP_FALLS_BACK_WITHOUT_NEW_REFUSAL").toBe(200); + await observed; expect(committed).toBe(true); + expect(upstream).toBe(1); + expect(f.controller.signal.aborted).toBe(false); + expect(f.journal.summary("voyage").state, "LEGACY_STOP_RETAINS_BASE_JOURNAL_BEHAVIOR").toBe("recording"); } finally { relay.stop(); origin.stop(true); await f.close(); } }); } diff --git a/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts b/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts index 7b604bfd8b..416bf9b64f 100644 --- a/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts +++ b/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts @@ -22,7 +22,8 @@ export async function fixture(cap = 100, realWorker?: Parameters {}; + const journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: brain, dbPath: path, objectsRoot: join(root, "objects"), observationTrace: () => name => () => { if (name === "observe_commit") nativeCommitted(); }, ...(writer ? { writer } : {}) }); let beforeScope = () => {}; journal.onObservation(() => beforeScope()); const scope = createTurnScope(db, { brainPath: brain, journal, ...(writer ? { writer } : {}), connected: () => true, changed() {}, space: () => ({ total: 100e9, free: 90e9 }) }); @@ -32,12 +33,17 @@ export async function fixture(cap = 100, realWorker?: Parameters controller.abort(error)); interval.finishRegistration(); await scope.begin("voyage", { sessionId: "ithaca", principalId: "captain", origin: "interactive", profile: "governed", policy, source: "policy", hardTimeoutMs: 1e6, current: () => !controller.signal.aborted, stop: reason => controller.abort(new Error(reason)) }); + await journal.observe(); let frozen = false, stops = 0, resumes = 0, ack: boolean | void = true; const worker = { freeze() { frozen = true; stops++; return ack; }, resume() { frozen = false; resumes++; return true; }, kill() { frozen = true; return true; }, exited: new Promise(() => {}) }; scope.workerStarted("voyage", realWorker ?? worker); const proxy = await prepareTurnEgress({ policy, controller, turnId: "voyage", sessionId: () => "ithaca", model: () => null, profile: "governed", origin: "interactive", journal, scope, bridge: { emit() {}, requestPermission: async () => ({ behavior: "deny" }) } as unknown as BackendBridge }); + proxy.inferenceRoutes?.(["/v1/messages"]); + const performanceDescriptor = Object.getOwnPropertyDescriptor(performance, "now"); + let deadlineClock = 0; + Object.defineProperty(performance, "now", { configurable: true, value: () => deadlineClock }); const descriptor = Object.getOwnPropertyDescriptor(globalThis, "setTimeout")!; const clearDescriptor = Object.getOwnPropertyDescriptor(globalThis, "clearTimeout")!; const realSet = setTimeout, realClear = clearTimeout; @@ -51,14 +57,14 @@ export async function fixture(cap = 100, realWorker?: Parameters item.handle === handle); if (item) item.cancelled = true; else realClear(handle); } }); - const restore = () => { interval.restore(); Object.defineProperty(globalThis, "setTimeout", descriptor); Object.defineProperty(globalThis, "clearTimeout", clearDescriptor); }; + const restore = () => { if (performanceDescriptor) Object.defineProperty(performance, "now", performanceDescriptor); else delete (performance as unknown as { now?: () => number }).now; interval.restore(); Object.defineProperty(globalThis, "setTimeout", descriptor); Object.defineProperty(globalThis, "clearTimeout", clearDescriptor); }; const result = (id = "loom") => { journal.toolStarted("voyage", id, "Write", true); return journal.toolEnded("voyage", id); }; - return { writer, beforeScope(fn: () => void) { beforeScope = fn; }, tick() { interval.advanceTo(15000); }, deadlines, fireDeadline() { const item = deadlines.find(item => !item.cancelled)!; item.cancelled = true; item.callback(); }, root, brain, db, native, journal, scope, proxy, controller, result, get frozen() { return frozen; }, get stops() { return stops; }, get resumes() { return resumes; }, ack(value: boolean | void) { ack = value; }, + return { afterNativeCommit(fn: () => void) { nativeCommitted = fn; }, elapseDeadline(ms: number) { deadlineClock += ms; }, writer, beforeScope(fn: () => void) { beforeScope = fn; }, tick() { interval.advanceTo(15000); }, deadlines, fireDeadline() { const item = deadlines.find(item => !item.cancelled)!; item.cancelled = true; item.callback(); }, root, brain, db, native, journal, scope, proxy, controller, result, get frozen() { return frozen; }, get stops() { return stops; }, get resumes() { return resumes; }, ack(value: boolean | void) { ack = value; }, async close() { try { controller.abort(); proxy.stop(); await proxy.settled(); await journal.idle(); scope.close(); await journal.close(); await writer?.close(); await native.close(); db.close(); rmSync(root, { recursive: true, force: true }); } finally { restore(); } } }; } -export function send(socketPath: string, content = body(), path = "/v1/messages") { +export function send(socketPath: string, content = body(), path = "/v1/messages", headers: Record = {}) { return new Promise<{ status: number; bytes: number }>((resolve, reject) => { - const outgoing = request({ socketPath, path, method: "POST", headers: { "content-type": "application/json" } }, incoming => { + const outgoing = request({ socketPath, path, method: "POST", headers: { "content-type": "application/json", ...headers } }, incoming => { let bytes = 0; incoming.on("data", chunk => { bytes += chunk.length; }); incoming.on("end", () => resolve({ status: incoming.statusCode!, bytes })); incoming.on("error", reject); }); outgoing.on("error", reject); outgoing.end(content); }); diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index 9cca169d63..ccd6472181 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -62,8 +62,12 @@ The timing run also writes `admission-join.json` (#4293): five samples at 10, 50 and 500 ms after a synthetic result, each with the audit queue drained and with the hold removed. Twenty prior inference records load the actual FULL writer; each sample retains `admitMs`, credential-to-dispatch elapsed -time and the two admission fences. This isolates the join with a real Unix -relay and write worker. It does not measure Claude runtime request assembly: +time, actual result-to-dispatch time and both admission fences. Every cell +attaches the real journal and scope monitor: hosted runs use the app's native +journal and writer; standalone runs use explicitly copied checkpoints with +the same product journal. Worker-control acknowledgements are simulated, so +these cells make no process-freeze qualification claim. This includes any +journal wait in the dispatch interval. It does not measure Claude runtime request assembly: the existing Claude hosted fixture uses a mock query. Standalone local measurement uses `bun scripts/native-proof/admission-join.ts `; its filesystem is the directory supplied, and it makes no native-storage claim. diff --git a/scripts/native-proof/admission-join.ts b/scripts/native-proof/admission-join.ts index f90d91302b..87a6e10da9 100644 --- a/scripts/native-proof/admission-join.ts +++ b/scripts/native-proof/admission-join.ts @@ -1,5 +1,5 @@ /** Offline measurement of both inference fences with real FULL audit writes. */ -import { mkdtempSync, rmSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { resolveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; @@ -9,51 +9,77 @@ import { openSqliteWriter } from "../../packages/ui-server/src/db/write-worker.j import { createGovernanceWrites } from "../../packages/ui-server/src/governance/event-writes.js"; import { prepareTurnEgress } from "../../packages/ui-server/src/brain/turn-egress.js"; import { request } from "node:http"; +import { createTurnJournal, type TurnJournal } from "../../packages/ui-server/src/brain/turn-journal.js"; +import { createTurnScope, type TurnScope } from "../../packages/ui-server/src/brain/turn-scope.js"; +import { journalInference } from "../../packages/ui-server/src/brain/journal-inference.js"; +import { journalDatabasePath } from "../../packages/ui-server/src/db/journal-database.js"; +import { createNativeJournalFixture } from "../../packages/ui-server/tests/helpers/native-journal-fixture.js"; +import type { Database } from "bun:sqlite"; +import type { GovernanceWrites } from "../../packages/ui-server/src/governance/event-writes.js"; -export async function measureAdmissionJoin(directory: string, samples = 5) { - const root = mkdtempSync(join(directory, "admission-join-")), db = createUiDb(join(root, "ui.db")); - const writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); - const rows: { hold: "drained" | "removed"; delayMs: number; sample: number; queuedCommits: number; admitMs: number; credentialToDispatchMs: number; fences: number; admissionFencesMs: number[]; requestAfterResultMs: number }[] = []; +export async function measureAdmissionJoin(directory: string, samples = 5, host?: { journal: TurnJournal; scope: TurnScope; db: Database; writes: GovernanceWrites }) { + const root = mkdtempSync(join(directory, "admission-join-")), path = join(root, "ui.db"), brain = join(root, "brain"); + mkdirSync(brain); writeFileSync(join(brain, "note.md"), "Odysseus returns to Ithaca."); + const db = host?.db ?? createUiDb(path); + const writer = host ? undefined : openSqliteWriter(db, { attach: [{ schema: "journal", path: journalDatabasePath(path) }] }); + const writes = host?.writes ?? createGovernanceWrites(db, writer); + const native = host ? undefined : createNativeJournalFixture(brain, root); + const journal = host?.journal ?? createTurnJournal(db, { brainPath: brain, dbPath: path, objectsRoot: join(root, "objects"), nativeManager: native!.manager, writer }); + const scope = host?.scope ?? createTurnScope(db, { brainPath: brain, journal, writer, governance: writes, connected: () => true, changed() {}, space: () => ({ total: 100e9, free: 90e9 }) }); + const policy = resolveGovernancePolicy({ schema_version: 1 }); + const rows: { hold: "drained" | "removed"; delayMs: number; sample: number; queuedCommits: number; admitMs: number; credentialToDispatchMs: number; fences: number; admissionFencesMs: number[]; requestAfterResultMs: number; dispatchAfterResultMs: number }[] = []; const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { await req.arrayBuffer(); return new Response("Ithaca"); } }); try { for (const hold of ["drained", "removed"] as const) for (const delayMs of [10, 50, 500]) for (let sample = 0; sample < samples; sample++) { + const turnId = `voyage-${hold}-${delayMs}-${sample}`; const controller = new AbortController(), records: EgressRecord[] = []; - let fences = 0, resultAt = 0, requestReceivedAt = 0; + let fences = 0, resultAt = 0, requestReceivedAt = 0, dispatchAt = 0; const admissionFencesMs: number[] = []; - const proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1 }), controller, - turnId: `voyage-${hold}-${delayMs}-${sample}`, sessionId: () => null, model: () => "odysseus", origin: "interactive", profile: "governed", + await journal.begin(turnId, { sessionId: null, actor: "interactive", model: "odysseus", profile: "governed", policyHash: null }, error => controller.abort(error)); + await scope.begin(turnId, { sessionId: null, principalId: "captain", origin: "interactive", profile: "governed", policy, source: "default", hardTimeoutMs: 1e6, current: () => !controller.signal.aborted, stop: reason => controller.abort(new Error(reason)) }); + await journal.observe(); + scope.workerStarted(turnId, { freeze: () => true, resume: () => true, kill: () => true, exited: new Promise(() => {}) }); + const proxy = await prepareTurnEgress({ policy, controller, journal, scope, + turnId, sessionId: () => null, model: () => "odysseus", origin: "interactive", profile: "governed", bridge: { emit() {}, requestPermission: async () => ({ behavior: "deny" }) } as unknown as BackendBridge, record(event) { if (event.kind === "egress_connection") records.push(event.payload as EgressRecord); return writes.record(event); } }); const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { + inferenceRoutes: proxy.inferenceRoutes, inference(...args) { requestReceivedAt = performance.now(); const operation = proxy.inference(...args); - return { ...operation, async admit() { + return { ...operation, dispatch() { const allowed = operation.dispatch(); if (allowed) dispatchAt = performance.now(); return allowed; }, async admit() { fences++; const start = performance.now(); try { return await operation.admit(); } finally { admissionFencesMs.push(performance.now() - start); } } }; }, } }); + let observed: Promise | undefined; try { // Twenty prior completed inference audit rows queue twenty separate // FULL commits. No fake writer latency or durability setting is used. for (let i = 0; i < 20; i++) proxy.inference("POST", new URL("/v1/messages", origin.url), controller.signal).finish("completed"); resultAt = performance.now(); - if (hold === "drained") await proxy.settled(); + journal.toolStarted(turnId, "loom", "Write", true); + observed = journal.toolEnded(turnId, "loom"); + if (hold === "drained") { await journalInference(journal)!.flushDeferred(); await observed; await proxy.settled(); } await Bun.sleep(Math.max(0, delayMs - (performance.now() - resultAt))); const status = await new Promise((resolve, reject) => { const outgoing = request({ socketPath: relay.socketPath, path: "/v1/messages", method: "POST" }, response => { response.resume(); response.on("error", reject); response.on("end", () => resolve(response.statusCode!)); - }); outgoing.on("error", reject); outgoing.end('{"model":"odysseus","messages":[]}'); + }); outgoing.on("error", reject); outgoing.end(JSON.stringify({ model: "odysseus", stream: true, tools: [{ name: "Write" }], messages: [ + { role: "assistant", content: [{ type: "tool_use", id: "loom", name: "Write", input: {} }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "loom", content: "Ithaca" }] }, + ] })); }); await proxy.settled(); const measured = records.at(-1)!; if (status !== 200 || fences !== 2 || measured.admitMs === undefined || measured.dispatchMs === undefined || measured.credentialMs === undefined) throw Error("Admission join measurement missing a successful request, two fences or marks"); - rows.push({ hold, delayMs, sample, queuedCommits: 20, admitMs: measured.admitMs, credentialToDispatchMs: measured.dispatchMs - measured.credentialMs, fences, admissionFencesMs, requestAfterResultMs: requestReceivedAt - resultAt }); - } finally { relay.stop(); controller.abort(); proxy.stop(); await proxy.settled(); } + rows.push({ hold, delayMs, sample, queuedCommits: 20, admitMs: measured.admitMs, credentialToDispatchMs: measured.dispatchMs - measured.credentialMs, fences, admissionFencesMs, requestAfterResultMs: requestReceivedAt - resultAt, dispatchAfterResultMs: dispatchAt - resultAt }); + } finally { relay.stop(); controller.abort(); proxy.stop(); await proxy.settled(); await observed; await journal.finish(turnId); await scope.finish(turnId); } } - return { coverage: "real FULL writer and Unix relay; synthetic twenty-record queue; no native worker or runtime assembly claim", rows }; - } finally { origin.stop(true); await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); } + return { journalAttached: true, coverage: host ? "native host journal/scope and FULL writer; synthetic twenty-record queue; simulated worker control; no runtime assembly claim" : "real journal/scope with copied checkpoints, FULL writer and Unix relay; synthetic twenty-record queue; simulated worker control", rows }; + } finally { origin.stop(true); if (!host) { scope.close(); await journal.close(); await native!.close(); await writer!.close(); db.close(); } rmSync(root, { recursive: true, force: true }); } } if (import.meta.main) { diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index 7d31df5bef..c44b3ea533 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -338,7 +338,7 @@ try { // Fixture-only endpoint; no product route or provider request is added. if (OBSERVATION_TIMING && new URL(request.url).pathname === "/__native_admission_join") { const { measureAdmissionJoin } = await import("./admission-join.js"); - admissionJoin ??= measureAdmissionJoin(dir!); + admissionJoin ??= measureAdmissionJoin(dir!, 5, { journal: app.wsHost.journal, scope: app.wsHost.scope, db: app.db, writes: app.wsHost.activity.governanceWrites }); try { return Response.json(await admissionJoin); } catch (error) { return Response.json({ error: String(error) }, { status: 500 }); } } if (OBSERVATION_TIMING && new URL(request.url).pathname === "/__native_observation_path_matrix") { From 164ec363a1f074b3492a364a0fa2a3d4af56b8e0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 10:21:03 +0000 Subject: [PATCH 09/13] test(ui-server): remove obsolete request counters from review regressions --- packages/ui-server/tests/deferred-freeze-review.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/deferred-freeze-review.test.ts b/packages/ui-server/tests/deferred-freeze-review.test.ts index 5af36f9e90..695565f75f 100644 --- a/packages/ui-server/tests/deferred-freeze-review.test.ts +++ b/packages/ui-server/tests/deferred-freeze-review.test.ts @@ -29,8 +29,8 @@ test("an ambiguous call identity keeps later results immediate (F5)", async () = for (const phase of ["arming", "dispatch"] as const) test(`partial coverage forbids deferral at ${phase} (F7)`, async () => { const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); - const checkpoint = f.native.manager.checkpoint; let upstream = 0; - const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const checkpoint = f.native.manager.checkpoint; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("Ithaca") }); const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); try { if (phase === "arming") await f.journal.writeOperation([{ sql: "UPDATE turn_journal_turns SET state='partial' WHERE turn_id=?", params: ["voyage"] }]); @@ -69,8 +69,8 @@ test("a second inference arrival remains ambiguous after it disconnects (F11)", test("elapsed deadline takes the immediate path before its timer callback runs (D1)", async () => { const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); - const checkpoint = f.native.manager.checkpoint; let upstream = 0; - const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const checkpoint = f.native.manager.checkpoint; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("Ithaca") }); const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); try { const observed = f.result(); f.elapseDeadline(51); From 93989b03d3fa48ec3b0c5b39bb24d3f3cad2cc4f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 13:07:20 +0000 Subject: [PATCH 10/13] fix(ui-server): enforce settled verdicts and contain predicate read failures --- packages/ui-server/src/brain/turn-journal.ts | 26 ++++++----- .../tests/deferred-freeze-review.test.ts | 43 +++++++++++++++++++ .../ui-server/tests/deferred-freeze.test.ts | 32 ++++++++++---- 3 files changed, 82 insertions(+), 19 deletions(-) diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index bbddbb6222..a56036ef49 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -312,7 +312,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const callKey = (turnId: string, toolUseId: string) => JSON.stringify([turnId, toolUseId]); const relays = new Map; eligible(): boolean; allowed(): boolean }>(); const immediateOnly = new Set(); - type Boundary = { turnId: string; toolUseId: string; generation: number; claimed: boolean; settled: boolean; observation: ReturnType; verdict: Promise }; + type Boundary = { turnId: string; toolUseId: string; generation: number; claimed: boolean; settled: boolean; allowed: boolean; observation: ReturnType; verdict: Promise }; const claimed = new Map(); let deferred: Boundary | undefined; /** @internal */ @@ -328,15 +328,19 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { } /** One control predicate, used at arming and at the synchronous dispatch boundary. */ function mayDefer(turnId: string, boundary?: Boundary, operation?: object): boolean { - const relay = relays.get(turnId); - if (failures.has(turnId) || summary(turnId).state !== "recording") immediateOnly.add(turnId); - if (!relay || !relay.messages || immediateOnly.has(turnId)) return false; - if (boundary && (boundary.observation.expired() || relay.generation !== boundary.generation + 1)) { + try { + const relay = relays.get(turnId); + if (failures.has(turnId) || summary(turnId).state !== "recording") immediateOnly.add(turnId); + if (!relay || !relay.messages || immediateOnly.has(turnId)) return false; + if (boundary && (boundary.observation.expired() || relay.generation !== boundary.generation + 1)) { + immediateOnly.add(turnId); return false; + } + return !closing && !holds && active.size === 1 && active.has(turnId) && !calls.size + && ![...lasting].some(id => id !== turnId) && relay.eligible() + && (operation ? relay.operations.size === 1 && relay.operations.has(operation) : relay.operations.size === 0); + } catch { immediateOnly.add(turnId); return false; } - return !closing && !holds && active.size === 1 && active.has(turnId) && !calls.size - && ![...lasting].some(id => id !== turnId) && relay.eligible() - && (operation ? relay.operations.size === 1 && relay.operations.has(operation) : relay.operations.size === 0); } let holds = 0; let observationFailures = 0; @@ -658,7 +662,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { }, dispatch() { if (!boundary) return true; - if (boundary.claimed) return boundary.settled; + if (boundary.claimed) return boundary.settled && boundary.allowed; if (!matched || !mayDefer(turnId, boundary, operation)) { void claimBoundary(boundary).catch(() => {}); return false; } @@ -792,13 +796,13 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const start = (confirmed?: { stopped: boolean }) => held(timing => observe(false, timing), false, traceFor("tool", turnId, toolUseId), undefined, { kind: "tool", turnId, toolUseId }, confirmed); if (call?.started && call.name !== null && mayDefer(turnId)) { - const pending: Boundary = { turnId, toolUseId, generation: relays.get(turnId)!.generation, claimed: false, settled: false, + const pending: Boundary = { turnId, toolUseId, generation: relays.get(turnId)!.generation, claimed: false, settled: false, allowed: false, observation: deferredObservation(confirmed => { if (deferred === pending) deferred = undefined; pending.claimed = true; claimed.set(turnId, pending); return start(confirmed); }), verdict: Promise.resolve(false) }; - pending.verdict = pending.observation.done.then(() => { pending.settled = true; return relays.get(turnId)?.allowed() === true; }); + pending.verdict = pending.observation.done.then(() => { pending.allowed = relays.get(turnId)?.allowed() === true; pending.settled = true; return pending.allowed; }); void pending.verdict.finally(() => { if (claimed.get(turnId) === pending) claimed.delete(turnId); }).catch(() => {}); deferred = pending; return pending.observation.done; diff --git a/packages/ui-server/tests/deferred-freeze-review.test.ts b/packages/ui-server/tests/deferred-freeze-review.test.ts index 695565f75f..8e7563021f 100644 --- a/packages/ui-server/tests/deferred-freeze-review.test.ts +++ b/packages/ui-server/tests/deferred-freeze-review.test.ts @@ -200,3 +200,46 @@ test("the synchronous dispatch predicate rechecks coverage after preparation (D1 await observed; } finally { operation?.finish("cancelled"); await f.close(); } }); + +test("a token-count request cannot dispatch after its immediate observation hit a cap (R2 A1)", async () => { + const f = await fixture(1); let upstream = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages", "/v1/messages/count_tokens"], credentials: {}, egress: f.proxy }); + try { + writeFileSync(join(f.brain, "note.md"), "Penelope"); + const observed = f.result(), response = send(relay.socketPath, body(), "/v1/messages/count_tokens"); + expect((await response).status).toBe(403); await observed; + expect(upstream, "CAPPED_IMMEDIATE_BOUNDARY_CANNOT_DISPATCH_AUXILIARY_REQUEST").toBe(0); + expect(f.journal.summary("voyage").scope!.receipts.at(-1)).toMatchObject({ dimension: "files_changed", state: "paused" }); + } finally { relay.stop(); origin.stop(true); await f.close(); } +}); + +for (const phase of ["arming", "dispatch"] as const) test(`a predicate read failure takes the immediate hold at ${phase} (R2 A2)`, async () => { + const f = await fixture(); + const saved = (f.db.query("SELECT summary FROM turn_scope WHERE turn_id='voyage'").get() as { summary: string }).summary; + let observed: Promise | undefined, operation: ReturnType | undefined; + try { + if (phase === "dispatch") { + observed = f.result(); void observed.catch(() => {}); + operation = f.proxy.inference("POST", new URL("http://127.0.0.1/v1/messages"), new AbortController().signal); + expect(await operation.prepareDispatch(Buffer.from(body()))).toBe(true); + } + f.db.query("UPDATE turn_scope SET summary='{' WHERE turn_id='voyage'").run(); + expect(() => { + if (phase === "arming") { observed = f.result(); void observed.catch(() => {}); } + else expect(operation!.dispatch()).toBe(false); + }, "PREDICATE_READ_FAILURE_RETURNS_TO_IMMEDIATE_HOLD").not.toThrow(); + expect(f.frozen, "PREDICATE_READ_FAILURE_SYNCHRONOUSLY_TAKES_HOLD").toBe(true); + expect(observed, "REQUIRED_OBSERVATION_RETURNS_A_PROMISE").toBeInstanceOf(Promise); + // Repair the read before the queued capture starts. The guard failure + // must still keep this turn immediate after a healthy observation. + f.db.query("UPDATE turn_scope SET summary=? WHERE turn_id='voyage'").run(saved); + await observed!; + operation?.finish("cancelled"); + const later = f.result("sail"); + expect(f.frozen, "PREDICATE_READ_FAILURE_LATCH_REMAINS_IMMEDIATE_ONLY").toBe(true); await later; + } finally { + f.db.query("UPDATE turn_scope SET summary=? WHERE turn_id='voyage'").run(saved); + operation?.finish("cancelled"); await f.close(); + } +}); diff --git a/packages/ui-server/tests/deferred-freeze.test.ts b/packages/ui-server/tests/deferred-freeze.test.ts index 130328e975..a60e5acd2e 100644 --- a/packages/ui-server/tests/deferred-freeze.test.ts +++ b/packages/ui-server/tests/deferred-freeze.test.ts @@ -107,19 +107,35 @@ for (const requestKind of ["token count", "title", "wrong result", "parallel res for (const ack of [false, undefined] as const) { test(`a ${String(ack)} stop receipt falls back to the base immediate hold`, async () => { - const f = await fixture(); let upstream = 0; - const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); - const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const checkpoint = f.native.manager.checkpoint; + const arrived = Promise.withResolvers(), fallbackGate = Promise.withResolvers(); + // Establish ordering before either event can happen; no polling or sleep + // stands in for observing an actual upstream request during the hold. + const firstBoundary = Promise.race([arrived.promise.then(() => "upstream"), fallbackGate.promise.then(() => "fallback")]); + let upstream = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; arrived.resolve(); return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { + ...f.proxy, inference(...args) { + const operation = f.proxy.inference(...args); + return { ...operation, responseReady() { fallbackGate.resolve(); return operation.responseReady(); } }; + }, + } }); try { + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; f.ack(ack); - const observed = f.result(); - let committed = false; void observed.then(() => { committed = true; }, () => {}); - expect((await send(relay.socketPath)).status, "UNCONFIRMED_STOP_FALLS_BACK_WITHOUT_NEW_REFUSAL").toBe(200); - await observed; expect(committed).toBe(true); + const observed = f.result(), response = send(relay.socketPath); void response.catch(() => {}); + await entered.promise; + const first = await firstBoundary; + expect(upstream, "UPSTREAM_STAYS_EMPTY_WHILE_FALLBACK_OBSERVATION_IS_HELD").toBe(0); + expect(first, "UNCONFIRMED_STOP_CANNOT_DISPATCH_BEFORE_FALLBACK_COMMIT").toBe("fallback"); + release.resolve(); + expect((await response).status, "UNCONFIRMED_STOP_FALLS_BACK_WITHOUT_NEW_REFUSAL").toBe(200); + await observed; expect(upstream).toBe(1); expect(f.controller.signal.aborted).toBe(false); expect(f.journal.summary("voyage").state, "LEGACY_STOP_RETAINS_BASE_JOURNAL_BEHAVIOR").toBe("recording"); - } finally { relay.stop(); origin.stop(true); await f.close(); } + } finally { release.resolve(); f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } }); } From 630eb5cc2c53c794149e6af1680f0b389ad7a65b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 14:20:50 +0000 Subject: [PATCH 11/13] fix(ui-server): gate relay traffic on committed result generations --- .changeset/tidy-ithaca-freeze.md | 2 +- docs/decisions/governed-writable-workers.md | 26 +- packages/ui-sdk/src/internal.ts | 2 + packages/ui-sdk/src/server/inference-relay.ts | 342 ++++++++++-------- packages/ui-server/src/brain/turn-egress.ts | 25 +- packages/ui-server/src/brain/turn-journal.ts | 147 +++++--- packages/ui-server/src/brain/turn-scope.ts | 5 +- .../tests/deferred-freeze-gate.test.ts | 179 +++++++++ .../tests/helpers/deferred-freeze-fixture.ts | 10 +- 9 files changed, 507 insertions(+), 231 deletions(-) create mode 100644 packages/ui-server/tests/deferred-freeze-gate.test.ts diff --git a/.changeset/tidy-ithaca-freeze.md b/.changeset/tidy-ithaca-freeze.md index 775ef67723..3c0e6e08fd 100644 --- a/.changeset/tidy-ithaca-freeze.md +++ b/.changeset/tidy-ithaca-freeze.md @@ -3,4 +3,4 @@ "@schlessera/brain-ui-sdk": patch --- -Overlap eligible per-tool journal observations with the next model request. Confirm the worker stop at full-request dispatch, retain every observation and its durability, and withhold the response until the observation and scope pause have committed. Unknown, partial, unsupported or ambiguous work retains the immediate hold. Early refusals share the result observation gate, and each request retains its own cap verdict after Continue. Unconfirmed stops use the existing immediate schedule. +Overlap eligible per-tool journal observations with the next model request. Confirm the worker stop at full-request dispatch, retain every observation and its durability, and withhold the response until the observation and scope pause have committed. Unknown, partial, unsupported or ambiguous work retains the immediate hold. Early refusals share the result observation gate, and each request retains its own cap verdict after Continue. Unconfirmed stops use the existing immediate schedule. Register every relay arrival before route checks, gate exceptions as well as ordinary replies on committed result generations, and refuse stragglers while their turn is paused. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index cca8d1b7e9..3aa41867bf 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1671,12 +1671,26 @@ Only a confirmed deferred stop waits for the scope writes to commit. Immediate, periodic, finish and admission holds keep their existing schedule, and an ordinary inference never joins unrelated work on the global journal queue. -Every answer for a request associated with an armed or claimed result boundary -passes one observation gate, including admission, size, byte-cap and credential -refusals. Its observation verdict is latched for that request when the -observation commits. A cap discards the in-flight upstream response even if the -owner chooses Continue before upstream headers arrive; later requests use their -own verdict. The existing cap receipt and authorized continuation remain. +Each turn with a relay keeps a monotonic result gate: every required result +increments its required generation before eligibility is read, and only that +result's observation advances its committed generation. Rejection keeps that +turn's gate failed. Periodic, begin and scope observations never advance it. +Every arrival records the generations pending at that instant, before method +or route checks. Dispatch requires all generations committed and current scope +authority, except for the one eligible latest result with a confirmed stop. +The stop receipt counts acknowledged workers for the cause turn; it must be +nonzero and equal the turn's worker count. + +Every relay answer crosses the same gate, including wrong methods and routes, +admission errors and exceptions, size, byte-cap and credential refusals. The +inner handler returns a branded value that only the gated exit can produce. +The exit claims any armed observation and waits for the required generations +to commit or fail, checking again after each wait. A denied generation pending +at arrival remains bound to that request even after Continue. A cap therefore +discards the in-flight upstream response even if the owner chooses Continue +before upstream headers arrive. A straggler arriving on a paused turn receives +403 until Continue authorizes dispatch. The existing cap receipt and authorized +continuation remain. Files changed, observed turn bytes, index capacity, wall minutes and free space may be discovered after one request has left. The tool-call cap stays checked at launch. No existing egress, credential, recording or authority fence is removed. diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index 9e524193c8..8d6f55c5e2 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -104,3 +104,5 @@ export { createCleanupReconciler, processCleanupReconciler, CLEANUP_RETRY_ATTEMP export type { CleanupNotice, CleanupReconciler, CleanupReconcilerOptions, RetainedCleanup } from "./server/cleanup-reconciler.js"; export { workspaceWriteRefusal } from "./server/workspace-refusal.js"; + +export type { InferenceArrival } from "./server/inference-relay.js"; diff --git a/packages/ui-sdk/src/server/inference-relay.ts b/packages/ui-sdk/src/server/inference-relay.ts index 917f7a87b5..a2104d6240 100644 --- a/packages/ui-sdk/src/server/inference-relay.ts +++ b/packages/ui-sdk/src/server/inference-relay.ts @@ -27,6 +27,17 @@ export const INFERENCE_PLACEHOLDER = INFERENCE_RELAY_PLACEHOLDER; /** A request body larger than this is refused before anything is forwarded. */ export const MAX_INFERENCE_REQUEST_BYTES = 32 * 1024 * 1024; +/** Internal turn-level gate, registered even when a request has no egress operation. */ +export interface InferenceArrival { + prepareDispatch(body: Uint8Array): Promise; + dispatch(): boolean; + responseReady(): Promise; + close(): void; +} +type InferenceOperation = ReturnType>["inference"]>; +const gated = Symbol("gated relay response"); +type Gated = { [gated]: Response }; + export interface InferenceRelayOptions { /** Server-selected upstream base, e.g. `https://api.anthropic.com`. */ upstream: string; @@ -35,7 +46,11 @@ export interface InferenceRelayOptions { /** Server-held headers, resolved for each dispatch after inbound credentials are removed. */ credentials: Readonly> | ((signal: AbortSignal, target: URL) => Promise>>); /** Concrete turn proxy: share its destination admission, application-byte ceiling and audit. */ - egress?: Pick>, "inference"> & { inferenceRoutes?(paths: readonly string[]): void }; + egress?: { + inference(method: string, target: URL, signal: AbortSignal, arrival?: InferenceArrival): InferenceOperation; + inferenceArrival?(path: string): InferenceArrival | undefined; + inferenceRoutes?(paths: readonly string[]): void; + }; /** Called for every request, forwarded or refused. Values are never logged. */ observe?(event: InferenceRelayEvent): void; /** Host receipt of an authorized route, before egress admission or reading its body. Observability only. */ @@ -117,166 +132,187 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe async fetch(request) { const url = new URL(request.url); const path = url.pathname; - if (request.method !== "POST") return refuse(request.method, path, 405, "Only inference requests are relayed"); - if (!routes.has(path)) return refuse(request.method, path, 403, "This path is not an authorized inference route"); - observeDiagnostic(() => options.received?.(path)); - const target = new URL(upstream.origin); - target.pathname = path; target.search = url.search; - const operation = options.egress?.inference(request.method, target, request.signal); - const mark = (name: InferenceTimingMark) => observeDiagnostic(() => operation?.mark(name)); - const signal = operation ? AbortSignal.any([request.signal, operation.signal]) : request.signal; - // Every answer for this operation crosses the same result boundary, - // including failures before full-body dispatch preparation. - const answer = async (create: () => Response | Promise, discard?: () => Promise): Promise => { - if (operation && !await operation.responseReady()) { - await discard?.(); operation.finish("denied", "deferred_observation_refused"); - return refuse(request.method, path, 403, "Inference request refused", "deferred_observation_refused"); + let operation: InferenceOperation | undefined; + let arrival: InferenceArrival | undefined; + // Only exit can brand an inner result. Every return, including catch, + // crosses the turn gate before the outer fetch can expose a Response. + const exit = async (create: () => Response | Promise, discard?: () => Promise): Promise => { + const ready = () => operation?.responseReady() ?? arrival?.responseReady() ?? Promise.resolve(true); + if (!await ready()) { + await discard?.(); await ready(); + operation?.finish("denied", "deferred_observation_refused"); + return { [gated]: refuse(request.method, path, 403, "Inference request refused", "deferred_observation_refused") }; } - return create(); + const response = await create(); + // Async response construction can cross a newer tool result too. + if (!await ready()) { + await response.body?.cancel().catch(() => {}); await ready(); + operation?.finish("denied", "deferred_observation_refused"); + return { [gated]: refuse(request.method, path, 403, "Inference request refused", "deferred_observation_refused") }; + } + return { [gated]: response }; }; - const denied = (reason: string, status = 403): Promise => answer(() => { - operation?.finish("denied", reason); - return refuse(request.method, path, status, reason === "max_bytes_per_turn" ? "Inference egress limit exceeded" : "Inference request refused", operation?.reason?.() ?? reason); - }); - if (operation && !await operation.admit()) { - const cancelled = request.signal.aborted || operation.outcome() === "cancelled"; - operation.finish(cancelled ? "cancelled" : "denied", "inference_admission_refused"); - return answer(() => refuse(request.method, path, cancelled ? 499 : 403, "Inference network admission refused", operation.reason?.())); - } - mark("admitMs"); - const declared = Number(request.headers.get("content-length") ?? "0"); - if (declared > MAX_INFERENCE_REQUEST_BYTES) return denied("inference_request_too_large", 413); - // Do not allocate an unbounded arrayBuffer before checking the ceiling. - // Charge each received body chunk before retaining or forwarding it. - const chunks: Uint8Array[] = []; - let length = 0; - const reader = request.body?.getReader(); - const cancelBody = () => { void reader?.cancel().catch(() => {}); }; - signal.addEventListener("abort", cancelBody, { once: true }); - if (signal.aborted) cancelBody(); - try { - if (reader) for (;;) { - const next = await reader.read(); - if (next.done) break; - length += next.value.byteLength; - if (length > MAX_INFERENCE_REQUEST_BYTES || operation && !operation.charge(next.value.byteLength + 16)) { - await reader.cancel().catch(() => {}); - return denied(length > MAX_INFERENCE_REQUEST_BYTES ? "inference_request_too_large" : "max_bytes_per_turn", - length > MAX_INFERENCE_REQUEST_BYTES ? 413 : 403); - } - chunks.push(next.value); + const handle = async (): Promise => { + arrival = options.egress?.inferenceArrival?.(path); + if (request.method !== "POST") return exit(() => refuse(request.method, path, 405, "Only inference requests are relayed")); + if (!routes.has(path)) return exit(() => refuse(request.method, path, 403, "This path is not an authorized inference route")); + observeDiagnostic(() => options.received?.(path)); + const target = new URL(upstream.origin); + target.pathname = path; target.search = url.search; + operation = options.egress?.inference(request.method, target, request.signal, arrival); + const op = operation; + const mark = (name: InferenceTimingMark) => observeDiagnostic(() => op?.mark(name)); + const signal = op ? AbortSignal.any([request.signal, op.signal]) : request.signal; + const denied = (reason: string, status = 403): Promise => exit(() => { + op?.finish("denied", reason); + return refuse(request.method, path, status, reason === "max_bytes_per_turn" ? "Inference egress limit exceeded" : "Inference request refused", op?.reason?.() ?? reason); + }); + if (op && !await op.admit()) { + const cancelled = request.signal.aborted || op.outcome() === "cancelled"; + op.finish(cancelled ? "cancelled" : "denied", "inference_admission_refused"); + return exit(() => refuse(request.method, path, cancelled ? 499 : 403, "Inference network admission refused", op.reason?.())); } - } catch { - operation?.finish("cancelled", "client_disconnected"); - return answer(() => refuse(request.method, path, 499, "Inference request cancelled")); - } finally { signal.removeEventListener("abort", cancelBody); reader?.releaseLock(); } - mark("bodyMs"); - const body = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { body.set(chunk, offset); offset += chunk.byteLength; } - const headers = new Headers(); - for (const [name, value] of request.headers) if (!STRIPPED.has(name.toLowerCase())) headers.set(name, value); - let credentials: Readonly>; - if (signal.aborted) { - operation?.finish("cancelled", "client_disconnected"); - return answer(() => refuse(request.method, path, 499, "Inference request cancelled")); - } - try { - credentials = typeof options.credentials === "function" ? await options.credentials(signal, new URL(target)) : options.credentials; - validateCredentials(credentials); - mark("credentialMs"); + mark("admitMs"); + const declared = Number(request.headers.get("content-length") ?? "0"); + if (declared > MAX_INFERENCE_REQUEST_BYTES) return denied("inference_request_too_large", 413); + // Do not allocate an unbounded arrayBuffer before checking the ceiling. + // Charge each received body chunk before retaining or forwarding it. + const chunks: Uint8Array[] = []; + let length = 0; + const reader = request.body?.getReader(); + const cancelBody = () => { void reader?.cancel().catch(() => {}); }; + signal.addEventListener("abort", cancelBody, { once: true }); + if (signal.aborted) cancelBody(); + try { + if (reader) for (;;) { + const next = await reader.read(); + if (next.done) break; + length += next.value.byteLength; + if (length > MAX_INFERENCE_REQUEST_BYTES || op && !op.charge(next.value.byteLength + 16)) { + await reader.cancel().catch(() => {}); + return denied(length > MAX_INFERENCE_REQUEST_BYTES ? "inference_request_too_large" : "max_bytes_per_turn", + length > MAX_INFERENCE_REQUEST_BYTES ? 413 : 403); + } + chunks.push(next.value); + } + } catch { + op?.finish("cancelled", "client_disconnected"); + return exit(() => refuse(request.method, path, 499, "Inference request cancelled")); + } finally { signal.removeEventListener("abort", cancelBody); reader?.releaseLock(); } + mark("bodyMs"); + const body = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { body.set(chunk, offset); offset += chunk.byteLength; } + const headers = new Headers(); + for (const [name, value] of request.headers) if (!STRIPPED.has(name.toLowerCase())) headers.set(name, value); + let credentials: Readonly>; if (signal.aborted) { - operation?.finish("cancelled", "client_disconnected"); - return answer(() => refuse(request.method, path, 499, "Inference request cancelled")); + op?.finish("cancelled", "client_disconnected"); + return exit(() => refuse(request.method, path, 499, "Inference request cancelled")); } - for (const [name, value] of Object.entries(credentials)) headers.set(name, value); - } catch { - // A resolver error may carry a provider reply, credential or host path. - const cancelled = signal.aborted; - operation?.finish(cancelled ? "cancelled" : "failed", "inference_credentials_unavailable"); - return answer(() => refuse(request.method, path, cancelled ? 499 : 503, - cancelled ? "Inference request cancelled" : "Inference credentials unavailable")); - } - // HTTP application framing before provider TLS: never describe this as - // measured TLS ciphertext/handshake bytes. Include every observable - // query/header byte plus a conservative runtime framing allowance. - const headerBytes = (first: string, values: Headers): number => { - let bytes = Buffer.byteLength(first) + 1028; - for (const [name, value] of values) bytes += Buffer.byteLength(name) + Buffer.byteLength(value) + 4; - return bytes; - }; - if (operation && !operation.charge(headerBytes(`${request.method} ${path}${url.search} HTTP/1.1`, headers))) { - return denied("max_bytes_per_turn"); - } - // Body/credential waits may have crossed an input-recording failure. - // Re-enter the concrete host admission at the last dispatch boundary. - if(operation&&!await operation.admit())return denied("inference_admission_refused"); - if (operation && !await operation.prepareDispatch(body)) return denied("inference_admission_refused"); - if (operation && !operation.dispatch()) { - // An unconfirmed speculative stop falls back to the existing held - // observation. After it commits, base admission may proceed normally. - if (!await operation.responseReady() || !await operation.admit() || !operation.dispatch()) return denied("inference_admission_refused"); - } - let response: Response; - try { - // Never follow a redirect: the upstream must not choose another host. - mark("dispatchMs"); - response = await fetch(target, { method: "POST", headers, body, redirect: "manual", signal }); - } catch { - const cancelled = signal.aborted; - operation?.finish(cancelled ? "cancelled" : "failed", "upstream_unreachable"); - return answer(() => refuse(request.method, path, cancelled ? 499 : 502, - cancelled ? "Inference request cancelled" : "Inference upstream unreachable")); - } - mark("headersMs"); - return answer(async () => { - if (response.status >= 300 && response.status < 400) { - operation?.finish("failed", "upstream_redirected"); - await response.body?.cancel().catch(() => {}); - return refuse(request.method, path, 502, "Inference upstream redirected; redirects are not followed"); + try { + credentials = typeof options.credentials === "function" ? await options.credentials(signal, new URL(target)) : options.credentials; + validateCredentials(credentials); + mark("credentialMs"); + if (signal.aborted) { + op?.finish("cancelled", "client_disconnected"); + return exit(() => refuse(request.method, path, 499, "Inference request cancelled")); + } + for (const [name, value] of Object.entries(credentials)) headers.set(name, value); + } catch { + // A resolver error may carry a provider reply, credential or host path. + const cancelled = signal.aborted; + op?.finish(cancelled ? "cancelled" : "failed", "inference_credentials_unavailable"); + return exit(() => refuse(request.method, path, cancelled ? 499 : 503, + cancelled ? "Inference request cancelled" : "Inference credentials unavailable")); } - observeDiagnostic(() => options.observe?.({ method: request.method, path, outcome: "forwarded", status: response.status })); - const out = new Headers(); - for (const [name, value] of response.headers) if (!RESPONSE_STRIPPED.has(name.toLowerCase())) out.set(name, value); - if (operation && !operation.charge(headerBytes(`HTTP/1.1 ${response.status} ${response.statusText}`, response.headers))) { - operation.finish("denied", "max_bytes_per_turn"); - await response.body?.cancel().catch(() => {}); - return refuse(request.method, path, 403, "Inference egress limit exceeded"); + // HTTP application framing before provider TLS: never describe this as + // measured TLS ciphertext/handshake bytes. Include every observable + // query/header byte plus a conservative runtime framing allowance. + const headerBytes = (first: string, values: Headers): number => { + let bytes = Buffer.byteLength(first) + 1028; + for (const [name, value] of values) bytes += Buffer.byteLength(name) + Buffer.byteLength(value) + 4; + return bytes; + }; + if (op && !op.charge(headerBytes(`${request.method} ${path}${url.search} HTTP/1.1`, headers))) { + return denied("max_bytes_per_turn"); } - if (!operation) return new Response(response.body, { status: response.status, headers: out }); - if (!response.body) { - operation.finish("completed"); - return new Response(null, { status: response.status, headers: out }); + // Body/credential waits may have crossed an input-recording failure. + // Re-enter the concrete host admission at the last dispatch boundary. + if(op&&!await op.admit())return denied("inference_admission_refused"); + if (op && !await op.prepareDispatch(body)) return denied("inference_admission_refused"); + if (op && !op.dispatch()) { + // An unconfirmed speculative stop falls back to the existing held + // observation. After it commits, base admission may proceed normally. + if (!await op.responseReady() || !await op.admit() || !op.dispatch()) return denied("inference_admission_refused"); } - const upstreamReader = response.body.getReader(); - let observeUsage: ((chunk: Uint8Array) => void) | undefined; - observeDiagnostic(() => { observeUsage = inferenceUsageObserver(usage => observeDiagnostic(() => operation.observeUsage(usage))); }); - let firstReadAttempted = false; - let released = false; - const release = () => { if (!released) { released = true; upstreamReader.releaseLock(); } }; - const output = new ReadableStream({ - async pull(controller) { - try { - const next = await upstreamReader.read(); - if (!firstReadAttempted) { firstReadAttempted = true; mark("firstChunkMs"); } - if (next.done) { operation.finish("completed"); release(); controller.close(); } - else if (!operation.charge(next.value.byteLength + 16)) { - operation.finish("denied", "max_bytes_per_turn"); - await upstreamReader.cancel().catch(() => {}); release(); - controller.error(new Error("Inference egress limit exceeded")); - } else { controller.enqueue(next.value); observeDiagnostic(() => observeUsage?.(next.value)); } - } catch { - operation.finish(signal.aborted ? "cancelled" : "failed", "upstream_response_failed"); - release(); controller.error(new Error("Inference response interrupted")); - } - }, - async cancel() { - operation.finish("cancelled", "client_disconnected"); - await upstreamReader.cancel().catch(() => {}); release(); - }, - }); - return new Response(output, { status: response.status, headers: out }); - }, async () => { await response.body?.cancel().catch(() => {}); }); + let response: Response; + try { + // Never follow a redirect: the upstream must not choose another host. + mark("dispatchMs"); + response = await fetch(target, { method: "POST", headers, body, redirect: "manual", signal }); + } catch { + const cancelled = signal.aborted; + op?.finish(cancelled ? "cancelled" : "failed", "upstream_unreachable"); + return exit(() => refuse(request.method, path, cancelled ? 499 : 502, + cancelled ? "Inference request cancelled" : "Inference upstream unreachable")); + } + mark("headersMs"); + return exit(async () => { + if (response.status >= 300 && response.status < 400) { + op?.finish("failed", "upstream_redirected"); + await response.body?.cancel().catch(() => {}); + return refuse(request.method, path, 502, "Inference upstream redirected; redirects are not followed"); + } + observeDiagnostic(() => options.observe?.({ method: request.method, path, outcome: "forwarded", status: response.status })); + const out = new Headers(); + for (const [name, value] of response.headers) if (!RESPONSE_STRIPPED.has(name.toLowerCase())) out.set(name, value); + if (op && !op.charge(headerBytes(`HTTP/1.1 ${response.status} ${response.statusText}`, response.headers))) { + op.finish("denied", "max_bytes_per_turn"); + await response.body?.cancel().catch(() => {}); + return refuse(request.method, path, 403, "Inference egress limit exceeded"); + } + if (!op) return new Response(response.body, { status: response.status, headers: out }); + if (!response.body) { + op.finish("completed"); + return new Response(null, { status: response.status, headers: out }); + } + const upstreamReader = response.body.getReader(); + let observeUsage: ((chunk: Uint8Array) => void) | undefined; + observeDiagnostic(() => { observeUsage = inferenceUsageObserver(usage => observeDiagnostic(() => op.observeUsage(usage))); }); + let firstReadAttempted = false; + let released = false; + const release = () => { if (!released) { released = true; upstreamReader.releaseLock(); } }; + const output = new ReadableStream({ + async pull(controller) { + try { + const next = await upstreamReader.read(); + if (!firstReadAttempted) { firstReadAttempted = true; mark("firstChunkMs"); } + if (next.done) { op.finish("completed"); release(); controller.close(); } + else if (!op.charge(next.value.byteLength + 16)) { + op.finish("denied", "max_bytes_per_turn"); + await upstreamReader.cancel().catch(() => {}); release(); + controller.error(new Error("Inference egress limit exceeded")); + } else { controller.enqueue(next.value); observeDiagnostic(() => observeUsage?.(next.value)); } + } catch { + op.finish(signal.aborted ? "cancelled" : "failed", "upstream_response_failed"); + release(); controller.error(new Error("Inference response interrupted")); + } + }, + async cancel() { + op.finish("cancelled", "client_disconnected"); + await upstreamReader.cancel().catch(() => {}); release(); + }, + }); + return new Response(output, { status: response.status, headers: out }); + }, async () => { await response.body?.cancel().catch(() => {}); }); + }; + try { return (await handle())[gated]; } + catch { + // Exception messages can contain provider bytes or credentials. + operation?.finish("failed", "inference_relay_failed"); + return (await exit(() => refuse(request.method, path, 500, "Inference relay failed")))[gated]; + } finally { if (!operation) arrival?.close(); } }, }); } catch (error) { rmSync(dir, { recursive: true, force: true }); throw error; } diff --git a/packages/ui-server/src/brain/turn-egress.ts b/packages/ui-server/src/brain/turn-egress.ts index dd38c2a629..11a32acd73 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -1,7 +1,7 @@ import { journalInference } from "./journal-inference.js"; /** One admitted turn's concrete proxy, approval surface and durable records. */ import type { EffectiveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; -import { startEgressProxy, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; +import { startEgressProxy, type EgressRecord, type InferenceArrival } from "@schlessera/brain-ui-sdk/internal"; import { requestToolPermission, type BackendActivityEvent, type BackendBridge } from "@schlessera/brain-ui-sdk/server"; import type { Database } from "bun:sqlite"; import { occurrence, type Occurrence } from "../governance/occurrence.js"; @@ -287,24 +287,24 @@ export async function prepareTurnEgress(options: { }, set: (value: BackendBridge["inputSafety"]) => { original.inputSafety = value; } }); } - const relayOperation = (kind: "inference" | "relayed", method: string, target: URL, signal: AbortSignal) => { + const relayOperation = (kind: "inference" | "relayed", method: string, target: URL, signal: AbortSignal, arrival?: InferenceArrival) => { const operation = proxy[kind](method, target, signal); const settledOperation = settleOperation(operation); if (kind !== "inference" || !inference || !options.scope) return settledOperation; - const boundary = inference.requestStarted(options.turnId); - operation.signal.addEventListener("abort", boundary.close, { once: true }); - if (operation.signal.aborted) boundary.close(); + const gate = arrival ?? inferenceArrival(target.pathname)!; + operation.signal.addEventListener("abort", gate.close, { once: true }); + if (operation.signal.aborted) gate.close(); return { ...settledOperation, async prepareDispatch(body: Uint8Array) { - try { return await boundary.prepare(target.pathname, body); } + try { return await gate.prepareDispatch(body); } catch { return false; } }, dispatch() { if (!operation.commit()) return false; - return boundary.dispatch(); + return gate.dispatch(); }, async responseReady() { - return boundary.responseReady(); + return gate.responseReady(); }, }; }; @@ -327,9 +327,14 @@ export async function prepareTurnEgress(options: { } finally { if (abort) operation.signal.removeEventListener("abort", abort); } } }; }; - return { ...proxy, inferenceRoutes(paths: readonly string[]) { inference?.routes(options.turnId, paths); }, bridge, recordingFailure: () => recordingFailure, settled, + const inferenceArrival = (path: string): InferenceArrival | undefined => { + if (!inference || !options.scope) return; + const request = inference.requestStarted(options.turnId); + return { ...request, prepareDispatch: body => request.prepare(path, body) }; + }; + return { ...proxy, inferenceArrival, inferenceRoutes(paths: readonly string[]) { inference?.routes(options.turnId, paths); }, bridge, recordingFailure: () => recordingFailure, settled, stop() { releaseJournalRelay?.(); proxy.stop(); }, - inference: (method: string, target: URL, signal: AbortSignal) => relayOperation("inference", method, target, signal), + inference: (method: string, target: URL, signal: AbortSignal, arrival?: InferenceArrival) => relayOperation("inference", method, target, signal, arrival), relayed: (method: string, target: URL, signal: AbortSignal) => relayOperation("relayed", method, target, signal), managedReference: (target: URL, signal: AbortSignal) => settleOperation(proxy.managedReference(target, signal)) }; } diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index a56036ef49..dcf40dd0e9 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -111,7 +111,7 @@ export interface TurnJournalOptions { /** Internal shared interval; scope records each turn's control acknowledgements. */ export interface JournalHold { /** @internal Control receipt required for speculative inference dispatch; never diagnostic. */ - requireConfirmedStop?: boolean; + stopReceipt?: { turnId: string; count: number; total: number }; records: Map; stoppedTurns: Set; paths: Map>; @@ -310,29 +310,40 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const calls = new Map(); const lasting = new Set(); const callKey = (turnId: string, toolUseId: string) => JSON.stringify([turnId, toolUseId]); - const relays = new Map; eligible(): boolean; allowed(): boolean }>(); + type Gate = { required: number; committed: number; denied: Set; failed: boolean; + armed?: { gen: number; observation: ReturnType } }; + const gates = new Map(); + const gateWaiters = new Map void>>(); + const relays = new Map; eligible(): boolean; allowed(): boolean }>(); const immediateOnly = new Set(); - type Boundary = { turnId: string; toolUseId: string; generation: number; claimed: boolean; settled: boolean; allowed: boolean; observation: ReturnType; verdict: Promise }; - const claimed = new Map(); - let deferred: Boundary | undefined; + function gateFor(turnId: string): Gate { + let gate = gates.get(turnId); + if (!gate) { gate = { required: 0, committed: 0, denied: new Set(), failed: false }; gates.set(turnId, gate); } + return gate; + } + function wakeGate(gate: Gate): void { + const waiters = gateWaiters.get(gate); gateWaiters.delete(gate); + for (const wake of waiters ?? []) wake(); + } + function claimGate(gate: Gate, confirmed?: { stopped: boolean }): Promise { + const armed = gate.armed; + if (!armed) return Promise.resolve(); + // Clear before entering held(), which flushes other armed results too. + gate.armed = undefined; + return armed.observation.claim(confirmed); + } /** @internal */ function flushDeferred(): Promise { - const pending = deferred; - if (!pending) return Promise.resolve(); - return claimBoundary(pending); - } - function claimBoundary(boundary: Boundary, confirmed?: { stopped: boolean }): Promise { - if (deferred === boundary) deferred = undefined; - if (!boundary.claimed) { boundary.claimed = true; claimed.set(boundary.turnId, boundary); } - return boundary.observation.claim(confirmed); + return Promise.all([...gates.values()].map(gate => claimGate(gate))).then(() => {}); } /** One control predicate, used at arming and at the synchronous dispatch boundary. */ - function mayDefer(turnId: string, boundary?: Boundary, operation?: object): boolean { + function mayDefer(turnId: string, armed?: Gate["armed"], operation?: object): boolean { try { const relay = relays.get(turnId); if (failures.has(turnId) || summary(turnId).state !== "recording") immediateOnly.add(turnId); if (!relay || !relay.messages || immediateOnly.has(turnId)) return false; - if (boundary && (boundary.observation.expired() || relay.generation !== boundary.generation + 1)) { + if (armed && (armed.observation.expired() || relay.generation !== relay.armedAt + 1)) { immediateOnly.add(turnId); return false; } return !closing && !holds && active.size === 1 && active.has(turnId) && !calls.size @@ -349,7 +360,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { cause: { kind: ActivityTurnHold["cause"]; turnId: string | null; toolUseId?: string; hold?: ActivityTurnHold } = { kind: "scope", turnId: null }, confirmed?: { stopped: boolean }): Promise { void flushDeferred().catch(() => {}); const holdId = cause.hold?.holdId ?? crypto.randomUUID(), requestedAt = Date.now(); - const interval: JournalHold = { ...(confirmed ? { requireConfirmedStop: true } : {}), records: new Map(), stoppedTurns: new Set(), paths: new Map(), + const interval: JournalHold = { ...(confirmed && cause.turnId ? { stopReceipt: { turnId: cause.turnId, count: 0, total: 0 } } : {}), records: new Map(), stoppedTurns: new Set(), paths: new Map(), inferenceInFlight: id => diagnostic(() => evidence.get(id)?.inference() ?? false) ?? null, participant(id) { const previous = interval.records.get(id); if (previous) return previous; @@ -371,7 +382,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { let acquired = 0; try { for (const holder of holders) { acquired++; holder.before(interval); } } catch (error) { holds--; for (const holder of holders.slice(0, acquired)) holder.after(false, interval); return Promise.reject(error); } - if (confirmed) confirmed.stopped = holders.length > 0 && interval.requireConfirmedStop === true; + if (confirmed) confirmed.stopped = !!interval.stopReceipt && interval.stopReceipt.count >= 1 && interval.stopReceipt.count === interval.stopReceipt.total; return serialize(async () => { waited?.(); currentHold = interval; @@ -629,7 +640,8 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const inference: Parameters[1] = { relayStarted(turnId, transport, signal) { void flushDeferred().catch(() => {}); - const relay = { ...transport, messages: false, generation: 0, operations: new Set() }; + gateFor(turnId); + const relay = { ...transport, messages: false, generation: 0, armedAt: 0, toolUseId: "", operations: new Set() }; relays.set(turnId, relay); const abort = () => { void flushDeferred().catch(() => {}); if (relays.get(turnId) === relay) relays.delete(turnId); }; signal.addEventListener("abort", abort, { once: true }); @@ -643,39 +655,51 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { }, flushDeferred, requestStarted(turnId) { - const relay = relays.get(turnId), operation = {}; - const boundary = deferred?.turnId === turnId ? deferred : claimed.get(turnId); + const gate = gateFor(turnId), relay = relays.get(turnId), operation = {}; + // Only generations pending at arrival bind their committed verdict to this request. + const bound = { after: gate.committed, through: gate.required }; + const denied = () => [...gate.denied].some(gen => gen > bound.after && gen <= bound.through); + const allowed = () => { try { return relay?.allowed() === true; } catch { return false; } }; if (relay) { relay.operations.add(operation); relay.generation++; - if (boundary && relay.generation > boundary.generation + 1) { - immediateOnly.add(turnId); void claimBoundary(boundary).catch(() => {}); + if (relay.operations.size > 1 || gate.armed && relay.generation > relay.armedAt + 1) { + immediateOnly.add(turnId); void claimGate(gate).catch(() => {}); } } let matched = false; + const responseReady = async (): Promise => { + for (;;) { + void claimGate(gate).catch(() => {}); + if (gate.failed) return false; + if (gate.committed === gate.required) return !denied(); + await new Promise(resolve => { + const waiters = gateWaiters.get(gate) ?? new Set(); + waiters.add(resolve); gateWaiters.set(gate, waiters); + }); + } + }; return { async prepare(path, body) { - matched = !!boundary && mayDefer(turnId, boundary, operation) && followsToolResult(path, body, boundary.toolUseId); - if (matched && !boundary!.claimed) return true; - // Join only this request's result boundary, never unrelated journal work. - if (boundary) await claimBoundary(boundary); + const armed = gate.armed; + matched = !!armed && mayDefer(turnId, armed, operation) && followsToolResult(path, body, relay!.toolUseId); + if (matched) return true; + // Join only this turn's required results, never unrelated journal work. + await responseReady(); return true; }, dispatch() { - if (!boundary) return true; - if (boundary.claimed) return boundary.settled && boundary.allowed; - if (!matched || !mayDefer(turnId, boundary, operation)) { - void claimBoundary(boundary).catch(() => {}); return false; + if (gate.failed) return false; + if (gate.committed === gate.required) return !denied() && allowed(); + const armed = gate.armed; + if (armed?.gen === gate.required && gate.committed === gate.required - 1 && matched && mayDefer(turnId, armed, operation)) { + const confirmed = { stopped: false }; + void claimGate(gate, confirmed).catch(() => {}); + if (!confirmed.stopped) immediateOnly.add(turnId); + return confirmed.stopped; } - const confirmed = { stopped: false }; - void claimBoundary(boundary, confirmed).catch(() => {}); - if (!confirmed.stopped) immediateOnly.add(turnId); - return confirmed.stopped; - }, - async responseReady() { - if (!boundary) return true; - try { await claimBoundary(boundary); return await boundary.verdict; } - catch { return false; } + void claimGate(gate).catch(() => {}); return false; }, + responseReady, close() { relay?.operations.delete(operation); }, }; }, @@ -790,23 +814,36 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { void flushDeferred().catch(() => {}); const key = callKey(turnId, toolUseId), call = calls.get(key); calls.delete(key); - const effect = call ? toolObservation(call.name, call.path) : "unproven"; - if (effect === "unproven" && active.has(turnId)) lasting.add(turnId); - if (effect === "read" && !lasting.size && !calls.size) return Promise.resolve(); - const start = (confirmed?: { stopped: boolean }) => held(timing => observe(false, timing), false, - traceFor("tool", turnId, toolUseId), undefined, { kind: "tool", turnId, toolUseId }, confirmed); - if (call?.started && call.name !== null && mayDefer(turnId)) { - const pending: Boundary = { turnId, toolUseId, generation: relays.get(turnId)!.generation, claimed: false, settled: false, allowed: false, - observation: deferredObservation(confirmed => { - if (deferred === pending) deferred = undefined; - pending.claimed = true; claimed.set(turnId, pending); + const gate = gateFor(turnId); + let required = true; + try { + const effect = call ? toolObservation(call.name, call.path) : "unproven"; + if (effect === "unproven" && active.has(turnId)) lasting.add(turnId); + required = effect !== "read" || !!lasting.size || !!calls.size; + } catch { immediateOnly.add(turnId); } + if (!required) return Promise.resolve(); + const gen = ++gate.required; + const relay = relays.get(turnId); + const commit = (work: Promise): Promise => work.then(() => { + if (relay?.allowed() !== true) gate.denied.add(gen); + gate.committed = gen; wakeGate(gate); + }).catch(error => { gate.failed = true; wakeGate(gate); throw error; }); + const start = (confirmed?: { stopped: boolean }) => { + try { return commit(held(timing => observe(false, timing), false, + traceFor("tool", turnId, toolUseId), undefined, { kind: "tool", turnId, toolUseId }, confirmed)); } + catch (error) { gate.failed = true; wakeGate(gate); return Promise.reject(error); } + }; + try { + if (call?.started && call.name !== null && mayDefer(turnId)) { + relay!.armedAt = relay!.generation; relay!.toolUseId = toolUseId; + const observation = deferredObservation(confirmed => { + if (gate.armed?.gen === gen) gate.armed = undefined; return start(confirmed); - }), verdict: Promise.resolve(false) }; - pending.verdict = pending.observation.done.then(() => { pending.allowed = relays.get(turnId)?.allowed() === true; pending.settled = true; return pending.allowed; }); - void pending.verdict.finally(() => { if (claimed.get(turnId) === pending) claimed.delete(turnId); }).catch(() => {}); - deferred = pending; - return pending.observation.done; - } + }); + gate.armed = { gen, observation }; + return observation.done; + } + } catch { immediateOnly.add(turnId); } return start(); }, /** diff --git a/packages/ui-server/src/brain/turn-scope.ts b/packages/ui-server/src/brain/turn-scope.ts index 478a4babd3..f90e3a7508 100644 --- a/packages/ui-server/src/brain/turn-scope.ts +++ b/packages/ui-server/src/brain/turn-scope.ts @@ -258,13 +258,14 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour if (observationHolds++ > 0) { timing(() => recordStops(hold)); return; } observationFailed = false; for (const [turnId, turn] of active) { + const receipt = hold?.stopReceipt?.turnId === turnId ? hold.stopReceipt : undefined; + if (receipt) receipt.total = turn.workers.size; if (!turn.current() || turn.summary.receipts.some(receipt => receipt.state === "paused")) continue; const held: Worker[] = []; periodicHeld.set(turnId, { turn, workers: held }); - if (hold?.requireConfirmedStop && !turn.workers.size) hold.requireConfirmedStop = false; for (const worker of turn.workers) { held.push(worker); freeze(worker); - if (hold?.requireConfirmedStop && !confirmed(worker)) hold.requireConfirmedStop = false; + if (receipt && confirmed(worker)) receipt.count++; } if (hold) timing(() => recordStop(hold, turnId, held.filter(confirmed))); } diff --git a/packages/ui-server/tests/deferred-freeze-gate.test.ts b/packages/ui-server/tests/deferred-freeze-gate.test.ts new file mode 100644 index 0000000000..d245db384a --- /dev/null +++ b/packages/ui-server/tests/deferred-freeze-gate.test.ts @@ -0,0 +1,179 @@ +import { expect, spyOn, test } from "bun:test"; +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { startInferenceRelay } from "@schlessera/brain-ui-sdk/internal"; +import { MAX_INFERENCE_REQUEST_BYTES } from "../../ui-sdk/src/server/inference-relay"; +import { journalInference } from "../src/brain/journal-inference"; +import { body, fixture, send } from "./helpers/deferred-freeze-fixture"; + +const cycle = () => new Promise(resolve => setImmediate(resolve)); +const operation = (f: Awaited>) => f.proxy.inference("POST", new URL("http://127.0.0.1/v1/messages"), new AbortController().signal); +function hold(f: Awaited>) { + const checkpoint = f.native.manager.checkpoint, entered = Promise.withResolvers(), release = Promise.withResolvers(); + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + return { entered: entered.promise, release: release.resolve, restore() { release.resolve(); f.native.manager.checkpoint = checkpoint; } }; +} + +for (const cause of ["predicate throw", "immediate void stop"] as const) test(`${cause} gates dispatch and response until its own commit (T1/T2)`, async () => { + const f = await fixture(); let op: ReturnType | undefined; + let blocked: ReturnType | undefined, upstream = 0, delivered = false; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); + try { + if (cause === "immediate void stop") { + f.ack(undefined); const prior = f.result(); op = operation(f); + await op.prepareDispatch(Buffer.from(body())); expect(op.dispatch()).toBe(false); + await prior; op.finish("cancelled"); op = undefined; + } + blocked = hold(f); + const saved = (f.db.query("SELECT summary FROM turn_scope WHERE turn_id='voyage'").get() as { summary: string }).summary; + if (cause === "predicate throw") f.db.query("UPDATE turn_scope SET summary='{' WHERE turn_id='voyage'").run(); + const observed = f.result("sail"); void observed.catch(() => {}); + f.db.query("UPDATE turn_scope SET summary=? WHERE turn_id='voyage'").run(saved); + op = operation(f); + let ready = false; + const response = op.responseReady().then(value => { ready = true; return value; }); + const relayed = send(relay.socketPath, body("sail"), "/v1/messages", {}, "POST", () => { delivered = true; }); void relayed.catch(() => {}); + await blocked.entered; await cycle(); + expect(op.dispatch(), "REQUIRED_RESULT_BLOCKS_UPSTREAM_UNTIL_COMMIT").toBe(false); + expect(ready, "REQUIRED_RESULT_BLOCKS_RESPONSE_UNTIL_COMMIT").toBe(false); + expect(upstream, "IMMEDIATE_RESULT_SENDS_NO_UPSTREAM_BEFORE_COMMIT").toBe(0); + expect(delivered, "IMMEDIATE_RESULT_SENDS_NO_RESPONSE_BEFORE_COMMIT").toBe(false); + blocked.release(); await observed; expect(await response).toBe(true); + expect(op.dispatch()).toBe(true); expect((await relayed).status).toBe(200); + } finally { blocked?.restore(); op?.finish("cancelled"); relay.stop(); origin.stop(true); await f.close(); } +}); + +test("a fallback cap refuses a straggler until Continue (T3)", async () => { + const f = await fixture(1); let op: ReturnType | undefined, upstream = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { upstream++; return new Response("Ithaca"); } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: f.proxy }); + try { + writeFileSync(join(f.brain, "note.md"), "Penelope"); + const observed = f.result(); f.fireDeadline(); await observed; + op = operation(f); await op.prepareDispatch(Buffer.from(body())); + expect(op.dispatch(), "PAUSED_STRAGGLER_CANNOT_DISPATCH").toBe(false); + expect((await send(relay.socketPath)).status, "PAUSED_STRAGGLER_RECEIVES_403").toBe(403); + expect(upstream).toBe(0); + const receipt = f.journal.summary("voyage").scope!.receipts.at(-1)!; + expect((await f.scope.decide({ type: "scope_decision", turnId: "voyage", sessionId: "ithaca", eventId: receipt.eventId, submissionId: "captain", action: "continue" }, true)).state).toBe("accepted"); + expect(op.dispatch(), "STRAGGLER_MAY_DISPATCH_AFTER_CONTINUE").toBe(true); + expect((await send(relay.socketPath)).status).toBe(200); expect(upstream).toBe(1); + } finally { op?.finish("cancelled"); relay.stop(); origin.stop(true); await f.close(); } +}); + +const exits = ["405", "403", "admit false", "first admit throws", "second admit throws", "credential throw", "body size", "byte cap", "abort", "upstream failure", "redirect", "success"] as const; +for (const cause of exits) test(`every relay exit gates ${cause} and observes exactly once (T4)`, async () => { + const f = await fixture(), blocked = hold(f); + let observations = 0, delivered = false, admissions = 0; + f.journal.onObservation(() => { observations++; }); + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("Ithaca", { status: cause === "redirect" ? 302 : 200 }) }); + const originalFetch = globalThis.fetch; + const fetchSpy = spyOn(globalThis, "fetch").mockImplementation(Object.assign((...args: Parameters) => { + if (cause === "upstream failure" && String(args[0]).startsWith(origin.url.origin)) return Promise.reject(new Error("fixture upstream unavailable")); + return originalFetch(...args); + }, { preconnect: originalFetch.preconnect })); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: async () => { + if (cause === "credential throw") throw Error("fixture credentials unavailable"); return {}; + }, egress: { ...f.proxy, inference(...args) { + const op = f.proxy.inference(...args); + return { ...op, signal: cause === "abort" ? AbortSignal.abort() : op.signal, + charge: cause === "byte cap" ? () => false : op.charge, + async admit() { + admissions++; + if (cause === "admit false") return false; + if (cause === "first admit throws" && admissions === 1 || cause === "second admit throws" && admissions === 2) throw Error("fixture safety read failed"); + return op.admit(); + } }; + } } }); + try { + const observed = f.result(); void observed.catch(() => {}); + const response = send(relay.socketPath, body(), cause === "403" ? "/forbidden" : "/v1/messages", + cause === "body size" ? { "content-length": String(MAX_INFERENCE_REQUEST_BYTES + 1) } : {}, cause === "405" ? "PUT" : "POST", () => { delivered = true; }); + void response.catch(() => {}); + const first = await Promise.race([blocked.entered.then(() => "observation"), response.then(() => "response")]); + expect(first, "EVERY_EXIT_STARTS_THE_REQUIRED_OBSERVATION").toBe("observation"); + await cycle(); await cycle(); + expect(delivered, "EVERY_EXIT_WITHHOLDS_ALL_RESPONSE_BYTES_UNTIL_COMMIT").toBe(false); + blocked.release(); await observed; + const expected = cause === "405" ? 405 : ["403", "admit false", "byte cap"].includes(cause) ? 403 : cause.includes("admit throws") ? 500 : cause === "credential throw" ? 503 : cause === "body size" ? 413 : cause === "abort" ? 499 : ["redirect", "upstream failure"].includes(cause) ? 502 : 200; + expect((await response).status).toBe(expected); + expect(observations, "EACH_EXIT_OBSERVES_ITS_RESULT_EXACTLY_ONCE").toBe(1); + } finally { blocked.restore(); relay.stop(); origin.stop(true); fetchSpy.mockRestore(); await f.close(); } +}); + +test("authority lost after canDefer cannot manufacture a stop receipt (T5)", async () => { + const f = await fixture(); let op: ReturnType | undefined; + const original = f.scope.canDefer; let flip = false; + const read = spyOn(f.scope, "canDefer").mockImplementation(id => { const allowed = original(id); if (flip) f.authority(false); return allowed; }); + try { + const observed = f.result(); op = operation(f); await op.prepareDispatch(Buffer.from(body())); flip = true; + expect(op.dispatch(), "ZERO_ACKNOWLEDGED_WORKERS_CANNOT_SPECULATE").toBe(false); + expect(f.stops).toBe(0); await observed; + } finally { read.mockRestore(); op?.finish("cancelled"); await f.close(); } +}); + +test("a second result cannot speculate for an older generation (T6)", async () => { + const f = await fixture(), blocked = hold(f); let op: ReturnType | undefined; + try { + const first = f.result(); op = operation(f); await op.prepareDispatch(Buffer.from(body())); + const second = f.result("sail"); await blocked.entered; + expect(op.dispatch(), "OLDER_GENERATION_CANNOT_AUTHORIZE_SPECULATION").toBe(false); + blocked.release(); await first; await second; + } finally { blocked.restore(); op?.finish("cancelled"); await f.close(); } +}); + +test("N results retain N observations and a periodic commit cannot open their gate (T7)", async () => { + const f = await fixture(); let op: ReturnType | undefined; + const checkpoint = f.native.manager.checkpoint, periodicEntered = Promise.withResolvers(), resultEntered = Promise.withResolvers(); + const periodicRelease = Promise.withResolvers(), firstResultRelease = Promise.withResolvers(), resultsRelease = Promise.withResolvers(); + const nextResultEntered = Promise.withResolvers(); + let checkpoints = 0, observations = 0; + f.native.manager.checkpoint = async (...args) => { + if (++checkpoints === 1) { periodicEntered.resolve(); await periodicRelease.promise; } + else if (checkpoints === 2) { resultEntered.resolve(); await firstResultRelease.promise; } + else { nextResultEntered.resolve(); await resultsRelease.promise; } + return checkpoint(...args); + }; + f.journal.onObservation(() => { observations++; }); + try { + f.tick(); await periodicEntered.promise; + const results = [f.result("loom"), f.result("sail"), f.result("bow")]; + op = operation(f); periodicRelease.resolve(); await resultEntered.promise; + expect(op.dispatch(), "PERIODIC_COMMIT_CANNOT_SATISFY_RESULT_GENERATIONS").toBe(false); + let ready = false; const response = op.responseReady().then(value => { ready = true; return value; }); await cycle(); + expect(ready).toBe(false); firstResultRelease.resolve(); await results[0]; await nextResultEntered.promise; await cycle(); + expect(ready, "RESPONSE_GATE_RECHECKS_AFTER_EACH_RESULT_COMMIT").toBe(false); + resultsRelease.resolve(); await Promise.all(results); expect(await response).toBe(true); + expect(observations, "N_RESULTS_GET_N_DISTINCT_OBSERVATIONS").toBe(4); + } finally { periodicRelease.resolve(); firstResultRelease.resolve(); resultsRelease.resolve(); f.native.manager.checkpoint = checkpoint; op?.finish("cancelled"); await f.close(); } +}); + +test("a rejected observation refuses only its turn (T8)", async () => { + const f = await fixture(); + const control = journalInference(f.journal)!; + let fail = true; + const unsubscribe = f.journal.onObservation(() => {}, { before() { if (fail) throw Error("fixture observer refused"); }, after() {} }); + let op: ReturnType | undefined; + let releaseOther: (() => void) | undefined; + try { + f.proxy.stop(); // Immediate observation; retain the gate created for this relay. + const observed = f.result(); await expect(observed).rejects.toThrow("fixture observer refused"); fail = false; + // The authority callback isolates gate failure from the scope monitor's stop. + releaseOther = control.relayStarted("pylos", { eligible: () => false, allowed: () => true }, new AbortController().signal); + const other = control.requestStarted("pylos"); + expect(other.dispatch(), "ANOTHER_TURN_IS_NOT_POISONED").toBe(true); expect(await other.responseReady()).toBe(true); other.close(); + op = operation(f); + expect(op.dispatch(), "REJECTED_OBSERVATION_NEVER_OPENS_ITS_GATE").toBe(false); + expect(await op.responseReady(), "REJECTED_OBSERVATION_NEVER_OPENS_ITS_GATE").toBe(false); + } finally { fail = false; unsubscribe(); releaseOther?.(); op?.finish("cancelled"); await f.close(); } +}); + +test("nothing pending dispatches synchronously without joining journal work (T9)", async () => { + const f = await fixture(), blocked = hold(f); let op: ReturnType | undefined; + try { + const unrelated = f.journal.observe(); await blocked.entered; op = operation(f); + expect(op.dispatch(), "EMPTY_GATE_DISPATCH_IS_A_SYNCHRONOUS_BOOLEAN").toBe(true); + blocked.release(); await unrelated; + } finally { blocked.restore(); op?.finish("cancelled"); await f.close(); } +}); diff --git a/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts b/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts index 416bf9b64f..bbe3592355 100644 --- a/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts +++ b/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts @@ -25,6 +25,7 @@ export async function fixture(cap = 100, realWorker?: Parameters {}; const journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: brain, dbPath: path, objectsRoot: join(root, "objects"), observationTrace: () => name => () => { if (name === "observe_commit") nativeCommitted(); }, ...(writer ? { writer } : {}) }); let beforeScope = () => {}; + let authority = true; journal.onObservation(() => beforeScope()); const scope = createTurnScope(db, { brainPath: brain, journal, ...(writer ? { writer } : {}), connected: () => true, changed() {}, space: () => ({ total: 100e9, free: 90e9 }) }); db.query("INSERT INTO sessions(id,title,created_at,last_active_at) VALUES ('ithaca','Voyage',0,0)").run(); @@ -32,7 +33,7 @@ export async function fixture(cap = 100, realWorker?: Parameters controller.abort(error)); interval.finishRegistration(); - await scope.begin("voyage", { sessionId: "ithaca", principalId: "captain", origin: "interactive", profile: "governed", policy, source: "policy", hardTimeoutMs: 1e6, current: () => !controller.signal.aborted, stop: reason => controller.abort(new Error(reason)) }); + await scope.begin("voyage", { sessionId: "ithaca", principalId: "captain", origin: "interactive", profile: "governed", policy, source: "policy", hardTimeoutMs: 1e6, current: () => authority && !controller.signal.aborted, stop: reason => controller.abort(new Error(reason)) }); await journal.observe(); let frozen = false, stops = 0, resumes = 0, ack: boolean | void = true; const worker = { freeze() { frozen = true; stops++; return ack; }, resume() { frozen = false; resumes++; return true; }, kill() { frozen = true; return true; }, exited: new Promise(() => {}) }; @@ -59,12 +60,13 @@ export async function fixture(cap = 100, realWorker?: Parameters { if (performanceDescriptor) Object.defineProperty(performance, "now", performanceDescriptor); else delete (performance as unknown as { now?: () => number }).now; interval.restore(); Object.defineProperty(globalThis, "setTimeout", descriptor); Object.defineProperty(globalThis, "clearTimeout", clearDescriptor); }; const result = (id = "loom") => { journal.toolStarted("voyage", id, "Write", true); return journal.toolEnded("voyage", id); }; - return { afterNativeCommit(fn: () => void) { nativeCommitted = fn; }, elapseDeadline(ms: number) { deadlineClock += ms; }, writer, beforeScope(fn: () => void) { beforeScope = fn; }, tick() { interval.advanceTo(15000); }, deadlines, fireDeadline() { const item = deadlines.find(item => !item.cancelled)!; item.cancelled = true; item.callback(); }, root, brain, db, native, journal, scope, proxy, controller, result, get frozen() { return frozen; }, get stops() { return stops; }, get resumes() { return resumes; }, ack(value: boolean | void) { ack = value; }, + return { authority(value: boolean) { authority = value; }, afterNativeCommit(fn: () => void) { nativeCommitted = fn; }, elapseDeadline(ms: number) { deadlineClock += ms; }, writer, beforeScope(fn: () => void) { beforeScope = fn; }, tick() { interval.advanceTo(15000); }, deadlines, fireDeadline() { const item = deadlines.find(item => !item.cancelled)!; item.cancelled = true; item.callback(); }, root, brain, db, native, journal, scope, proxy, controller, result, get frozen() { return frozen; }, get stops() { return stops; }, get resumes() { return resumes; }, ack(value: boolean | void) { ack = value; }, async close() { try { controller.abort(); proxy.stop(); await proxy.settled(); await journal.idle(); scope.close(); await journal.close(); await writer?.close(); await native.close(); db.close(); rmSync(root, { recursive: true, force: true }); } finally { restore(); } } }; } -export function send(socketPath: string, content = body(), path = "/v1/messages", headers: Record = {}) { +export function send(socketPath: string, content = body(), path = "/v1/messages", headers: Record = {}, method = "POST", received?: () => void) { return new Promise<{ status: number; bytes: number }>((resolve, reject) => { - const outgoing = request({ socketPath, path, method: "POST", headers: { "content-type": "application/json", ...headers } }, incoming => { + const outgoing = request({ socketPath, path, method, headers: { "content-type": "application/json", ...headers } }, incoming => { + received?.(); let bytes = 0; incoming.on("data", chunk => { bytes += chunk.length; }); incoming.on("end", () => resolve({ status: incoming.statusCode!, bytes })); incoming.on("error", reject); }); outgoing.on("error", reject); outgoing.end(content); }); From 461556afb766d388b3288ad61fe85d06e4bf5e71 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 14:29:59 +0000 Subject: [PATCH 12/13] fix(ui-server): release completed turn gates with their relay --- packages/ui-server/src/brain/turn-journal.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index dcf40dd0e9..730ab78492 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -643,7 +643,11 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { gateFor(turnId); const relay = { ...transport, messages: false, generation: 0, armedAt: 0, toolUseId: "", operations: new Set() }; relays.set(turnId, relay); - const abort = () => { void flushDeferred().catch(() => {}); if (relays.get(turnId) === relay) relays.delete(turnId); }; + const abort = () => { + void flushDeferred().catch(() => {}); + if (relays.get(turnId) === relay) relays.delete(turnId); + if (!active.has(turnId) && !relays.has(turnId)) gates.delete(turnId); + }; signal.addEventListener("abort", abort, { once: true }); if (signal.aborted) abort(); return () => { signal.removeEventListener("abort", abort); abort(); }; @@ -941,6 +945,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { try { const end = bothTimers(lifecycle)?.("final_observation"); await observe(false, timing); end?.(); } finally { active.delete(turnId); counters.delete(turnId); lasting.delete(turnId); immediateOnly.delete(turnId); + if (!relays.has(turnId)) gates.delete(turnId); for (const [key, call] of calls) if (call.turnId === turnId) calls.delete(key); let step = [...worktrees.values()].some(root => root.turnId === turnId) ? timing?.("finish_worktrees") : undefined; if (await dropWorktrees(turnId)) step?.(); From 435896e36b6384190c95ae042c2a9cb259e4162f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 15:49:30 +0000 Subject: [PATCH 13/13] fix(ui-sdk): charge received headers before waiting on the result gate --- api-report/ui-sdk.txt | 1 + packages/ui-sdk/src/server/inference-relay.ts | 7 +++-- .../tests/deferred-freeze-header.test.ts | 29 +++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 packages/ui-server/tests/deferred-freeze-header.test.ts diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 781890c091..30e9a4f4c6 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1408,6 +1408,7 @@ export "./internal" (./src/internal.ts) type HostCredentialDomain HostCredentialExclusionError INFERENCE_PLACEHOLDER + type InferenceArrival type InferenceRelay type InferenceRelayEvent type InferenceTimingMark diff --git a/packages/ui-sdk/src/server/inference-relay.ts b/packages/ui-sdk/src/server/inference-relay.ts index c578b7f7d0..9e1346c6bb 100644 --- a/packages/ui-sdk/src/server/inference-relay.ts +++ b/packages/ui-sdk/src/server/inference-relay.ts @@ -282,9 +282,12 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe return cause.failure?chargeDenied(cause.failure):exit(() => refuse(request.method,path,cause.status,"Inference upstream unreachable")); } mark("headersMs"); + const incoming=readRelayResponse(response,{charge:chargeFailure,remaining:allowance.remaining}); + const headerFailure = incoming.headerFailure; + if (headerFailure) return exit(async () => { + await incoming.cancel().catch(() => {}); return chargeRefused(headerFailure); + }, async () => { await incoming.cancel().catch(() => {}); }); return exit(async () => { - const incoming=readRelayResponse(response,{charge:chargeFailure,remaining:allowance.remaining}); - if(incoming.headerFailure){await incoming.cancel().catch(()=>{});return chargeRefused(incoming.headerFailure);} if (response.status >= 300 && response.status < 400) { op?.finish("failed", "upstream_redirected"); await response.body?.cancel().catch(() => {}); diff --git a/packages/ui-server/tests/deferred-freeze-header.test.ts b/packages/ui-server/tests/deferred-freeze-header.test.ts new file mode 100644 index 0000000000..638b45edeb --- /dev/null +++ b/packages/ui-server/tests/deferred-freeze-header.test.ts @@ -0,0 +1,29 @@ +import { expect, test } from "bun:test"; +import { startInferenceRelay } from "@schlessera/brain-ui-sdk/internal"; +import { fixture, send } from "./helpers/deferred-freeze-fixture"; + +test("received upstream headers are charged before waiting for the result gate", async () => { + const f = await fixture(), entered = Promise.withResolvers(), release = Promise.withResolvers(); + const boundary = Promise.withResolvers(), checkpoint = f.native.manager.checkpoint; + let upstream = 0, charged = false; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { + upstream++; return new Response("Ithaca", { headers: { "x-odysseus": "Ithaca" } }); + } }); + const relay = startInferenceRelay({ upstream: origin.url.origin, routes: ["/v1/messages"], credentials: {}, egress: { + ...f.proxy, inference(...args) { + const operation = f.proxy.inference(...args); + return { ...operation, + charge(bytes) { if (upstream && bytes > 0) charged = true; return operation.charge(bytes); }, + responseReady() { boundary.resolve(charged); return operation.responseReady(); }, + }; + }, + } }); + try { + f.native.manager.checkpoint = async (...args) => { entered.resolve(); await release.promise; return checkpoint(...args); }; + const observed = f.result(), response = send(relay.socketPath); void response.catch(() => {}); + await entered.promise; + expect(await boundary.promise, "UPSTREAM_HEADERS_ARE_CHARGED_BEFORE_THE_OBSERVATION_WAIT").toBe(true); + release.resolve(); await observed; + expect((await response).status).toBe(200); expect(upstream).toBe(1); + } finally { release.resolve(); f.native.manager.checkpoint = checkpoint; relay.stop(); origin.stop(true); await f.close(); } +});