Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix(coding-agent): enforce session ownership when joining an in-flight open (#1864)

Sebastian Müller5b6c0e94e11a
diff --git a/packages/coding-agent/.changes/pending-open-ownership.md b/packages/coding-agent/.changes/pending-open-ownership.md
new file mode 100644
index 0000000000..0750e13c65
--- /dev/null
+++ b/packages/coding-agent/.changes/pending-open-ownership.md
@@ -0,0 +1 @@
+- Fixed a race where a concurrent open of a session already being opened by another client bypassed the session ownership check instead of failing with session-already-active.
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index d4e4d3e8bf..1db1f8eb72 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -2278,7 +2278,18 @@ export class DaemonSupervisor {
: `new:${command.id ? createCommandIdempotencyKey(clientId, command.id) : createActiveSessionId()}`;
const pending = this.openingWorkers.get(key);
if (pending) {
- return pending;
+ return this.joinOpeningWorker(pending, ownerClientId, createCommand.sessionPath ?? key);
+ }
+ if (createCommand.sessionPath) {
+ const existing = this.findWorkerBySessionFile(createCommand.sessionPath);
+ if (existing && !(await this.reclaimStaleWorkerRegistration(existing, command.launchEnv !== undefined))) {
+ return this.reuseWorkerForCreate(existing, ownerClientId, createCommand.sessionPath);
+ }
+ // The reclaim await may have let a concurrent opener register; join it instead of double-launching.
+ const opened = this.openingWorkers.get(key);
+ if (opened) {
+ return this.joinOpeningWorker(opened, ownerClientId, createCommand.sessionPath);
+ }
}
if (createCommand.sessionPath) {
const existing = this.findWorkerBySessionFile(createCommand.sessionPath);
@@ -2323,9 +2334,7 @@ export class DaemonSupervisor {
`Session "${sessionPath}" is registered to a failed worker that could not be safely reclaimed`,
);
}
- if (worker.descriptor.ownerClientId !== ownerClientId) {
- throw new SessionAlreadyActiveError(sessionPath, worker.descriptor.rootActiveSessionId);
- }
+ this.assertWorkerCreateOwner(worker, ownerClientId, sessionPath);
if (!this.isWorkerReadyForCreate(worker)) {
if (worker.recovery) {
await worker.recovery;
@@ -2337,9 +2346,7 @@ export class DaemonSupervisor {
if (!current) {
throw new Error(`Session "${sessionPath}" worker recovery was interrupted; retry opening the session`);
}
- if (current.descriptor.ownerClientId !== ownerClientId) {
- throw new SessionAlreadyActiveError(sessionPath, current.descriptor.rootActiveSessionId);
- }
+ this.assertWorkerCreateOwner(current, ownerClientId, sessionPath);
if (!this.isWorkerReadyForCreate(current)) {
if (!current.summaries.has(current.descriptor.rootActiveSessionId)) {
throw new Error(
@@ -2352,6 +2359,26 @@ export class DaemonSupervisor {
return current;
}
+ private async joinOpeningWorker(
+ pending: Promise<ResidentWorker>,
+ ownerClientId: string | undefined,
+ sessionPath: string,
+ ): Promise<ResidentWorker> {
+ const worker = await pending;
+ this.assertWorkerCreateOwner(worker, ownerClientId, sessionPath);
+ return worker;
+ }
+
+ private assertWorkerCreateOwner(
+ worker: ResidentWorker,
+ ownerClientId: string | undefined,
+ sessionPath: string,
+ ): void {
+ if (worker.descriptor.ownerClientId !== ownerClientId) {
+ throw new SessionAlreadyActiveError(sessionPath, worker.descriptor.rootActiveSessionId);
+ }
+ }
+
private isWorkerReadyForCreate(worker: ResidentWorker): boolean {
return (
worker.descriptor.lifecycle === "ready" &&
diff --git a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts
index 665c13587a..74332846c2 100644
--- a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts
@@ -22,7 +22,7 @@ interface SupervisorInternals {
findSummaryInWorker(worker: WorkerFixture, selector: string): SessionSummary | undefined;
createOrReuseWorker(
clientId: string,
- command: { type: "create"; name?: string; sessionPath?: string },
+ command: { type: "create"; name?: string; sessionPath?: string; lifecycle?: "client_owned" },
): Promise<WorkerFixture>;
assertSupervisorSavedSessionNameAvailable(sessionPath: string, name: string): Promise<void>;
assertSavedSiblingNameAvailable(
@@ -352,6 +352,108 @@ describe("daemon supervisor passive subagent topology", () => {
expect(launchWorker).toHaveBeenCalledOnce();
});
+ it("enforces session ownership when joining an in-flight open", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-pending-owner-"));
+ tempDirs.push(directory);
+ const sessionPath = join(directory, "session.jsonl");
+ let releaseLaunch!: () => void;
+ const launchGate = new Promise<void>((resolve) => {
+ releaseLaunch = resolve;
+ });
+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: directory, cwd: directory },
+ descriptorDir: join(directory, "workers"),
+ }) as unknown as SupervisorInternals;
+ const resident = worker("opened");
+ resident.descriptor.ownerClientId = "owner";
+ const launchWorker = vi.fn(async () => {
+ await launchGate;
+ return resident;
+ });
+ Object.assign(supervisor, { launchWorker });
+
+ const create = { type: "create" as const, sessionPath, lifecycle: "client_owned" as const };
+ const first = supervisor.createOrReuseWorker("owner", create);
+ const sameOwner = supervisor.createOrReuseWorker("owner", create);
+ const otherClient = supervisor.createOrReuseWorker("intruder", create);
+ const expectations = Promise.all([
+ expect(first).resolves.toBe(resident),
+ expect(sameOwner).resolves.toBe(resident),
+ expect(otherClient).rejects.toMatchObject({ code: "session_already_active" }),
+ ]);
+ releaseLaunch();
+ await expectations;
+ expect(launchWorker).toHaveBeenCalledOnce();
+ });
+
+ it("rejoins an open registered while reclaiming a stale worker registration", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-reclaim-rejoin-"));
+ tempDirs.push(directory);
+ const sessionPath = join(directory, "session.jsonl");
+ let releaseReclaim!: () => void;
+ const reclaimGate = new Promise<void>((resolve) => {
+ releaseReclaim = resolve;
+ });
+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: directory, cwd: directory },
+ descriptorDir: join(directory, "workers"),
+ }) as unknown as SupervisorInternals;
+ const stale = worker("stale");
+ stale.descriptor.createCommand = { config: { cwd: directory }, sessionPath };
+ supervisor.workers.set(stale.descriptor.workerId, stale);
+ const resident = worker("opened");
+ resident.descriptor.ownerClientId = "owner";
+ const launchWorker = vi.fn(async () => resident);
+ const reclaimStaleWorkerRegistration = vi.fn(async () => {
+ await reclaimGate;
+ supervisor.workers.delete(stale.descriptor.workerId);
+ return true;
+ });
+ Object.assign(supervisor, { launchWorker, reclaimStaleWorkerRegistration });
+
+ const create = { type: "create" as const, sessionPath, lifecycle: "client_owned" as const };
+ const first = supervisor.createOrReuseWorker("owner", create);
+ const second = supervisor.createOrReuseWorker("owner", create);
+ const intruder = supervisor.createOrReuseWorker("intruder", create);
+ const expectations = Promise.all([
+ expect(first).resolves.toBe(resident),
+ expect(second).resolves.toBe(resident),
+ expect(intruder).rejects.toMatchObject({ code: "session_already_active" }),
+ ]);
+ releaseReclaim();
+ await expectations;
+ expect(launchWorker).toHaveBeenCalledOnce();
+ });
+
+ it("propagates an in-flight open failure to joiners", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-pending-failure-"));
+ tempDirs.push(directory);
+ const sessionPath = join(directory, "session.jsonl");
+ let releaseLaunch!: () => void;
+ const launchGate = new Promise<void>((resolve) => {
+ releaseLaunch = resolve;
+ });
+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: directory, cwd: directory },
+ descriptorDir: join(directory, "workers"),
+ }) as unknown as SupervisorInternals;
+ const launchWorker = vi.fn(async () => {
+ await launchGate;
+ throw new Error("launch exploded");
+ });
+ Object.assign(supervisor, { launchWorker });
+
+ const create = { type: "create" as const, sessionPath, lifecycle: "client_owned" as const };
+ const first = supervisor.createOrReuseWorker("owner", create);
+ const joiner = supervisor.createOrReuseWorker("intruder", create);
+ const expectations = Promise.all([
+ expect(first).rejects.toThrow("launch exploded"),
+ expect(joiner).rejects.toThrow("launch exploded"),
+ ]);
+ releaseLaunch();
+ await expectations;
+ });
+
it("uses injective structural session name reservation keys", () => {
expect(sessionNameReservationKey({ name: "b:c", depth: 1, parentSessionPath: "/a" })).not.toBe(
sessionNameReservationKey({ name: "c", depth: 1, parentSessionPath: "/a:b" }),