From d43f31f071f723d65ddb9527d498ec1a284b10f8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 14:18:33 +0000 Subject: [PATCH 1/2] docs(backends): report duplicate pi worker acquisition reachability Two concurrent resumes of one non-resident session through the public pi backend each launch a real worker; the later return loses the pool race and refuses busy before its worker exits, closes its turn temp or releases stdio. ui-server's coordinator cannot reach the branch. Adds a keyless real-worker test that pins the contracts a repair keeps, and hands the awaited loser teardown off as #3488. Refs #2918 Co-Authored-By: Claude Opus 5.5 --- docs/investigations/README.md | 1 + .../duplicate-pi-worker-acquisition.md | 138 ++++++++++++++++++ .../tests/duplicate-acquisition.test.ts | 130 +++++++++++++++++ 3 files changed, 269 insertions(+) create mode 100644 docs/investigations/duplicate-pi-worker-acquisition.md create mode 100644 packages/ui-backend-pi/tests/duplicate-acquisition.test.ts diff --git a/docs/investigations/README.md b/docs/investigations/README.md index b169301eba..ca19086120 100644 --- a/docs/investigations/README.md +++ b/docs/investigations/README.md @@ -17,6 +17,7 @@ with their harnesses; their authored cases are kept in | Report | Historical evidence | Source issue | | --- | --- | --- | | [audit-capability-investigation.md](audit-capability-investigation.md) | Audit suggestion and executable repair evidence. | [#841](https://github.com/schlessera/brain-kit/issues/841) | +| [duplicate-pi-worker-acquisition.md](duplicate-pi-worker-acquisition.md) | Real-worker reachability of the pi pool's duplicate-resume branch and its loser's teardown. | [#2918](https://github.com/schlessera/brain-kit/issues/2918) | | [haiku-5-5-current-path-investigation.md](haiku-5-5-current-path-investigation.md) | Haiku 5.5 reruns of every Sonnet-measured #838 current path, plus two effort sweeps. | [#1611](https://github.com/schlessera/brain-kit/issues/1611) | | [live-conversation-investigation.md](live-conversation-investigation.md) | Two-engine live voice qualification and interface specification. | [#317](https://github.com/schlessera/brain-kit/issues/317) | | [live-result-recall.md](live-result-recall.md) | Exact result handover, bounded text and replacement-epoch context loss; no live semantic recall measurement. | [#3131](https://github.com/schlessera/brain-kit/issues/3131) | diff --git a/docs/investigations/duplicate-pi-worker-acquisition.md b/docs/investigations/duplicate-pi-worker-acquisition.md new file mode 100644 index 0000000000..acf1369676 --- /dev/null +++ b/docs/investigations/duplicate-pi-worker-acquisition.md @@ -0,0 +1,138 @@ +# Duplicate pi worker acquisition: reachability and teardown + +This report answers [#2918](https://github.com/schlessera/brain-kit/issues/2918). +Source was read and the runtime receipt was recorded on 2026-11-03 at main +`adf371ffab5da62abfd311d95a6583100b22b324`. The test used keyless real workers +under bwrap on Linux. No model or provider was contacted. + +## Result + +**Reachable, through the public backend, but not through ui-server.** Two +concurrent `startTurn` calls on one `createPiBackend()` instance, both +resuming the same non-resident session, each launch and initialize their own +real worker. The acquisition that returns second loses the pool race. It +receives `BackendBusyError`, emits no frames and never prompts. The winner is +not signalled and finishes with its normal `success` result. At the moment the +loser's refusal settles, though, its worker has not exited, its turn temp has +not been closed and its stdio release has not been awaited. This is the gap +the [#2863 lifecycle ruling](https://github.com/schlessera/brain-kit/issues/2863#issuecomment-6391630082) +forbids. The repair is handed off as +[#3488](https://github.com/schlessera/brain-kit/issues/3488). + +The new-session duplicate branch cannot be reached by production +worker-backed sessions. + +## Call paths + +**The pool.** A production backend has no `sessionFactory`, so it never +retains a session (`createSessionPool(runtime, Boolean(options.sessionFactory))`, +`packages/ui-backend-pi/src/backend.ts:117-120`). `finish()` removes and +disposes every interactive entry when its turn ends. That makes every resume +non-resident, and every resume opens a worker. A resumed acquisition checks +the map, awaits `runtime.openSession` and then checks the map again. If +another acquisition registered the session in the meantime, it calls +synchronous `disposeSession(opened.session)` and then either refuses +`BackendBusyError` or claims the idle entry (`if (req.sessionId)`, +`packages/ui-backend-pi/src/session-pool.ts:76-99`). Without retention, an +entry in the map is always running, so in production the loser always +refuses busy. The runner re-throws that refusal to its caller unchanged +(`let acquired`, `packages/ui-backend-pi/src/turn-runner.ts:63-84`). + +**The new-session branch.** A worker-backed session's identity is +`resumeId ?? randomUUID()` (`const sessionId = resumeId`, +`packages/ui-backend-pi/src/worker-session.ts:112`). Autonomous acquisitions +return before the map is consulted (`runtime.newSession`, `packages/ui-backend-pi/src/session-pool.ts:101-103`). +So the duplicate check +(`sessions.get(created.session.sessionId)`, `packages/ui-backend-pi/src/session-pool.ts:104-117`) +fires only for injected `sessionFactory` doubles, which reuse identities. + +**ui-server.** The interactive turn path admits one in-flight `startTurn` per +session. `handleChatMessage` queues a message for a session found in +`startingBySession` or `bySession` +(`const runningTurn`, `packages/ui-server/src/ws/run-session.ts:1216-1247`). Otherwise it calls +`runSession`, which calls `runRetainedSession`. That registers +`startingBySession` before its first await +(`runRetainedSession`, `packages/ui-server/src/ws/run-session.ts:201-216`). Nothing on that path +awaits between the check and the registration. The turn then moves to +`bySession` (`coordinator.running.add(turn)`, `packages/ui-server/src/ws/run-session.ts:288-289`), awaits +`backend.startTurn` directly (`await backend.startTurn`, `packages/ui-server/src/ws/run-session.ts:787`), +and releases `bySession` only in the slot's final `finally` +(`coordinator.bySession.get(turn.sessionId) === turn`, `packages/ui-server/src/ws/run-session.ts:993-995`). Retry admission refuses +on the same two maps (`coordinator.bySession.has(msg.sessionId)`, `packages/ui-server/src/ws/dispatch.ts:242`). The other +two backend callers run autonomous turns and pass no `sessionId`: the handoff +summary (`await backend.startTurn`, `packages/ui-server/src/ws/handoff.ts:374-388`) and inbox work +(`installApplication(request`, `packages/ui-server/src/inbox/autonomous-turn.ts:409-417`). + +The SDK contract suite also resumes a session while it is running +(`busy-ness is per session`, `packages/ui-sdk/src/testing/index.ts:558-575`). That entry is resident, so +the pool refuses before any worker opens. The contract treats a concurrent +same-session resume as supported input that must refuse busy. A host that +calls the backend directly, without ui-server's coordinator, can therefore +reach the loser branch. + +## Losing-worker lifecycle today + +`dispose()` sets `ended`, ends stdin and requests SIGKILL synchronously +(`dispose()`, `packages/ui-backend-pi/src/worker-session.ts:776`). For a worker that was +never prompted, the only turn-temp close is a detached hook on exit, and its +refusal is swallowed (`A worker that never ran a turn`, `packages/ui-backend-pi/src/worker-session.ts:318-322`). +Nothing calls the launcher's `released()` (`stdioReleased`, +`packages/ui-backend-pi/src/worker-session.ts:357`) for this worker. The +awaited owner already exists: the session's shared inactive `abort()` waits +for exit and protocol consumption, then the turn-temp close, then the bounded +stdio release (`abort()`, `packages/ui-backend-pi/src/worker-session.ts:758-774`). +#2880 uses it for cancelled acquisitions (`cancelAcquiredSession`, +`packages/ui-backend-pi/src/session-pool.ts:159-166`). + +## Runtime receipt + +`packages/ui-backend-pi/tests/duplicate-acquisition.test.ts` runs the real +launcher with a credential-free shell protocol peer. It gates both +`openPiWorkerSession` returns until each owns a ready worker, then releases +the winner. After the winner has registered and reached its prompt, it +releases the loser. The test tells the two apart by each turn's own signal, +and identifies each worker by its turn-temp root. The committed assertions +hold the facts a repair must keep: two distinct launches, a busy refusal for +the loser with no frames and no prompt, the winner not signalled while +running, the loser stopped, the winner's normal result, the winner's single +turn-temp close and stdio release, and the loser's eventual exit. + +A temporary probe, not committed, recorded the loser's state at two moments. +The result was the same in three runs: + +| Moment | Loser exited | Kill requests | Turn-temp closes | Stdio releases | Ledger above baseline | +| --- | --- | --- | --- | --- | --- | +| Loser's `BackendBusyError` settled (winner still prompting) | no | 1 | 0 | 0 | 512 MiB (both workers' reservations) | +| Winner settled, loser exited | yes | 1 | 1 (detached hook) | 0 | 0 | + +So the detached hook eventually releases the reservation, and Bun eventually +closed the FIFO descriptors. Neither the refusal nor any other owner waits +for either step, and a refused close would be lost. + +Mutation receipts for the committed test: + +- Removing the loser's `disposeSession(opened.session)` fails + `PI_DUPLICATE_RESUME_LOSER_IS_STOPPED` (expected > 0, received 0). +- Disposing `raced.session` instead fails + `PI_DUPLICATE_RESUME_WINNER_NOT_STOPPED_BY_LOSER` (expected 0, received 1). +- Removing the busy refusal fails `PI_DUPLICATE_RESUME_LOSER_REFUSES_BUSY` + (received `undefined`). + +## Repair handoff + +[#3488](https://github.com/schlessera/brain-kit/issues/3488) specifies the +narrow owner under the existing ruling. The losing resumed acquisition decides +busy or reuse, and claims a reused entry, synchronously. It then awaits its +own worker's shared inactive `abort()`, disposes it and re-raises the original +outcome. A cleanup refusal is reported, not substituted. That issue also +carries the failing-first and mutation plan. Public `dispose()`, the busy and +result shapes, worker protocols and release bounds are unchanged, so the +contract impact is none. + +## Limitations + +The receipt replaces the pi worker entry with a shell protocol peer, and it +uses the governed fixture sandbox. A separate-UID broker close and a refused +close on the loser path were not exercised. #3488 covers the refused close. +Concurrent resumes from separate server processes use separate pools, and this +branch does not cover them. diff --git a/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts b/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts new file mode 100644 index 0000000000..8dcf5422d3 --- /dev/null +++ b/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts @@ -0,0 +1,130 @@ +/** + * #2918: two concurrent resumes of one non-resident session through the public + * `startTurn` each launch a real worker; the later return loses the pool race. + * Pins reachability and the contracts a repair must keep: the winner's normal + * result, a per-session busy refusal with no frames, and only the loser stopped. + */ +import { afterEach, expect, spyOn, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as worker from "@schlessera/brain-ui-sdk/internal"; +import { BackendBusyError, type ServerMessage } from "@schlessera/brain-ui-sdk/server"; +import { createPiBackend, type PiSessionLike } from "../src/backend.js"; +import * as sessions from "../src/worker-session.js"; +import { savePiSession } from "../src/session-storage.js"; +import { prepareFixtureWorkerSandbox } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { ownedWorkerFifos } from "../../ui-sdk/tests/helpers/work-pool.js"; +import { startFixtureTurn } from "../../../tests/fixtures/worker-input-fixture.js"; + +const cleanup: Array<() => unknown> = []; +afterEach(async () => { for (const remove of cleanup.splice(0).reverse()) await remove(); }); +const ID = "22222222-2222-4222-8222-222222222222"; +const native = process.platform === "linux" && Boolean(Bun.which("bwrap")); + +/** A credential-free protocol peer: ready on init, done once its prompt arrives. */ +const ANSWERING = `IFS= read -r init +id=$(printf %s "$init" | grep -o '"sessionId":"[^"]*"' | tail -n 1 | cut -d '"' -f 4) +printf '{"type":"ready","sessionId":"%s","levels":[],"cost":0}\\n' "$id" +IFS= read -r prompt +printf '{"type":"done","cost":0}\\n'`; + +interface Launched { root: unknown; exited: Promise; hasExited: boolean; kills: number; closes: number; releases: number; prompts: number; session?: PiSessionLike } + +test.skipIf(!native)("a concurrent duplicate resume reaches the pool race with two real workers and refuses only the loser", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-pi-duplicate-")); + const brain = join(root, "ithaca"), sessionDir = join(root, "sessions"); + mkdirSync(brain); mkdirSync(sessionDir); + cleanup.push(() => rmSync(root, { recursive: true, force: true })); + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = join(root, "agent"); + cleanup.push(() => { if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previous; }); + const fifos = ownedWorkerFifos(); + cleanup.push(fifos.restore); + savePiSession(sessionDir, ID, [{ type: "session", version: 3, id: ID, cwd: brain, timestamp: "2026-07-12T00:00:00.000Z" }]); + const options = { brainPath: brain, sessionDir, loadExtensions: false, + profiles: [{ id: "fixture", label: "Fixture", vendor: "openai", model: "gpt-4o-mini", thinkingLevel: "off" as const }], confirmBashPatterns: [] }; + const sandbox = prepareFixtureWorkerSandbox(brain, { profile: "governed", areas: [] }); + + const workers: Launched[] = []; + const realLaunch = worker.launchAgentWorkerAsync; + const launch = spyOn(worker, "launchAgentWorkerAsync").mockImplementation(async input => { + const child = await realLaunch({ ...input, command: ["/bin/sh", "-c", ANSWERING] }); + const record: Launched = { root: child.turnTemp?.root, exited: child.exited, hasExited: false, kills: 0, closes: 0, releases: 0, prompts: 0 }; + void child.exited.then(() => { record.hasExited = true; }); + workers.push(record); + const kill = child.kill.bind(child), release = child.released.bind(child), turnTemp = child.turnTemp; + child.kill = signal => { record.kills++; return kill(signal); }; + child.released = () => { record.releases++; return release(); }; + if (turnTemp) child.turnTemp = Object.assign(Object.create(Object.getPrototypeOf(turnTemp)), turnTemp, + { closeAsync: () => { record.closes++; return turnTemp.closeAsync(); } }); + return child; + }); + // Both acquisitions hold a ready worker before either returns to the pool; + // each is told apart by its own turn's signal, which the pool hands the worker. + const signals = { winner: new AbortController().signal, loser: new AbortController().signal }; + const gate = () => ({ opened: Promise.withResolvers(), returns: Promise.withResolvers(), record: undefined as Launched | undefined }); + const gates = new Map([[signals.winner, gate()], [signals.loser, gate()]]); + const winnerPrompted = Promise.withResolvers(), finishWinner = Promise.withResolvers(); + const realOpen = sessions.openPiWorkerSession; + const opening = spyOn(sessions, "openPiWorkerSession").mockImplementation(async (...args) => { + const own = gates.get(args[2].workerSignal!)!; + const result = await realOpen(...args); + // The launch that owns this session, by the turn-temp root it handed the turn context. + const record = own.record = workers.find(entry => entry.root !== undefined && entry.root === result.turnContext.turnTemp?.root())!; + record.session = result.session; + const prompt = result.session.prompt.bind(result.session); + result.session.prompt = async (...input) => { + record.prompts++; winnerPrompted.resolve(); await finishWinner.promise; return prompt(...input); + }; + own.opened.resolve(); + await own.returns.promise; + return result; + }); + const baseline = worker.processStateLedger().turnTempHeld; + const backend = createPiBackend(options); + const turn = (signal: AbortSignal, frames: ServerMessage[]) => startFixtureTurn(backend, brain, { prompt: "Return to Ithaca", profileId: "fixture", + sessionId: ID, signal, workerSandbox: sandbox, + bridge: { emit: frame => { frames.push(frame); }, requestPermission: async () => ({ behavior: "deny", message: "Odysseus fixture" }) } }); + const winnerFrames: ServerMessage[] = [], loserFrames: ServerMessage[] = []; + const winning = turn(signals.winner, winnerFrames).then(() => undefined, error => error); + const losing = turn(signals.loser, loserFrames).then(() => undefined, error => error); + cleanup.push(async () => { + for (const own of gates.values()) own.returns.resolve(); + finishWinner.resolve(); + await winning; await losing; + // Release whatever a still-synchronous loser disposal left reserved. + for (const record of workers) await record.session?.abort().catch(() => {}); + opening.mockRestore(); launch.mockRestore(); + }); + + await Promise.all([...gates.values()].map(own => own.opened.promise)); + expect(workers, "PI_DUPLICATE_RESUME_LAUNCHES_TWO_WORKERS").toHaveLength(2); + expect(new Set(workers.map(entry => entry.root)).size, "PI_DUPLICATE_RESUME_DISTINCT_LAUNCHES").toBe(2); + const winner = gates.get(signals.winner)!.record!, loser = gates.get(signals.loser)!.record!; + expect(winner.session!.sessionId).toBe(ID); + expect(loser.session!.sessionId).toBe(ID); + expect(winner.session, "PI_DUPLICATE_RESUME_OWNS_DISTINCT_WORKERS").not.toBe(loser.session); + + // The first acquisition to return wins the pool; the other loses the race. + gates.get(signals.winner)!.returns.resolve(); + await winnerPrompted.promise; + gates.get(signals.loser)!.returns.resolve(); + const refusal = await losing; + expect(refusal, "PI_DUPLICATE_RESUME_LOSER_REFUSES_BUSY").toBeInstanceOf(BackendBusyError); + expect(loserFrames, "PI_DUPLICATE_RESUME_LOSER_EMITS_NO_FRAMES").toEqual([]); + expect(loser.prompts, "PI_DUPLICATE_RESUME_LOSER_NEVER_PROMPTS").toBe(0); + expect(winner.kills, "PI_DUPLICATE_RESUME_WINNER_NOT_STOPPED_BY_LOSER").toBe(0); + expect(winner.hasExited, "PI_DUPLICATE_RESUME_WINNER_STILL_RUNNING").toBe(false); + expect(loser.kills, "PI_DUPLICATE_RESUME_LOSER_IS_STOPPED").toBeGreaterThan(0); + + finishWinner.resolve(); + expect(await winning, "PI_DUPLICATE_RESUME_WINNER_SETTLES_NORMALLY").toBeUndefined(); + expect(winnerFrames.filter(frame => frame.type === "result" || frame.type === "error"), "PI_DUPLICATE_RESUME_WINNER_RESULT") + .toEqual([expect.objectContaining({ type: "result", sessionId: ID, outcome: "success", isError: false })]); + expect(winner.prompts).toBe(1); + expect(winner.closes, "PI_DUPLICATE_RESUME_WINNER_CLOSES_TURN_TEMP").toBe(1); + expect(winner.releases, "PI_DUPLICATE_RESUME_WINNER_RELEASES_STDIO").toBeGreaterThan(0); + await loser.exited; + expect(loser.hasExited, "PI_DUPLICATE_RESUME_LOSER_EXITS").toBe(true); +}); From cb11786639c8dc9f9e6ae71768c877ceaaa7f239 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 14:22:17 +0000 Subject: [PATCH 2/2] test(backends): drop the probe's unused ledger baseline Refs #2918 Co-Authored-By: Claude Opus 5.5 --- packages/ui-backend-pi/tests/duplicate-acquisition.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts b/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts index 8dcf5422d3..691ca1f43a 100644 --- a/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts +++ b/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts @@ -81,7 +81,6 @@ test.skipIf(!native)("a concurrent duplicate resume reaches the pool race with t await own.returns.promise; return result; }); - const baseline = worker.processStateLedger().turnTempHeld; const backend = createPiBackend(options); const turn = (signal: AbortSignal, frames: ServerMessage[]) => startFixtureTurn(backend, brain, { prompt: "Return to Ithaca", profileId: "fixture", sessionId: ID, signal, workerSandbox: sandbox,