From e782dc9eec5e8c5a1ed733a1800aa17adc843810 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 20:26:43 +0000 Subject: [PATCH 1/2] fix(ui-server): hold conversation intake writes across a journal observation or scope pause (#2869) A turn's inbox_add checked the turn's strict authority at entry and again before the receipt commit, with unguarded staging writes in between. An observation or scope pause that began while it staged let those writes run through the hold, then refused a still-valid turn and removed the staging during the hold. Every intake write now runs through one write boundary: staging, publication and the receipt commit wait out a hold, bounded by one deadline shared across the intake, and run in the tick their final check passes. The check renews the turn, principal, origin thread and the provider masks over the staging directory. Revocation, replacement and cancellation refuse at once. Compensation never writes during a hold: inline removal skips, and the intake that owns the arrival removes it after the hold, off the reply's path, or leaves its cleanup receipt queued for reconciliation. Co-Authored-By: Claude Opus 5.5 --- .changeset/2869-intake-hold-aware-writes.md | 5 + docs/decisions/governed-writable-workers.md | 29 +- .../plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 4 +- docs/plans/chat-attachments.md | 6 +- packages/ui-server/src/inbox/bridge-tools.ts | 24 +- packages/ui-server/src/inbox/intake.ts | 116 +++++-- packages/ui-server/src/share/staging-fs.ts | 11 +- packages/ui-server/src/share/staging.ts | 86 ++++-- .../src/ws/bridge-capabilities/activity.ts | 39 ++- .../tests/inbox-intake-holds.test.ts | 290 ++++++++++++++++++ .../tests/ws-inbox-intake-hold.test.ts | 78 +++++ 12 files changed, 613 insertions(+), 77 deletions(-) create mode 100644 .changeset/2869-intake-hold-aware-writes.md create mode 100644 packages/ui-server/tests/inbox-intake-holds.test.ts create mode 100644 packages/ui-server/tests/ws-inbox-intake-hold.test.ts diff --git a/.changeset/2869-intake-hold-aware-writes.md b/.changeset/2869-intake-hold-aware-writes.md new file mode 100644 index 0000000000..7b5359a613 --- /dev/null +++ b/.changeset/2869-intake-hold-aware-writes.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +A conversation turn's `inbox_add` no longer refuses a still-valid turn when a journal observation or a scope pause begins while it stages its arrival (#2869). Before, the arrival's staging writes ran unchecked through such a hold, and the final check then refused with "Inbox principal or turn is no longer authorized" and removed the staged files during the hold. Now every intake write (staging, publication, the receipt commit and cleanup) waits for the hold, bounded by the existing 60-second wait shared across the whole intake, and is checked again in the tick it runs. The turn, its principal and the provider masks over the staging directory are checked again after the wait, and one item is accepted once the hold ends. Revocation, turn replacement and cancellation still refuse at once, and a hold past the bound refuses with nothing accepted. Cleanup of an abandoned arrival never runs during a hold: when it cannot run in time, its receipt stays queued for reconciliation. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index be94561c15..0e9f51d2ee 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -355,7 +355,7 @@ the same places, where links lead included. Inbox staging is judged at each dire it publishes, and before every compensation removes anything: its own partial or published arrival, and an earlier arrival that the call reconciles (`conversation: (input`, -`packages/ui-server/src/inbox/intake.ts:137-140`). A call refused before +`packages/ui-server/src/inbox/intake.ts:212-216`). A call refused before staging leaves no receipt and no item. Links are read at each change, so a link a governed worker swaps in between two changes stops the next one; one swapped in between a check and its own system call is not covered, because @@ -1178,6 +1178,25 @@ since a long hold is not revocation. A principal that really lost authority refuses `authority_revoked` at once, waiting or not (`export async function retryHeld`, `packages/ui-server/src/brain/authority-hold.ts:92-102`). +**Conversation intake waits out a hold at every write (#2869, maintainer, +2026-10-25).** A turn's `inbox_add` stages its arrival, publishes it, commits +its receipt and compensates what it abandoned, and each of those writes is +coordinated with the same hold rather than checked once at entry. Each change +runs through one write gate: it waits for a hold outside any transaction or +lock, sharing one 60-second deadline across the whole intake, then makes its +final check and its change in the same tick, so a hold that begins after that +check cannot overlap it. Staging writes are synchronous under the gate for that +reason. The final check renews the turn, the principal, the origin thread and +the turn's provider masks over the staging directory, and the receipt +transaction still refuses a receipt that reconciliation took meanwhile. +Revocation, turn replacement and cancellation refuse at once; a hold past the +bound refuses; none of them leaves a queue claim. Compensation is the host's +own effect: it waits for a hold on brain writes whatever the turn's authority, +and when it cannot run within the bound or after cancellation it removes +nothing and leaves its `cleanup` receipt for reconciliation. A committed +receipt is never compensated (`function writeBoundary`, +`packages/ui-server/src/inbox/intake.ts:113-127`). + **A pause the policy observation raises is a no-publication outcome (#2870, maintainer, 2026-10-25).** Policy publication runs inside its own journal observation, and that observation can itself reach a scope cap. Waiting there @@ -3036,7 +3055,7 @@ every turn without a proven recipient: roadblock signatures (`scope=roadblocks`). `running` and `rollups` return labels and counts that may also name documents. - `inbox_list` and `inbox_get` (`inboxList`, - `packages/ui-server/src/inbox/bridge-tools.ts:62-83`): each item's stored + `packages/ui-server/src/inbox/bridge-tools.ts:78-99`): each item's stored payload, titles, details and option labels, and its thread. None of these fields records which documents its text came from. A run from @@ -3055,7 +3074,7 @@ every turn without a proven recipient: #2741 option C).** #2698 left autonomous turns out. Their bridge still serves `inbox_list` and `inbox_get` when the exact roster allows them, scoped to the turn's origin thread (`inboxList: async`, - `packages/ui-server/src/inbox/bridge-tools.ts:62-83`), and the dispatcher + `packages/ui-server/src/inbox/bridge-tools.ts:78-99`), and the dispatcher embeds the thread's text in the first message (`async function context`, `packages/ui-server/src/inbox/dispatcher.ts:163-185`). Source inspection finds these retained thread inputs: @@ -3076,14 +3095,14 @@ every turn without a proven recipient: context is built afterwards, from the admission's arrival read and in the transaction that revalidates it, and both reads revalidate in their own transaction before building any payload (`function authorizeRead`, - `packages/ui-server/src/inbox/bridge-tools.ts:52-56`). Host code records + `packages/ui-server/src/inbox/bridge-tools.ts:68-72`). Host code records the evidence in `inbox_provenance`, in the transaction that writes the item or checkpoint, bound to a digest of its text (`export function recordInboxProvenance`, `packages/ui-server/src/inbox/provenance.ts:93-117`). Compatible evidence is exactly: a person's arrival through the authenticated share or queue route, outside any turn, also bound to a digest of the staged bytes intake read (`const evidence = author`, - `packages/ui-server/src/inbox/intake.ts:105`); text the server composed + `packages/ui-server/src/inbox/intake.ts:178`); text the server composed from no brain content or model output (schedule instructions, cleanup and lifecycle notices); text an autonomous run wrote (escalations, yields) whose admitted masks hid every folder now masked; and, since #2816, an diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index c14c8d78ea..534dbb27fd 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -95,7 +95,7 @@ Stated before the requirements because five of them derive from it. that arrived from outside, including every v1 share). It is never present in any model-authored payload schema, and no model output can change it. The share manifest has its source selected server-side - (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:101`); this generalizes that. + (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:174`); this generalizes that. - **T2. Model output is data, never authority.** `state_md`, T1 classifications, and follow-up payloads are authored by a model that has read attacker-controllable text. They may describe, request, and summarize. They may not select a tool profile, widen a diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index efcd04f9dc..1efd091450 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -153,7 +153,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. (`function createIntent(input: {`, `packages/ui-server/src/activity/notify.ts:102-154`) and (`async deliverPending(notifier) {`, `packages/ui-server/src/activity/push-sender.ts:218-286`) are run-bound and do not maintain an Actions aggregate count. -- **Share provenance/limits:** (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:101`) assigns the source in server code. +- **Share provenance/limits:** (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:174`) assigns the source in server code. (`export const SHARE_MAX_TEXT_BYTES =`, `packages/ui-sdk/src/protocol.ts:2701`) bounds text, not binary uploads; extracted T1 context needs its own byte/token bound. - **Interactive locks:** (`const cap = host.maxConcurrentSessions();`, `packages/ui-server/src/ws/run-session.ts:1346-1358`) gates WS starts; @@ -751,7 +751,7 @@ recovered tick after killing the interval **Approach:** - One arrival → one thread (trust class from the source record, hardcoded server-side per the - (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:101`) precedent) + one `triage` Queue item; bytes stay in the staging + (`const result = await stageShareAt(`, `packages/ui-server/src/inbox/intake.ts:174`) precedent) + one `triage` Queue item; bytes stay in the staging directory - `dedup_key` from a content hash for shares; from an explicit key for authenticated CLI adds - Trust class is written by the server and is not a parameter of any request body diff --git a/docs/plans/chat-attachments.md b/docs/plans/chat-attachments.md index 68280fd7e5..12fa9f3b7c 100644 --- a/docs/plans/chat-attachments.md +++ b/docs/plans/chat-attachments.md @@ -49,11 +49,11 @@ operational inbox intake for `/share`. `/track-upload` calls `stageShare` with **Staging.** `stageShareAt` writes generic bytes under a server-minted ID in `.brain-ui/inbox//`, sanitizes names and publishes them with an atomic -rename (`stageShareAt`, `packages/ui-server/src/share/staging.ts:298-463`). It +rename (`stageShareAt`, `packages/ui-server/src/share/staging.ts:312-516`). It tries the shared track parser on every file -(`let imported`, `packages/ui-server/src/share/staging.ts:379-381`). The +(`let imported`, `packages/ui-server/src/share/staging.ts:416-418`). The MIME-to-extension table lists PDF -(`EXTENSION_BY_TYPE`, `packages/ui-server/src/share/staging.ts:91-114`), which +(`EXTENSION_BY_TYPE`, `packages/ui-server/src/share/staging.ts:96-119`), which only names the stored file and reads nothing. Staged shares are pruned after seven days (`SHARE_STAGING_TTL_MS`, `packages/ui-sdk/src/protocol.ts:2614`). diff --git a/packages/ui-server/src/inbox/bridge-tools.ts b/packages/ui-server/src/inbox/bridge-tools.ts index 05cecb1779..be39a7a77f 100644 --- a/packages/ui-server/src/inbox/bridge-tools.ts +++ b/packages/ui-server/src/inbox/bridge-tools.ts @@ -4,7 +4,8 @@ import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; import { INBOX_ADD_INPUT_SCHEMA, INBOX_GET_INPUT_SCHEMA, INBOX_LIST_INPUT_SCHEMA, RESOLVE_ACTION_INPUT_SCHEMA } from "@schlessera/brain-ui-sdk/tool-contracts"; import type { V1ResolutionEffect } from "@schlessera/brain-ui-sdk/protocol"; import { isUsablePrincipal, resolvePrincipal } from "../db/principals.js"; -import type { InboxIntake } from "./intake.js"; +import type { InboxIntake, IntakeHolds } from "./intake.js"; +import { AuthorityHeld } from "../brain/authority-hold.js"; import { createInboxStore } from "./store.js"; import { createInteractiveShares } from "./interactive-share.js"; import type { createInboxResolver } from "./resolve.js"; @@ -29,6 +30,16 @@ export interface InboxBridgeContext { * compensation refuse a protected target, as the turn's application does. */ protectedPaths?: readonly string[]; + /** + * The turn's write boundary (#2869): a journal observation or a scope pause + * that begins during an `inbox_add` holds its writes rather than revoking it. + */ + holds?: IntakeHolds; + /** + * Checks again, before each `inbox_add` write, what the turn admitted the + * call under, such as its provider masks; throws to refuse. + */ + requalify?: () => void; /** Server-held exact approval only. V1 never creates a discuss binding. */ approvedAction?: { sessionId: string; itemId: string; optionId: string; expectedVersion: number; effect: V1ResolutionEffect }; } @@ -42,10 +53,15 @@ export function createInboxBridgeTools(db: Database, intake: InboxIntake, resolv const threadId = context.origin === "interactive" ? undefined : context.origin.threadId; // A caller cannot mutate an approved effect after this bridge is constructed. const approved = context.approvedAction ? structuredClone(context.approvedAction) : undefined; - function authorize() { + /** `write` marks an `inbox_add` write's check: a hold, not revocation, reports `AuthorityHeld` so intake waits it out. */ + function authorize(write = false) { const principal = resolvePrincipal(db, principalId); - if (!isCurrent() || !principal || !isUsablePrincipal(principal, Date.now())) throw new Error("Inbox principal or turn is no longer authorized"); + if (!isCurrent() || !principal || !isUsablePrincipal(principal, Date.now())) { + if (write && principal && isUsablePrincipal(principal, Date.now()) && context.holds?.hold.active()) throw new AuthorityHeld(); + throw new Error("Inbox principal or turn is no longer authorized"); + } if (threadId && store.getThread(threadId)?.status !== "open") throw new Error("Inbox origin thread is unavailable"); + if (write) context.requalify?.(); return principal; } const reads = [...(context.allowedReads ?? [])]; @@ -88,7 +104,7 @@ export function createInboxBridgeTools(db: Database, intake: InboxIntake, resolv // Reuse compensated, principal-checked intake; never accept a model // source/trust field. The turn is this bridge's own: its host lineage // alone decides what the item can qualify for (#2816). - const result = await intake.conversation({ text: parsed.text, files: [] }, `bridge:${principalId}:${turnId}:${parsed.idempotencyKey}`, principal, turnId, () => { authorize(); return true; }, context.protectedPaths); + const result = await intake.conversation({ text: parsed.text, files: [] }, `bridge:${principalId}:${turnId}:${parsed.idempotencyKey}`, principal, turnId, () => { authorize(true); return true; }, context.protectedPaths, context.holds); return { created: result.created, threadId: result.threadId, itemId: result.itemId }; }, resolveAction: async input => { diff --git a/packages/ui-server/src/inbox/intake.ts b/packages/ui-server/src/inbox/intake.ts index 03ebf2cd97..d474482461 100644 --- a/packages/ui-server/src/inbox/intake.ts +++ b/packages/ui-server/src/inbox/intake.ts @@ -6,7 +6,8 @@ import { SHARE_STAGING_DIR } from "@schlessera/brain-ui-sdk/protocol"; import { removeStagedArrival, StagingTopologyError } from "../share/staging-fs.js"; import { isUsablePrincipal, resolvePrincipal, type Principal } from "../db/principals.js"; -import { shareContentHash, stageShareAt, type ShareInput } from "../share/staging.js"; +import { shareContentHash, stageShareAt, type ShareInput, type StagingWriteGate } from "../share/staging.js"; +import { AuthorityHeld, retryHeld, type AuthorityHold } from "../brain/authority-hold.js"; import { publishedArrival, stagedArrivalDigest } from "./arrival.js"; import { inboxIntakeWrites, IntakeAuthorizationError } from "./intake-writes.js"; export { IntakeAuthorizationError, IntakeKeyConflictError } from "./intake-writes.js"; @@ -19,6 +20,26 @@ import { createProtectedTargetCheck, ProtectedTargetRefusedError } from "../brai */ type StagingGuard = (path: string) => void; +/** + * A conversation turn's write boundary (#2869). A journal observation or a + * scope pause stops the turn's writes for a while and revokes nothing: every + * intake write waits for one, bounded and outside any transaction or lock, + * and runs in the tick its final check passes. + */ +export interface IntakeHolds { + /** The turn's authority is held, not revoked; its `isCurrent` throws `AuthorityHeld` while it is. */ + hold: AuthorityHold; + /** A hold that stops brain writes whatever the turn's authority: compensation waits for it alone. */ + writes: AuthorityHold; + /** The turn's cancellation: it ends every wait. */ + signal: AbortSignal; +} + +/** Compensation met a hold it could not wait out: nothing was removed, and its receipt stays queued for reconciliation. */ +class CompensationHeld extends Error { + constructor() { super("Intake cleanup stayed held by a journal observation or a scope pause; its receipt is kept for reconciliation"); this.name = "CompensationHeld"; } +} + interface IntakeOutcome { result: ShareIntakeResult; created: boolean; threadId: string; itemId: string } interface Receipt { @@ -46,12 +67,15 @@ export function createInboxIntake(db: Database, brainRoot: string, log?: Logger) function committed(key: string): Receipt | null { return db.query("SELECT * FROM inbox_intake_receipts WHERE dedup_key = ? AND state = 'committed'").get(key) as Receipt | null; } - async function clean(id: string, guard?: StagingGuard): Promise { + /** `run` admits the removal at a turn's write boundary (#2869); without one it runs at once. */ + async function clean(id: string, guard?: StagingGuard, run?: (remove: () => void) => Promise): Promise { // Server-only UUIDs and descriptor-anchored, no-follow removal (#2907) // keep compensation inside the real staging directory. A turn's - // compensation judges each directory just before removing it. A refusal + // compensation judges each directory just before removing it, and never + // removes during a hold (#2869). A refusal, or a hold it cannot wait out, // keeps the receipt for a later, safe retry. - removeStagedArrival(brainRoot, id, guard); + const remove = () => removeStagedArrival(brainRoot, id, guard); + if (run) await run(remove); else remove(); await write("clean", id); } /** @@ -59,7 +83,7 @@ export function createInboxIntake(db: Database, brainRoot: string, log?: Logger) * staging directory refuses with `StagingTopologyError` and keeps the * receipt, as a turn's protection refusal does. */ - async function reconcile(guard?: StagingGuard): Promise { + async function reconcile(guard?: StagingGuard, run?: (remove: () => void) => Promise): Promise { const rows = db.query("SELECT staging_id FROM inbox_intake_receipts WHERE state = 'cleanup' OR (state = 'preparing' AND reconcile_after <= ?)").all(Date.now()) as { staging_id: string }[]; for (const { staging_id: id } of rows) { if (active.has(id)) continue; @@ -67,9 +91,40 @@ export function createInboxIntake(db: Database, brainRoot: string, log?: Logger) // Another process may have committed a later row while this sweep awaited // cleanup of an earlier one. Never compensate a newly committed receipt. const row = db.query("SELECT state FROM inbox_intake_receipts WHERE staging_id = ?").get(id) as { state: string } | null; - if (row?.state === "cleanup") await clean(id, guard); + if (row?.state !== "cleanup") continue; + try { await clean(id, guard, run); } + catch (error) { + // A held removal stays queued, as every later one does; this sweep is opportunistic. + if (error instanceof CompensationHeld) return; + throw error; + } } } + /** + * The write boundary of one conversation intake (#2869). `gate` admits a + * change in the tick its final check passes: `stage`, a change of the + * turn's own authority, waits out a hold, while `compensate`, an inline + * removal of what it staged, never waits and leaves the removal to its + * owner. `cleanup` is that owner: it waits for a hold on writes alone, + * since compensation follows revocation and cancellation too. Every wait + * shares one deadline across the whole intake. Revocation and cancellation + * refuse at once; a hold past the bound refuses. + */ + function writeBoundary(principal: Principal, isCurrent: (() => boolean) | undefined, holds: IntakeHolds) { + const budget: { deadline?: number } = {}; + const expired = (): never => { + throw new IntakeAuthorizationError(holds.signal.aborted ? "Intake turn was cancelled; nothing was accepted" + : "Intake stayed held by a journal observation or a scope pause past the wait bound; nothing was accepted"); + }; + const kept = (): never => { throw new CompensationHeld(); }; + const unheld = (change: () => T | Promise) => { if (holds.writes.active()) throw new AuthorityHeld(); return change(); }; + const gate: StagingWriteGate = async (effect, change) => { + if (effect === "stage") return retryHeld(holds.hold, holds.signal, () => { authorize(principal, isCurrent); return change(); }, expired, budget); + if (holds.writes.active()) kept(); + return change(); + }; + return { gate, cleanup: (change: () => void) => retryHeld(holds.writes, holds.signal, () => unheld(change), kept, budget) }; + } /** * `person` marks an arrival a person made through an authenticated route, * outside any turn (#2741); a conversation turn's `inbox_add` names that @@ -80,42 +135,62 @@ export function createInboxIntake(db: Database, brainRoot: string, log?: Logger) * arrivals, before it is changed. */ async function ingest(source: "share" | "cli", input: ShareInput, principal: Principal, explicitKey?: string, isCurrent?: () => boolean, - author: "person" | { conversationTurn: string } | null = null, guard?: StagingGuard) { + author: "person" | { conversationTurn: string } | null = null, guard?: StagingGuard, holds?: IntakeHolds) { if (closed) throw new Error("Intake is closed"); - authorize(principal, isCurrent); - await reconcile(guard); + const boundary = holds && writeBoundary(principal, isCurrent, holds); + const gate = boundary?.gate; + /** Runs `change` after the turn's final check; across a hold when the turn has a write boundary. */ + const admitted = (change: () => T | Promise): Promise => + gate ? gate("stage", change) : (async () => { authorize(principal, isCurrent); return await change(); })(); + await admitted(() => {}); + await reconcile(guard, gate && (remove => gate("compensate", remove))); const hash = await shareContentHash(input); const key = source === "share" ? `share:${hash}` : `cli:${explicitKey}`; const existing = committed(key); - if (existing) { authorize(principal, isCurrent); return write("replay", existing, hash, principal); } + if (existing) return admitted(() => write("replay", existing, hash, principal)); const id = crypto.randomUUID(); // A refused target leaves no receipt to compensate. for (const name of [id, `.${id}.partial`]) guard?.(`${SHARE_STAGING_DIR}/${name}`); // Journal BEFORE any file write. A killed writer leaves bounded compensation, // never a Queue claim. Other live writers get an hour before reconciliation. - await write("prepare", id, source, principal, key, hash); + await admitted(() => write("prepare", id, source, principal, key, hash)); active.add(id); + let owned = false; + /** + * Removes this intake's own abandoned arrival, whose receipt is already + * `cleanup`. With a write boundary the reply does not wait for it: the + * removal waits for a hold, bounded, and this intake keeps owning the + * receipt until it settles; one it cannot run stays queued for reconciliation. + */ + const compensate = (): Promise => { + if (!boundary) return clean(id, guard); + owned = true; + void tracked(() => clean(id, guard, boundary.cleanup).catch(() => {}).finally(() => active.delete(id))); + return Promise.resolve(); + }; let accepted = false; try { let published: ReadonlyMap | undefined; - const result = await stageShareAt(brainRoot, input, id, log, source === "cli" ? "cli" : "web-share-target", files => { published = files; }, guard); + const result = await stageShareAt(brainRoot, input, id, log, source === "cli" ? "cli" : "web-share-target", files => { published = files; }, guard, gate); const binaryHashes = result.skipped?.length ? [] : await Promise.all(input.files.map(async (file, index) => ({ path: result.files[index]?.path, sha256: createHash("sha256").update(new Uint8Array(await file.arrayBuffer())).digest("hex") }))); // Evidence of the bytes this process wrote, never a re-read of the // published directory; unreadable staging records none. const evidence = author && published ? await publishedArrival(id, published).then(stagedArrivalDigest, () => null) : null; - authorize(principal, isCurrent); // The turn must still own intake at submission. - const outcome = await write("accept", id, source, principal, key, hash, result, binaryHashes, evidence, author); + // The turn must still own intake at submission: a hold here waits and + // checks again, and the receipt commits in the tick that check passes. + const outcome = await admitted(() => write("accept", id, source, principal, key, hash, result, binaryHashes, evidence, author)); accepted = outcome.result.id === id; - if (!accepted) await clean(id, guard); + // A losing duplicate's receipt is already `cleanup`. + if (!accepted) await compensate(); return outcome; } catch (error) { // A committed receipt is never compensated, even if reporting/cleanup fails. if (!accepted && committed(key)?.staging_id !== id) { await write("compensate", id); - await clean(id, guard).catch(() => {}); + await compensate().catch(() => {}); } throw error; - } finally { active.delete(id); } + } finally { if (!owned) active.delete(id); } } function tracked(operation: () => Promise): Promise { const task = operation(); @@ -134,10 +209,10 @@ export function createInboxIntake(db: Database, brainRoot: string, log?: Logger) * names the turn. With the turn's admitted protection set, every staging * effect refuses a protected target as the turn's application does (#2876). */ - conversation: (input: ShareInput, key: string, principal: Principal, turnId: string, isCurrent: () => boolean, protectedPaths?: readonly string[]) => { + conversation: (input: ShareInput, key: string, principal: Principal, turnId: string, isCurrent: () => boolean, protectedPaths?: readonly string[], holds?: IntakeHolds) => { const isProtected = protectedPaths ? createProtectedTargetCheck(brainRoot, protectedPaths) : undefined; const guard = isProtected && ((path: string) => { if (isProtected(path)) throw new ProtectedTargetRefusedError(); }); - return tracked(() => ingest("cli", input, principal, key, isCurrent, { conversationTurn: turnId }, guard)); + return tracked(() => ingest("cli", input, principal, key, isCurrent, { conversationTurn: turnId }, guard, holds)); }, reconcile, /** Startup reconciliation: a refused staging directory keeps its receipts and does not stop the server (#2907). */ @@ -146,7 +221,8 @@ export function createInboxIntake(db: Database, brainRoot: string, log?: Logger) log?.emit({ severityText: "ERROR", body: "inbox intake reconciliation refused the staging directory", attributes: { error: error.message } }); }), protectedIds: () => new Set((db.query("SELECT staging_id FROM inbox_intake_receipts WHERE state != 'cleanup'").all() as { staging_id: string }[]).map(row => row.staging_id)), - close: async () => { closed = true; await Promise.allSettled([...pending]); }, + // An intake's owned cleanup may start as the intake settles: wait for that too. + close: async () => { closed = true; while (pending.size) await Promise.allSettled([...pending]); }, }; } diff --git a/packages/ui-server/src/share/staging-fs.ts b/packages/ui-server/src/share/staging-fs.ts index 3377010977..4d508533f9 100644 --- a/packages/ui-server/src/share/staging-fs.ts +++ b/packages/ui-server/src/share/staging-fs.ts @@ -12,7 +12,7 @@ * the boundary inbox cleanup and the TTL prune already enforced by pathname. */ import { - closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, realpathSync, renameSync, rmdirSync, unlinkSync, + closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync, } from "node:fs"; import { open } from "node:fs/promises"; import { join } from "node:path"; @@ -125,6 +125,15 @@ export async function writeExclusive(dir: StagingDirectory, name: string, bytes: try { await file.writeFile(bytes); } finally { await file.close(); } } +/** + * `writeExclusive` in one synchronous step, for a write that must not yield + * between the check that admits it and the change itself (#2869). + */ +export function writeExclusiveSync(dir: StagingDirectory, name: string, bytes: Uint8Array | string): void { + const fd = openSync(at(dir, validName(name)), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o644); + try { writeFileSync(fd, bytes); } finally { closeSync(fd); } +} + /** * Rename the directory `from` to the absent name `to`, both inside `parent`, * and confirm what was published is still `moved`. A link or an unrelated diff --git a/packages/ui-server/src/share/staging.ts b/packages/ui-server/src/share/staging.ts index 1413e93432..bf3f590f8e 100644 --- a/packages/ui-server/src/share/staging.ts +++ b/packages/ui-server/src/share/staging.ts @@ -20,7 +20,7 @@ import { } from "@schlessera/brain-ui-sdk/protocol"; import { safeResolve } from "../files/walker.js"; import { - at, listDirectory, makeDirectory, openStagingRoot, publishDirectory, removeEntry, verifyEntry, writeExclusive, + at, listDirectory, makeDirectory, openStagingRoot, publishDirectory, removeEntry, verifyEntry, writeExclusive, writeExclusiveSync, type StagingDirectory, type StagingRoot, } from "./staging-fs.js"; @@ -129,6 +129,15 @@ const DEFAULT_MEDIA_TYPE = "application/octet-stream"; /** A partial directory older than this was orphaned by a crash mid-write. */ const PARTIAL_TTL_MS = 60 * 60 * 1000; +/** + * Runs one staging change at a write boundary (#2869): it may wait first, then + * runs `change` synchronously, in the tick its own final check passes, so + * nothing that begins after that check can overlap the change. `stage` is an + * effect of the caller's own authority; `compensate` removes what it staged + * and needs only that no hold stops writes. A refusal leaves the change unmade. + */ +export type StagingWriteGate = (effect: "stage" | "compensate", change: () => T | Promise) => Promise; + export class UnsupportedTrackError extends Error { constructor() { super("Not a validated GPX, KML or supported GeoJSON track."); this.name = "UnsupportedTrackError"; } } @@ -314,7 +323,12 @@ export async function stageShareAt( * again before each change, since links can move in between; a refusal is * never recorded as a skipped file. */ - guard?: (path: string) => void + guard?: (path: string) => void, + /** + * Every change this call makes runs through it, each written in one + * synchronous step after its gate admits it. Without one, changes run at once. + */ + gate?: StagingWriteGate ): Promise { if (!/^[a-f0-9-]{36}$/.test(id)) throw new Error("Invalid staging id"); input.signal?.throwIfAborted(); @@ -357,16 +371,23 @@ export async function stageShareAt( // The guard judges each change by the name it is made under; it follows // whatever links lie on the way itself, as they are when it is asked. const check = (name: string) => guard?.(`${SHARE_STAGING_DIR}/${name}`); + const run = (effect: "stage" | "compensate", change: () => T): T | Promise => gate ? gate(effect, change) : change(); check(partialDir); // Every staging change goes through descriptors opened without following // links (#2907): a linked staging directory refuses, as cleanup and the // prune refuse it, and a link swapped in later cannot redirect a change. - const root = openStagingRoot(brainPath, true)!; + let root: StagingRoot | undefined; let partial: StagingDirectory; - try { root.verify(); partial = makeDirectory(root.dir, partialName); } - catch (err) { root.close(); throw err; } + try { + partial = await run("stage", () => { + check(partialDir); + root ??= openStagingRoot(brainPath, true)!; + root.verify(); return makeDirectory(root.dir, partialName); + }); + } catch (err) { root?.close(); throw err; } + const staging = root!; /** The staging root and the partial are still the directories this call opened. */ - const anchored = () => { root.verify(); verifyEntry(root.dir, partialName, partial); }; + const anchored = () => { staging.verify(); verifyEntry(staging.dir, partialName, partial); }; try { // meta.json is reserved: a shared file called that must not overwrite it. @@ -411,19 +432,20 @@ export async function stageShareAt( trackMeta = { incomingName, sha256: createHash("sha256").update(bytes).digest("hex"), detected: imported.format, summary: { ...summary, waypointCount: imported.waypointCount, waypointOmitted: imported.waypointOmissions.length } }; } - check(`${partialDir}/${name}`); - // A refusal is never recorded as a skipped file. - anchored(); - try { - // Exclusive and no-follow: never follow a link, never truncate - // something that exists. In a freshly minted directory nothing can - // pre-exist, so this is a loud assertion rather than a fix. - await writeExclusive(partial, name, bytes); - published.set(path, bytes); - } catch (err) { + // A refusal is never recorded as a skipped file: the gate, the guard and + // the anchor all refuse before the write is attempted. Exclusive and + // no-follow: never follow a link, never truncate something that exists. + // In a freshly minted directory nothing can pre-exist, so this is a loud + // assertion rather than a fix. + const admit = () => { check(`${partialDir}/${name}`); anchored(); }; + let failed: { err: unknown } | undefined; + if (gate) failed = await gate("stage", () => { admit(); try { writeExclusiveSync(partial, name, bytes); return undefined; } catch (err) { return { err }; } }); + else { admit(); failed = await writeExclusive(partial, name, bytes).then(() => undefined, (err: unknown) => ({ err })); } + if (failed) { // One unwritable file (ENOSPC, a stricter filesystem) must not throw // away the other four. Record it and carry on; the share is only lost // if nothing at all survives. + const { err } = failed; log?.emit({ severityText: "ERROR", body: "could not stage a shared file", @@ -432,6 +454,7 @@ export async function stageShareAt( skipped.push(name); continue; } + published.set(path, bytes); staged.push({ name, @@ -458,31 +481,38 @@ export async function stageShareAt( ...(skipped.length ? { skipped } : {}), }; const meta = `${JSON.stringify(manifest, null, 2)}\n`; - check(`${partialDir}/meta.json`); - anchored(); - // Operation-owned: created exclusively, so a planted entry refuses. - await writeExclusive(partial, "meta.json", meta); + await run("stage", () => { + check(`${partialDir}/meta.json`); + anchored(); + // Operation-owned: created exclusively, so a planted entry refuses. + return gate ? writeExclusiveSync(partial, "meta.json", meta) : writeExclusive(partial, "meta.json", meta); + }); published.set(`${dir}/meta.json`, new TextEncoder().encode(meta)); onPublish?.(published); // The share becomes visible here, whole, in one operation. input.signal?.throwIfAborted(); - check(partialDir); check(finalDir); - root.verify(); - publishDirectory(root.dir, partialName, finalDir, partial); + await run("stage", () => { + check(partialDir); check(finalDir); + staging.verify(); + publishDirectory(staging.dir, partialName, finalDir, partial); + }); if (input.signal?.aborted) { - check(finalDir); - root.verify(); - removeEntry(root.dir, finalDir); + await run("compensate", () => { + check(finalDir); + staging.verify(); + removeEntry(staging.dir, finalDir); + }); input.signal.throwIfAborted(); } const { source: _source, ...result } = manifest; return result; } catch (err) { - try { check(partialDir); root.verify(); removeEntry(root.dir, partialName); } catch { /* A refused or failed removal leaves the partial for reconciliation. */ } + try { await run("compensate", () => { check(partialDir); staging.verify(); removeEntry(staging.dir, partialName); }); } + catch { /* A refused, held or failed removal leaves the partial for reconciliation. */ } throw err; - } finally { closeSync(partial.fd); root.close(); } + } finally { closeSync(partial.fd); staging.close(); } } /** diff --git a/packages/ui-server/src/ws/bridge-capabilities/activity.ts b/packages/ui-server/src/ws/bridge-capabilities/activity.ts index 84011cf625..ebd635453a 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/activity.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/activity.ts @@ -16,9 +16,29 @@ type InboxSlice = ReturnType !!host.journal?.isHeld() || scopePaused(), settled: () => hold.settled() }; return host.inboxTools?.forTurn({ principalId, turnId, isCurrent: () => !signal.aborted && isAuthorized(), sessionId: () => turn.sessionId ?? undefined, - origin: "interactive", membership: work?.posture === "voice" ? "voice" : "interactive", ...(protectedPaths ? { protectedPaths } : {}) }); + origin: "interactive", membership: work?.posture === "voice" ? "voice" : "interactive", ...(protectedPaths ? { protectedPaths } : {}), + holds: { hold, writes, signal }, ...(maskGuard ? { requalify: () => assertStagingUnmasked(ctx, maskGuard) } : {}) }); +} + +/** + * Intake stages the submitted item under the share staging directory and + * reconciles what is already staged there, so a mask at, above or inside + * that directory, or one it resolves into, refuses the whole addition. + */ +function assertStagingUnmasked(ctx: BridgeContext, maskGuard: NonNullable): void { + const { host, toolName } = ctx; + const tool = toolName("inbox_add"); + maskGuard.assert(tool, [`${SHARE_STAGING_DIR}/new`, ...maskGuard.folders.filter(folder => isWithin(SHARE_STAGING_DIR, folder, { includeRoot: false }))]); + if (host.brainPath) { + let resolved: string | undefined; + try { resolved = relative(realpathSync(host.brainPath), realpathSync(join(host.brainPath, SHARE_STAGING_DIR))); } catch { /* not staged yet */ } + if (resolved !== undefined) maskGuard.assert(tool, [`${resolved}/new`]); + } } /** Activity events, usage and promotions the backend reports, and the activity query tool. */ @@ -99,24 +119,17 @@ export function createActivity(ctx: BridgeContext, transcript: TurnTranscript, /** * Masks the server's own records on a bridge whose turn has masked folders. - * Intake stages the submitted item under the share staging directory and - * reconciles what is already staged there, so a mask at, above or inside - * that directory, or one it resolves into, refuses the whole addition. + * `inbox_add` refuses a masked staging directory at entry, and again before + * each intake write, since the staging directory may move during a hold. * The activity record and inbox items are the server's own text, kept from * earlier runs, and may quote a masked document. They are refused whole, * before any record is read; the tools stay registered (#2698, option A). */ export function guardMaskedRecords(ctx: BridgeContext, bridge: BackendBridge): void { - const { host, maskGuard, toolName } = ctx; + const { maskGuard, toolName } = ctx; const inboxAdd = bridge.inboxAdd; if (maskGuard && inboxAdd) bridge.inboxAdd = async input => { - const tool = toolName("inbox_add"); - maskGuard.assert(tool, [`${SHARE_STAGING_DIR}/new`, ...maskGuard.folders.filter(folder => isWithin(SHARE_STAGING_DIR, folder, { includeRoot: false }))]); - if (host.brainPath) { - let resolved: string | undefined; - try { resolved = relative(realpathSync(host.brainPath), realpathSync(join(host.brainPath, SHARE_STAGING_DIR))); } catch { /* not staged yet */ } - if (resolved !== undefined) maskGuard.assert(tool, [`${resolved}/new`]); - } + assertStagingUnmasked(ctx, maskGuard); return inboxAdd(input); }; if (maskGuard) for (const [name, tool, what] of [["queryActivity", "query_activity", "The activity record"], diff --git a/packages/ui-server/tests/inbox-intake-holds.test.ts b/packages/ui-server/tests/inbox-intake-holds.test.ts new file mode 100644 index 0000000000..745be3a9ff --- /dev/null +++ b/packages/ui-server/tests/inbox-intake-holds.test.ts @@ -0,0 +1,290 @@ +// #2869: a conversation turn's `inbox_add` treats a journal observation or a +// scope pause that begins while it stages as a hold, not as revocation. Every +// intake write (staging, publication, the receipt commit and compensation) +// waits for one, bounded and outside any transaction, and none overlaps it. +// Real revocation, cancellation and a stale premise still refuse. +import { afterEach, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { SHARE_STAGING_DIR } from "@schlessera/brain-ui-sdk/protocol"; +import type { AuthorityHold } from "../src/brain/authority-hold.js"; +import { createUiDb } from "../src/db/client.js"; +import { createPrincipal, revokePrincipal } from "../src/db/principals.js"; +import { createInboxBridgeTools } from "../src/inbox/bridge-tools.js"; +import { createInboxIntake } from "../src/inbox/intake.js"; +import { createInboxResolver } from "../src/inbox/resolve.js"; + +const closes: (() => unknown)[] = []; +afterEach(async () => { for (const close of closes.splice(0).reverse()) await close(); }); + +/** A point in one intake at which a check of the turn's authority runs, read from what is on disk and in the store. */ +type Phase = "entry" | "staging" | "publication" | "receipt"; + +/** + * One interactive turn's `inbox_add` over real intake and staging. `held` + * stands for a journal observation or a scope pause: the turn's strict + * `isCurrent` is false while it holds, as the bridge's is. `raiseAt` raises + * the hold the first time a check runs in that phase. + */ +function turn(options: { waitMs?: number; journal?: boolean } = {}) { + const root = mkdtempSync(join(tmpdir(), "inbox-intake-holds-")); closes.push(() => rmSync(root, { recursive: true, force: true })); + const db = createUiDb(":memory:"); closes.push(() => db.close()); + const principal = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + const intake = createInboxIntake(db, root); closes.push(() => intake.close()); + const cancel = new AbortController(); + const state = { held: false, current: true, raiseAt: undefined as Phase | undefined, raised: [] as Phase[], waitReads: 0, + checksWhileHeld: 0, requalify: undefined as (() => void) | undefined, raiseOnCompensate: false }; + const staging = join(root, SHARE_STAGING_DIR); + const entries = () => existsSync(staging) ? readdirSync(staging).sort() : []; + const receipts = () => db.query("SELECT staging_id, state FROM inbox_intake_receipts ORDER BY created_at").all() as { staging_id: string; state: string }[]; + const items = () => (db.query("SELECT COUNT(*) AS n FROM inbox_items").get() as { n: number }).n; + // The furthest phase any preparing arrival has reached, so concurrent intakes raise the hold at the first to reach it. + const phase = (): Phase => { + const names = entries(), mine = receipts().filter(row => row.state === "preparing").map(row => row.staging_id); + if (!mine.length) return "entry"; + if (mine.some(id => names.includes(id))) return "receipt"; + if (mine.some(id => existsSync(join(staging, `.${id}.partial`, "meta.json")))) return "publication"; + return "staging"; + }; + // A journal observation settles with an event; a scope pause has none and is rechecked. + let settle: (() => void) | undefined; + const settled = () => options.journal ? new Promise(resolve => { settle = resolve; }) : new Promise(() => {}); + const waitMs = options.waitMs ?? 60_000; + const hold: AuthorityHold = { get waitMs() { state.waitReads++; return waitMs; }, settled, + active: () => { if (state.held) state.checksWhileHeld++; return !cancel.signal.aborted && state.current && state.held; } }; + const writes: AuthorityHold = { get waitMs() { state.waitReads++; return waitMs; }, settled, + active: () => { if (state.raiseOnCompensate) { state.raiseOnCompensate = false; state.held = true; } return state.held; } }; + const isCurrent = () => { + if (state.raiseAt && !state.held && phase() === state.raiseAt) { state.raised.push(state.raiseAt); state.raiseAt = undefined; state.held = true; } + if (state.held) state.checksWhileHeld++; + return !cancel.signal.aborted && state.current && !state.held; + }; + const tools = createInboxBridgeTools(db, intake, createInboxResolver(db, { allowedOperations: () => [] }), root).forTurn({ + principalId: principal.id, turnId: "raft-turn", origin: "interactive", membership: "interactive", sessionId: () => "raft-session", + isCurrent, holds: { hold, writes, signal: cancel.signal }, requalify: () => state.requalify?.() }); + const add = (key = "raft") => tools.inboxAdd!({ text: "Odysseus lashes the raft before the storm.", idempotencyKey: key }); + const release = () => { state.held = false; settle?.(); }; + return { root, db, principal, intake, state, cancel, staging, entries, receipts, items, add, release }; +} + +/** Resolves once `ready()` holds, failing after a generous bound rather than hanging. */ +async function until(ready: () => boolean, label: string) { + for (let turn = 0; turn < 400 && !ready(); turn++) await new Promise(resolve => setTimeout(resolve, 5)); + expect(ready(), label).toBe(true); +} + +/** Lets the wait recheck several times while the hold stays. */ +const rechecks = () => new Promise(resolve => setTimeout(resolve, 150)); + +for (const kind of ["journal", "scope"] as const) { + test.each(["staging", "publication", "receipt"] as const)(`a ${kind} hold raised at the %s check waits, writes nothing under it and accepts one item after release (#2869)`, async at => { + const f = turn({ journal: kind === "journal" }); + f.state.raiseAt = at; + let outcome: unknown; + const pending = f.add().then(value => { outcome = value; return value; }, error => { outcome = error; throw error; }); + await until(() => f.state.held, `INTAKE_HOLD_RAISED_AT_${at.toUpperCase()}`); + const during = f.entries(); + await rechecks(); + expect(outcome, "INTAKE_HOLD_WAITS_RATHER_THAN_REFUSING").toBeUndefined(); + expect(f.state.checksWhileHeld, "INTAKE_HOLD_RECHECKS").toBeGreaterThanOrEqual(kind === "journal" ? 1 : 2); + expect(f.entries(), "INTAKE_HOLD_NO_STAGING_WRITE_UNDER_HOLD").toEqual(during); + expect(f.items(), "INTAKE_HOLD_NO_ACCEPTED_ITEM_UNDER_HOLD").toBe(0); + // The wait holds no transaction: another writer commits at once. + f.db.transaction(() => { f.db.query("SELECT 1").get(); }).immediate(); + f.release(); + const added = await pending; + expect(added.created, "INTAKE_HOLD_ACCEPTS_AFTER_RELEASE").toBe(true); + expect(f.items()).toBe(1); + expect(f.receipts().map(row => row.state)).toEqual(["committed"]); + expect(f.entries(), "INTAKE_HOLD_PUBLISHES_ONCE").toEqual([f.receipts()[0]!.staging_id]); + expect(f.state.raised).toEqual([at]); + }); +} + +test("a hold that begins after the entry check, while intake stages, keeps every staging write out of it (#2869)", async () => { + const f = turn(); + let outcome: unknown; + // The entry check runs synchronously; the hold begins in the next + // macrotask, while intake is between that check and its staging writes. + const pending = f.add().then(value => { outcome = value; return value; }, error => { outcome = error; throw error; }); + const checks = f.state.checksWhileHeld; + setImmediate(() => { f.state.held = true; }); + await until(() => f.state.held, "INTAKE_HOLD_RAISED_AFTER_ENTRY"); + await rechecks(); + expect(outcome, "INTAKE_HOLD_AFTER_ENTRY_WAITS").toBeUndefined(); + expect(f.entries().filter(name => !name.startsWith(".")), "INTAKE_HOLD_AFTER_ENTRY_NOTHING_PUBLISHED").toEqual([]); + expect(f.items()).toBe(0); + expect(f.state.checksWhileHeld, "INTAKE_HOLD_AFTER_ENTRY_RECHECKS").toBeGreaterThan(checks); + f.release(); + expect((await pending).created).toBe(true); + expect(f.items()).toBe(1); +}); + +test("repeated holds share one wait deadline and a hold past it refuses with no accepted item (#2869)", async () => { + const f = turn({ waitMs: 400 }); + f.state.raiseAt = "staging"; + let outcome: unknown; + const started = Date.now(); + const pending = f.add().then(value => { outcome = value; return value; }, error => { outcome = error; return error; }); + await until(() => f.state.held, "INTAKE_FIRST_HOLD"); + await new Promise(resolve => setTimeout(resolve, 150)); + f.release(); + f.state.raiseAt = "receipt"; + await until(() => f.state.held, "INTAKE_SECOND_HOLD"); + const error = await pending as Error; + expect(error, "INTAKE_HOLD_PAST_BOUND_REFUSES").toBeInstanceOf(Error); + expect(error.message).toContain("past the wait bound"); + // One deadline, from the first hold: a fresh one per hold would read the bound again. + expect(f.state.waitReads, "INTAKE_HOLDS_SHARE_ONE_DEADLINE").toBe(1); + expect(Date.now() - started, "INTAKE_HOLD_DEADLINE_IS_FINITE").toBeLessThan(5_000); + expect(f.items(), "INTAKE_HOLD_TIMEOUT_NO_QUEUE_CLAIM").toBe(0); + // The hold still stands: the staged arrival waits, durably, for safe cleanup. + expect(f.receipts().map(row => row.state)).toEqual(["cleanup"]); + expect(f.entries()).toHaveLength(1); + await f.intake.close(); + f.release(); + await f.intake.reconcile(); + expect(f.receipts(), "INTAKE_HELD_CLEANUP_RECONCILES").toEqual([]); + expect(f.entries()).toEqual([]); + expect(outcome).toBe(error); +}); + +test("revocation during a hold refuses at once; its owned cleanup waits for the hold and then removes the staging (#2869)", async () => { + const f = turn(); + f.state.raiseAt = "receipt"; + let heldAtAnswer: boolean | undefined; + const pending = f.add().then(value => value, error => { heldAtAnswer = f.state.held; return error; }); + await until(() => f.state.held, "INTAKE_HOLD_AT_RECEIPT"); + const published = f.entries(); + expect(published).toHaveLength(1); + revokePrincipal(f.db, f.principal.id, Date.now()); + f.state.current = false; + const error = await pending as Error; + expect(error.message, "INTAKE_REVOCATION_REFUSES").toContain("no longer authorized"); + expect(heldAtAnswer, "INTAKE_REVOCATION_DOES_NOT_WAIT_FOR_HOLD").toBe(true); + expect(f.items()).toBe(0); + await rechecks(); + // Compensation is the host's own effect, but it does not write through the hold. + expect(f.entries(), "INTAKE_COMPENSATION_WAITS_FOR_HOLD").toEqual(published); + expect(f.receipts().map(row => row.state), "INTAKE_REVOKED_RECEIPT_QUEUED_FOR_CLEANUP").toEqual(["cleanup"]); + f.release(); + await until(() => f.entries().length === 0, "INTAKE_COMPENSATION_AFTER_HOLD"); + await until(() => f.receipts().length === 0, "INTAKE_COMPENSATION_CLEARS_RECEIPT"); +}); + +test("a turn replaced during a hold refuses without waiting for the hold to end (#2869)", async () => { + const f = turn(); + f.state.raiseAt = "publication"; + let heldAtAnswer: boolean | undefined; + const pending = f.add().then(value => value, error => { heldAtAnswer = f.state.held; return error; }); + await until(() => f.state.held, "INTAKE_HOLD_AT_PUBLICATION"); + const partial = f.entries(); + f.state.current = false; + expect((await pending as Error).message, "INTAKE_REPLACED_REFUSES").toContain("no longer authorized"); + expect(heldAtAnswer, "INTAKE_REPLACED_REFUSES_WHILE_HELD").toBe(true); + expect(f.receipts().map(row => row.state)).toEqual(["cleanup"]); + // Not published, and the partial is not removed through the hold either. + expect(f.entries(), "INTAKE_REPLACED_NOTHING_WRITTEN_UNDER_HOLD").toEqual(partial); + f.release(); + await until(() => f.entries().length === 0 && f.receipts().length === 0, "INTAKE_REPLACED_CLEANED_AFTER_HOLD"); + expect(f.items()).toBe(0); +}); + +test("cancellation during a hold terminates without a queue claim and keeps the cleanup receipt for reconciliation (#2869)", async () => { + const f = turn(); + f.state.raiseAt = "receipt"; + const pending = f.add().then(value => value, error => error); + await until(() => f.state.held, "INTAKE_HOLD_BEFORE_CANCEL"); + f.cancel.abort(); + const error = await pending as Error; + expect(error.message, "INTAKE_CANCELLED_REFUSES").toContain("cancelled"); + expect(f.items(), "INTAKE_CANCELLED_NO_QUEUE_CLAIM").toBe(0); + // The hold still stands, so cleanup did not write through it. + expect(f.entries(), "INTAKE_CANCELLED_CLEANUP_NOT_UNDER_HOLD").toHaveLength(1); + await f.intake.close(); + expect(f.receipts().map(row => row.state), "INTAKE_CANCELLED_CLEANUP_RECEIPT_KEPT").toEqual(["cleanup"]); + expect(f.entries()).toHaveLength(1); + f.release(); + await f.intake.reconcile(); + expect(f.entries()).toEqual([]); + expect(f.receipts()).toEqual([]); +}); + +test("a premise that changes during the hold is checked again before the receipt commits (#2869)", async () => { + const f = turn(); + f.state.raiseAt = "receipt"; + const pending = f.add().then(value => value, error => error); + await until(() => f.state.held, "INTAKE_HOLD_BEFORE_REQUALIFY"); + // A mask over the staging directory, admitted before the hold, now refuses. + f.state.requalify = () => { throw new Error("The staging directory is masked for this turn"); }; + f.release(); + const error = await pending as Error; + expect(error, "INTAKE_REQUALIFIES_AFTER_HOLD").toBeInstanceOf(Error); + expect(error.message).toContain("masked"); + expect(f.items(), "INTAKE_STALE_PREMISE_NOT_ADMITTED").toBe(0); + await f.intake.close(); + expect(f.entries()).toEqual([]); + expect(f.receipts()).toEqual([]); +}); + +test("a receipt reconciled away during the hold is not accepted after it (#2869)", async () => { + const f = turn(); + f.state.raiseAt = "receipt"; + const pending = f.add().then(value => value, error => error); + await until(() => f.state.held, "INTAKE_HOLD_BEFORE_RECONCILE"); + // Another process's reconciliation took the receipt while this one waited. + f.db.query("UPDATE inbox_intake_receipts SET state = 'cleanup'").run(); + f.release(); + expect((await pending as Error).message, "INTAKE_RECEIPT_OWNERSHIP_RECHECKED").toContain("reconciled"); + expect(f.items()).toBe(0); +}); + +/** Two concurrent intakes under one key, both staged before either commits: the hold at the first receipt check keeps them apart. */ +async function duplicates(f: ReturnType) { + f.state.raiseAt = "receipt"; + const first = f.add("bow"), second = f.add("bow"); + await until(() => f.state.held && f.receipts().length === 2, "INTAKE_DUPLICATES_BOTH_PREPARED"); + await rechecks(); + expect(f.items(), "INTAKE_DUPLICATES_NOTHING_ACCEPTED_UNDER_HOLD").toBe(0); + return [first, second] as const; +} + +test("duplicate intakes held before their receipts produce one winner, and the loser cleans only its own staging (#2869)", async () => { + const f = turn(); + const pending = await duplicates(f); + f.release(); + const results = await Promise.all(pending); + expect(results.map(result => result.created).sort(), "INTAKE_DUPLICATE_ONE_WINNER").toEqual([false, true]); + expect(results[0]!.itemId).toBe(results[1]!.itemId); + expect(f.items()).toBe(1); + const winner = f.receipts().filter(row => row.state === "committed"); + expect(winner).toHaveLength(1); + await f.intake.close(); + expect(f.receipts(), "INTAKE_DUPLICATE_LOSER_RECEIPT_CLEANED").toHaveLength(1); + expect(f.entries(), "INTAKE_DUPLICATE_WINNER_KEPT").toEqual([winner[0]!.staging_id]); +}); + +test("a losing duplicate whose cleanup meets a hold keeps its receipt queued and never touches the winner (#2869)", async () => { + const f = turn(); + const pending = await duplicates(f); + // The loser's removal is the only compensation: the hold begins as it starts. + f.state.raiseOnCompensate = true; + f.release(); + const results = await Promise.all(pending); + expect(results.map(result => result.created).sort(), "INTAKE_LOSER_REPORTS_THE_WINNER").toEqual([false, true]); + await until(() => f.state.held, "INTAKE_LOSER_CLEANUP_HELD"); + const winner = f.receipts().find(row => row.state === "committed")!.staging_id; + const loser = f.receipts().find(row => row.state === "cleanup")!.staging_id; + await rechecks(); + expect(f.entries().sort(), "INTAKE_LOSER_CLEANUP_NOT_UNDER_HOLD").toEqual([loser, winner].sort()); + // The wait ends with the turn; the receipt stays queued. + f.cancel.abort(); + await f.intake.close(); + expect(f.receipts().find(row => row.staging_id === loser)?.state, "INTAKE_LOSER_RECEIPT_QUEUED").toBe("cleanup"); + f.release(); + await f.intake.reconcile(); + expect(f.entries(), "INTAKE_COMMITTED_WINNER_NEVER_CLEANED").toEqual([winner]); + expect(f.receipts().map(row => row.staging_id)).toEqual([winner]); + expect(f.items()).toBe(1); +}); diff --git a/packages/ui-server/tests/ws-inbox-intake-hold.test.ts b/packages/ui-server/tests/ws-inbox-intake-hold.test.ts new file mode 100644 index 0000000000..9699bec23d --- /dev/null +++ b/packages/ui-server/tests/ws-inbox-intake-hold.test.ts @@ -0,0 +1,78 @@ +// #2869: the live bridge hands a conversation's `inbox_add` its write +// boundary. A journal observation or a scope pause that begins after the +// bridge's entry wait, at intake's receipt check, holds the intake rather than +// refusing it, keeps the brain lock free, and one item is accepted after it. +import { expect, test } from "bun:test"; +import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { SHARE_STAGING_DIR } from "@schlessera/brain-ui-sdk/protocol"; +import { BRAIN_LOCK_KEY, type BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { createStaticBackendRegistry } from "../src/agent/backend.js"; +import type { TurnJournal } from "../src/brain/turn-journal.js"; +import type { TurnScope } from "../src/brain/turn-scope.js"; +import { createUiDb } from "../src/db/client.js"; +import { createPrincipal } from "../src/db/principals.js"; +import { createInboxBridgeTools } from "../src/inbox/bridge-tools.js"; +import { createInboxIntake } from "../src/inbox/intake.js"; +import { createInboxResolver } from "../src/inbox/resolve.js"; +import { WsHost } from "../src/ws/host.js"; +import { runSession } from "../src/ws/run-session.js"; +import { createSessionCatalog } from "../src/ws/session-catalog.js"; +import { makeFakeBackend } from "./helpers/fake-backend.js"; + +test.each(["journal", "scope"] as const)("a %s hold that begins at inbox_add's receipt check waits and accepts one item after it (#2869)", async kind => { + const root = mkdtempSync(join(tmpdir(), "ws-inbox-hold-")); + const db = createUiDb(":memory:"); + const principal = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); + const staging = join(root, SHARE_STAGING_DIR); + const published = () => existsSync(staging) ? readdirSync(staging).filter(name => !name.startsWith(".")) : []; + const items = () => (db.query("SELECT COUNT(*) AS n FROM inbox_items").get() as { n: number }).n; + // The hold begins the first time a check runs once the arrival is + // published: the receipt check, after the bridge's own entry wait. + const state = { armed: false, held: false, raised: false }; + const raise = () => { if (state.armed && !state.raised && published().length) { state.raised = true; state.held = true; } }; + let settle: (() => void) | undefined; + const journal = { + isHeld: () => { if (kind === "journal") raise(); return kind === "journal" && state.held; }, + idle: async () => { if (kind === "journal" && state.held) await new Promise(resolve => { settle = resolve; }); }, + observe: async () => {}, toolStarted() {}, toolEnded: async () => {}, summary: () => ({ state: "unknown" }), bindSession: async () => {}, finish: async () => {}, + } as unknown as TurnJournal; + const scope = { isPaused: () => { if (kind === "scope") raise(); return kind === "scope" && state.held; }, toolCall() {}, bindSession() {}, finish() {}, close() {} } as unknown as TurnScope; + let failure: unknown, proven = false; + let host!: WsHost; + const backend = makeFakeBackend({ id: "pi", startTurn: async req => { + try { await proof(req.bridge); } catch (error) { failure = error; } + } }); + async function proof(bridge: BackendBridge) { + state.armed = true; + let outcome: unknown; + const pending = bridge.inboxAdd!({ text: "Odysseus lashes the raft before the storm.", idempotencyKey: "raft" }) + .then(value => { outcome = value; return value; }, error => { outcome = error; throw error; }); + for (let turn = 0; turn < 400 && !state.held && outcome === undefined; turn++) await new Promise(resolve => setTimeout(resolve, 5)); + expect(state.raised, "WS_INBOX_HOLD_RAISED_AT_RECEIPT").toBe(true); + await new Promise(resolve => setTimeout(resolve, 150)); + expect(outcome, "WS_INBOX_HOLD_WAITS_RATHER_THAN_REFUSING").toBeUndefined(); + expect(items(), "WS_INBOX_HOLD_NO_RECEIPT_UNDER_HOLD").toBe(0); + // The wait holds no brain lock: Continue/Stop and the observation can proceed. + let locked = false; + await host.workerLock.withLock(BRAIN_LOCK_KEY, async () => { locked = true; }); + expect(locked, "WS_INBOX_HOLD_LEAVES_BRAIN_LOCK_FREE").toBe(true); + state.held = false; settle?.(); + expect((await pending).created, "WS_INBOX_HOLD_ACCEPTS_AFTER_RELEASE").toBe(true); + expect(items()).toBe(1); + expect(published()).toHaveLength(1); + proven = true; + } + const intake = createInboxIntake(db, root); + host = new WsHost({ brainPath: root, registry: createStaticBackendRegistry([backend], "pi"), catalog: createSessionCatalog(() => db), + inboxTools: createInboxBridgeTools(db, intake, createInboxResolver(db, { allowedOperations: () => [] }), root), + isPrincipalAuthorized: () => true, journal, scope }); + const authorization = host.coordinator.openAuthorization({ principalId: principal.id, valid: true, expiresAt: Number.MAX_SAFE_INTEGER }); + try { + const running = runSession(host, { authorization, text: "Add the raft to the inbox", attachments: [] }); + authorization.release(); await running; + if (failure) throw failure; + expect(proven, "WS_INBOX_HOLD_TURN_RAN").toBe(true); + } finally { host.close(); await intake.close(); db.close(); rmSync(root, { recursive: true, force: true }); } +}); From 6e96b392eb70cd891e3d2fd255ecc3f22f8b9827 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 04:57:22 +0000 Subject: [PATCH 2/2] fix(ui-server): judge the partial staging directory once before creating it (#2869) The gated partial creation judged the partial directory both before and inside its change, so the guard saw the first change twice and share-staging-protection's in-order guard test failed. The check inside the change already runs before the staging root opens, as before. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/share/staging.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/src/share/staging.ts b/packages/ui-server/src/share/staging.ts index bf3f590f8e..5504aa40a5 100644 --- a/packages/ui-server/src/share/staging.ts +++ b/packages/ui-server/src/share/staging.ts @@ -372,7 +372,6 @@ export async function stageShareAt( // whatever links lie on the way itself, as they are when it is asked. const check = (name: string) => guard?.(`${SHARE_STAGING_DIR}/${name}`); const run = (effect: "stage" | "compensate", change: () => T): T | Promise => gate ? gate(effect, change) : change(); - check(partialDir); // Every staging change goes through descriptors opened without following // links (#2907): a linked staging directory refuses, as cleanup and the // prune refuse it, and a link swapped in later cannot redirect a change. @@ -380,6 +379,7 @@ export async function stageShareAt( let partial: StagingDirectory; try { partial = await run("stage", () => { + // Judged before the staging root is opened, and again after any wait. check(partialDir); root ??= openStagingRoot(brainPath, true)!; root.verify(); return makeDirectory(root.dir, partialName);