fix(runner): record the run terminal when a run stops during a wait

When a Claude turn ends with background work running, the Runner holds the
run terminal and waits for the provider's own next turn. Stop during that
wait was acknowledged only in the controller, and the close path sent no
command because no turn was active. The Runner released the terminal on
suspend, after the closing drain, so the journal never got it. The next
run on the task was then refused with journal_not_settled. The wait limit
had the same gap.

The close path now sends turn.stop before the drain when the run's last
turn is still waiting. The Runner already ends the wait and publishes the
terminal on that command. A Stop that ends a wait also marks the saved
session as cancelled and no longer waiting, as a Stop during a turn does.

Tested with the real Runner and the fake sidecar for Stop and for the wait
limit. Both tests fail without the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Nicky LeachandClaude Opus 5.5 committed 2026-12-03 14:04:47 -08:00
1 parent 7e025ae65f
commit 4ab5fc974e
7 files changed
+133 -6

No files matched your search

+4
View File
@@ -624,6 +624,10 @@ The outcome is logged as `stopped run's task session`. If the provider later
confirms that the retained state is gone, the next run retires the stopped run's
controller state and starts a new session.
A Stop that ends a wait for background work counts as a Stop of that turn: the
saved session records it as cancelled and no longer waiting, and the closing
Runner commits the run terminal that it held for the wait.
A rejected warm-session close retains its owner, even when no managed instruction
copy exists. Idle expiry, failed-turn release, and restart must not report that
owner as quiet or launch a replacement over it. The next retirement attempt uses
@@ -303,6 +303,10 @@ When a `run.attach` from a different run succeeds, the wait ends and Runner
discards the held `run.terminal`. If that attach fails, the wait and its held
`run.terminal` stay with the old run. A `run.attach` from the same run publishes
the held `run.terminal`.
When a controller closes the transport while its run's last turn is still
awaiting, it sends `turn.stop` before its closing drain. Runner then ends the
wait and publishes the held `run.terminal`, and the drain commits it. A
`run.terminal` published only by `runner.suspend` would miss that drain.
Runner saves the wait with its held `run.terminal` in the provider state; a
Runner restart during the wait publishes that `run.terminal` once and resumes
in a fresh process.
@@ -1266,6 +1266,41 @@ describe("HarnessDriverBackend", () => {
await expect(session.snapshot()).resolves.toMatchObject({ terminal: { runTerminalState: "cancelled" } });
});
it.each([
{ title: "a Stop", stop: true, terminal: { turnTerminalState: "cancelled", runTerminalState: "cancelled", reportedWorkDisposition: "yielded" } },
{ title: "anything else", stop: false, terminal: null },
])("records how a wait for the provider's own next turn ended when $title ends it", async ({ stop, terminal }) => {
let end!: () => void;
const ended = new Promise<void>(resolve => { end = resolve; });
class WaitingSession extends FakeHarnessSession {
override async *events() {
yield prpEvent(1, "turn.completed", { status: "completed", awaitingProviderTurn: true });
await ended;
yield prpEvent(2, "item.completed", { kind: "interrupt_acknowledgement", status: "provider_turn_wait_ended" });
}
async interrupt() { end(); }
override async snapshot(): Promise<PersistedHarnessSession> {
return { ...(await super.snapshot()), semanticResult: null, activeTurnId: null, awaitingProviderTurn: true };
}
}
const backend = new HarnessDriverBackend({ ...driver, async openSession() { return new WaitingSession(); } });
const session = await backend.openSession({
identity: { runId: "run-1", sessionId: "session-1", companyId: "company-1", issueId: "issue-1", agentId: "agent-1" },
workingDirectory: "/workspace",
});
const iterator = session.events()[Symbol.asyncIterator]();
await iterator.next();
await expect(session.snapshot()).resolves.toMatchObject({ terminal: null, awaitingProviderTurn: true });
if (stop) await cancelSession(session, { reason: "operator stop", signal: new AbortController().signal }).cleanup;
else end();
await expect(iterator.next()).resolves.toMatchObject({ value: { eventType: "item.completed", sourceSeq: 2 } });
const saved = await session.snapshot();
if (terminal) expect(saved.terminal).toMatchObject(terminal);
else expect(saved.terminal).toBeNull();
expect(saved.awaitingProviderTurn).toBe(stop ? undefined : true);
await expect(session.result()).resolves.toBeNull();
});
it("does not synthesize a fallback after explicit run cancellation", async () => {
class CancelledProviderSession extends FakeHarnessSession {
override async *events() {
@@ -410,6 +410,7 @@ class HarnessNativeSession implements NativeSession {
#terminal: PrpTerminalState | null = null;
#explicitlyCancelled = false;
#stopRequested = false;
#providerTurnWaitCancelled = false;
#protocolIntegrityFailure: NativeSessionProtocolIntegrityError | null = null;
#assertProtocolIntegrity(): void {
@@ -533,6 +534,7 @@ class HarnessNativeSession implements NativeSession {
this.#terminal = null;
this.#explicitlyCancelled = false;
this.#stopRequested = false;
this.#providerTurnWaitCancelled = false;
}
async release(): Promise<DurableRecoveryIdentity | false> {
@@ -627,6 +629,16 @@ class HarnessNativeSession implements NativeSession {
: null;
if (requestId) observedPendingInputs.delete(requestId);
}
if (this.#explicitlyCancelled && event.eventType === "item.completed"
&& event.payload.status === "provider_turn_wait_ended") {
this.#providerTurnWaitCancelled = true;
this.#terminal = {
schema: "paperclip.prp.terminal.v1",
turnTerminalState: "cancelled",
runTerminalState: "cancelled",
reportedWorkDisposition: "yielded",
};
}
if (event.eventType === "run.terminal") {
sawTerminal = true;
this.#terminal = structuredClone(event.payload as PrpTerminalState);
@@ -932,7 +944,7 @@ class HarnessNativeSession implements NativeSession {
pendingRuntimeRequests: snapshot.pendingRuntimeRequests ?? [],
goal: snapshot.goal ?? null,
lineage: snapshot.lineage ?? [],
...(snapshot.awaitingProviderTurn === true ? { awaitingProviderTurn: true } : {}),
...(snapshot.awaitingProviderTurn === true && !this.#providerTurnWaitCancelled ? { awaitingProviderTurn: true } : {}),
};
}
@@ -50,7 +50,7 @@ function storeSourceEvent(committed: PrpEvent[], value: PrpEvent) {
return { cursor: value.sourceSeq, highestContiguousSourceSeq, disposition: existing ? "duplicate" as const : "committed" as const };
}
async function runProviderTurnScenario(tokens: string, options: { agent?: "claude" | "codex"; capMs?: number; providerStartedTurns?: boolean } = {}) {
async function runProviderTurnScenario(tokens: string, options: { agent?: "claude" | "codex"; capMs?: number; providerStartedTurns?: boolean; stopWhileWaiting?: boolean } = {}) {
const agent = options.agent ?? "claude";
const providerStartedTurns = options.providerStartedTurns ?? agent === "claude";
const turnStarts: Array<Record<string, unknown>> = [];
@@ -118,6 +118,8 @@ async function runProviderTurnScenario(tokens: string, options: { agent?: "claud
const appended: PrpEvent[] = [], committed: PrpEvent[] = [];
const completeRun = vi.fn(async () => undefined);
const resolveMissingResult = vi.fn(async () => null);
const checkpoints: PersistedNativeSession[] = [];
let session: NativeSession | null = null;
try {
const backend = createNativeSessionBackend(execution, { codexTransportFactory: () => bundle.transport,
environment: { PAPERCLIP_WORKSPACE_CWD: root }, dynamicTools: [] });
@@ -125,25 +127,32 @@ async function runProviderTurnScenario(tokens: string, options: { agent?: "claud
const outcome = await executeNativeSession({
input: execution, backend, runnerInstanceId: identity.runnerInstanceId, controlPlaneInstanceId: "control-provider-turn",
controlPlane: {
async openRun() {}, async checkpointSession() {},
async openRun() {},
async checkpointSession(saved: PersistedNativeSession) { checkpoints.push(structuredClone(saved)); },
async appendEvent(value: PrpEvent) {
appended.push(structuredClone(value));
if (options.stopWhileWaiting && value.eventType === "turn.completed" && value.payload.awaitingProviderTurn === true) {
setTimeout(() => void session?.cancel?.({ reason: "Operator stop", signal: new AbortController().signal })?.cleanup, 250);
}
return storeSourceEvent(committed, value);
},
async replayEvents() { return { events: [], highestContiguousSourceSeq: 0 }; },
completeRun,
},
onSession: published => { if (published) session = published; },
timeoutMs: 30_000, resolveMissingResult,
providerTurnWait: options.capMs === undefined ? undefined : { capMs: options.capMs },
}).then(() => "finalized", (error: unknown) => String(error instanceof Error ? error.message : error));
const elapsedMs = Date.now() - started;
const closeOutcome = await bundle.transport.close().then(() => "closed", (error: unknown) => String(error instanceof Error ? error.message : error));
const durable = await durableState(root);
const controlJournal = JSON.parse(await readFile(join(root, "control-plane/control-plane-state.json"), "utf8")) as {
commands: Array<{ type: string; status: string }>; committedEvents: Array<{ eventType: string }> };
const journalled = await calls();
const providerPids = journalled.flatMap(entry => [entry.processStart, entry.childPid]).filter((pid): pid is number => typeof pid === "number");
await vi.waitFor(() => { for (const pid of providerPids) expect(alive(pid)).toBe(false); }, { timeout: 5_000, interval: 50 }).catch(() => undefined);
const providerProcesses = providerPids.map(pid => ({ pid, exited: !alive(pid) }));
return { outcome, appended, completeRun, resolveMissingResult, journalled, providerProcesses, root, elapsedMs, turnStarts, notificationMethods, closeOutcome, diagnostics, durable };
return { outcome, appended, completeRun, resolveMissingResult, journalled, providerProcesses, root, elapsedMs, turnStarts, notificationMethods, closeOutcome, diagnostics, durable, journal: controlJournal, checkpoints };
} catch (error) {
const diagnostics = (await readFile(join(root, "native.stderr"), "utf8").catch(() => ""))
+ (await readFile(join(root, "diagnostics", "runnerd.stderr.log"), "utf8").catch(() => ""));
@@ -164,6 +173,12 @@ const expectCleanClose = (run: Awaited<ReturnType<typeof runProviderTurnScenario
expect(unsettled(run.diagnostics)).toEqual([]);
expect(run.durable).not.toContain("conflicting duplicate");
};
const expectReleasedRunTerminal = (run: Awaited<ReturnType<typeof runProviderTurnScenario>>) => {
const types = run.journal.committedEvents.map(event => event.eventType);
expect(types.filter(type => type === "run.terminal")).toHaveLength(1);
expect(types.indexOf("run.terminal")).toBeGreaterThan(types.lastIndexOf("turn.completed"));
expect(run.journal.commands.filter(command => command.status !== "completed")).toEqual([]);
};
it.skipIf(process.platform === "win32")("continues a run in the provider's own turn after background work and settles its result", async () => {
const run = await runProviderTurnScenario("live provider-turn provider-result-resolved");
@@ -209,6 +224,22 @@ it.skipIf(process.platform === "win32")("ends the wait at the cap and takes toda
expect(run.appended.some(event => event.payload.origin === "provider")).toBe(false);
expect(run.providerProcesses.length).toBeGreaterThan(1);
expect(run.providerProcesses.filter(entry => !entry.exited)).toEqual([]);
expectReleasedRunTerminal(run);
expect(run.journal.commands.map(command => command.type)).toContain("turn.stop");
expectCleanClose(run);
}, 60_000);
it.skipIf(process.platform === "win32")("stops a run that waits for the provider's own turn and records its run terminal", async () => {
const run = await runProviderTurnScenario("live provider-turn provider-turn-hold", { capMs: 30_000, stopWhileWaiting: true });
expect(run.completeRun).not.toHaveBeenCalled();
expect(run.elapsedMs).toBeLessThan(15_000);
expect(run.appended.some(event => event.payload.origin === "provider")).toBe(false);
expect(run.providerProcesses.filter(entry => !entry.exited)).toEqual([]);
expectReleasedRunTerminal(run);
expect(run.journal.commands.map(command => command.type)).toContain("turn.stop");
expect(run.checkpoints.at(-1)).toMatchObject({ activeTurnId: null, semanticResult: null,
terminal: { turnTerminalState: "cancelled", runTerminalState: "cancelled" } });
expect(run.checkpoints.at(-1)).not.toHaveProperty("awaitingProviderTurn");
expectCleanClose(run);
}, 60_000);
@@ -237,6 +268,8 @@ it.skipIf(process.platform === "win32")("leaves a Claude turn without background
expect(run.appended.some(event => event.payload.awaitingProviderTurn === true)).toBe(false);
expect(run.appended.some(event => event.payload.status === "provider_turn_wait_ended")).toBe(false);
expect(sidecarCommands(run.journalled)).not.toContain("session.provider_turn");
expect(run.journal.commands.map(command => command.type)).not.toContain("turn.stop");
expectReleasedRunTerminal(run);
expectCleanClose(run);
}, 60_000);
@@ -1529,6 +1529,24 @@ it("infers a remote provider turn until its own terminal event is durable", () =
).toBe(false);
});
it("holds a run terminal only while the run's last turn waits for the provider's own next turn", () => {
const event = (eventType: string, payload: Record<string, unknown> = {}, runId = "run") => ({ eventType, envelope: { runId, payload: { payload } } });
const waiting = event("turn.completed", { awaitingProviderTurn: true });
const held = (...events: ReturnType<typeof event>[]) => runnerdRecoveryInternals.runnerHoldsRunTerminal(events, "run");
expect(held(event("turn.started"), waiting)).toBe(true);
expect(held(event("turn.started"), waiting, event("turn.started", { origin: "provider" }), waiting)).toBe(true);
expect(held(waiting, event("item.completed", { kind: "usage" }))).toBe(true);
expect(held(waiting, event("run.terminal", {}, "earlier"))).toBe(true);
expect(held()).toBe(false);
expect(held(event("turn.completed"))).toBe(false);
expect(held(waiting, event("run.terminal"))).toBe(false);
expect(held(waiting, event("turn.started", { origin: "provider" }))).toBe(false);
expect(held(waiting, event("turn.completed"))).toBe(false);
expect(held(waiting, event("turn.interrupted"))).toBe(false);
expect(held(event("turn.completed", { awaitingProviderTurn: true }, "earlier"))).toBe(false);
expect(held(event("turn.failed", { awaitingProviderTurn: true }))).toBe(false);
});
it("accepts only the observed provider start correlated by the command result", () => {
const requestedTurnId = "turn_lab_0123456789abcdef0123456789abcdef";
expect(
@@ -903,6 +903,22 @@ function providerTurnIsActiveFromCommittedEvents(
return active;
}
function runnerHoldsRunTerminal(
events: readonly Pick<DurableRecoveryCommittedEvent, "eventType" | "envelope">[],
runId: string,
): boolean {
let held = false;
for (const event of events) {
if (event.envelope.runId !== runId) continue;
if (event.eventType === "turn.completed") {
held = record(record(event.envelope.payload).payload).awaitingProviderTurn === true;
} else if (["run.terminal", "turn.started", "turn.failed", "turn.interrupted", "turn.cancelled"].includes(event.eventType)) {
held = false;
}
}
return held;
}
function turnStartResponseReady(input: {
responseEpoch: number;
observedEpoch: number;
@@ -5561,9 +5577,11 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
&& this.options.acpxAgent === "pi"
&& state !== "unreadable"
&& (state === null || (state.activeProviderTurnId === null && state.providerSettled));
const releaseRunTerminal = activeProviderTurnId === null && core !== null
&& runnerHoldsRunTerminal(core.store.state.committedEvents, core.store.state.identity.runId);
if (
state === "unreadable" ||
(activeProviderTurnId === null && !stopIdlePi && this.options.recoveryPurpose !== "stop_cleanup") ||
(activeProviderTurnId === null && !stopIdlePi && !releaseRunTerminal && this.options.recoveryPurpose !== "stop_cleanup") ||
core === null
) {
return false;
@@ -5582,7 +5600,9 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
);
if (command?.status === "completed") {
this.#diagnostic(
activeProviderTurnId === null
releaseRunTerminal
? "ended the provider turn wait before runner suspension"
: activeProviderTurnId === null
? "stopped idle Pi provider before runner suspension"
: `stopped active provider turn ${activeProviderTurnId} before runner suspension`,
);
@@ -9974,6 +9994,7 @@ export const runnerdRecoveryInternals = Object.freeze({
RunnerSuspensionProofRefutedError,
providerDrainStateFromSnapshot,
providerTurnIsActiveFromCommittedEvents,
runnerHoldsRunTerminal,
recoveredRunAttachment,
cutOffRunAttachmentPayload,
releaseRunnerProcessOwnership,