diff --git a/.changeset/automatic-index-admission-requeue.md b/.changeset/automatic-index-admission-requeue.md new file mode 100644 index 0000000000..cba38630bc --- /dev/null +++ b/.changeset/automatic-index-admission-requeue.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-sdk": patch +"@schlessera/brain-ui-server": patch +--- +An automatic index refused at maintenance admission because the temporary-storage budget is busy, for example by a turn's scratch check, now stays pending and runs once the budget frees instead of failing. A turn's scratch check and an index you request keep their current outcomes. The busy message names what holds the budget by kind (index, scratch query, git, sync, probe or command), without paths or identities. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 0318d5aa14..b7a131c661 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1057,6 +1057,8 @@ export "./internal" (./src/internal.ts) type MaintenanceEnvelope type MaintenanceHost type MaintenanceResult + MaintenanceTempBusyError + type MaintenanceTempKind type MaintenanceWorker NATIVE_MANAGER_MAX_DELTA_BYTES NATIVE_MANAGER_OPERATION_TIMEOUT_MS @@ -1265,6 +1267,7 @@ export "./internal" (./src/internal.ts) requestPolicyPermission requireWorkerHost requireWorkerHostAsync + reserveMaintenanceTemp resolveMaintenanceTempLimits resolveOutputStagingLimits resolveTurnTempLimits diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 25d16e42e9..eda5b74658 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -63,7 +63,7 @@ next to it. - **Updated.** Nothing in the tree installs, updates, pins or reads the version of this binary. The only version probe in the server is for the `brain` CLI (`Probe the selected content CLI`, - `packages/ui-server/src/brain/client.ts:152-220`, called at + `packages/ui-server/src/brain/client.ts:163-231`, called at `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:450`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, `packages/core/src/cli/commands/doctor.ts:503-507`) — the user's own Claude @@ -243,7 +243,7 @@ than refuses on a mismatch.** pair is one nobody measured. - **At boot, from the binary a turn would spawn.** The same shape as the `brain` CLI probe (`Probe the selected content CLI`, - `packages/ui-server/src/brain/client.ts:152`). The SDK's + `packages/ui-server/src/brain/client.ts:163`). The SDK's resolver is not exported, so the probe must not re-implement it. The SDK resolves the binary when a query is built, and fails there if none is found (`node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs:228`); it then hands diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 69f2ccf5ba..9fac2d7119 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -543,7 +543,7 @@ maintenance worker no longer receives the keys the provider relay carries (`GEMINI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and keys the operator lists for it), and the brain's `.env*` files are masked as they are for a credential-free worker. Its `brain` CLI reaches those providers through its own -relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:420-427`). +relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:422-429`). What remains is narrower and stated in the status: keys the relay does not carry (the `jev` reranker's, a `brain sync` agent runner's login) and every key on a host without managed native storage, where there is no relay. @@ -2267,7 +2267,7 @@ as agent workers. It retains one execution view and binds the owned stage drain before setup can spawn a worker, so setup failure also preserves unresolved cleanup authority. Credentialed and no-helper maintenance keep their existing paths (`launchMaintenanceWorker`, -`packages/ui-sdk/src/server/maintenance-worker.ts:248-330`). +`packages/ui-sdk/src/server/maintenance-worker.ts:250-332`). The frozen Git adapter is concrete first-party input. Its bounded installer places only its fixed files in an initially absent private control directory @@ -2275,7 +2275,7 @@ inside the existing attested stage. Each consumer sees the fixed Git target read-only; its writable stage alias is concealed and the control directory is excluded even from default-scope publication. This changes no source modes, manager reader authority or helper protocol (`prepareMaintenanceGitInput`, -`packages/ui-sdk/src/server/maintenance-worker.ts:97-115`). Required lower Git +`packages/ui-sdk/src/server/maintenance-worker.ts:99-117`). Required lower Git metadata must still support the actual consumer operations; safe.directory is an exact host-selected-root check, not permission to write an unmapped inode. For the three fixed Git mask targets, originally absent directories are created @@ -3918,7 +3918,7 @@ files, `.claude/`, `.agents/`, `.pi/`, `.mcp.json`, and - The core CLI loads `brain.config.ts` or `brain.config.json` at the canonical brain cwd (`loadUserConfig`, `packages/core/src/lib/config.ts:594-628`). Host commands bind that cwd to the selected brain (`function hostSpawn`, - `packages/ui-server/src/brain/host-boundary.ts:511-522`). + `packages/ui-server/src/brain/host-boundary.ts:514-525`). - Bun startup uses root `bunfig.toml` and `package.json`; retained literal preload/module inputs can identify a nested module's nearest package scope. The inventory walks parent directories only within the originating journal diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index 1d86cc9d71..6af11350dc 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:918`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:939`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1145`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:920`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:941`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1147`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1165-1186`). That order establishes access; +`packages/ui-server/src/app.ts:1167-1188`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/native-brain-storage.md b/docs/decisions/native-brain-storage.md index 3d1957315e..d750b23c05 100644 --- a/docs/decisions/native-brain-storage.md +++ b/docs/decisions/native-brain-storage.md @@ -167,7 +167,7 @@ A failed or interrupted preparation poisons the stage for further payloads and publication until it is discarded. The private control marker is bound to the existing stage/checkpoint, command generation, descriptor and owned drain; no generic copying or reader authority is added (`prepareMaintenanceWorker`, -`packages/ui-sdk/src/server/maintenance-worker.ts:117-148`). +`packages/ui-sdk/src/server/maintenance-worker.ts:119-150`). The root manager configuration fixes the application UID/group and the existing output allowance and aggregate budget. Requests cannot choose host paths or diff --git a/docs/decisions/runtime-requirements.md b/docs/decisions/runtime-requirements.md index c48c88531d..070413274d 100644 --- a/docs/decisions/runtime-requirements.md +++ b/docs/decisions/runtime-requirements.md @@ -194,7 +194,7 @@ Paths may appear in local diagnostics; public fixtures use temporary paths. | Requirement | Initial value | Evidence and limit of the claim | | --- | --- | --- | | Claude backend's SDK range | Retain `^0.3.241` | It is the published declaration (`"@anthropic-ai/claude-agent-sdk"`, `packages/ui-backend-claude/package.json:49`). Registry metadata on 2026-09-30 confirms 0.3.241 exists. This is a declared compatibility bound, not proof every allowed release passed current measurements. | -| ui-server's content CLI floor | Retain `0.33.0` | `--` support is the reason documented immediately above `MIN_BRAIN_CLI_VERSION` (`MIN_BRAIN_CLI_VERSION`, `packages/ui-server/src/brain/client.ts:121`); the initial boot refusal test used 0.32.9. The current test exercises the corrected floor (`a 0.40.0 brain repo pin`, `packages/ui-server/tests/brain-client.test.ts:247-259`). | +| ui-server's content CLI floor | Retain `0.33.0` | `--` support is the reason documented immediately above `MIN_BRAIN_CLI_VERSION` (`MIN_BRAIN_CLI_VERSION`, `packages/ui-server/src/brain/client.ts:132`); the initial boot refusal test used 0.32.9. The current test exercises the corrected floor (`a 0.40.0 brain repo pin`, `packages/ui-server/tests/brain-client.test.ts:247-259`). | | Bun engine floor | Retain existing `>=1.3.5` declarations | Existing engine metadata and the doctor's CVE-based warning (`const MIN_BUN`, `packages/core/src/cli/commands/doctor.ts:48`; `function checkRuntime`, `packages/core/src/cli/commands/doctor.ts:85-92`). This record introduces no new doctor verdict or blanket boot gate. | | Pi SDK requirements | Retain existing exact `0.87.1` declarations | `packages/ui-backend-pi/package.json`; a host floor composes with each actual imported Pi dependency's existing exact requirement. The Claude range ruling does not authorize changing Pi's pins. | | Additional default Claude runtime floor | None | There is no evidenced numerical incompatibility threshold in the existing record. The successful pairs are observations, not proof that the preceding release fails. A new library floor needs a feature requirement or reproducible incompatibility and its versioning review. | @@ -275,7 +275,7 @@ reciprocal host-version negotiation is involved. | Existing boundary | How this design uses it | | --- | --- | -| `probeBrainCliVersion` / `brainCliCommand` (`export async function probeBrainCliVersion`, `packages/ui-server/src/brain/client.ts:153-220`) | Reuse executable selection, wrapper, deadline and cleanup; add host floor composition, strict comparison and invocation verification without duplicating the 0.33.0 constant. | +| `probeBrainCliVersion` / `brainCliCommand` (`export async function probeBrainCliVersion`, `packages/ui-server/src/brain/client.ts:164-231`) | Reuse executable selection, wrapper, deadline and cleanup; add host floor composition, strict comparison and invocation verification without duplicating the 0.33.0 constant. | | `installedAgentSdkVersion` (`export function installedAgentSdkVersion`, `packages/ui-backend-claude/src/runtime-probe.ts:55-61`) | Retain importer-relative resolution; validate package name/version and the owner's manifest range. | | `selectedSpawn` / `probeClaudeRuntime` (`export function selectedSpawn`, `packages/ui-backend-claude/src/runtime-probe.ts:69-96`; `export async function probeClaudeRuntime`, `packages/ui-backend-claude/src/runtime-probe.ts:127-147`) | Keep SDK-selected command capture, native/JS override argv, environment, timeout and group cleanup; add strict identity validation and composed runtime floors. | | `probeBackendRuntimes` (`export async function probeBackendRuntimes`, `packages/ui-server/src/agent/backend.ts:394-444`) | Forward validated host requirements; retain active-backend selection and separate unmeasured-pair logging. | diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index da2e92c1b6..46272f78ef 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:924` | mounted **before** the guard at `authGuard(authMode`, `app.ts:939`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:949` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1145-1162` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:926` | mounted **before** the guard at `authGuard(authMode`, `app.ts:941`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:951` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1147-1164` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/hosting/README.md b/docs/hosting/README.md index a9bd80230b..24c9aa6128 100644 --- a/docs/hosting/README.md +++ b/docs/hosting/README.md @@ -44,7 +44,7 @@ the separately authorized cache measurement procedure. **The server refuses to boot against `@schlessera/brain` older than 0.44.0.** The floor is enforced at -(`MIN_BRAIN_CLI_VERSION`, `packages/ui-server/src/brain/client.ts:121`) and covers +(`MIN_BRAIN_CLI_VERSION`, `packages/ui-server/src/brain/client.ts:132`) and covers all commands and flags the server invokes, including 0.42.0’s scratch pin input. From 0.44.0 the search index lives in `.brain-index/` instead of a root-level `brain.db`: the server reads it there, deletes the old root-level copy at boot diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index a45ff9d74f..728269e6f6 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -487,6 +487,17 @@ aggregate explicitly for parallel maintenance. Neither value derives from agent-session concurrency or uses agent turn temp, runtime state or the separately bounded startup/publication storage. +Admission is immediate: a command that does not fit is refused with +`worker_state_busy` before anything runs. The refusal names what holds the +budget by kind only (`index`, `scratch query`, `git`, `sync`, `probe` or +`command`), never a path or a process. At the defaults one allowance fills the +budget, so the automatic index and a turn's scratch check cannot overlap +(#3461). An automatic index that loses that race stays pending and runs as +soon as the budget frees; it is not reported as a failure, and close +discards it. A turn whose scratch check loses keeps `.brain/scratch/` +read-only for that turn, as before. An index you request still reports busy +at once. + Each command's sized private `/tmp` contains scratch and fresh XDG config, cache, data and state directories. Credential-free HOME is also in that filesystem. Credentialed HOME is readable but read-only; writes requiring a diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 185cb1be7f..778f0a6443 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:939`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:941`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 0e2a4ea001..0b7f81f3e5 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:27-44`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:939`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:941`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`requestPermission: (req) => {`, `packages/ui-server/src/ws/bridge.ts:362-456`). Timeout unwind is diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index f64ed1dbe6..635d0c6a69 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -298,7 +298,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1255-1305`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1257-1307`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:274-287`). A caller deadline diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index dff7fd8d17..724b299b18 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -397,7 +397,7 @@ implementation. Any PR moving these lines owns their citation repairs. - Activity resolution: (`.get("/activity/runs", (c) => {`, `packages/ui-server/src/routes/activity.ts:145-283`). -- API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:939`). +- API authorization: (`app.use("/api/*", authGuard(authMode, auth, db));`, `packages/ui-server/src/app.ts:941`). - Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:1107-1152`). diff --git a/docs/plans/storage-lifecycle.md b/docs/plans/storage-lifecycle.md index 10cca90139..c431b19b85 100644 --- a/docs/plans/storage-lifecycle.md +++ b/docs/plans/storage-lifecycle.md @@ -31,7 +31,7 @@ Use maintenance workers for repository code, the CLI and Git. Host routes may perform narrowly validated descriptor operations, as the journal/revert do; they must not evaluate brain configuration, hooks, filters or executables. The existing brain client supplies boundary execution -(`async function execBrain`, `packages/ui-server/src/brain/client.ts:271-325`). +(`async function execBrain`, `packages/ui-server/src/brain/client.ts:285-340`). Do not turn the new surface into a host command runner or an extension seam. Reuse existing authorization. A requested reversible, fully journaled edit diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index 3cb234c96e..a5239f30d8 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -50,6 +50,7 @@ export { workerHostProven, HOST_MASKS, MAINTENANCE_HOME, WORKER_PROVIDER_RELAY_D export type { MaintenanceEnvelope } from "./server/worker-launcher.js"; export { brainGitSync, CREDENTIAL_FREE_ENV, prepareMaintenanceGitInput, prepareMaintenanceWorker, launchMaintenanceWorker, launchMaintenanceWorkerAsync, maintenanceLaunch, probeMaintenanceWorker, probeNativeMaintenanceWorker, runMaintenanceWorker, runMaintenanceWorkerSync } from "./server/maintenance-worker.js"; export type { MaintenanceHost, MaintenanceCommand, MaintenanceResult, MaintenanceWorker } from "./server/maintenance-worker.js"; +export { MaintenanceTempBusyError, reserveMaintenanceTemp, type MaintenanceTempKind } from "./server/maintenance-temp-budget.js"; export { createWorkerStartupView, prepareNativeWorkerStartupView, retainWorkerStartupView, nativeWorkerStartupInput, isManagedWorkerStartupView, hasManagedNativeStorage } from "./server/worker-startup-view.js"; export type { WorkerStartupView } from "./server/worker-startup-view.js"; export function maintenanceGitEntry(): string { return Bun.resolveSync("./server/maintenance-git-entry", import.meta.dir); } diff --git a/packages/ui-sdk/src/server/bridge-tools/mask.ts b/packages/ui-sdk/src/server/bridge-tools/mask.ts index 7eeaa51f42..1219e87f5c 100644 --- a/packages/ui-sdk/src/server/bridge-tools/mask.ts +++ b/packages/ui-sdk/src/server/bridge-tools/mask.ts @@ -150,9 +150,9 @@ function* scratchIgnoredSteps(rootReal: string, maintenance?: import("../mainten // a maintenance worker (#1648); one that cannot run refuses the mask. const inRepo = existsSync(join(rootReal, ".git")) || - (yield* brainGitSteps(rootReal, ["rev-parse", "--git-dir"], maintenance)) === 0; + (yield* brainGitSteps(rootReal, ["rev-parse", "--git-dir"], { ...maintenance, tempKind: "scratch_query" })) === 0; const query = ["check-ignore", "-q", "--no-index", "--", SCRATCH_DIR]; - return scratchIgnoreResult({ exitCode: yield* brainGitSteps(rootReal, query, { ...maintenance, ...(!inRepo ? { emptyRepository: true } : {}) }), killed: false }); + return scratchIgnoreResult({ exitCode: yield* brainGitSteps(rootReal, query, { ...maintenance, tempKind: "scratch_query", ...(!inRepo ? { emptyRepository: true } : {}) }), killed: false }); } function scratchIgnoreUnavailable(): Error { diff --git a/packages/ui-sdk/src/server/maintenance-temp-budget.ts b/packages/ui-sdk/src/server/maintenance-temp-budget.ts index 57500a765d..207825ed72 100644 --- a/packages/ui-sdk/src/server/maintenance-temp-budget.ts +++ b/packages/ui-sdk/src/server/maintenance-temp-budget.ts @@ -9,7 +9,16 @@ import { FIRST_PARTY_FAILURE_CLASSES } from "../protocol.js"; import { mib, resolveMaintenanceTempLimits, type WorkerStateLimits } from "./worker-state-limits.js"; interface Identity { pid: number; start: string; boot: string; namespace: string } -interface Entry { id: string; bytes: number; owner: string; worker: string | null; released: number } +interface Entry { id: string; bytes: number; owner: string; worker: string | null; released: number; kind?: string | null } +/** + * What a reservation is for, recorded with it so a busy refusal names its + * holders (#3461). A label only: no path, brain or process identity. + */ +export type MaintenanceTempKind = "index" | "scratch_query" | "git" | "sync" | "probe" | "command"; +const KIND_LABELS: Record = { + index: "index", scratch_query: "scratch query", git: "git", sync: "sync", probe: "probe", command: "command", +}; +const kindLabel = (kind: string | null | undefined) => kind && Object.hasOwn(KIND_LABELS, kind) ? KIND_LABELS[kind as MaintenanceTempKind] : "unlabelled"; /** Internal trusted operational-state identity, never repository-selected. */ export interface MaintenanceTempDomain { statePath: string } export interface MaintenanceTempReservation { @@ -121,6 +130,13 @@ function connect(file: string): Database { const db = new Database(file, { strict: true }); try { db.exec("PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS reservations (id TEXT PRIMARY KEY, bytes INTEGER NOT NULL, owner TEXT NOT NULL, worker TEXT, released INTEGER NOT NULL DEFAULT 0)"); + // A ledger an earlier release created has no holder kind; its rows and + // an earlier writer's inserts stay valid with the column absent (#3461). + const columns = db.query("PRAGMA table_info(reservations)").all() as { name: string }[]; + if (!columns.some(column => column.name === "kind")) { + try { db.exec("ALTER TABLE reservations ADD COLUMN kind TEXT"); } + catch (error) { if (!String(error).includes("duplicate column")) throw error; } + } return db; } catch (error) { db.close(); throw error; } } @@ -159,8 +175,55 @@ function prune(db: Database): Entry[] { }); } +/** + * A maintenance-temp admission refusal: nothing ran. Its message and + * `holders` name what holds the budget by kind only (#3461), and `freed()` + * settles once this command's allowance would fit again, so an automatic + * caller can keep its work pending instead of failing it. + */ +export class MaintenanceTempBusyError extends WorkerStateError { + constructor(message: string, readonly holders: readonly string[], private readonly capacity: () => boolean) { + super(FIRST_PARTY_FAILURE_CLASSES.worker_state_busy, message); + this.name = "WorkerStateError"; + } + /** Resolves when the budget can take this allowance again; rejects with the signal's reason. */ + freed(signal?: AbortSignal): Promise { return waitFor(this.capacity, signal); } +} + +/** In-process releases wake waiters at once; another process's release is found by the bounded recheck. */ +const releaseWaiters = new Set<() => void>(); +const RECHECK_MIN_MS = 250, RECHECK_MAX_MS = 2_000; +function waitFor(capacity: () => boolean, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + let timer: ReturnType | undefined; + let delay = RECHECK_MIN_MS; + const finish = (error?: unknown) => { + releaseWaiters.delete(check); if (timer) clearTimeout(timer); + signal?.removeEventListener("abort", aborted); + if (error === undefined) resolve(); else reject(error); + }; + const aborted = () => finish(signal!.reason); + const check = () => { + if (timer) { clearTimeout(timer); timer = undefined; } + let fits: boolean; + try { fits = capacity(); } catch (error) { finish(error); return; } + if (fits) { finish(); return; } + timer = setTimeout(check, delay); delay = Math.min(delay * 2, RECHECK_MAX_MS); + }; + if (signal?.aborted) { reject(signal.reason); return; } + signal?.addEventListener("abort", aborted, { once: true }); + releaseWaiters.add(check); + check(); + }); +} +function holderSummary(entries: readonly Entry[]): string[] { + const counts = new Map(); + for (const entry of entries) { const label = kindLabel(entry.kind); counts.set(label, (counts.get(label) ?? 0) + 1); } + return [...counts].map(([label, count]) => count === 1 ? label : `${label} ×${count}`); +} + /** Immediate atomic admission, shared by server, cron and recreated backends. */ -export function reserveMaintenanceTemp(configured: WorkerStateLimits, domain?: MaintenanceTempDomain): MaintenanceTempReservation { +export function reserveMaintenanceTemp(configured: WorkerStateLimits, domain?: MaintenanceTempDomain, kind: MaintenanceTempKind = "command"): MaintenanceTempReservation { const limits = resolveMaintenanceTempLimits(configured); const shared = domain ? sharedState(domain) : undefined; const path = shared?.parent ?? directory(); @@ -171,12 +234,21 @@ export function reserveMaintenanceTemp(configured: WorkerStateLimits, domain?: M const entries = prune(db); const held = entries.reduce((total, entry) => total + BigInt(entry.bytes), 0n); if (held + BigInt(limits.allowanceBytes) > BigInt(limits.budgetBytes)) { - throw new WorkerStateError(FIRST_PARTY_FAILURE_CLASSES.worker_state_busy, + const holders = holderSummary(entries); + throw new MaintenanceTempBusyError( `Maintenance temporary storage is busy: this command needs ${mib(limits.allowanceBytes)}, ` - + `${entries.length} maintenance reservations hold ${mib(Number(held))} of the separate ${mib(limits.budgetBytes)} budget. ` - + "Nothing ran. Retry after a maintenance command finishes; no agent runtime state was lost."); + + `${entries.length} maintenance reservations hold ${mib(Number(held))} of the separate ${mib(limits.budgetBytes)} budget` + + `${holders.length ? ` (held by: ${holders.join(", ")})` : ""}. ` + + "Nothing ran. Retry after a maintenance command finishes; no agent runtime state was lost.", + holders, () => { + const db = ledger(path, selected); + return db.transaction(() => { + const current = prune(db).reduce((total, entry) => total + BigInt(entry.bytes), 0n); + return current + BigInt(limits.allowanceBytes) <= BigInt(limits.budgetBytes); + }).immediate(); + }); } - db.query("INSERT INTO reservations (id, bytes, owner) VALUES (?, ?, ?)").run(id, limits.allowanceBytes, JSON.stringify(identity())); + db.query("INSERT INTO reservations (id, bytes, owner, kind) VALUES (?, ?, ?, ?)").run(id, limits.allowanceBytes, JSON.stringify(identity()), kind); }).immediate(); let released = false; return { id, directory: path, ...(selected ?? {}), release() { @@ -187,6 +259,7 @@ export function reserveMaintenanceTemp(configured: WorkerStateLimits, domain?: M prune(db); }).immediate(); released = true; + for (const wake of [...releaseWaiters]) wake(); } }; } diff --git a/packages/ui-sdk/src/server/maintenance-worker.ts b/packages/ui-sdk/src/server/maintenance-worker.ts index e1225273d6..f2f6d2d4ef 100644 --- a/packages/ui-sdk/src/server/maintenance-worker.ts +++ b/packages/ui-sdk/src/server/maintenance-worker.ts @@ -20,7 +20,7 @@ import { MAINTENANCE_HOME, MAINTENANCE_XDG_DIRS, launchAgentWorkerSteps, workerB import { WorkerIdentityCleanupError, workerCleanupUnconfirmed, workerIdentityHelper } from "./worker-identity.js"; import { createWorkerStartupView, retainWorkerStartupView, type WorkerStartupView } from "./worker-startup-view.js"; import { hostMaintenanceTempLimits } from "./maintenance-temp-limits.js"; -import { reserveMaintenanceTemp, type MaintenanceTempDomain } from "./maintenance-temp-budget.js"; +import { reserveMaintenanceTemp, type MaintenanceTempDomain, type MaintenanceTempKind } from "./maintenance-temp-budget.js"; import { OUTPUT_STAGING_BYTES_ENV, resolveMaintenanceTempLimits, type WorkerStateLimits } from "./worker-state-limits.js"; import { WorkerStateError } from "./worker-state-budget.js"; import { HOST_GIT_CREDENTIAL_ENV } from "./subprocess-env.js"; @@ -37,6 +37,8 @@ export interface MaintenanceCommand { tempLimits?: WorkerStateLimits; /** Existing host operational-state identity; absent standalone callers use their private domain. */ tempDomain?: MaintenanceTempDomain; + /** What the reservation is for, named by a busy refusal (#3461); default `command`. */ + tempKind?: MaintenanceTempKind; brainPath: string; startupView?: WorkerStartupView; /** Host-chosen output workspace; never mounted over the configuration view. */ @@ -260,7 +262,7 @@ export function launchMaintenanceWorkerAsync(input: MaintenanceCommand): Promise function* launchMaintenanceWorkerSteps(input: MaintenanceCommand): WorkerSteps { const limits = input.tempLimits ? resolveMaintenanceTempLimits(input.tempLimits) : hostMaintenanceTempLimits(); - const reservation = reserveMaintenanceTemp(limits, tempDomain(input)); + const reservation = reserveMaintenanceTemp(limits, tempDomain(input), input.tempKind); let startupView: WorkerStartupView | undefined; let pipes: ReturnType | undefined; let child: ReturnType | undefined; @@ -426,7 +428,7 @@ export async function probeNativeMaintenanceWorker(brainPath: string, tempLimits try { outputs = await prepareNativeWorkerOutput(realpathSync(brainPath), { startupView, signal }); const result = await runMaintenanceWorker({ brainPath, startupView: outputs.view, output: { ...outputs.output, target: "/tmp/brain-maintenance-output" }, - command: ["/bin/sh", "-c", 'printf "qualified" > "$BRAIN_ROOT/.brain-maintenance-probe"'], env: { PATH: "/usr/bin:/bin" }, credentials: false, + command: ["/bin/sh", "-c", 'printf "qualified" > "$BRAIN_ROOT/.brain-maintenance-probe"'], env: { PATH: "/usr/bin:/bin" }, credentials: false, tempKind: "probe", ...(tempLimits ? { tempLimits } : {}), ...(tempDomain ? { tempDomain } : {}), signal, timeoutMs: 5_000 }); if (result.exitCode === 0) return { ok: true }; return { ok: false, requirement: `a credential-free maintenance worker could not start (${result.stderr.trim().slice(0,300) || `exit ${result.exitCode}`})` }; @@ -449,12 +451,12 @@ const EMPTY_REPOSITORY = "/tmp/brain-empty-repository"; * trusts the brain it serves. `emptyRepository` asks through a fresh empty * repository inside the worker, for a brain outside any repository. */ -export function brainGitSync(brain: string, args: readonly string[], options: { emptyRepository?: boolean; timeoutMs?: number } & MaintenanceHost = {}): number { +export function brainGitSync(brain: string, args: readonly string[], options: { emptyRepository?: boolean; timeoutMs?: number; tempKind?: MaintenanceTempKind } & MaintenanceHost = {}): number { return runWorkerStepsSync(brainGitSteps(brain, args, options)); } /** `brainGitSync` as steps, for a caller that can await the worker (#2416). */ -export function* brainGitSteps(brain: string, args: readonly string[], options: { emptyRepository?: boolean; timeoutMs?: number } & MaintenanceHost = {}): WorkerSteps { +export function* brainGitSteps(brain: string, args: readonly string[], options: { emptyRepository?: boolean; timeoutMs?: number; tempKind?: MaintenanceTempKind } & MaintenanceHost = {}): WorkerSteps { const git = Bun.which("git"); if (!git) return 127; const root = realpathSync(brain); @@ -473,7 +475,7 @@ export function* brainGitSteps(brain: string, args: readonly string[], options: : [git, ...safe, ...args]; try { return (yield* runMaintenanceWorkerSteps({ ...options, brainPath: brain, command, ...(parent ? { readPaths: [parent] } : {}), env: { PATH: [dirname(git), "/usr/bin:/bin"].join(":"), GIT_DISCOVERY_ACROSS_FILESYSTEM: "1" }, - credentials: false, timeoutMs: options.timeoutMs ?? 10_000 })).exitCode; + credentials: false, tempKind: options.tempKind ?? "git", timeoutMs: options.timeoutMs ?? 10_000 })).exitCode; } catch (error) { if (error instanceof WorkerStateError) throw error; return 127; } } @@ -488,7 +490,7 @@ export function probeMaintenanceWorker(brainPath: string, tempLimits?: WorkerSta outputs = prepareWorkerOutput(realpathSync(brainPath), { startupView }); const result = runMaintenanceWorkerSync({ brainPath, startupView: outputs.view, output: outputs.output, command: ["/bin/sh", "-c", 'printf "qualified" > "$BRAIN_ROOT/.brain-maintenance-probe"'], env: { PATH: "/usr/bin:/bin" }, - credentials: false, ...(tempLimits ? { tempLimits } : {}), ...(tempDomain ? { tempDomain } : {}), timeoutMs: 5_000 }); + credentials: false, tempKind: "probe", ...(tempLimits ? { tempLimits } : {}), ...(tempDomain ? { tempDomain } : {}), timeoutMs: 5_000 }); if (result.exitCode === 0) return { ok: true }; return { ok: false, requirement: `a credential-free maintenance worker could not start (${result.stderr.trim().slice(0, 300) || `exit ${result.exitCode}`})` }; } catch (error) { @@ -507,7 +509,7 @@ export function runMaintenanceWorkerSync(input: MaintenanceCommand & { timeoutMs function* runMaintenanceWorkerSteps(input: MaintenanceCommand & { timeoutMs: number }): WorkerSteps { const limits = input.tempLimits ? resolveMaintenanceTempLimits(input.tempLimits) : hostMaintenanceTempLimits(); - const reservation = reserveMaintenanceTemp(limits, tempDomain(input)); + const reservation = reserveMaintenanceTemp(limits, tempDomain(input), input.tempKind); let startupView: WorkerStartupView | undefined; let pipes: ReturnType | undefined; try { diff --git a/packages/ui-sdk/src/server/worker-sandbox.ts b/packages/ui-sdk/src/server/worker-sandbox.ts index 02a7fc0963..d0ec81d370 100644 --- a/packages/ui-sdk/src/server/worker-sandbox.ts +++ b/packages/ui-sdk/src/server/worker-sandbox.ts @@ -411,12 +411,12 @@ function* scratchIgnoredByGit(brain: string, maintenance?: import("./maintenance const own = Boolean(lstatSync(join(brain, ".git"), { throwIfNoEntry: false })); if (!own) { if (!git) return true; - const inRepo = yield* brainGitSteps(brain, ["rev-parse", "--git-dir"], maintenance); + const inRepo = yield* brainGitSteps(brain, ["rev-parse", "--git-dir"], { ...maintenance, tempKind: "scratch_query" }); if (inRepo === 127) return { refused: "git could not run to confirm .brain/scratch/ is gitignored" }; if (inRepo !== 0) return true; } if (!git) return { refused: "git is not available to confirm .brain/scratch/ is gitignored" }; - const exitCode = yield* brainGitSteps(brain, ["check-ignore", "-q", "--no-index", "--", BRAIN_SCRATCH_DIR], maintenance); + const exitCode = yield* brainGitSteps(brain, ["check-ignore", "-q", "--no-index", "--", BRAIN_SCRATCH_DIR], { ...maintenance, tempKind: "scratch_query" }); if (exitCode === 0) return true; return { refused: exitCode === 1 ? ".brain/scratch/ is not gitignored, so a file written there could be committed; run `brain doctor --fix` outside a hosted turn" diff --git a/packages/ui-sdk/tests/maintenance-temp-holders.test.ts b/packages/ui-sdk/tests/maintenance-temp-holders.test.ts new file mode 100644 index 0000000000..68f3a258d4 --- /dev/null +++ b/packages/ui-sdk/tests/maintenance-temp-holders.test.ts @@ -0,0 +1,106 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { MaintenanceTempBusyError, reserveMaintenanceTemp, type MaintenanceTempReservation } from "../src/server/maintenance-temp-budget"; +import { prepareWorkerSandboxAsync } from "../src/server/worker-launcher"; +import { FIRST_PARTY_FAILURE_CLASSES } from "../src/protocol"; + +// #3461: production limits (one 256 MiB allowance in a 256 MiB budget) on a +// private shared-state domain, so no other test's ledger is involved. +const LIMITS = { allowanceBytes: 268435456, budgetBytes: 268435456 }; +let root: string; +let domain: { statePath: string }; +const held: MaintenanceTempReservation[] = []; +beforeEach(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), "odysseus-maintenance-holders-"))); + mkdirSync(join(root, "state")); + domain = { statePath: join(root, "state", "ui.db") }; +}); +afterEach(() => { + for (const reservation of held.splice(0)) reservation.release(); + rmSync(root, { recursive: true, force: true }); +}); +const hold = (kind: Parameters[2]) => { + const reservation = reserveMaintenanceTemp(LIMITS, domain, kind); held.push(reservation); return reservation; +}; +const refusal = (kind: Parameters[2] = "index") => { + try { held.push(reserveMaintenanceTemp(LIMITS, domain, kind)); } catch (error) { return error; } + throw Error("admission unexpectedly succeeded"); +}; + +test("a busy refusal names its holders by kind, without paths or identities", () => { + hold("scratch_query"); + const error = refusal() as MaintenanceTempBusyError; + expect(error, "MAINTENANCE_BUSY_IS_A_TYPED_REFUSAL").toBeInstanceOf(MaintenanceTempBusyError); + expect(error.errorClass, "MAINTENANCE_BUSY_KEEPS_WORKER_STATE_BUSY").toBe(FIRST_PARTY_FAILURE_CLASSES.worker_state_busy); + expect(error.name, "MAINTENANCE_BUSY_KEEPS_ITS_SERIALIZED_CLASS_NAME").toBe("WorkerStateError"); + expect(error.holders, "MAINTENANCE_BUSY_NAMES_HOLDER_KIND").toEqual(["scratch query"]); + expect(error.message, "MAINTENANCE_BUSY_MESSAGE_NAMES_HOLDER_KIND").toBe("Maintenance temporary storage is busy: this command needs 256 MiB, " + + "1 maintenance reservations hold 256 MiB of the separate 256 MiB budget (held by: scratch query). " + + "Nothing ran. Retry after a maintenance command finishes; no agent runtime state was lost."); + expect(error.message.includes(root), "MAINTENANCE_BUSY_MESSAGE_HAS_NO_PATH").toBe(false); + expect(error.message.includes(String(process.pid)), "MAINTENANCE_BUSY_MESSAGE_HAS_NO_PROCESS_IDENTITY").toBe(false); +}); + +test("several holders are counted per kind", () => { + const limits = { allowanceBytes: 4096, budgetBytes: 4096 * 3 }; + for (const kind of ["git", "sync", "git"] as const) held.push(reserveMaintenanceTemp(limits, domain, kind)); + let error: MaintenanceTempBusyError | undefined; + try { held.push(reserveMaintenanceTemp(limits, domain, "index")); } catch (caught) { error = caught as MaintenanceTempBusyError; } + expect(error?.holders, "MAINTENANCE_BUSY_COUNTS_HOLDERS_PER_KIND").toEqual(["git ×2", "sync"]); +}); + +test("a ledger an earlier release created gains the kind column and labels its rows unlabelled", () => { + // The ledger an earlier release creates for this state identity, with one live row of its own. + const statePath = domain.statePath; + const file = join(root, "state", `.brain-maintenance-${createHash("sha256").update(statePath).digest("hex").slice(0, 24)}.db`); + const legacy = new Database(file); + try { + legacy.exec("CREATE TABLE reservations (id TEXT PRIMARY KEY, bytes INTEGER NOT NULL, owner TEXT NOT NULL, worker TEXT, released INTEGER NOT NULL DEFAULT 0)"); + const stat = readFileSync("/proc/self/stat", "utf8"), fields = stat.slice(stat.lastIndexOf(")") + 2).split(" "); + const owner = { pid: process.pid, start: fields[19], boot: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), namespace: readlinkSync("/proc/self/ns/pid") }; + legacy.query("INSERT INTO reservations (id, bytes, owner) VALUES (?, ?, ?)").run("legacy-row", LIMITS.allowanceBytes, JSON.stringify(owner)); + } finally { legacy.close(); } + chmodSync(file, 0o600); + expect((refusal() as MaintenanceTempBusyError).holders, "LEGACY_LEDGER_ROWS_ARE_UNLABELLED").toEqual(["unlabelled"]); + const db = new Database(file); + try { + expect((db.query("PRAGMA table_info(reservations)").all() as { name: string }[]).map(column => column.name), "LEGACY_LEDGER_GAINS_KIND_COLUMN").toContain("kind"); + db.query("DELETE FROM reservations WHERE id = 'legacy-row'").run(); + } finally { db.close(); } +}); + +test("freed() settles on an in-process release and rejects with its signal's reason", async () => { + const holder = hold("scratch_query"); + const error = refusal() as MaintenanceTempBusyError; + let settled = false; + const freed = error.freed().then(() => { settled = true; }); + await Promise.resolve(); + expect(settled, "MAINTENANCE_FREED_WAITS_WHILE_HELD").toBe(false); + holder.release(); + await freed; + expect(settled, "MAINTENANCE_FREED_SETTLES_ON_RELEASE").toBe(true); + + hold("scratch_query"); + const again = refusal() as MaintenanceTempBusyError; + const ending = new AbortController(), reason = new Error("Server shutting down"); + const waiting = again.freed(ending.signal); + ending.abort(reason); + await expect(waiting, "MAINTENANCE_FREED_ENDS_WITH_ITS_SIGNAL").rejects.toBe(reason); +}); + +test("opposite order: a turn's scratch check refused while an index holds the budget stays read-only and names the index", async () => { + const brain = join(root, "brain"); + mkdirSync(brain); + hold("index"); + const sandbox = await prepareWorkerSandboxAsync(brain, { areas: ["scratch"], maintenance: { tempLimits: LIMITS, tempDomain: domain } }); + const scratch = sandbox.areas.find(area => area.name === "scratch"); + expect(scratch?.mount.writable, "TURN_SCRATCH_CHECK_LOSES_TO_HELD_INDEX").toBe(false); + const reason = scratch?.mount.writable === false ? scratch.mount.reason : ""; + expect(reason, "TURN_SCRATCH_CHECK_KEEPS_ITS_DOCUMENTED_OUTCOME") + .toStartWith(".brain/scratch/ could not be checked (Maintenance temporary storage is busy: "); + expect(reason, "TURN_SCRATCH_CHECK_NAMES_THE_INDEX_HOLDER").toContain("(held by: index)"); +}); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 7329d53e0c..eefb728b3f 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -139,7 +139,7 @@ import { validateBackendVersionRequirements, type BackendRegistry, } from "./agent/backend.js"; -import { createBrainClient, probeBrainCliVersion } from "./brain/client.js"; +import { createBrainClient, probeBrainCliVersion, requeueWhenBusy } from "./brain/client.js"; import { boundaryPlanner } from "./brain/application.js"; import { createIndexBatch } from "./brain/index-batch.js"; import { INDEX_READ_ROUTES, indexReadBarrier } from "./routes/index-barrier.js"; @@ -542,9 +542,11 @@ export async function createApp(options: CreateAppOptions = {}): Promise { if (error !== shutdown.signal.reason) throw error; }; - const keyedReindex = coalesced(() => brain.index().catch(ignoreShutdown), error => brainLog.emit({ severityText: "WARN", + // A refresh cancelled by close(), or still pending for maintenance + // admission when close() begins (#3461), is not a failure; every other + // error still reports. + const ignoreShutdown = (error: unknown) => { if (error !== shutdown.signal.reason && error !== closeBegun.signal.reason) throw error; }; + const keyedReindex = coalesced(() => brain.index(requeueWhenBusy({})).catch(ignoreShutdown), error => brainLog.emit({ severityText: "WARN", body: `the keyed reindex after an application failed: ${error instanceof Error ? error.message : String(error)}` })); bootCleanup.push(() => keyedReindex.idle()); // A migrating brain rebuilds its index in the new directory once, at boot, @@ -636,7 +638,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise governedRecords("recordPolicy", turnId, origin, profile, policy.hash, policy.source, JSON.stringify(policy.policy), JSON.stringify(policy.errors), Date.now()), maskPaths: turnMaskPaths, - index: lock => brain.index({ lock }).catch(ignoreShutdown), report: message => brainLog.emit({ severityText: "WARN", body: message }), + index: lock => brain.index(requeueWhenBusy({ lock })).catch(ignoreShutdown), report: message => brainLog.emit({ severityText: "WARN", body: message }), exposures: createProviderExposures(db, writer), ...(config.providerRecipientOrigins ? { recipientOrigins: config.providerRecipientOrigins } : {}), indexBatch }); bootCleanup.push(() => governedTurns.close()); // Budget writes commit on the write worker (#2850). diff --git a/packages/ui-server/src/brain/client.ts b/packages/ui-server/src/brain/client.ts index 9129f956bb..234cfb6f21 100644 --- a/packages/ui-server/src/brain/client.ts +++ b/packages/ui-server/src/brain/client.ts @@ -2,7 +2,7 @@ import { existsSync } from "fs"; import { join } from "path"; import type { Logger } from "@opentelemetry/api-logs"; import { ambientExecConfig, subprocessEnv } from "../config/env.js"; -import { VERSION_PROBE_TIMEOUT_MS } from "@schlessera/brain-ui-sdk/internal"; +import { MaintenanceTempBusyError, VERSION_PROBE_TIMEOUT_MS } from "@schlessera/brain-ui-sdk/internal"; import { probeVersionCommand, assertVersionRequirements, @@ -86,6 +86,17 @@ export interface BrainClient { storagePack?(opts?: MaintenanceRequest): Promise; } +type IndexOptions = NonNullable[0]>; +const requeued = new WeakSet(); +/** + * First-party wiring only, not exported by the package: options marked here + * make an automatic index refused at maintenance admission, because the + * budget is busy, stay pending and run again once the budget frees instead of + * failing (#3461). `close()` beginning ends the wait. A requested index + * passes unmarked options and still reports busy at once. + */ +export function requeueWhenBusy(opts: T): T { requeued.add(opts); return opts; } + interface ExecResult { stdout: string; stderr: string; @@ -261,6 +272,9 @@ export function createBrainClient(opts: BrainClientOptions): BrainClient { const exec = opts.exec ?? ambientExecConfig(); const boundary = opts.boundary ?? createHostBoundary({ brainPath, exec }); const minimumVersion = opts.minimumVersion; + // A pending automatic index is discarded, not run, once close() begins (#3461). + const ends = [opts.closing, opts.shutdown].filter((signal): signal is AbortSignal => signal !== undefined); + const requeueEnds = ends.length > 1 ? AbortSignal.any(ends) : ends[0]; if (minimumVersion !== undefined) validateVersionMinimum(minimumVersion, "host versionRequirements.brainCli", "brain CLI during client construction"); const log = opts.log ?? { emit() {}, enabled: () => false }; const searchTimeoutMs = opts.searchTimeoutMs ?? SEARCH_TIMEOUT_MS; @@ -296,6 +310,7 @@ export function createBrainClient(opts: BrainClientOptions): BrainClient { credentials, gate, purpose: `brain ${args.slice(0, 2).join(" ")}`, + ...(args[0] === "index" ? { maintenanceKind: "index" as const } : args[0] === "storage" ? { maintenanceKind: "git" as const } : {}), admissionSignal: maintenance?.admissionSignal, ...(args[0] === "sync" ? { sync: true } : {}), ...(lock ? { lock: { keyed: lock, key: "brain-docs" } } : {}), @@ -475,7 +490,18 @@ export function createBrainClient(opts: BrainClientOptions): BrainClient { // Full rebuild; indexing is incremental by default since brain 22e82e1. if (opts?.force) args.push("--force"); - const result = await execBrain(args, undefined, undefined, opts?.lock); + let result: ExecResult; + for (;;) { + try { result = await execBrain(args, undefined, undefined, opts?.lock); break; } + catch (error) { + // Nothing ran: admission refused before the worker started. Only an + // automatic caller waits; a requested index still reports busy. + if (!opts || !requeued.has(opts) || !(error instanceof MaintenanceTempBusyError)) throw error; + log.emit({ severityText: "INFO", body: "automatic index pending: maintenance temporary storage is busy; it runs when the budget frees", + attributes: { holders: error.holders.join(", ") } }); + await error.freed(requeueEnds); + } + } if (result.exitCode !== 0) { throw new Error(`brain index failed: ${result.stderr}`); } diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 50c6ea79f4..92e6626fb2 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -27,7 +27,7 @@ import { isAbsolute, join, resolve } from "node:path"; import type { Logger } from "@opentelemetry/api-logs"; import { WorkerStateError, workerIdentityHelper, CREDENTIAL_FREE_ENV, HOST_GIT_CREDENTIAL_ENV, execWrapperSpawnOptions, prepareMaintenanceWorker, launchMaintenanceWorkerAsync, probeNativeMaintenanceWorker, restrictedReadPaths, runMaintenanceWorker, workerHostBoundary, - runMaintenanceWorkerSync, workerHostProven, hostMaintenanceTempLimits, resolveMaintenanceTempLimits, type WorkerStateLimits, type MaintenanceCommand, type WorkerHostProbe, + type MaintenanceTempKind, runMaintenanceWorkerSync, workerHostProven, hostMaintenanceTempLimits, resolveMaintenanceTempLimits, type WorkerStateLimits, type MaintenanceCommand, type WorkerHostProbe, prepareNativeWorkerStartupView, hasManagedNativeStorage, type WorkerStartupView, acquireHostCredentialExclusion, type HostCredentialDomain, startProviderRelay, relayedProviderKeys, hostProviderCredential, type ProviderRelay, type ProviderRelayReceipt, @@ -87,6 +87,8 @@ export interface BrainExecution { lock?: { keyed: import("@schlessera/brain-ui-sdk/server").KeyedLock; key: string }; /** @internal The turn whose tool started this run: its relayed provider spend is charged there (#1673). */ turnId?: string; + /** @internal What its maintenance reservation is for, named by a busy refusal (#3461). Default `sync` for a sync, else `command`. */ + maintenanceKind?: MaintenanceTempKind; } export interface ExecutionResult { @@ -456,6 +458,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { brainPath: brain, ...(startupView ? { startupView } : {}), tempLimits: maintenanceTemp, + tempKind: ("maintenanceKind" in execution && execution.maintenanceKind) || ("sync" in execution && execution.sync ? "sync" : "command"), ...("outputBytes" in execution && execution.outputBytes ? { outputBytes: execution.outputBytes } : {}), ...(tempDomain ? { tempDomain } : {}), // The operator's exec wrapper runs inside the worker, as it does for agent workers. diff --git a/packages/ui-server/src/brain/maintenance-git.ts b/packages/ui-server/src/brain/maintenance-git.ts index 01b924e5f5..d81f906439 100644 --- a/packages/ui-server/src/brain/maintenance-git.ts +++ b/packages/ui-server/src/brain/maintenance-git.ts @@ -30,7 +30,7 @@ export async function privateGitSources(command: MaintenanceCommand, outputs: Aw }; validate(); const entry = Bun.resolveSync("./maintenance-git-source", import.meta.dir), maximum = storage.allowanceBytes; - const result = await runMaintenanceWorker({ ...command, startupView: view, output: undefined, git: undefined, + const result = await runMaintenanceWorker({ ...command, tempKind: "git", startupView: view, output: undefined, git: undefined, command: [process.execPath, "--config=/dev/null", "--no-env-file", entry, binary ?? "", String(maximum), expectedRoot], readPaths: [...(command.readPaths ?? []), entry, ...(binary ? [binary] : [])], network: false, timeoutMs: 30000, ...(signal ? { signal } : {}) }); validate(); @@ -59,7 +59,7 @@ export async function prepareMaintenanceGit(command: MaintenanceCommand, outputs let config: [string, string][]; if (privateInputs) config = privateInputs.config; else { - const result = await runMaintenanceWorker({ ...command, startupView: outputs.view, + const result = await runMaintenanceWorker({ ...command, tempKind: "git", startupView: outputs.view, command: [binary, "-c", `safe.directory=${command.brainPath}`, "config", "--null", "--list", "--includes"], network: false, timeoutMs: 5000, ...(signal ? { signal } : {}) }); if (result.exitCode !== 0 || result.killed) throw new Error(`cannot freeze Git configuration: ${result.stderr.slice(-400)}`); config = result.stdout.split("\0").filter(Boolean).map(record => { const separator = record.indexOf("\n"); @@ -105,7 +105,7 @@ export async function prepareMaintenanceGit(command: MaintenanceCommand, outputs const directories = new Set(attributes.flatMap(({ path }) => path.split("/").slice(0, -1).map((_, index, parts) => parts.slice(0, index + 1).join("/")))); const freezer = Bun.resolveSync("./maintenance-git-attributes", import.meta.dir); await refreshInput(); - const answer = await runMaintenanceWorker({ ...command, startupView: outputs.view, output: outputs.output, git: spec, + const answer = await runMaintenanceWorker({ ...command, tempKind: "git", startupView: outputs.view, output: outputs.output, git: spec, command: [process.execPath, "--config=/dev/null", "--no-env-file", freezer, entry], stdin: JSON.stringify(attributes), readPaths: [...(command.readPaths ?? []), freezer], network: false, timeoutMs: 5000 * (1 + attributes.length + (attributes.length ? 1 + directories.size : 0)), ...(signal ? { signal } : {}) }); diff --git a/packages/ui-server/src/brain/reference-transport.ts b/packages/ui-server/src/brain/reference-transport.ts index ddc6260ad0..3d3b282582 100644 --- a/packages/ui-server/src/brain/reference-transport.ts +++ b/packages/ui-server/src/brain/reference-transport.ts @@ -108,7 +108,7 @@ export function createReferenceTransport(options: { // The credential value exists only in this network transport's environment. if (input.token) env.BRAIN_REFERENCE_TOKEN = input.token; const readPaths = input.repository?.scheme === "file" ? [input.repository.url.slice("file://".length)] : []; - return { brainPath: options.brainPath, credentials: input.network, env, command: [...UMASK, ...input.argv], + return { brainPath: options.brainPath, credentials: input.network, env, command: [...UMASK, ...input.argv], tempKind: "git", ...(options.tempLimits ? { tempLimits: options.tempLimits } : {}), ...(options.tempDomain ? { tempDomain: options.tempDomain } : {}), transport: { mirror: input.mirror, readPaths, network: input.network }, ...(input.signal ? { signal: input.signal } : {}), timeoutMs }; } diff --git a/packages/ui-server/src/brain/scratch-mask-query.ts b/packages/ui-server/src/brain/scratch-mask-query.ts index 242563ae9a..5efaa93841 100644 --- a/packages/ui-server/src/brain/scratch-mask-query.ts +++ b/packages/ui-server/src/brain/scratch-mask-query.ts @@ -34,7 +34,7 @@ export function createScratchIgnoreQuery(input: { try { // Read-only consumers still share the maintenance temporary budget. // Serialize with its existing owner, without creating or publishing a stage. - const result = await runMaintenanceWorker({ ...input.maintenance, brainPath: brain, startupView: view, + const result = await runMaintenanceWorker({ ...input.maintenance, tempKind: "scratch_query", brainPath: brain, startupView: view, command, env: { PATH: `${dirname(git)}:/usr/bin:/bin`, GIT_DISCOVERY_ACROSS_FILESYSTEM: "1" }, credentials: false, readPaths: [git, ...(parent ? [parent] : [])], signal, timeoutMs: 10_000 }); return { exitCode: result.exitCode, killed: result.killed }; diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index 9b0eb74464..cbd67e99a5 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -74,7 +74,7 @@ function prepareMirror(mirror: string, brain: string): void { async function origin(command: MaintenanceCommand): Promise { const git = Bun.which("git", { PATH: "/usr/bin:/bin" }); if (!git) throw new Error("host sync needs system git"); - const result = await runMaintenanceWorker({ ...command, command: [git, "config", "--local", "--no-includes", "--get", "remote.origin.url"], + const result = await runMaintenanceWorker({ ...command, tempKind: "sync", command: [git, "config", "--local", "--no-includes", "--get", "remote.origin.url"], credentials: false, timeoutMs: 10_000 }); if (result.killed) throw new Error("reading the host sync remote timed out"); // No configured remote means there is no credentialed transport. Run the @@ -117,7 +117,7 @@ export function syncTransportCommand(input: { brain: string; mirror: string; rem if (token) env.BRAIN_SYNC_TOKEN = token; } } - return { brainPath: input.brain, credentials: true, env, + return { brainPath: input.brain, credentials: true, tempKind: "sync", env, ...(input.tempLimits ? { tempLimits: input.tempLimits } : {}), ...(input.tempDomain ? { tempDomain: input.tempDomain } : {}), command: [git, "--git-dir", input.mirror, "-c", "credential.helper=", "-c", `credential.helper=${CREDENTIAL_HELPER}`, @@ -134,7 +134,7 @@ async function runLocalSync(command: MaintenanceCommand & { signal?: AbortSignal command.signal?.throwIfAborted(); outputs = await prepareMaintenanceOutput(command.brainPath, { startupView: view, folderPaths, signal: command.signal }); const git = await prepareMaintenanceGit(command, outputs, command.signal, log); - const result = await runMaintenanceWorker({ ...command, startupView: outputs.view, output: outputs.output, ...(git ? { git } : {}) }); + const result = await runMaintenanceWorker({ ...command, tempKind: "sync", startupView: outputs.view, output: outputs.output, ...(git ? { git } : {}) }); if (!result.killed) await outputs.publish(); return result; } finally { try { await outputs?.cleanup(); } finally { await view.cleanup(); } } diff --git a/packages/ui-server/tests/automatic-index-requeue.test.ts b/packages/ui-server/tests/automatic-index-requeue.test.ts new file mode 100644 index 0000000000..8f0e9ce0c7 --- /dev/null +++ b/packages/ui-server/tests/automatic-index-requeue.test.ts @@ -0,0 +1,102 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { MaintenanceTempBusyError, reserveMaintenanceTemp } from "@schlessera/brain-ui-sdk/internal"; +import { createBrainClient, requeueWhenBusy } from "../src/brain/client.js"; +import type { BrainExecution, HostBoundary } from "../src/brain/host-boundary.js"; + +// #3461: the automatic index and a turn's scratch-mask query share one +// maintenance budget. Production limits: one 256 MiB allowance in a 256 MiB +// budget, so the two can never overlap. A private shared-state domain keeps +// this ledger apart from every other test's. +const LIMITS = { allowanceBytes: 268435456, budgetBytes: 268435456 }; +let root: string; +let domain: { statePath: string }; +const held: ReturnType[] = []; +beforeEach(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), "odysseus-index-requeue-"))); + mkdirSync(join(root, "brain")); mkdirSync(join(root, "state")); + domain = { statePath: join(root, "state", "ui.db") }; +}); +afterEach(() => { + for (const reservation of held.splice(0)) reservation.release(); + rmSync(root, { recursive: true, force: true }); +}); + +/** + * A worker boundary whose every run takes the real maintenance admission, as + * `runMaintenanceWorker` does before launch, with the kind the client names. + * Admission is the only part under test; no worker starts. + */ +function admittingBoundary(runs: (string | undefined)[]): HostBoundary { + return { + isolated: () => true, + async run(execution: BrainExecution) { + runs.push(execution.maintenanceKind); + const reservation = reserveMaintenanceTemp(LIMITS, domain, execution.maintenanceKind ?? "command"); + try { return { stdout: "", stderr: "", exitCode: 0 }; } finally { reservation.release(); } + }, + } as unknown as HostBoundary; +} + +/** The hosted proof's own observation of each automatic index (`scripts/native-proof/hosted-app-child.ts`). */ +function observed(index: () => Promise) { + const events: { kind: string; error?: string }[] = []; + const run = async () => { + events.push({ kind: "automatic_index_started" }); + try { await index(); events.push({ kind: "automatic_index_finished" }); } + catch (error) { events.push({ kind: "automatic_index_failed", error: String(error) }); throw error; } + }; + return { events, run }; +} + +function client(runs: (string | undefined)[], closing?: AbortSignal) { + let pending!: () => void; + const refused = new Promise(resolve => { pending = resolve; }); + const logs: { body?: unknown; attributes?: Record }[] = []; + const brain = createBrainClient({ brainPath: join(root, "brain"), exec: {}, boundary: admittingBoundary(runs), ...(closing ? { closing } : {}), + log: { emit(record: { body?: unknown; attributes?: Record }) { logs.push(record); pending(); }, enabled: () => true } as never }); + return { brain, refused, logs }; +} + +test("an automatic index refused while a scratch query holds the budget stays pending, then completes", async () => { + const scratch = reserveMaintenanceTemp(LIMITS, domain, "scratch_query"); held.push(scratch); + const runs: (string | undefined)[] = []; + const { brain, refused, logs } = client(runs); + const automatic = observed(() => brain.index(requeueWhenBusy({}))); + const outcome = automatic.run(); + // Either the refusal is recorded as pending work, or the index has failed. + await Promise.race([refused, outcome.catch(() => {})]); + expect(automatic.events.find(event => event.kind === "automatic_index_failed")?.error, "AUTOMATIC_INDEX_REFUSED_AT_ADMISSION_STAYS_PENDING").toBeUndefined(); + expect(automatic.events.map(event => event.kind), "AUTOMATIC_INDEX_IS_PENDING_WHILE_HELD").toEqual(["automatic_index_started"]); + expect(runs, "AUTOMATIC_INDEX_ADMISSION_WAS_REFUSED_ONCE").toEqual(["index"]); + expect(logs[0]?.attributes?.holders, "AUTOMATIC_INDEX_PENDING_NAMES_THE_HOLDER_KIND").toBe("scratch query"); + scratch.release(); + await outcome; + expect(automatic.events.map(event => event.kind), "AUTOMATIC_INDEX_COMPLETES_ONCE_THE_BUDGET_FREES") + .toEqual(["automatic_index_started", "automatic_index_finished"]); + expect(runs, "AUTOMATIC_INDEX_RUNS_AGAIN_AFTER_RELEASE").toEqual(["index", "index"]); +}); + +test("a requested index still reports busy at once and names the holder kind", async () => { + held.push(reserveMaintenanceTemp(LIMITS, domain, "scratch_query")); + const runs: (string | undefined)[] = []; + const { brain } = client(runs); + const error = await brain.index().then(() => undefined, caught => caught); + expect(error, "REQUESTED_INDEX_IS_NOT_REQUEUED").toBeInstanceOf(MaintenanceTempBusyError); + expect(String(error), "REQUESTED_INDEX_BUSY_NAMES_HOLDER").toContain("(held by: scratch query)"); + expect(runs, "REQUESTED_INDEX_RAN_ONCE").toEqual(["index"]); +}); + +test("close beginning discards a pending automatic index with its own reason", async () => { + held.push(reserveMaintenanceTemp(LIMITS, domain, "scratch_query")); + const runs: (string | undefined)[] = []; + const closing = new AbortController(), reason = new Error("Server shutting down"); + const { brain, refused } = client(runs, closing.signal); + const outcome = brain.index(requeueWhenBusy({})); + await refused; + closing.abort(reason); + await expect(outcome, "PENDING_AUTOMATIC_INDEX_ENDS_WITH_CLOSE").rejects.toBe(reason); + expect(runs, "PENDING_AUTOMATIC_INDEX_DID_NOT_RUN_AGAIN").toEqual(["index"]); +});