Skip to content

Commit 1a1f271

Browse files
committed
fix(gateway): recover admitted turns across restart
1 parent 25a16dd commit 1a1f271

8 files changed

Lines changed: 118 additions & 36 deletions

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

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type { OpenClawConfig } from "../../config/types.openclaw.js";
1111
import { resolveGatewaySessionStoreTarget } from "../../gateway/session-utils.js";
1212
import { getAgentEventLifecycleGeneration } from "../../infra/agent-events.js";
1313
import { listAgentRunsForSession } from "../../infra/agent-run-registry.js";
14+
import { collectActiveSessionWorkAdmissions } from "../../sessions/session-lifecycle-admission.js";
1415
import {
1516
listActiveEmbeddedRunSessionIds,
1617
listActiveEmbeddedRunSessionKeys,
@@ -37,7 +38,13 @@ async function markRecoveryStore(params: {
3738
entry: SessionEntry,
3839
sessionKey: string,
3940
) =>
40-
| { action: "mark"; replaceRuns?: boolean; resetRuntime?: boolean; runs?: RestartRecoveryRun[] }
41+
| {
42+
action: "mark";
43+
forceRestartSafeTools?: boolean;
44+
replaceRuns?: boolean;
45+
resetRuntime?: boolean;
46+
runs?: RestartRecoveryRun[];
47+
}
4148
| { action: "retire_terminal" }
4249
| undefined;
4350
}) {
@@ -71,6 +78,9 @@ async function markRecoveryStore(params: {
7178
if (plan.replaceRuns) {
7279
entry.restartRecoveryRuns = plan.runs;
7380
}
81+
if (plan.forceRestartSafeTools) {
82+
entry.restartRecoveryForceSafeTools = true;
83+
}
7484
transitionMainSessionRecovery(entry, {
7585
kind: "mark_interrupted",
7686
cycleId: randomUUID(),
@@ -121,7 +131,15 @@ export async function markRestartAbortedMainSessions(params: {
121131
.filter((run) => run.runId && run.lifecycleGeneration && (run.sessionKey || run.sessionId));
122132
const currentLifecycleGeneration = getAgentEventLifecycleGeneration();
123133
const result = { marked: 0, skipped: 0 };
124-
if (sessionKeys.size === 0 && sessionIds.size === 0) {
134+
// Channel work can outlive its chat-run registration. The admission owner
135+
// retains the authoritative store and session identities until the turn releases.
136+
const activeAdmissions = collectActiveSessionWorkAdmissions();
137+
if (
138+
sessionKeys.size === 0 &&
139+
sessionIds.size === 0 &&
140+
activeRuns.length === 0 &&
141+
activeAdmissions.size === 0
142+
) {
125143
return result;
126144
}
127145

@@ -169,7 +187,11 @@ export async function markRestartAbortedMainSessions(params: {
169187
storePaths.add(path.join(sessionsDir, "sessions.json"));
170188
}
171189

190+
for (const storePath of activeAdmissions.keys()) {
191+
storePaths.add(storePath);
192+
}
172193
for (const storePath of storePaths) {
194+
const activeAdmissionIdentities = activeAdmissions.get(storePath) ?? new Set<string>();
173195
const storeResult = await markRecoveryStore({
174196
storePath,
175197
plan: (entry, sessionKey) => {
@@ -190,14 +212,20 @@ export async function markRestartAbortedMainSessions(params: {
190212
if (
191213
entry.status !== "running" &&
192214
matchingActiveRuns.length === 0 &&
193-
registeredActiveRuns.length === 0
215+
registeredActiveRuns.length === 0 &&
216+
!activeAdmissionIdentities.has(sessionKey) &&
217+
!activeAdmissionIdentities.has(entry.sessionId)
194218
) {
195219
return undefined;
196220
}
221+
const matchedActiveAdmission =
222+
activeAdmissionIdentities.has(sessionKey) ||
223+
activeAdmissionIdentities.has(entry.sessionId);
197224
const matches =
198-
typeof entry.sessionId === "string" && sessionIds.has(entry.sessionId)
225+
matchedActiveAdmission ||
226+
(typeof entry.sessionId === "string" && sessionIds.has(entry.sessionId)
199227
? true
200-
: !preferSessionIdMatch && sessionKeys.has(sessionKey);
228+
: !preferSessionIdMatch && sessionKeys.has(sessionKey));
201229
if (!matches) {
202230
return undefined;
203231
}
@@ -212,7 +240,13 @@ export async function markRestartAbortedMainSessions(params: {
212240
lifecycleGeneration,
213241
})),
214242
]);
215-
return { action: "mark", replaceRuns: true, resetRuntime: !wasRunning, runs };
243+
return {
244+
action: "mark",
245+
forceRestartSafeTools: matchedActiveAdmission,
246+
replaceRuns: true,
247+
resetRuntime: !wasRunning,
248+
runs,
249+
};
216250
},
217251
});
218252
result.marked += storeResult.marked;

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import {
5252
tryBeginGatewayRootWorkAdmission,
5353
} from "../../process/gateway-work-admission.js";
5454
import {
55+
beginSessionWorkAdmission,
5556
interruptSessionWorkAdmissions,
5657
isSessionLifecycleMutationActive,
5758
isSessionWorkAdmissionActive,
@@ -540,6 +541,34 @@ describe("main-session-restart-recovery", () => {
540541
]);
541542
});
542543

544+
it("marks an admitted channel turn when no chat run remains", async () => {
545+
const storePath = path.join(tmpDir, "admitted-channel", "sessions.json");
546+
const sessionKey = "agent:main:main";
547+
const sessionId = "admitted-channel-session";
548+
await writeStorePath(storePath, {
549+
[sessionKey]: runningSessionEntry(sessionId),
550+
});
551+
const admission = await beginSessionWorkAdmission({
552+
scope: storePath,
553+
identities: [sessionKey, sessionId],
554+
assertAllowed: () => undefined,
555+
});
556+
557+
try {
558+
await expect(markRestartAbortedMainSessions({ stateDir: tmpDir })).resolves.toEqual({
559+
marked: 1,
560+
skipped: 0,
561+
});
562+
expect(readStore(storePath)[sessionKey]).toMatchObject({
563+
status: "running",
564+
abortedLastRun: true,
565+
restartRecoveryForceSafeTools: true,
566+
});
567+
} finally {
568+
admission.release();
569+
}
570+
});
571+
543572
it("does not scan stale stores for agents absent from the configured roster", async () => {
544573
const configuredSessionsDir = await makeSessionsDir("main");
545574
await writeMainSession({ sessionsDir: configuredSessionsDir });

‎src/config/sessions/session-history-eviction.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import path from "node:path";
33
import { executeSqliteQuerySync } from "../../infra/kysely-sync.js";
44
import { createSubsystemLogger } from "../../logging/subsystem.js";
55
import {
6-
collectActiveSessionWorkAdmissionIdentities,
6+
collectActiveSessionWorkAdmissions,
77
runExclusiveSessionLifecycleMutation,
88
} from "../../sessions/session-lifecycle-admission.js";
99
import { runQueuedStoreWrite, type StoreWriterQueue } from "../../shared/store-writer-queue.js";
@@ -230,7 +230,8 @@ export function collectAdmissionProtectedSessionIds(params: {
230230
storePath: string;
231231
}): Set<string> {
232232
const protectedSessionIds = new Set<string>();
233-
const admissionIdentities = collectActiveSessionWorkAdmissionIdentities(params.storePath);
233+
const admissionIdentities =
234+
collectActiveSessionWorkAdmissions().get(params.storePath) ?? new Set<string>();
234235
if (admissionIdentities.size === 0) {
235236
return protectedSessionIds;
236237
}

‎src/config/sessions/store-maintenance-preserve.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Maintenance preserve providers protect runtime-owned sessions from pruning/capping.
2-
import { collectActiveSessionWorkAdmissionIdentities } from "../../sessions/session-lifecycle-admission.js";
2+
import { collectActiveSessionWorkAdmissions } from "../../sessions/session-lifecycle-admission.js";
33
import { normalizeStoreSessionKey } from "./store-entry.js";
44
import type { SessionEntry } from "./types.js";
55

@@ -58,7 +58,8 @@ export function collectActiveSessionWorkAdmissionKeys(params: {
5858
storePath: string;
5959
store: Record<string, SessionEntry>;
6060
}): Set<string> | undefined {
61-
const activeIdentities = collectActiveSessionWorkAdmissionIdentities(params.storePath);
61+
const activeIdentities =
62+
collectActiveSessionWorkAdmissions().get(params.storePath) ?? new Set<string>();
6263
if (activeIdentities.size === 0) {
6364
return undefined;
6465
}

‎src/gateway/server-close.test.ts‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -835,6 +835,32 @@ describe("createGatewayCloseHandler", () => {
835835
).toBe(true);
836836
});
837837

838+
it("marks pending reply work after its chat run registration is gone", async () => {
839+
const markMainSessionsAbortedForRestart = vi.fn<MarkMainSessionsAbortedForRestart>();
840+
const close = createGatewayCloseHandler(
841+
createGatewayCloseTestDeps({
842+
getPendingReplyCount: () => 1,
843+
markMainSessionsAbortedForRestart,
844+
}),
845+
);
846+
847+
const result = await close({
848+
reason: "gateway restarting",
849+
restartExpectedMs: 123,
850+
drainTimeoutMs: 0,
851+
});
852+
853+
expect(result.warnings).toContain("restart-reply-drain");
854+
expect(markMainSessionsAbortedForRestart).toHaveBeenCalledWith(
855+
expect.objectContaining({
856+
sessionKeys: new Set(),
857+
sessionIds: new Set(),
858+
activeRuns: [],
859+
reason: "gateway restart shutdown",
860+
}),
861+
);
862+
});
863+
838864
it("aborts active runs when restart reply drain times out", async () => {
839865
vi.useFakeTimers();
840866
const controller = new AbortController();
@@ -1340,7 +1366,7 @@ describe("createGatewayCloseHandler", () => {
13401366
expect(nodeSendToSession).not.toHaveBeenCalled();
13411367
});
13421368

1343-
it("awaits terminal persistence before deciding restart recovery", async () => {
1369+
it("awaits terminal persistence before deferring restart recovery to its owner", async () => {
13441370
const controller = new AbortController();
13451371
const markMainSessionsAbortedForRestart = vi.fn<MarkMainSessionsAbortedForRestart>();
13461372
const chatAbortControllers = new Map([
@@ -1374,7 +1400,13 @@ describe("createGatewayCloseHandler", () => {
13741400
drainTimeoutMs: 0,
13751401
});
13761402

1377-
expect(markMainSessionsAbortedForRestart).not.toHaveBeenCalled();
1403+
expect(markMainSessionsAbortedForRestart).toHaveBeenCalledWith(
1404+
expect.objectContaining({
1405+
sessionKeys: new Set(),
1406+
sessionIds: new Set(),
1407+
activeRuns: [],
1408+
}),
1409+
);
13781410
expect(controller.signal.aborted).toBe(true);
13791411
expect(chatAbortControllers.size).toBe(0);
13801412
});

‎src/gateway/server-close.ts‎

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -375,9 +375,6 @@ async function markActiveRunsForRestartRecovery(
375375
}
376376
await settleTerminalSessionPersistenceForRestart(params.chatAbortControllers);
377377
const refs = collectActiveRestartSessionRefs(params);
378-
if (refs.sessionKeys.size === 0 && refs.sessionIds.size === 0) {
379-
return;
380-
}
381378
try {
382379
const markerTimeout = createTimeoutRace(
383380
RESTART_MARKER_SLOW_WARNING_MS,
@@ -523,14 +520,6 @@ async function drainRestartPendingRepliesForShutdown(
523520
shutdownLog.warn(`aborted ${abortedQueuedTurns} queued turn(s) during restart shutdown`);
524521
}
525522

526-
if (
527-
drainResult.counts.activeRuns <= 0 &&
528-
(params.restartRecoveryCandidates?.size ?? 0) === 0 &&
529-
listRestartRecoveryRuns(params.chatAbortControllers).length === 0
530-
) {
531-
return;
532-
}
533-
534523
await markActiveRunsForRestartRecovery({
535524
...params,
536525
reason: "gateway restart shutdown",

‎src/gateway/server-lifecycle.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -535,9 +535,6 @@ export async function prepareGatewayLifecycle(params: {
535535
reason,
536536
isActiveRun,
537537
}) => {
538-
if (sessionKeys.size === 0 && sessionIds.size === 0) {
539-
return;
540-
}
541538
await shutdownRuntime.markRestartAbortedMainSessions({
542539
cfg: getRuntimeConfig(),
543540
sessionKeys,

‎src/sessions/session-lifecycle-admission.ts‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -377,23 +377,22 @@ export function getSessionWorkAdmissionRelease(
377377
);
378378
}
379379

380-
/** Active session identities for one store/lifecycle scope. */
381-
export function collectActiveSessionWorkAdmissionIdentities(scope: string): Set<string> {
382-
const normalizedScope = scope.trim();
383-
if (!normalizedScope) {
384-
throw new Error("session lifecycle scope is required");
385-
}
386-
const identities = new Set<string>();
380+
/** Active session identities grouped by their authoritative store/lifecycle scope. */
381+
export function collectActiveSessionWorkAdmissions(): Map<string, Set<string>> {
382+
const targets = new Map<string, Set<string>>();
387383
for (const [normalizedIdentity, admissions] of ACTIVE_SESSION_WORK_ADMISSIONS) {
388384
if (admissions.size === 0) {
389385
continue;
390386
}
391387
const decoded = decodeSessionIdentity(normalizedIdentity);
392-
if (decoded?.scope === normalizedScope) {
393-
identities.add(decoded.identity);
388+
if (!decoded) {
389+
continue;
394390
}
391+
const identities = targets.get(decoded.scope) ?? new Set<string>();
392+
identities.add(decoded.identity);
393+
targets.set(decoded.scope, identities);
395394
}
396-
return identities;
395+
return targets;
397396
}
398397

399398
/** Unique admitted turns; one lease can be indexed under several identities. */

0 commit comments

Comments
 (0)