Skip to content

Commit 14694c1

Browse files
committed
fix(runtime): preserve restart claims and deadline outcomes
Forward the missing release runtime fixes while retaining main native accounting ownership. Validate restart cleanup in the synchronous commit after queued patch preparation, preserve parent deadline precedence, and mark empty-session token totals stale when a turn supplies no usage.
1 parent d7337b9 commit 14694c1

7 files changed

Lines changed: 353 additions & 86 deletions

File tree

‎src/agents/command/session-store.test.ts‎

Lines changed: 43 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1141,52 +1141,55 @@ describe("updateSessionStoreAfterAgentRun", () => {
11411141
});
11421142
});
11431143

1144-
it("preserves previous totalTokens when provider returns no usage data (#67667)", async () => {
1145-
await withTempSessionStore(async ({ storePath }) => {
1146-
const cfg = {} as OpenClawConfig;
1147-
const sessionKey = "agent:main:explicit:test-no-usage";
1148-
const sessionId = "test-session";
1149-
1150-
const sessionStore: Record<string, SessionEntry> = {
1151-
[sessionKey]: {
1152-
sessionId,
1153-
updatedAt: 1,
1154-
totalTokens: 21225,
1155-
totalTokensFresh: true,
1156-
},
1157-
};
1158-
await seedSessionStore(storePath, sessionStore);
1144+
it.each([21_225, 0])(
1145+
"marks previous totalTokens=%i stale without provider usage (#67667)",
1146+
async (totalTokens) => {
1147+
await withTempSessionStore(async ({ storePath }) => {
1148+
const cfg = {} as OpenClawConfig;
1149+
const sessionKey = "agent:main:explicit:test-no-usage";
1150+
const sessionId = "test-session";
11591151

1160-
const result: EmbeddedAgentRunResult = {
1161-
meta: {
1162-
durationMs: 500,
1163-
agentMeta: {
1152+
const sessionStore: Record<string, SessionEntry> = {
1153+
[sessionKey]: {
11641154
sessionId,
1165-
provider: "minimax",
1166-
model: "MiniMax-M2.7",
1155+
updatedAt: 1,
1156+
totalTokens,
1157+
totalTokensFresh: true,
11671158
},
1168-
},
1169-
};
1159+
};
1160+
await seedSessionStore(storePath, sessionStore);
11701161

1171-
await updateSessionStoreAfterAgentRun({
1172-
cfg,
1173-
sessionId,
1174-
sessionKey,
1175-
storePath,
1176-
sessionStore,
1177-
defaultProvider: "minimax",
1178-
defaultModel: "MiniMax-M2.7",
1179-
result,
1180-
});
1162+
const result: EmbeddedAgentRunResult = {
1163+
meta: {
1164+
durationMs: 500,
1165+
agentMeta: {
1166+
sessionId,
1167+
provider: "minimax",
1168+
model: "MiniMax-M2.7",
1169+
},
1170+
},
1171+
};
11811172

1182-
expect(sessionStore[sessionKey]?.totalTokens).toBe(21225);
1183-
expect(sessionStore[sessionKey]?.totalTokensFresh).toBe(false);
1173+
await updateSessionStoreAfterAgentRun({
1174+
cfg,
1175+
sessionId,
1176+
sessionKey,
1177+
storePath,
1178+
sessionStore,
1179+
defaultProvider: "minimax",
1180+
defaultModel: "MiniMax-M2.7",
1181+
result,
1182+
});
11841183

1185-
const persisted = loadPersistedSessionStore(storePath);
1186-
expect(persisted[sessionKey]?.totalTokens).toBe(21225);
1187-
expect(persisted[sessionKey]?.totalTokensFresh).toBe(false);
1188-
});
1189-
});
1184+
expect(sessionStore[sessionKey]?.totalTokens).toBe(totalTokens);
1185+
expect(sessionStore[sessionKey]?.totalTokensFresh).toBe(false);
1186+
1187+
const persisted = loadPersistedSessionStore(storePath);
1188+
expect(persisted[sessionKey]?.totalTokens).toBe(totalTokens);
1189+
expect(persisted[sessionKey]?.totalTokensFresh).toBe(false);
1190+
});
1191+
},
1192+
);
11901193

11911194
it("persists estimated context budget status without marking stale usage fresh", async () => {
11921195
await withTempSessionStore(async ({ storePath }) => {

‎src/agents/command/session-store.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -220,11 +220,8 @@ export async function updateSessionStoreAfterAgentRun(params: {
220220
next.totalTokensFresh = totalTokens !== undefined;
221221
next.totalTokensVersion =
222222
totalTokens !== undefined ? SESSION_TOTAL_TOKENS_VERSION : undefined;
223-
} else if (
224-
typeof entry.totalTokens === "number" &&
225-
Number.isFinite(entry.totalTokens) &&
226-
entry.totalTokens > 0
227-
) {
223+
} else {
224+
// Empty-session zero is no longer current after a turn without usage.
228225
next.totalTokensFresh = false;
229226
next.totalTokensVersion = undefined;
230227
}

‎src/auto-reply/reply/agent-runner-execute.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,7 @@ export function createReplyAgentRestartRecoveryController(
501501
clear: clearRestartRecoveryDeliveryClaim,
502502
isArmed: isRestartRecoveryArmed,
503503
} = createReplyRestartRecoveryClaimController({
504+
lifecycleGeneration: replyOperation.lifecycleGeneration,
504505
admissionRunId:
505506
normalizeOptionalString(sessionCtx.MessageSid) ??
506507
normalizeOptionalString(sessionCtx.MessageSidFull),

‎src/auto-reply/reply/restart-recovery-claim.test.ts‎

Lines changed: 182 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,24 @@
11
import path from "node:path";
22
import { afterEach, describe, expect, it, vi } from "vitest";
3+
import { createDeferred } from "../../../test/helpers/promise.js";
34
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
5+
import { transitionMainSessionRecovery } from "../../agents/main-session-recovery/main-session-recovery-state.js";
46
import {
57
claimMainSessionRecoveryOwner,
68
releaseMainSessionRecoveryOwner,
79
} from "../../agents/main-session-recovery/main-session-recovery-store.js";
810
import {
911
loadSessionEntry,
12+
markSessionAbortTarget,
1013
replaceSessionEntry,
1114
updateSessionEntry,
1215
} from "../../config/sessions/session-accessor.js";
1316
import type { InternalSessionEntry, SessionEntry } from "../../config/sessions/types.js";
14-
import { getAgentEventLifecycleGeneration } from "../../infra/agent-events.js";
17+
import {
18+
getAgentEventLifecycleGeneration,
19+
rotateAgentEventLifecycleGeneration,
20+
} from "../../infra/agent-events.js";
21+
import { isAgentRunStaleLifecycleError } from "../../infra/agent-lifecycle-error.js";
1522
import { createUserTurnTranscriptRecorder } from "../../sessions/user-turn-transcript.js";
1623
import type {
1724
UserTurnTranscriptRecorder,
@@ -64,6 +71,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
6471
};
6572
await replaceSessionEntry({ storePath, sessionKey }, entry);
6673
const controller = createReplyRestartRecoveryClaimController({
74+
lifecycleGeneration: getAgentEventLifecycleGeneration(),
6775
admissionRunId: "recovery-run",
6876
getEntry: () => entry,
6977
getSessionId: () => sessionId,
@@ -110,6 +118,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
110118
};
111119
await replaceSessionEntry({ storePath, sessionKey }, entry);
112120
const controller = createReplyRestartRecoveryClaimController({
121+
lifecycleGeneration: getAgentEventLifecycleGeneration(),
113122
admissionRunId: "recovery-run",
114123
getEntry: () => entry,
115124
getSessionId: () => sessionId,
@@ -133,6 +142,173 @@ describe("createReplyRestartRecoveryClaimController", () => {
133142
});
134143
});
135144

145+
it.each([
146+
"restart-handoff",
147+
"restart-abort",
148+
"successor-generation",
149+
"missing-generation",
150+
"commit-rotation",
151+
"commit-abort",
152+
] as const)(
153+
"preserves the delivery claim when queued cleanup loses ownership through %s",
154+
async (interruption) => {
155+
const root = tempDirs.make("openclaw-reply-claim-queued-cleanup-");
156+
const scope = { storePath: path.join(root, "sessions.json"), sessionKey: "agent:main:main" };
157+
const lifecycleGeneration = getAgentEventLifecycleGeneration();
158+
const deliveryContext = { channel: "telegram", to: "chat", accountId: "default" };
159+
let restartAborted = false;
160+
let interruptBeforeCommit = false;
161+
let entry: InternalSessionEntry = {
162+
sessionId: "session",
163+
updatedAt: 1,
164+
status: "running",
165+
abortedLastRun: false,
166+
restartRecoveryDeliveryRunId: "recovery-run",
167+
restartRecoveryDeliverySourceRunId: "source-turn",
168+
restartRecoveryDeliveryContext: deliveryContext,
169+
restartRecoverySourceIngress: "channel",
170+
};
171+
await replaceSessionEntry(scope, entry);
172+
const controller = createReplyRestartRecoveryClaimController({
173+
lifecycleGeneration:
174+
interruption === "missing-generation" ? undefined : lifecycleGeneration,
175+
admissionRunId: "recovery-run",
176+
getEntry: () => entry,
177+
getSessionId: () => {
178+
if (interruptBeforeCommit) {
179+
interruptBeforeCommit = false;
180+
// The store awaits the prepared patch before entering its write transaction.
181+
queueMicrotask(() => {
182+
if (interruption === "commit-rotation") {
183+
rotateAgentEventLifecycleGeneration();
184+
} else {
185+
restartAborted = true;
186+
}
187+
});
188+
}
189+
return "session";
190+
},
191+
isRestartAbort: () => restartAborted,
192+
resolveDeliveryContext: () => deliveryContext,
193+
setEntry: (next) => {
194+
entry = next;
195+
},
196+
...scope,
197+
});
198+
await expect(controller.admitUserTurn()).resolves.toBe("admitted");
199+
200+
const writerEntered = createDeferred();
201+
const releaseWriter = createDeferred();
202+
let successorGeneration: string | undefined;
203+
const handoff = updateSessionEntry(scope, async (current) => {
204+
writerEntered.resolve();
205+
await releaseWriter.promise;
206+
if (interruption === "restart-handoff" || interruption === "successor-generation") {
207+
transitionMainSessionRecovery(current, {
208+
kind: "mark_interrupted",
209+
cycleId: "restart-cycle",
210+
now: 2,
211+
runs: [{ runId: "original-run", lifecycleGeneration }],
212+
});
213+
if (successorGeneration) {
214+
const recovery = current.mainRestartRecovery!;
215+
transitionMainSessionRecovery(current, {
216+
kind: "prepare_attempt",
217+
attempt: 1,
218+
lifecycleGeneration: successorGeneration,
219+
now: 3,
220+
observation: {
221+
sessionId: current.sessionId,
222+
cycleId: recovery.cycleId,
223+
revision: recovery.revision,
224+
},
225+
runId: "recovery-run",
226+
executionIdentity: { state: "disabled" },
227+
});
228+
transitionMainSessionRecovery(current, {
229+
kind: "admit_recovery",
230+
lifecycleGeneration: successorGeneration,
231+
now: 4,
232+
runId: "recovery-run",
233+
sessionId: current.sessionId,
234+
});
235+
}
236+
}
237+
return current;
238+
});
239+
await writerEntered.promise;
240+
interruptBeforeCommit = interruption === "commit-rotation" || interruption === "commit-abort";
241+
// The old cleanup enters before shutdown; its actual write waits behind the handoff.
242+
const clearing = controller.clear().catch((error: unknown) => {
243+
expect(isAgentRunStaleLifecycleError(error)).toBe(true);
244+
});
245+
try {
246+
if (interruption === "restart-abort") {
247+
restartAborted = true;
248+
} else if (interruption === "successor-generation") {
249+
successorGeneration = rotateAgentEventLifecycleGeneration();
250+
}
251+
} finally {
252+
releaseWriter.resolve();
253+
}
254+
await Promise.all([handoff, clearing]);
255+
256+
const persisted = loadSessionEntry(scope);
257+
expect(persisted).toMatchObject({
258+
status: "running",
259+
abortedLastRun: interruption === "restart-handoff",
260+
restartRecoveryDeliveryRunId: "recovery-run",
261+
restartRecoveryDeliverySourceRunId: "source-turn",
262+
restartRecoveryDeliveryContext: deliveryContext,
263+
restartRecoverySourceIngress: "channel",
264+
});
265+
expect(persisted?.restartRecoveryTerminalRunIds).toBeUndefined();
266+
if (successorGeneration) {
267+
expect(persisted?.restartRecoveryRuns).toContainEqual({
268+
runId: "recovery-run",
269+
lifecycleGeneration: successorGeneration,
270+
});
271+
}
272+
},
273+
);
274+
275+
it("retires the source claim after an ordinary user abort", async () => {
276+
const root = tempDirs.make("openclaw-reply-claim-user-abort-");
277+
const scope = { storePath: path.join(root, "sessions.json"), sessionKey: "agent:main:main" };
278+
let entry: InternalSessionEntry = {
279+
sessionId: "session",
280+
updatedAt: 1,
281+
status: "running",
282+
restartRecoveryDeliveryRunId: "recovery-run",
283+
restartRecoveryDeliverySourceRunId: "source-turn",
284+
restartRecoveryDeliveryContext: { channel: "telegram", to: "chat" },
285+
restartRecoverySourceIngress: "channel",
286+
};
287+
await replaceSessionEntry(scope, entry);
288+
const controller = createReplyRestartRecoveryClaimController({
289+
lifecycleGeneration: getAgentEventLifecycleGeneration(),
290+
admissionRunId: "recovery-run",
291+
getEntry: () => entry,
292+
getSessionId: () => "session",
293+
isRestartAbort: () => false,
294+
resolveDeliveryContext: () => undefined,
295+
setEntry: (next) => {
296+
entry = next;
297+
},
298+
...scope,
299+
});
300+
await expect(controller.admitUserTurn()).resolves.toBe("admitted");
301+
await markSessionAbortTarget({ scope });
302+
await controller.clear();
303+
304+
const persisted = loadSessionEntry(scope);
305+
expect(persisted?.abortedLastRun).toBe(true);
306+
expect(persisted?.restartRecoveryDeliveryRunId).toBeUndefined();
307+
expect(persisted?.restartRecoveryDeliveryContext).toBeUndefined();
308+
expect(persisted?.restartRecoveryDeliverySourceRunId).toBeUndefined();
309+
expect(persisted?.restartRecoveryTerminalRunIds).toContain("source-turn");
310+
});
311+
136312
it("adopts an exact channel recovery claim before execution starts", async () => {
137313
const root = tempDirs.make("openclaw-reply-channel-claim-adoption-");
138314
const storePath = path.join(root, "sessions.json");
@@ -160,6 +336,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
160336
};
161337
await replaceSessionEntry({ storePath, sessionKey }, entry);
162338
const controller = createReplyRestartRecoveryClaimController({
339+
lifecycleGeneration: getAgentEventLifecycleGeneration(),
163340
admissionRunId: "recovery-run",
164341
getEntry: () => entry,
165342
getSessionId: () => sessionId,
@@ -228,6 +405,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
228405
persistFallback: async () => undefined,
229406
} satisfies UserTurnTranscriptRecorder;
230407
const controller = createReplyRestartRecoveryClaimController({
408+
lifecycleGeneration: getAgentEventLifecycleGeneration(),
231409
getEntry: () => entry,
232410
getSessionId: () => sessionId,
233411
isRestartAbort: () => false,
@@ -311,6 +489,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
311489
persistFallback: async () => undefined,
312490
} satisfies UserTurnTranscriptRecorder;
313491
const controller = createReplyRestartRecoveryClaimController({
492+
lifecycleGeneration: getAgentEventLifecycleGeneration(),
314493
getEntry: () => entry,
315494
getSessionId: () => sessionId,
316495
isRestartAbort: () => false,
@@ -405,6 +584,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
405584
persistFallback: async () => undefined,
406585
} satisfies UserTurnTranscriptRecorder;
407586
const controller = createReplyRestartRecoveryClaimController({
587+
lifecycleGeneration: getAgentEventLifecycleGeneration(),
408588
getEntry: () => entry,
409589
getSessionId: () => sessionId,
410590
isRestartAbort: () => false,
@@ -505,6 +685,7 @@ describe("createReplyRestartRecoveryClaimController", () => {
505685
},
506686
} satisfies UserTurnTranscriptRecorder;
507687
const controller = createReplyRestartRecoveryClaimController({
688+
lifecycleGeneration: getAgentEventLifecycleGeneration(),
508689
getEntry: () => entry,
509690
getSessionId: () => sessionId,
510691
isRestartAbort: () => false,

0 commit comments

Comments
 (0)