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
1 change: 1 addition & 0 deletions docs/investigations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
138 changes: 138 additions & 0 deletions docs/investigations/duplicate-pi-worker-acquisition.md
Original file line number Diff line number Diff line change
@@ -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.
129 changes: 129 additions & 0 deletions packages/ui-backend-pi/tests/duplicate-acquisition.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/**
* #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<number>; 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<void>(), returns: Promise.withResolvers<void>(), record: undefined as Launched | undefined });
const gates = new Map([[signals.winner, gate()], [signals.loser, gate()]]);
const winnerPrompted = Promise.withResolvers<void>(), finishWinner = Promise.withResolvers<void>();
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 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);
});
Loading