diff --git a/.changeset/tidy-ithaca-freeze.md b/.changeset/tidy-ithaca-freeze.md new file mode 100644 index 0000000000..3c0e6e08fd --- /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, 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/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/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 263a826ae1..cd1738cff7 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1641,15 +1641,80 @@ 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 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. + +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. +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:518-563`), 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: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. @@ -1658,7 +1723,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:1013-1048`). 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 new file mode 100644 index 0000000000..d7f593f682 --- /dev/null +++ b/experiments/admission-join.test.ts @@ -0,0 +1,24 @@ +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.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); + expect(row.credentialToDispatchMs).toBeGreaterThanOrEqual(0); + } + } finally { rmSync(root, { recursive: true, force: true }); } +}); diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index 3962346d00..99d3d15eb5 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -105,3 +105,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 4149465e74..9e1346c6bb 100644 --- a/packages/ui-sdk/src/server/inference-relay.ts +++ b/packages/ui-sdk/src/server/inference-relay.ts @@ -35,6 +35,21 @@ function inferenceRefusalMessage(failure: EgressChargeFailure): string { : failure.reason === "cancelled" ? "Inference request cancelled" : "Inference network admission refused"; } +/** 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"]> & { + prepareDispatch?(body: Uint8Array): Promise; + dispatchReady?(): boolean; + responseReady?(): Promise; +}; +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; @@ -43,7 +58,12 @@ 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"> & Partial>, "remainingBytes">>; + egress?: { + inference(method: string, target: URL, signal: AbortSignal, arrival?: InferenceArrival): InferenceOperation; + inferenceArrival?(path: string): InferenceArrival | undefined; + inferenceRoutes?(paths: readonly string[]): void; + remainingBytes?(): number; + }; /** 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. */ @@ -95,6 +115,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,153 +145,197 @@ 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; - const denied = (reason: string, status = 403): Response => { - 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); + let operation: InferenceOperation | undefined; + let arrival: InferenceArrival | undefined; + const responseReady = () => operation?.responseReady?.() ?? arrival?.responseReady() ?? Promise.resolve(true); + // 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 => { + if (!await responseReady()) { + await discard?.(); await responseReady(); + operation?.finish("denied", "deferred_observation_refused"); + return { [gated]: refuse(request.method, path, 403, "Inference request refused", "deferred_observation_refused") }; + } + const response = await create(); + // Async response construction can cross a newer tool result too. + if (!await responseReady()) { + await response.body?.cancel().catch(() => {}); await responseReady(); + operation?.finish("denied", "deferred_observation_refused"); + return { [gated]: refuse(request.method, path, 403, "Inference request refused", "deferred_observation_refused") }; + } + return { [gated]: response }; }; - const allowance=relayAllowance(operation,options.egress?.remainingBytes?.bind(options.egress),MAX_INFERENCE_REQUEST_BYTES); - const chargeFailure=allowance.charge; - const receivedFailure=(count:number)=>chargeReceivedBytes(count,{charge:chargeFailure,remaining:allowance.remaining}); - const chargeDenied = (failure: EgressChargeFailure) => { const detail = egressChargeRefusal(failure,"Inference"); return refuse(request.method,path,detail.status,inferenceRefusalMessage(failure),operation?.reason?.() ?? detail.reason); }; - const admitFailure = async ():Promise => operation && !await operation.admit() ? operation.failure() ?? {ok:false,reason:"unavailable"} : undefined; - const initialAdmissionFailure=await admitFailure(); - if (initialAdmissionFailure) return chargeDenied(initialAdmissionFailure); - mark("admitMs"); - const initialDecision = operation?.charge(0); - if (initialDecision && !initialDecision.ok) return chargeDenied(initialDecision); - const requestHead=readRelayRequestHead(`${request.method} ${url.pathname}${url.search} HTTP/1.1`,request.headers,{charge:chargeFailure,remaining:allowance.remaining}); - if(requestHead.failure)return chargeDenied(requestHead.failure); - 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; - const failure = receivedFailure(next.value.byteLength + 16); - if (length > MAX_INFERENCE_REQUEST_BYTES || failure) { - await reader.cancel().catch(() => {}); - return failure ? chargeDenied(failure) : denied("inference_request_too_large",413); + 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); + }); + const allowance=relayAllowance(op,options.egress?.remainingBytes?.bind(options.egress),MAX_INFERENCE_REQUEST_BYTES); + const chargeFailure=allowance.charge; + const receivedFailure=(count:number)=>chargeReceivedBytes(count,{charge:chargeFailure,remaining:allowance.remaining}); + const chargeRefused = (failure: EgressChargeFailure): Response => { const detail = egressChargeRefusal(failure,"Inference"); return refuse(request.method,path,detail.status,inferenceRefusalMessage(failure),op?.reason?.() ?? detail.reason); }; + const chargeDenied = (failure: EgressChargeFailure): Promise => exit(() => chargeRefused(failure)); + const admitFailure = async ():Promise => op && !await op.admit() ? op.failure() ?? {ok:false,reason:"unavailable"} : undefined; + const initialAdmissionFailure=await admitFailure(); + if (initialAdmissionFailure) return chargeDenied(initialAdmissionFailure); + mark("admitMs"); + const initialDecision = op?.charge(0); + if (initialDecision && !initialDecision.ok) return chargeDenied(initialDecision); + const requestHead=readRelayRequestHead(`${request.method} ${url.pathname}${url.search} HTTP/1.1`,request.headers,{charge:chargeFailure,remaining:allowance.remaining}); + if(requestHead.failure)return chargeDenied(requestHead.failure); + 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; + const failure = receivedFailure(next.value.byteLength + 16); + if (length > MAX_INFERENCE_REQUEST_BYTES || failure) { + await reader.cancel().catch(() => {}); + return failure ? chargeDenied(failure) : denied("inference_request_too_large",413); + } + chunks.push(next.value); } - chunks.push(next.value); - } - } catch { - const cause=captureEgressFailure(signal,operation); - operation?.finish(cause.outcome,"request_body_failed"); - return cause.failure?chargeDenied(cause.failure):refuse(request.method,path,cause.status,"Inference request interrupted"); - } 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) { - const cause=captureEgressFailure(signal,operation); - operation?.finish(cause.outcome,"client_disconnected"); - return chargeDenied(cause.failure ?? {ok:false,reason:"cancelled"}); - } - try { - credentials = typeof options.credentials === "function" ? await options.credentials(signal, new URL(target)) : options.credentials; - validateCredentials(credentials); - mark("credentialMs"); + } catch { + const cause=captureEgressFailure(signal,op); + op?.finish(cause.outcome,"request_body_failed"); + return cause.failure?chargeDenied(cause.failure):exit(() => refuse(request.method,path,cause.status,"Inference request interrupted")); + } 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) { - const cause=captureEgressFailure(signal,operation); - operation?.finish(cause.outcome,"client_disconnected"); + const cause=captureEgressFailure(signal,op); + op?.finish(cause.outcome,"client_disconnected"); return chargeDenied(cause.failure ?? {ok:false,reason:"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 cause=captureEgressFailure(signal,operation); - operation?.finish(cause.outcome,"inference_credentials_unavailable"); - return cause.failure?chargeDenied(cause.failure):refuse(request.method,path,cause.status,"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 requestChargeFailure = requestHead.forward(`${request.method} ${path}${url.search} HTTP/1.1`,headers); - if (requestChargeFailure) return chargeDenied(requestChargeFailure); - // Body/credential waits may have crossed an input-recording failure. - // Re-enter the concrete host admission at the last dispatch boundary. - const finalAdmissionFailure=await admitFailure(); - if (finalAdmissionFailure) return chargeDenied(finalAdmissionFailure); - const dispatchDecision = operation?.prepare(); - if (dispatchDecision && !dispatchDecision.ok) return chargeDenied(dispatchDecision); - let response: Response; - try { - // Never follow a redirect: the upstream must not choose another host. - signal.throwIfAborted(); - let pending!:Promise; - const send=()=>{mark("dispatchMs");pending=fetch(target,{method:"POST",headers,body,redirect:"manual",signal});}; - const decision=operation?operation.dispatch(send):(send(),{ok:true as const}); - if(!decision.ok)return chargeDenied(decision); - response=await pending; - } catch { - const cause=captureEgressFailure(signal,operation); - operation?.finish(cause.outcome,"upstream_unreachable"); - return cause.failure?chargeDenied(cause.failure):refuse(request.method,path,cause.status,"Inference upstream unreachable"); - } - mark("headersMs"); - const incoming=readRelayResponse(response,{charge:chargeFailure,remaining:allowance.remaining}); - if(incoming.headerFailure){await incoming.cancel().catch(()=>{});return chargeDenied(incoming.headerFailure);} - 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 (!response.body) { - const failure=incoming.fence();if(failure)return chargeDenied(failure); - operation?.finish("completed"); - return new Response(null, { status: response.status, headers: out }); - } - const upstreamReader = incoming; - 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.release(); } }; - const output = new ReadableStream({ - async pull(controller) { - let next:Awaited>; - try { next=await upstreamReader.read(); if (!firstReadAttempted) { firstReadAttempted = true; mark("firstChunkMs"); } } - catch { - const cause=captureEgressFailure(signal,operation); - operation?.finish(cause.outcome,"upstream_response_failed"); - release();controller.error(new Error(cause.failure?inferenceRefusalMessage(cause.failure):"Inference response interrupted"));return; + try { + credentials = typeof options.credentials === "function" ? await options.credentials(signal, new URL(target)) : options.credentials; + validateCredentials(credentials); + mark("credentialMs"); + if (signal.aborted) { + const cause=captureEgressFailure(signal,op); + op?.finish(cause.outcome,"client_disconnected"); + return chargeDenied(cause.failure ?? {ok:false,reason:"cancelled"}); } - const failure=next.deliver(()=>{ - if(next.done){controller.close();operation?.finish("completed");release();} - else { controller.enqueue(next.value); observeDiagnostic(() => observeUsage?.(next.value)); } + 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 cause=captureEgressFailure(signal,op); + op?.finish(cause.outcome,"inference_credentials_unavailable"); + return cause.failure?chargeDenied(cause.failure):exit(() => refuse(request.method,path,cause.status,"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 requestChargeFailure = requestHead.forward(`${request.method} ${path}${url.search} HTTP/1.1`,headers); + if (requestChargeFailure) return chargeDenied(requestChargeFailure); + // Body/credential waits may have crossed an input-recording failure. + // Re-enter the concrete host admission at the last dispatch boundary. + const finalAdmissionFailure=await admitFailure(); + if (finalAdmissionFailure) return chargeDenied(finalAdmissionFailure); + const dispatchDecision = op?.prepare(); + if (dispatchDecision && !dispatchDecision.ok) return chargeDenied(dispatchDecision); + if (op?.prepareDispatch && !await op.prepareDispatch(body)) return denied("inference_admission_refused"); + const dispatchReady = () => op?.dispatchReady?.() ?? arrival?.dispatch() ?? true; + if (!dispatchReady()) { + if (!await responseReady()) return denied("inference_admission_refused"); + const failure = await admitFailure(); + if (failure) return chargeDenied(failure); + if (!dispatchReady()) return denied("inference_admission_refused"); + } + let response: Response; + try { + // Never follow a redirect: the upstream must not choose another host. + signal.throwIfAborted(); + let pending!:Promise; + const send=()=>{mark("dispatchMs");pending=fetch(target,{method:"POST",headers,body,redirect:"manual",signal});}; + const decision=op?op.dispatch(send):(send(),{ok:true as const}); + if(!decision.ok)return chargeDenied(decision); + response=await pending; + } catch { + const cause=captureEgressFailure(signal,op); + op?.finish(cause.outcome,"upstream_unreachable"); + 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 () => { + 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 (!response.body) { + const failure=incoming.fence();if(failure)return chargeRefused(failure); + op?.finish("completed"); + return new Response(null, { status: response.status, headers: out }); + } + const upstreamReader = incoming; + 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.release(); } }; + const output = new ReadableStream({ + async pull(controller) { + let next:Awaited>; + try { next=await upstreamReader.read(); if (!firstReadAttempted) { firstReadAttempted = true; mark("firstChunkMs"); } } + catch { + const cause=captureEgressFailure(signal,op); + op?.finish(cause.outcome,"upstream_response_failed"); + release();controller.error(new Error(cause.failure?inferenceRefusalMessage(cause.failure):"Inference response interrupted"));return; + } + const failure=next.deliver(()=>{ + if(next.done){controller.close();op?.finish("completed");release();} + else { controller.enqueue(next.value); observeDiagnostic(() => observeUsage?.(next.value)); } + }); + if(failure){release();controller.error(new Error(inferenceRefusalMessage(failure)));} + }, + async cancel() { + op?.finish("cancelled", "client_disconnected"); + await upstreamReader.cancel().catch(() => {}); release(); + }, }); - if(failure){release();controller.error(new Error(inferenceRefusalMessage(failure)));} - }, - async cancel() { - operation?.finish("cancelled", "client_disconnected"); - await upstreamReader.cancel().catch(() => {}); release(); - }, - }); - return new Response(output, { status: response.status, headers: out }); + 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/deferred-observation.ts b/packages/ui-server/src/brain/deferred-observation.ts new file mode 100644 index 0000000000..73158901b5 --- /dev/null +++ b/packages/ui-server/src/brain/deferred-observation.ts @@ -0,0 +1,36 @@ +/** One result boundary, claimed synchronously by dispatch or an interruption. */ +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); + 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, expired: () => performance.now() >= deadline }; +} + +/** 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/journal-inference.ts b/packages/ui-server/src/brain/journal-inference.ts new file mode 100644 index 0000000000..28c81d3fde --- /dev/null +++ b/packages/ui-server/src/brain/journal-inference.ts @@ -0,0 +1,16 @@ +/** Concrete journal/scope/relay wiring, outside the public WsHost.journal type. */ +interface JournalInference { + flushDeferred(): 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(); +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 d64d3c692d..c6a74c255a 100644 --- a/packages/ui-server/src/brain/turn-egress.ts +++ b/packages/ui-server/src/brain/turn-egress.ts @@ -1,7 +1,8 @@ +import { journalInference } from "./journal-inference.js"; /** One admitted turn's concrete proxy, approval surface and durable records. */ import { originTrustMatchSnapshot, type OriginTrust, type OriginDestination } from "./origin-trust.js"; import type { EffectiveGovernancePolicy, TrustMatch } from "@schlessera/brain-common/internal/governance-policy"; -import { startEgressProxy, canonicalEgressHost, validatedEgressProvenance, EgressAdmissionRefused, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; +import { startEgressProxy, canonicalEgressHost, validatedEgressProvenance, EgressAdmissionRefused, 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"; @@ -14,6 +15,8 @@ import { settleTurnSessionBinding, type SessionBindingRefusal } from "../ws/brid 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; @@ -93,6 +96,8 @@ export function createOutwardCalls() { export async function prepareTurnEgress(options: { trust?: OriginTrust; + 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"; @@ -395,6 +400,9 @@ export async function prepareTurnEgress(options: { releaseTrust = options.trust?.subscribe(() => proxy.invalidateInputs()); options.controller.signal.addEventListener("abort", () => releaseTrust?.(), { once: true }); const original = options.bridge; + const inference = options.journal && journalInference(options.journal); + const releaseJournalRelay = inference && options.scope ? inference.relayStarted(options.turnId, + { 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); }, @@ -411,9 +419,26 @@ 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); - return settleOperation(operation); + const settledOperation = settleOperation(operation); + if (kind !== "inference" || !inference || !options.scope) return { ...settledOperation, + async prepareDispatch(_body: Uint8Array) { return true; }, dispatchReady() { return true; }, async responseReady() { return true; } }; + 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 gate.prepareDispatch(body); } + catch { return false; } + }, + // The relay checks this without yielding before the typed transport's + // own dispatch(send) fence. A pending result never marks a send as done. + dispatchReady() { return gate.dispatch(); }, + async responseReady() { + return gate.responseReady(); + }, + }; }; const settleOperation = (operation: ReturnType) => { return { ...operation, async admit() { @@ -434,8 +459,14 @@ export async function prepareTurnEgress(options: { } finally { if (abort) operation.signal.removeEventListener("abort", abort); } } }; }; - return { ...proxy, stop() { releaseTrust?.(); proxy.stop(); }, bridge, recordingFailure: () => recordingFailure, settled, - inference: (method: string, target: URL, signal: AbortSignal) => relayOperation("inference", method, target, signal), + 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?.(); releaseTrust?.(); proxy.stop(); }, + 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 5a48ac668c..e0b8a89c0a 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -1,3 +1,5 @@ +import { retainJournalInference } from "./journal-inference.js"; +import { deferredObservation, followsToolResult } from "./deferred-observation.js"; import { startCronSpan } from "../cron/activity.js"; import type { JournalScrubResult } from "./journal-scrub.js"; import { FINISH_REFERENCE_CLEANUP } from "./journal-reference-cleanup.js"; @@ -120,6 +122,8 @@ 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. */ + stopReceipt?: { turnId: string; count: number; total: number }; records: Map; stoppedTurns: Set; paths: Map>; @@ -465,13 +469,57 @@ 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]); + 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(); + 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 { + 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, 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 (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 + && ![...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; + } + } 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 && 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; @@ -493,12 +541,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 = !!interval.stopReceipt && interval.stopReceipt.count >= 1 && interval.stopReceipt.count === interval.stopReceipt.total; 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); + if (confirmed?.stopped) await inference.settleScope?.(); + completed = true; return result; } finally { // A cancelled/refused new admission made no worker writes. Existing // participants resume when their shared observation itself succeeded, @@ -512,6 +563,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 @@ -777,7 +829,78 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { throw failure; } } - return { + const inference: Parameters[1] = { + relayStarted(turnId, transport, signal) { + void flushDeferred().catch(() => {}); + 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); + 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(); }; + }, + 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(() => {}); } + }, + flushDeferred, + requestStarted(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 (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) { + 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 (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; + } + void claimGate(gate).catch(() => {}); return false; + }, + responseReady, + close() { relay?.operations.delete(operation); }, + }; + }, + }; + const journal = { /** * @internal Host scope monitor consumes this same observation window. * `changedPaths` counts every changed path; `workspacePaths` counts paths @@ -870,10 +993,11 @@ 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; } - 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`). */ @@ -887,12 +1011,40 @@ 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 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); + }); + gate.armed = { gen, observation }; + return observation.done; + } + } catch { immediateOnly.add(turnId); } + return start(); }, /** * Cover one managed worktree (#2430) for an active turn before any of its @@ -957,6 +1109,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 @@ -1023,7 +1176,8 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { finally { for (const [key, root] of checkouts) if (root.turnId === turnId) checkouts.delete(key); await write([statement("UPDATE turn_journal_code_receipts SET receipt=json_set(receipt,'$.state','partial') WHERE turn_id=? AND json_extract(receipt,'$.state')='recording'", turnId)]); - active.delete(turnId); counters.delete(turnId); codeScopeFacts.delete(turnId); lasting.delete(turnId); + active.delete(turnId); counters.delete(turnId); codeScopeFacts.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?.(); @@ -1232,7 +1386,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 { @@ -1248,6 +1402,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 9a568f4c4e..212bfecae2 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"; @@ -279,12 +280,21 @@ 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 }); - for (const worker of turn.workers) { held.push(worker); freeze(worker); } + for (const worker of turn.workers) { + held.push(worker); + freeze(worker); + if (receipt && confirmed(worker)) receipt.count++; + } 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; @@ -325,6 +335,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"] }) { @@ -340,6 +352,7 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour }); }, workerStarted(turnId: string, worker: Worker) { + 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(() => {}); @@ -359,6 +372,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.summary.changedPaths !== null && turn.summary.observedBytes !== null && 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 @@ -384,7 +406,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 { 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 18c585991d..f05d22a5c6 100644 --- a/packages/ui-server/src/ws/session-run/backend-entry.ts +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -180,6 +180,7 @@ export async function prepareRelayedEgress(run: TurnRun, bridge: BackendBridge, await host.originTrust?.refresh?.(abortController.signal); abortController.signal.throwIfAborted(); 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, trust: host.originTrust, profile: heldProfile(run), origin,policyHash:governedHold.policy.hash, brainPath: host.brainPath, 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..c9e5aa0da1 --- /dev/null +++ b/packages/ui-server/tests/deferred-freeze-gate.test.ts @@ -0,0 +1,180 @@ +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.dispatchReady()).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.dispatchReady(), "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.dispatchReady()).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.dispatchReady(), "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.dispatchReady(), "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, + failure: cause === "admit false" ? () => ({ ok: false as const, reason: "policy_denied" as const }) : op.failure, + charge: cause === "byte cap" ? () => ({ ok: false as const, reason: "budget" as const }) : 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" ? 502 : 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.dispatchReady(), "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.dispatchReady(), "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.dispatchReady(), "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.dispatchReady(), "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.dispatchReady(), "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/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(); } +}); 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..fa10f6beb1 --- /dev/null +++ b/packages/ui-server/tests/deferred-freeze-review.test.ts @@ -0,0 +1,246 @@ +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; + 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"] }]); + 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; + 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); + 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" ? () => ({ ok: false as const, reason: "budget" as const }) : operation.charge, + admit: cause === "admission" ? async () => false : operation.admit, + failure: cause === "admission" ? () => ({ ok: false as const, reason: "policy_denied" as const }) : operation.failure, + }; }, + } }); + 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" ? 502 : 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.dispatchReady(), "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.dispatchReady(), "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.dispatchReady(), "DISPATCH_HAS_THE_SAME_DEFERRAL_PREDICATE").toBe(false); + 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!.dispatchReady()).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-runtime.test.ts b/packages/ui-server/tests/deferred-freeze-runtime.test.ts new file mode 100644 index 0000000000..aa1155be1c --- /dev/null +++ b/packages/ui-server/tests/deferred-freeze-runtime.test.ts @@ -0,0 +1,64 @@ +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 realNow = performance.now.bind(performance); + 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, earlyResume: unknown; + const freeze = () => { + child.kill("SIGSTOP"); + 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 (realNow() > deadline) throw new Error("Owned worker did not stop"); + Bun.sleepSync(1); + } + }; + 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; + 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 = realNow(); await Bun.sleep(10_000); + return checkpoint(...args); + }; + 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; + 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(""); + 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..a60e5acd2e --- /dev/null +++ b/packages/ui-server/tests/deferred-freeze.test.ts @@ -0,0 +1,265 @@ +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_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); + } 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 falls back to the base immediate hold`, async () => { + 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(), 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 { release.resolve(); f.native.manager.checkpoint = checkpoint; 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(); } +}); + +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 new file mode 100644 index 0000000000..bbe3592355 --- /dev/null +++ b/packages/ui-server/tests/helpers/deferred-freeze-fixture.ts @@ -0,0 +1,73 @@ +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 { 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"; +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], 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 writer = offloopScope ? openSqliteWriter(db, { attach: [{ schema: "journal", path: journalDatabasePath(path) }] }) : undefined; + let nativeCommitted = () => {}; + 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(); + 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: () => 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(() => {}) }; + 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; + 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 = () => { 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 { 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 = {}, method = "POST", received?: () => void) { + return new Promise<{ status: number; bytes: number }>((resolve, reject) => { + 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); + }); +} diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index 10506bbe4b..d2f22966d1 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -58,6 +58,20 @@ 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, 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. + `--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..e648f3c34e --- /dev/null +++ b/scripts/native-proof/admission-join.ts @@ -0,0 +1,89 @@ +/** Offline measurement of both inference fences with real FULL audit writes. */ +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"; +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"; +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, 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, dispatchAt = 0; + const admissionFencesMs: number[] = []; + 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, dispatch(send: () => void) { return operation.dispatch(() => { dispatchAt = performance.now(); send(); }); }, 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(); + 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(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, dispatchAfterResultMs: dispatchAt - resultAt }); + } finally { relay.stop(); controller.abort(); proxy.stop(); await proxy.settled(); await observed; await journal.finish(turnId); await scope.finish(turnId); } + } + 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) { + 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 9bce1b3a5a..1d1212a6fd 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -337,9 +337,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!, 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") { 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); @@ -359,7 +364,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 9f05d8f2df..461c6b4d6c 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 => {