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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/identity-setup-progress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@schlessera/brain-ui-sdk": minor
---

**Separate-UID setup timeouts name their last step (#3664).** When a separate-UID worker's identity supervisor misses the 5,000 ms readiness deadline, the refusal's requirement now carries the supervisor's last recorded setup step in its existing parenthetical detail. For example: `worker_identity_setup_timed_out (step: launch-sent, ms: 312, sinceSpawnMs: 340)`. The steps are `started`, `listening`, `launch-sent`, `launch-acked`, `status-read` and `mounts-acked`. `step: none` means no step was recorded. `step: refused (…)` means the record was oversized, a link or malformed, and was not read. Any launch stderr follows the step after a `; `.

The supervisor keeps that one private `0600` record in the server's own `0700` broker directory, which the broker's close removes. The record never reaches the worker. `errorClass` stays `worker_host_unsupported`, and the deadline, every supervisor bound, cleanup and identity verification are unchanged.
2 changes: 1 addition & 1 deletion docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -2513,7 +2513,7 @@ relative to the handle (`function requireWorkerBrainMount`,
The server returns the handle before release, and the coordinator refuses to
release the start gate, or open a second view, while one is held
(`if operation == 'release':`,
`packages/ui-sdk/src/server/worker-identity-program.ts:189-209`).
`packages/ui-sdk/src/server/worker-identity-program.ts:206-226`).

The view grants observation of exactly what the gated worker sees at its own
brain path, and nothing the server cannot already read: the live brain, the
Expand Down
16 changes: 16 additions & 0 deletions docs/integration-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,22 @@ same-commit update of the index or relevant authoritative component. How they ar

The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md).

## Setup timeouts name their step (additive, 0.45.0, #3664)

A separate-UID worker launch that misses its identity readiness deadline still
refuses with `errorClass: "worker_host_unsupported"` and the requirement
`worker_identity_setup_timed_out`. That requirement now always carries a
parenthetical detail, which it never had before. The detail names the
supervisor's last recorded setup step, for example
`(step: launch-sent, ms: 312, sinceSpawnMs: 340)`. The steps are `started`,
`listening`, `launch-sent`, `launch-acked`, `status-read` and `mounts-acked`.
`step: none` means no step was recorded, and `step: refused (…)` means the record
was not read. Any launch stderr follows after `; `, within the existing 400-byte
detail. Requirement text is descriptive and other requirements already carry
such a detail, so no field, class or meaning changes. See
[wire](integration-contract/wire.md) and [the worker-host status](integration-contract/http.md).
This ships in a minor.

## Observed live content map (additive, 0.45.0, #3630)

`ConversationOrientation.knowledge[].topic` additionally accepts `content_map`:
Expand Down
4 changes: 4 additions & 0 deletions docs/integration-contract/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,10 @@ The status reports; it does not decide. A pass is never cached and a known
failure never short-circuits a turn: every turn runs its own probe and refuses
with `worker_host_unsupported` naming the requirement
([maintainer ruling](https://github.com/schlessera/brain-kit/issues/1632#issuecomment-6112509133)).
A requirement may end in a parenthetical detail. When a turn's separate-UID
launch times out during identity setup, its refusal names the supervisor's last
recorded setup step there. The probe's own requirement is unchanged
([additive, #3664](../integration-contract.md#setup-timeouts-name-their-step-additive-0450-3664)).
Clients must tolerate either mode being absent.

<a id="root-server-warning-additive-1638"></a>
Expand Down
4 changes: 4 additions & 0 deletions docs/integration-contract/wire.md
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,10 @@ SessionHistoryMessage.failure?: TurnFailure // on the assistant message the fa
the host refused before runtime initialization because its required worker
boundary probe failed; the message names the requirement and the verified
Linux/qualifying WSL2 route. It creates no backend session or transcript.
The requirement is descriptive text, not an enumerated value; it may carry a
parenthetical detail. A separate-UID setup timeout names the supervisor's last
recorded step there (additive, #3664):
`worker_identity_setup_timed_out (step: launch-sent, ms: 312, sinceSpawnMs: 340)`.
`worker_resource_limit` (#1660) means a host resource limit ended the turn's
worker; the message names the limit, its value and whether an rlimit or the
worker's cgroup enforced it.
Expand Down
17 changes: 17 additions & 0 deletions packages/ui-sdk/src/server/worker-identity-program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,28 @@ export const WORKER_IDENTITY_SUPERVISOR = String.raw`
import array, errno, json, os, select, signal, socket, stat, struct, subprocess, sys, time

MAX_PACKET = 65536
STARTED = time.monotonic()
cfg = json.loads(sys.argv[1])
server_uid = os.getuid()
if server_uid == 0:
raise RuntimeError("worker_identity_server_must_be_nonroot")
def identity(pid):
text = open('/proc/%s/stat' % pid).read().rsplit(') ', 1)[1].split()
return {'pid': pid, 'start': text[19]}
def progress(step):
# Diagnostic only (#3664): the last setup step reached, for a host readiness
# timeout. One private 0600 record in the server's 0700 directory, never the worker's.
path = cfg['ready'] + '.progress'
try:
fd = os.open(path + '.tmp', os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
try: os.write(fd, json.dumps({'step': step, 'ms': int((time.monotonic() - STARTED) * 1000), 'wallMs': int(time.time() * 1000)}, separators=(',', ':')).encode())
finally: os.close(fd)
os.rename(path + '.tmp', path)
except OSError: pass
server = dict(cfg['server'], uid=server_uid)
if identity(server['pid'])['start'] != server['start']:
raise RuntimeError('worker_identity_server_changed')
progress('started')
supervisor = identity(os.getpid())
base = {'version': 1, 'launch': cfg['launch'], 'server': server, 'supervisor': supervisor}
held = {}
Expand Down Expand Up @@ -104,6 +116,7 @@ def cleanup_owned():

listener = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
listener.bind(cfg['socket']); os.chmod(cfg['socket'], 0o600); listener.listen(4)
progress('listening')
status_read, status_write = os.pipe()
gate_read, gate_write = os.pipe()
launch_local, launch_remote = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET)
Expand All @@ -127,9 +140,11 @@ try:
launch_local.sendmsg([json.dumps(dict(base, argv=argv, statusFd=status_write, gateFd=gate_read,
roots=cfg['roots'], keeper=cfg.get('stage', {}).get('keeper'), cgroup=cfg.get('cgroup'),
**({'view': cfg['view']} if cfg.get('view') else {}))).encode()], authority)
progress('launch-sent')
ack, fds = packet(launch_local)
for fd in fds: os.close(fd)
if fds: raise RuntimeError('worker_identity_unexpected_launch_handles')
progress('launch-acked')
if stage_ticket is not None: os.close(stage_ticket); stage_ticket = None
os.close(status_write); os.close(gate_read)
status = b''; deadline = time.monotonic() + 5
Expand All @@ -142,10 +157,12 @@ try:
status += chunk
if len(status) > 4096: raise RuntimeError('worker_identity_malformed_status')
reported = json.loads(status.split(b'\n', 1)[0]).get('child-pid')
progress('status-read')
if type(reported) is not int or reported <= 1: raise RuntimeError('worker_identity_malformed_status')
worker = identity(reported)
answer, descriptors = helper('mounts', {'worker': worker, 'roots': cfg['roots']})
pending = descriptors
progress('mounts-acked')
if len(descriptors) != len(cfg['roots']) or len(answer.get('roots', [])) != len(descriptors):
raise RuntimeError('worker_identity_unexpected_mount_handles')
if type(answer.get('workerUid')) is not int or not 0 < answer['workerUid'] < 0xffffffff or answer['workerUid'] == server_uid:
Expand Down
27 changes: 26 additions & 1 deletion packages/ui-sdk/src/server/worker-identity.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/** Host-only identity broker client. No authority from this module enters a payload. */
import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readFileSync, realpathSync, rmSync, statfsSync } from "node:fs";
import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, rmSync, statfsSync } from "node:fs";
import { isAbsolute, join } from "node:path";
import { tmpdir } from "node:os";
import { workerIdentityHelperInput } from "../config/env.js";
Expand All @@ -15,6 +15,10 @@ export function workerCleanupUnconfirmed(error: unknown): boolean {
return typeof error === "object" && error !== null && "cleanupUnconfirmed" in error && error.cleanupUnconfirmed === true;
}
export interface IdentityRoot { name: "state" | "temp"; path: string; bytes: number }
/** The supervisor's setup steps, in order, as its progress record names them (#3664). */
const SETUP_STEPS = new Set(["started", "listening", "launch-sent", "launch-acked", "status-read", "mounts-acked"]);
/** The largest progress record read; the supervisor writes about 60 bytes. */
const SETUP_PROGRESS_BYTES = 128;
interface Ready { ok: true; workerUid: number; worker: { pid: number; start: string }; roots: Record<string, { fd: number; dev: number; ino: number }> }

/** Resolve only trusted host configuration, never a worker's child environment. */
Expand Down Expand Up @@ -202,6 +206,27 @@ export function prepareWorkerIdentity(helper: string, argv: string[], roots: Ide
try { request("signal", { signal: "KILL" }); }
catch { fallback(["signal"]); }
},
/**
* The supervisor's last recorded setup step, for a readiness timeout's
* detail (#3664). Read before close removes the directory; never follows
* a link, never blocks and never reads more than the bound.
*/
setupProgress(spawnedAt: number): string {
let fd: number | undefined;
try {
fd = openSync(`${readyPath}.progress`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
if (!fstatSync(fd).isFile()) return "step: refused (not a regular file)";
const chunk = Buffer.alloc(SETUP_PROGRESS_BYTES + 1), length = readSync(fd, chunk, 0, chunk.length, 0);
if (length > SETUP_PROGRESS_BYTES) return "step: refused (oversized)";
const record = JSON.parse(chunk.subarray(0, length).toString("utf8")) as { step?: unknown; ms?: unknown; wallMs?: unknown } | null;
if (!record || typeof record.step !== "string" || !SETUP_STEPS.has(record.step) || !Number.isSafeInteger(record.ms) || (record.ms as number) < 0
|| !Number.isSafeInteger(record.wallMs)) return "step: refused (malformed)";
return `step: ${record.step}, ms: ${record.ms as number}, sinceSpawnMs: ${(record.wallMs as number) - spawnedAt}`;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
return code === "ENOENT" ? "step: none" : code === "ELOOP" ? "step: refused (symlink)" : error instanceof SyntaxError ? "step: refused (malformed)" : "step: refused (unreadable)";
} finally { if (fd !== undefined) closeSync(fd); }
},
close() { runWorkerStepsSync(closeSteps()); },
/** `close`, with the same refusal and fallback cleanup, as steps (#2844). */
closeSteps,
Expand Down
16 changes: 12 additions & 4 deletions packages/ui-sdk/src/server/worker-launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1371,6 +1371,8 @@ export function* launchAgentWorkerSteps(input: WorkerLaunch): WorkerSteps<Launch
let status: ReturnType<typeof createWorkerStatusPipe> | undefined;
let identityBroker: ReturnType<typeof prepareWorkerIdentity> | undefined;
let identityFinished = false, identityReferences = 0;
/** A setup timeout's last recorded supervisor step, read before close removes it (#3664). */
let setupProgress = "";
let completeMaintenanceSetup: (() => void) | undefined;
let failMaintenanceSetup: ((error: unknown) => void) | undefined;
const identityHandles: WorkerStateHandle[] = [];
Expand Down Expand Up @@ -1444,7 +1446,11 @@ export function* launchAgentWorkerSteps(input: WorkerLaunch): WorkerSteps<Launch
let pid: number;
let identityReady: ReturnType<NonNullable<typeof identityBroker>["ready"]> | undefined;
try { identityReady = identityBroker ? yield* identityBroker.readySteps(child.pid, deadline) : undefined; }
catch (error) { throw new WorkerHostError(error instanceof Error ? error.message : String(error)); }
catch (error) {
const requirement = error instanceof Error ? error.message : String(error);
if (requirement === "worker_identity_setup_timed_out") setupProgress = identityBroker!.setupProgress(deadline - STATE_SETUP_MS);
throw new WorkerHostError(requirement);
}
try { pid = identityReady?.worker.pid ?? (yield* status!.childPidSteps(child.pid, deadline)); }
catch (error) { throw new WorkerHostError(error instanceof Error ? error.message : String(error)); }
status?.closeWriter();
Expand Down Expand Up @@ -1581,7 +1587,9 @@ export function* launchAgentWorkerSteps(input: WorkerLaunch): WorkerSteps<Launch
child?.kill("SIGKILL");
if (stateFd !== undefined) closeSync(stateFd);
if (tempFd !== undefined) closeSync(tempFd);
const detail = error instanceof WorkerHostError && pipes ? launchDiagnostics(pipes.parent[2]) : "";
const diagnostics = error instanceof WorkerHostError && pipes ? launchDiagnostics(pipes.parent[2]) : "";
// The recorded step leads: a supervisor's own failure line may follow it, and need not name one.
const detail = [setupProgress, diagnostics].filter(Boolean).join("; ").slice(0, 400);
pipes?.cleanup();
if (cleanupFailure) {
// Keep native ownership/recovery intent and admission held: cleanup
Expand All @@ -1595,8 +1603,8 @@ export function* launchAgentWorkerSteps(input: WorkerLaunch): WorkerSteps<Launch
if (child) void child.exited.finally(async () => { try { await areaOutput?.cleanup(); } finally { if (!input.preparedOutput) await startupView?.cleanup(); } }).catch(() => { /* Native broker retains unresolved release intent for recovery. */ });
else { void Promise.resolve(areaOutput?.cleanup()).finally(() => input.preparedOutput ? undefined : startupView?.cleanup()).catch(() => { /* No child ran; durable ownership retains unresolved release intent. */ }); }
if (detail) {
throw new WorkerHostError(NO_TMPFS_SIZE.test(detail)
? `bubblewrap 0.7 or later, for the worker's size-limited tmpfs mounts (${detail})`
throw new WorkerHostError(NO_TMPFS_SIZE.test(diagnostics)
? `bubblewrap 0.7 or later, for the worker's size-limited tmpfs mounts (${diagnostics})`
: `${(error as WorkerHostError).requirement} (${detail})`);
}
throw error;
Expand Down
16 changes: 16 additions & 0 deletions packages/ui-sdk/tests/identity-broker-qualification.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,22 @@ print(json.dumps(dict(uid=os.getuid(),value=value)))`, {sandbox:{brain,profile:"
}
} finally { if (configured !== undefined) process.env.BRAIN_UI_WORKER_IDENTITY_HELPER = configured; }
});
await check("a helper that never acknowledges launch times out naming launch-sent, and its cleanup is confirmed", async () => {
const configured = process.env.BRAIN_UI_WORKER_IDENTITY_HELPER;
process.env.BRAIN_UI_WORKER_IDENTITY_HELPER = "/usr/local/bin/identity-helper-fault-no-launch-ack";
const marker = join(brain, "no-launch-ack-payload");
try {
let refusal: { requirement?: string; errorClass?: string; message?: string } | undefined;
try { launch(`open('${marker}','w').write('unexpected')`); } catch (error) { refusal = error as typeof refusal; }
console.log(JSON.stringify({ setupTimeout: { requirement: refusal?.requirement, errorClass: refusal?.errorClass } }));
// An unconfirmed cleanup would refuse as WorkerIdentityCleanupError, with no requirement.
expect(refusal?.errorClass, "NO_LAUNCH_ACK_REFUSES_AS_HOST_UNSUPPORTED").toBe("worker_host_unsupported");
expect(refusal?.requirement, "NO_LAUNCH_ACK_NAMES_LAUNCH_SENT")
.toMatch(/^worker_identity_setup_timed_out \(step: launch-sent, ms: \d+, sinceSpawnMs: -?\d+(;|\)$)/);
expect(existsSync(marker), "NO_LAUNCH_ACK_KEEPS_GATE_CLOSED").toBe(false);
await until(() => workerPids().length === 0, "NO_LAUNCH_ACK_LEFT_WORKER");
} finally { if (configured !== undefined) process.env.BRAIN_UI_WORKER_IDENTITY_HELPER = configured; }
});
await check("helper final exec resets inherited ignored signals and pipelines stay quiet", async () => {
for(const [command,verify] of [
[["/usr/bin/cat","/proc/self/status"],(output:string)=>expect(output.match(/^SigIgn:\s+([0-9a-f]+)$/m)?.[1]).toBe("0000000000000000")],
Expand Down
Loading
Loading