A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[RSI, bug] Hold spawn name reservations until admission is durable (#2396)
Seth Karten126fe7010855
diff --git a/packages/coding-agent/.changes/hold-spawn-name-reservation.md b/packages/coding-agent/.changes/hold-spawn-name-reservation.mdnew file mode 100644index 0000000000..bd2857e196--- /dev/null+++ b/packages/coding-agent/.changes/hold-spawn-name-reservation.md@@ -0,0 +1 @@+- Fixed spawn name reservations releasing before admission was durable, which let two parallel same-name spawns both admit and write duplicate ledger edges that made child selectors ambiguous.diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 01bedd69d5..712b0cf32e 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -11947,7 +11947,14 @@ export class AgentSession {}this._pendingRlmSubagentSessionNames.add(requestedSessionName);}+ // The name stays reserved until the spawn admission settles: the+ // detached runtime task releases it at admission completion (success+ // or failure), and every pre-admission failure path releases it here.+ const releaseReservedSessionName = () => {+ if (requestedSessionName) this._pendingRlmSubagentSessionNames.delete(requestedSessionName);+ };let modelSelection: RlmSubagentModelSelection;+ let childSessionDir: string;try {if (requestedSessionName) await this._assertRlmSubagentSessionNameAvailable(requestedSessionName, true);// An unpinned spawn model resolves against the persisted subagent@@ -11956,20 +11963,22 @@ export class AgentSession {modelSelection = await this._resolveRlmSubagentModel(requestedModel ?? this.settingsManager.getSubagentDefaultModel(),);- } finally {- if (requestedSessionName) this._pendingRlmSubagentSessionNames.delete(requestedSessionName);- }- if (requestedThinkingLevel !== undefined) {- const supported = getSupportedThinkingLevels(modelSelection.model) as ThinkingLevel[];- if (!supported.includes(requestedThinkingLevel)) {- throw new Error(- `Requested thinking level "${requestedThinkingLevel}" is not supported by model "${modelSelection.model.provider}/${modelSelection.model.id}"; supported levels: ${supported.join(", ")}`,- );+ if (requestedThinkingLevel !== undefined) {+ const supported = getSupportedThinkingLevels(modelSelection.model) as ThinkingLevel[];+ if (!supported.includes(requestedThinkingLevel)) {+ throw new Error(+ `Requested thinking level "${requestedThinkingLevel}" is not supported by model "${modelSelection.model.provider}/${modelSelection.model.id}"; supported levels: ${supported.join(", ")}`,+ );+ }}+ if (this._disposed || this._disposing) {+ throw new Error("Cannot spawn a subagent after its parent was disposed");+ }+ childSessionDir = this._createChildRlmSessionDir();+ } catch (error) {+ releaseReservedSessionName();+ throw error;}- if (this._disposed || this._disposing) throw new Error("Cannot spawn a subagent after its parent was disposed");-- const childSessionDir = this._createChildRlmSessionDir();const childNodeId = basename(childSessionDir);const sessionName = requestedSessionName ?? createDefaultRlmSubagentSessionName(prompt, childNodeId);if (!requestedSessionName) await this._assertRlmSubagentSessionNameAvailable(sessionName);@@ -12154,7 +12163,14 @@ export class AgentSession {void (async () => {let childRuntime: RlmSubagentRuntime | undefined;try {- childRuntime = await this._createRlmSubagentRuntime(subagentOptions);+ try {+ childRuntime = await this._createRlmSubagentRuntime(subagentOptions);+ } finally {+ // Admission settled: in daemon mode the spawn edge is now+ // durable, so the name transfers from the pending reservation+ // to the admitted run. A failed admission frees the name.+ releaseReservedSessionName();+ }const child = childRuntime.session;if (run.status === "cancelled") throw new Error(run.error ?? "RLM child cancelled");if (child.sessionName !== sessionName) child.setSessionName(sessionName);diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex a8123dbd35..99a9c79890 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -2893,6 +2893,33 @@ export class AgentDaemon {private async createRlmSubagentRuntime(parentState: ActiveSessionState,options: CreateRlmSubagentRuntimeOptions,+ ): Promise<AgentSessionRuntime> {+ // The sibling name is held under a daemon-wide reservation for the+ // whole admission and re-asserted at this boundary, so a same-name+ // sibling that lands mid-admission fails closed before the durable+ // ledger edge is appended.+ const nameReservation = {+ name: options.sessionName,+ depth: options.rlmDepth,+ parentSessionId: options.parentSession.sessionId,+ ...(options.parentSession.sessionFile ? { parentSessionPath: options.parentSession.sessionFile } : {}),+ };+ const reservationKey = sessionNameReservationKey(nameReservation);+ if (this.pendingSessionNames.has(reservationKey)) {+ throw new Error(formatAgentSessionNameUnavailable(options.sessionName, options.rlmDepth));+ }+ this.pendingSessionNames.add(reservationKey);+ try {+ await this.assertFamilySessionNameAvailable(nameReservation, parentState, true);+ return await this.admitRlmSubagentRuntime(parentState, options);+ } finally {+ this.pendingSessionNames.delete(reservationKey);+ }+ }++ private async admitRlmSubagentRuntime(+ parentState: ActiveSessionState,+ options: CreateRlmSubagentRuntimeOptions,): Promise<AgentSessionRuntime> {const sessionManager = SessionManager.create(options.parentSession.sessionManager.getCwd(), options.sessionDir);sessionManager.newSession({diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex 637162cdb3..a49404f0c0 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -17,6 +17,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {type AgentSessionMessageController,createAgentSessionMessage,+ formatAgentSessionNameUnavailable,isAgentSessionMessage,} from "../src/core/agent-messages.js";import { AgentSession } from "../src/core/agent-session.js";@@ -539,6 +540,28 @@ describe("AgentSession rlm recursion", () => {);});+ it("holds a spawn name reservation until admission settles, then frees it", async () => {+ const releaseAdmission = deferred<void>();+ const root = createSession({+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ await releaseAdmission.promise;+ throw new Error("kernel startup failed");+ },+ deleteRlmSubagentRuntime: async () => {},+ },+ });+ const internals = root as unknown as InspectableRlmSession & { _pendingRlmSubagentSessionNames: Set<string> };+ const unavailable = formatAgentSessionNameUnavailable("slow-worker", root.rlmDepth + 1);+ const spawned = await root.runRlmChild("slow admitting child", { name: "slow-worker" });+ expect(internals._pendingRlmSubagentSessionNames.has("slow-worker")).toBe(true);+ await expect(root.runRlmChild("racing spawn", { name: "slow-worker" })).rejects.toThrow(unavailable);+ releaseAdmission.resolve();+ await internals._activeRlmChildRuns.get(spawned.rlm_child_id)!.settlement!.promise;+ expect(internals._pendingRlmSubagentSessionNames.has("slow-worker")).toBe(false);+ await expect(root.runRlmChild("respawn while retained", { name: "slow-worker" })).rejects.toThrow(unavailable);+ });+it("makes an externally restored retained child listable and deletable", async () => {const childId = "restored-child";const childDir = join(tempDir, childId);diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 6d69ec8881..a59a310204 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -106,6 +106,7 @@ describe("daemon mode helpers", () => {saved: Awaited<ReturnType<typeof SessionManager.listAll>>,jobs: AgentCronJob[],): Promise<Array<{ sessionFile?: string; rlmChildId?: string }>>;+ rlmSpawnLedger(): { liveEdges(): Promise<Array<{ childId: string; name: string }>> };};const parentState = await internals.createRuntime({ type: "create", sessionPath: parentSessionFile });Object.assign(parentState.runtime.session, {@@ -118,24 +119,30 @@ describe("daemon mode helpers", () => {hasRunningRlmChildren: () => false,getSessionActionSnapshot: () => ({ queuedCount: 0, steering: [], followUps: [] }),});- const childRuntime = await internals.createRlmSubagentRuntime(parentState, {- parentSession: parentState.runtime.session,- id: "child-1",- prompt: "complete and persist",- sessionName: "real-worker",- sessionDir: childSessionDir,- model: { provider: "test", id: "model" } as Model<Api>,- thinkingLevel: "off",- serviceTier: null,- scopedModels: [],- activeToolNames: [],- customTools: [],- includeGoals: false,- includeCompactSkill: false,- rlmDepth: 1,- rlmMaxDepth: 4,- rlmParentNodeId: "child-1",- });+ const spawn = (id: string) =>+ internals.createRlmSubagentRuntime(parentState, {+ parentSession: parentState.runtime.session,+ id,+ prompt: "complete and persist",+ sessionName: "real-worker",+ sessionDir: join(parentManager.getSessionArtifactDir()!, id),+ model: { provider: "test", id: "model" } as Model<Api>,+ thinkingLevel: "off" as const,+ serviceTier: null,+ scopedModels: [],+ activeToolNames: [],+ customTools: [],+ includeGoals: false,+ includeCompactSkill: false,+ rlmDepth: 1,+ rlmMaxDepth: 4,+ rlmParentNodeId: id,+ });+ const admission = spawn("child-1");+ await expect(spawn("child-2")).rejects.toThrow('Agent name "real-worker" is unavailable');+ const childRuntime = await admission;+ const edges = await internals.rlmSpawnLedger().liveEdges();+ expect(edges.filter((edge) => edge.name === "real-worker")).toHaveLength(1);const childState = [...internals.sessions.values()].find((state) => state.runtime.session === childRuntime.session,);@@ -173,6 +180,12 @@ describe("daemon mode helpers", () => {status: "completed",prompt: "complete and persist",});+ await host.deleteRlmSubagentRuntime?.("child-1", childRuntime.session);+ await spawn("child-3");+ const edgesAfter = await internals.rlmSpawnLedger().liveEdges();+ const namedEdges = edgesAfter.filter((edge) => edge.name === "real-worker");+ expect(namedEdges).toHaveLength(1);+ expect(namedEdges[0]?.childId).toBe("child-3");} finally {rmSync(tempDir, { recursive: true, force: true });}