Skip to content

Commit 678a3c1

Browse files
fix(gateway): finish successful sessions after timestamp races (#119752)
* fix(gateway): correlate session lifecycle by run * test(qa): expect settled handoffs to survive restart quietly * test(agents): split embedded run persistence coverage
1 parent a20746e commit 678a3c1

39 files changed

Lines changed: 472 additions & 120 deletions

‎extensions/qa-lab/src/scenario-catalog-channels.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,8 @@ describe("qa scenario catalog channel contracts", () => {
170170
expect(flow).toContain("task.deliveryStatus === 'delivered'");
171171
expect(flow).toContain("readSettledTerminalTask('restart')");
172172
expect(flow).toContain("readSettledTerminalTask('empty')");
173+
expect(flow).toContain("postRestartUnexpectedPayloads.length === 0");
174+
expect(flow).not.toContain("interrupted by a gateway restart");
173175
expect(flow).toContain("verdicts.length === 5");
174176
expect(flow).not.toContain('"call":"sleep"');
175177
});

‎qa/scenarios/agents/subagent-completion-direct-fallback.yaml‎

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ scenario:
2424
- Visible completion output reaches the originating QA DM exactly once.
2525
- Exact NO_REPLY completion output produces no channel delivery.
2626
- Genuinely empty completion output is represented intentionally once.
27-
- Gateway restart does not replay prior terminal payloads, represents the interrupted handoff explicitly, and a post-restart completion is delivered exactly once.
27+
- Gateway restart does not replay prior terminal payloads or synthesize interruption notices for already-settled handoffs, and a post-restart completion is delivered exactly once.
2828
- Direct fallback strips protected internal metadata before one channel delivery.
2929
docsRefs:
3030
- docs/tools/subagents.md
@@ -179,29 +179,6 @@ flow:
179179
args:
180180
- ref: env
181181
- 180000
182-
- call: waitForCondition
183-
args:
184-
- lambda:
185-
expr: "state.getSnapshot().messages.find((message) => message.direction === 'outbound' && verdicts.some((verdict) => verdict.conversationId === message.conversation.id) && !preRestartOutbound.some((before) => before.id === message.id) && String(message.text ?? '').includes('interrupted by a gateway restart'))"
186-
- 60000
187-
- 250
188-
- set: postRestartOutbound
189-
value:
190-
expr: "state.getSnapshot().messages.filter((message) => message.direction === 'outbound' && verdicts.some((verdict) => verdict.conversationId === message.conversation.id)).map((message) => ({ id: message.id, conversationId: message.conversation.id, text: String(message.text ?? '') }))"
191-
- set: postRestartTerminalPayloads
192-
value:
193-
expr: "postRestartOutbound.filter((message) => verdicts.some((verdict) => verdict.capturedTerminalPayloads.includes(message.text)))"
194-
- set: restartInterruptionPayloads
195-
value:
196-
expr: "postRestartOutbound.filter((message) => !preRestartOutbound.some((before) => before.id === message.id))"
197-
- assert:
198-
expr: "JSON.stringify(postRestartTerminalPayloads) === JSON.stringify(preRestartTerminalPayloads)"
199-
message:
200-
expr: "`Gateway restart replayed or lost a prior terminal payload: before=${JSON.stringify(preRestartTerminalPayloads)} after=${JSON.stringify(postRestartTerminalPayloads)}`"
201-
- assert:
202-
expr: "restartInterruptionPayloads.length === 1 && restartInterruptionPayloads.every((message) => message.text.includes('interrupted by a gateway restart'))"
203-
message:
204-
expr: "`Gateway restart did not represent the interrupted completion handoff exactly once: ${JSON.stringify(restartInterruptionPayloads)}`"
205182
- set: restartStartIndex
206183
value:
207184
expr: state.getSnapshot().messages.length
@@ -241,9 +218,28 @@ flow:
241218
expr: "restartTask.title === 'qa-terminal-restart' && restartTask.status === 'completed' && restartTask.deliveryStatus === 'delivered'"
242219
message:
243220
expr: "`restart completion task lifecycle did not settle authoritatively; task=${JSON.stringify(restartTask)}`"
221+
# Use a new durably delivered task as the observation boundary. By then,
222+
# restart recovery must not have replayed or invented output for settled tasks.
223+
- set: postRestartOutbound
224+
value:
225+
expr: "state.getSnapshot().messages.filter((message) => message.direction === 'outbound' && verdicts.some((verdict) => verdict.conversationId === message.conversation.id)).map((message) => ({ id: message.id, conversationId: message.conversation.id, text: String(message.text ?? '') }))"
226+
- set: postRestartTerminalPayloads
227+
value:
228+
expr: "postRestartOutbound.filter((message) => verdicts.some((verdict) => verdict.capturedTerminalPayloads.includes(message.text)))"
229+
- set: postRestartUnexpectedPayloads
230+
value:
231+
expr: "postRestartOutbound.filter((message) => !preRestartOutbound.some((before) => before.id === message.id))"
232+
- assert:
233+
expr: "JSON.stringify(postRestartTerminalPayloads) === JSON.stringify(preRestartTerminalPayloads)"
234+
message:
235+
expr: "`Gateway restart replayed or lost a prior terminal payload: before=${JSON.stringify(preRestartTerminalPayloads)} after=${JSON.stringify(postRestartTerminalPayloads)}`"
236+
- assert:
237+
expr: "postRestartUnexpectedPayloads.length === 0"
238+
message:
239+
expr: "`Gateway restart synthesized output for already-settled handoffs: ${JSON.stringify(postRestartUnexpectedPayloads)}`"
244240
- set: appendRestartVerdict
245241
value:
246-
expr: "verdicts.push({ case: 'restart', conversationId: restartConversationId, taskId: restartTask.taskId, taskDeliveryStatus: restartTask.deliveryStatus, inputDisposition: 'visible', restart: true, fallback: true, preRestartTerminalMessageCount: preRestartTerminalPayloads.length, postRestartTerminalPayloadCount: postRestartTerminalPayloads.length, priorTerminalPayloadReplayCount: postRestartTerminalPayloads.length - preRestartTerminalPayloads.length, interruptedHandoffRepresentationCount: restartInterruptionPayloads.length, interruptedHandoffPayloads: restartInterruptionPayloads.map((message) => message.text), expectedTerminalSendCount: 1, actualTerminalSendCount: restartMatches.length, capturedTerminalPayloads: restartMatches.map((message) => String(message.text ?? '')), silenceTokenLeaked: false, internalMetadataLeak: false, pass: true })"
242+
expr: "verdicts.push({ case: 'restart', conversationId: restartConversationId, taskId: restartTask.taskId, taskDeliveryStatus: restartTask.deliveryStatus, inputDisposition: 'visible', restart: true, fallback: true, preRestartTerminalMessageCount: preRestartTerminalPayloads.length, postRestartTerminalPayloadCount: postRestartTerminalPayloads.length, priorTerminalPayloadReplayCount: postRestartTerminalPayloads.length - preRestartTerminalPayloads.length, unexpectedPostRestartPayloadCount: postRestartUnexpectedPayloads.length, unexpectedPostRestartPayloads: postRestartUnexpectedPayloads.map((message) => message.text), expectedTerminalSendCount: 1, actualTerminalSendCount: restartMatches.length, capturedTerminalPayloads: restartMatches.map((message) => String(message.text ?? '')), silenceTokenLeaked: false, internalMetadataLeak: false, pass: true })"
247243
- set: emptyStartIndex
248244
value:
249245
expr: state.getSnapshot().messages.length

‎src/agents/command/session.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import {
2727
import { resolveChannelResetConfig, resolveSessionResetType } from "../../config/sessions/reset.js";
2828
import { listSessionEntries } from "../../config/sessions/session-accessor.js";
2929
import { resolveSessionKey } from "../../config/sessions/session-key.js";
30-
import type { SessionEntry } from "../../config/sessions/types.js";
30+
import type { InternalSessionEntry as SessionEntry } from "../../config/sessions/types.js";
3131
import type { OpenClawConfig } from "../../config/types.openclaw.js";
3232
import {
3333
classifySessionKeyShape,
@@ -67,6 +67,7 @@ export function clearRotatedSessionMetadata(entry: SessionEntry): SessionEntry {
6767
...entry,
6868
sessionFile: undefined,
6969
status: undefined,
70+
lifecycleRunId: undefined,
7071
startedAt: undefined,
7172
endedAt: undefined,
7273
runtimeMs: undefined,
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { loadSessionEntry, replaceSessionEntry } from "../../config/sessions/session-accessor.js";
6+
import type { InternalSessionEntry } from "../../config/sessions/types.js";
7+
import { testing } from "./runs.test-support.js";
8+
9+
describe("embedded-agent runner persistence", () => {
10+
afterEach(() => {
11+
testing.resetActiveEmbeddedRuns();
12+
});
13+
14+
it("clears lifecycle ownership when a forced run clear persists killed state", async () => {
15+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-force-clear-"));
16+
const storePath = path.join(root, "sessions.json");
17+
const sessionKey = "agent:main:main";
18+
const entry: InternalSessionEntry = {
19+
lifecycleRunId: "stuck-run",
20+
sessionId: "session-stuck",
21+
startedAt: 10,
22+
status: "running",
23+
updatedAt: 20,
24+
};
25+
try {
26+
await replaceSessionEntry({ storePath, sessionKey }, entry);
27+
await testing.persistForceClearedEmbeddedRunTerminalState({
28+
sessionId: entry.sessionId,
29+
sessionKey,
30+
startedAt: entry.startedAt,
31+
storePath,
32+
updatedAt: entry.updatedAt,
33+
});
34+
35+
const persisted = loadSessionEntry({ storePath, sessionKey }) as InternalSessionEntry;
36+
expect(persisted.status).toBe("killed");
37+
expect(persisted.lifecycleRunId).toBeUndefined();
38+
} finally {
39+
await fs.rm(root, { recursive: true, force: true });
40+
}
41+
});
42+
});

‎src/agents/embedded-agent-runner/runs.test-support.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
import "./runs.js";
22

33
type EmbeddedRunsTestApi = {
4+
persistForceClearedEmbeddedRunTerminalState(params: {
5+
sessionId: string;
6+
sessionKey: string;
7+
startedAt?: number;
8+
storePath: string;
9+
updatedAt: number;
10+
}): Promise<void>;
411
resetActiveEmbeddedRuns(): void;
512
};
613

‎src/agents/embedded-agent-runner/runs.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
import { getRuntimeConfig } from "../../config/io.js";
2626
import { resolveStorePath } from "../../config/sessions/paths.js";
2727
import { loadSessionEntry, updateSessionEntry } from "../../config/sessions/session-accessor.js";
28+
import type { InternalSessionEntry } from "../../config/sessions/types.js";
2829
import {
2930
getAgentEventLifecycleGeneration,
3031
isAgentEventLifecycleGenerationCurrent,
@@ -958,7 +959,8 @@ async function persistForceClearedEmbeddedRunTerminalState(params: {
958959
try {
959960
await updateSessionEntry(
960961
{ sessionKey: params.sessionKey, storePath: params.storePath },
961-
(entry) => {
962+
(storedEntry) => {
963+
const entry = storedEntry as InternalSessionEntry;
962964
// A replacement can reuse the session id; bind this patch to both owners' exact snapshot.
963965
if (
964966
ACTIVE_EMBEDDED_RUNS.has(params.sessionId) ||
@@ -976,6 +978,7 @@ async function persistForceClearedEmbeddedRunTerminalState(params: {
976978
return {
977979
status: "killed",
978980
abortedLastRun: true,
981+
lifecycleRunId: undefined,
979982
endedAt,
980983
updatedAt: endedAt,
981984
};
@@ -1130,6 +1133,7 @@ function forceClearEmbeddedAgentRun(
11301133
}
11311134

11321135
const testing = {
1136+
persistForceClearedEmbeddedRunTerminalState,
11331137
resetActiveEmbeddedRuns() {
11341138
for (const waiters of EMBEDDED_RUN_WAITERS.values()) {
11351139
for (const waiter of waiters) {

‎src/agents/main-session-recovery-state.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ describe("main session recovery state", () => {
130130

131131
it("marks without charging and replaces an older lifecycle owner for the same run", () => {
132132
const entry = interruptedEntry({
133+
lifecycleRunId: "dead-run",
133134
restartRecoveryRuns: [
134135
{ runId: "older-run", lifecycleGeneration: "generation-old" },
135136
{ runId: "shared-run", lifecycleGeneration: "generation-1" },
@@ -161,6 +162,7 @@ describe("main session recovery state", () => {
161162
{ runId: "older-run", lifecycleGeneration: "generation-old" },
162163
{ runId: "shared-run", lifecycleGeneration: "generation-2" },
163164
]);
165+
expect(entry.lifecycleRunId).toBeUndefined();
164166
});
165167

166168
it("rejects foreground work after the automatic recovery budget is exhausted", () => {
@@ -343,6 +345,7 @@ describe("main session recovery state", () => {
343345
},
344346
});
345347
expect(entry.mainRestartRecovery?.reservation).toBeUndefined();
348+
expect(entry.lifecycleRunId).toBe("recovery-1");
346349

347350
expect(
348351
transitionMainSessionRecovery(entry, {
@@ -358,6 +361,7 @@ describe("main session recovery state", () => {
358361
expect(entry.abortedLastRun).toBe(true);
359362
expect(entry.restartRecoveryDeliveryRunId).toBeUndefined();
360363
expect(entry.restartRecoveryDeliverySourceRunId).toBe("source-1");
364+
expect(entry.lifecycleRunId).toBeUndefined();
361365
});
362366

363367
it("rejects a reservation created by an older lifecycle generation", () => {
@@ -565,6 +569,7 @@ describe("main session recovery state", () => {
565569

566570
it("tombstones an exhausted cycle and exposes only the Doctor repair action", () => {
567571
const entry = interruptedEntry({
572+
lifecycleRunId: "exhausted-run",
568573
mainRestartRecovery: recoveryState({
569574
chargedAttempts: 3,
570575
}),
@@ -584,6 +589,7 @@ describe("main session recovery state", () => {
584589
}),
585590
).toEqual({ kind: "tombstoned" });
586591
expect(entry.mainRestartRecovery?.tombstone?.reason).toBe(view.reason);
592+
expect(entry.lifecycleRunId).toBeUndefined();
587593
expect(observe(entry, "generation-1")).toEqual({ status: "tombstoned" });
588594

589595
entry.abortedLastRun = true;

‎src/agents/main-session-recovery-state.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,7 @@ export function transitionMainSessionRecovery(
266266
entry.mainRestartRecovery = createCycle(command.cycleId);
267267
}
268268
entry.status = "running";
269+
entry.lifecycleRunId = undefined;
269270
entry.abortedLastRun = true;
270271
if (command.resetRuntime) {
271272
entry.startedAt = undefined;
@@ -419,6 +420,7 @@ export function transitionMainSessionRecovery(
419420
foregroundClaims: undefined,
420421
});
421422
entry.abortedLastRun = false;
423+
entry.lifecycleRunId = command.runId;
422424
recordLifecycleFence(entry, {
423425
runId: command.runId,
424426
lifecycleGeneration: command.lifecycleGeneration,
@@ -449,6 +451,7 @@ export function transitionMainSessionRecovery(
449451
return { kind: "rejected", reason: "stale_reservation" };
450452
}
451453
entry.status = "running";
454+
entry.lifecycleRunId = undefined;
452455
entry.abortedLastRun = true;
453456
entry.startedAt = undefined;
454457
entry.endedAt = undefined;
@@ -599,6 +602,7 @@ export function transitionMainSessionRecovery(
599602
});
600603
entry.abortedLastRun = false;
601604
entry.status = "failed";
605+
entry.lifecycleRunId = undefined;
602606
entry.endedAt = command.now;
603607
entry.runtimeMs = Math.max(0, command.now - (entry.startedAt ?? command.now));
604608
entry.updatedAt = command.now;
@@ -611,6 +615,7 @@ export function transitionMainSessionRecovery(
611615
}
612616
const noticeEntry = structuredClone(entry);
613617
entry.status = "failed";
618+
entry.lifecycleRunId = undefined;
614619
entry.abortedLastRun = true;
615620
entry.endedAt = command.now;
616621
entry.updatedAt = command.now;

‎src/agents/main-session-restart-recovery-checkpoint.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ export async function reconcileInterruptedCompletionReport(params: {
6666
...buildRestartRecoveryClaimCleanupPatch({ entry, recordTerminalSource: false }),
6767
...buildMainSessionRecoveryClearPatch(entry),
6868
status: "killed",
69+
lifecycleRunId: undefined,
6970
abortedLastRun: false,
7071
endedAt,
7172
lastRunError: undefined,
@@ -315,6 +316,7 @@ export async function markSessionCompletedAfterRecoveryCheckpoint(params: {
315316
terminalSourceRunId: expectedRecoverySourceRunId,
316317
}),
317318
abortedLastRun: false,
319+
lifecycleRunId: undefined,
318320
endedAt,
319321
pendingFinalDelivery: undefined,
320322
restartRecoveryForceSafeTools: undefined,

‎src/agents/main-session-restart-recovery-failure.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ export async function tombstoneMainRestartRecoveryWithNotice(params: {
8181
sessionLifecyclePatch: {
8282
abortedLastRun: false,
8383
endedAt: now,
84+
lifecycleRunId: undefined,
8485
mainRestartRecovery: {
8586
...recoveryState,
8687
revision: recoveryState.revision + 1,

0 commit comments

Comments
 (0)