Skip to content

Commit e6c2990

Browse files
committed
fix(tasks): skip completed deleted-agent stores
1 parent a369c7c commit e6c2990

3 files changed

Lines changed: 196 additions & 47 deletions

File tree

Lines changed: 171 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,21 @@
1-
// Covers the session-registry sweep's cron-store failure behavior: an
2-
// unreadable cron store must skip the sweep, not prune running transcripts.
1+
// Covers session-registry sweep isolation: unreadable cron facts fail the whole
2+
// sweep closed, while completed agent deletions are reported as per-store skips.
3+
import fs from "node:fs/promises";
34
import path from "node:path";
45
import { afterEach, describe, expect, it, vi } from "vitest";
6+
import { beginAgentDeletion } from "../agents/agent-lifecycle-registry.js";
57
import { resetConfigRuntimeState } from "../config/config.js";
68
import { loadSessionEntry, replaceSessionEntry } from "../config/sessions/session-accessor.js";
9+
import { resolveSqliteTargetFromSessionStorePath } from "../config/sessions/session-sqlite-target.js";
10+
import type { RuntimeEnv } from "../runtime.js";
711
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
12+
import * as taskRegistryMaintenance from "../tasks/task-registry.maintenance.js";
813
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
14+
import type { OpenClawTestState } from "../test-utils/openclaw-test-state.js";
915
import { runSessionRegistryMaintenance } from "./tasks-session-registry-maintenance.js";
16+
import { tasksMaintenanceCommand } from "./tasks.js";
1017

18+
const DAY_MS = 24 * 60 * 60_000;
1119
const mocks = vi.hoisted(() => ({
1220
cronStoreLoadError: undefined as Error | undefined,
1321
}));
@@ -25,54 +33,177 @@ vi.mock("../cron/store.js", async (importOriginal) => {
2533
};
2634
});
2735

36+
function writeAgentDeletion(
37+
state: OpenClawTestState,
38+
agentId: string,
39+
cleanupCompleted: boolean,
40+
): void {
41+
const deletion = beginAgentDeletion({
42+
agentId,
43+
agentDir: state.agentDir(agentId),
44+
workspaceDir: state.path(`workspace-${agentId}`),
45+
sessionsDir: state.sessionsDir(agentId),
46+
deleteFiles: false,
47+
});
48+
if (cleanupCompleted) {
49+
deletion.finish();
50+
}
51+
}
52+
53+
async function writeStaleCronSession(storePath: string, agentId: string): Promise<string> {
54+
const sessionKey = `agent:${agentId}:cron:done-job:run:old-run`;
55+
await replaceSessionEntry(
56+
{ sessionKey, storePath },
57+
{ sessionId: `${agentId}-old-run`, updatedAt: Date.now() - 8 * DAY_MS },
58+
);
59+
return sessionKey;
60+
}
61+
62+
async function withMaintenanceState(run: (state: OpenClawTestState) => Promise<void>) {
63+
await withOpenClawTestState(
64+
{ layout: "state-only", prefix: "openclaw-session-registry-maintenance-" },
65+
async (state) => {
66+
resetConfigRuntimeState();
67+
await run(state);
68+
},
69+
);
70+
}
71+
72+
function createRuntime(): RuntimeEnv {
73+
return {
74+
log: vi.fn(),
75+
error: vi.fn(),
76+
exit: vi.fn(),
77+
} as unknown as RuntimeEnv;
78+
}
79+
2880
describe("runSessionRegistryMaintenance", () => {
2981
afterEach(() => {
3082
mocks.cronStoreLoadError = undefined;
83+
taskRegistryMaintenance.stopTaskRegistryMaintenance();
84+
taskRegistryMaintenance.resetTaskRegistryMaintenanceRuntimeForTests();
3185
resetConfigRuntimeState();
3286
closeOpenClawAgentDatabasesForTest();
3387
});
3488

3589
it("skips the sweep instead of pruning when the cron store is unreadable", async () => {
36-
await withOpenClawTestState(
37-
{ layout: "state-only", prefix: "openclaw-session-registry-maintenance-" },
38-
async (state) => {
39-
resetConfigRuntimeState();
40-
const storePath = path.join(state.sessionsDir("main"), "sessions.json");
41-
const staleCronKey = "agent:main:cron:maybe-running:run:old-run";
42-
await replaceSessionEntry(
43-
{ sessionKey: staleCronKey, storePath },
44-
{ sessionId: "maybe-running", updatedAt: Date.now() - 8 * 24 * 60 * 60_000 },
45-
);
46-
mocks.cronStoreLoadError = new Error("SQLITE_CORRUPT: database disk image is malformed");
47-
48-
const summary = await runSessionRegistryMaintenance({ apply: true });
49-
50-
expect(summary.skippedReason).toContain("cron store unreadable");
51-
expect(summary.pruned).toBe(0);
52-
// The possibly-running cron transcript survives until cron facts are readable.
53-
expect(loadSessionEntry({ sessionKey: staleCronKey, storePath })).toBeDefined();
54-
},
55-
);
90+
await withMaintenanceState(async (state) => {
91+
const storePath = path.join(state.sessionsDir("main"), "sessions.json");
92+
const staleCronKey = "agent:main:cron:maybe-running:run:old-run";
93+
await replaceSessionEntry(
94+
{ sessionKey: staleCronKey, storePath },
95+
{ sessionId: "maybe-running", updatedAt: Date.now() - 8 * DAY_MS },
96+
);
97+
mocks.cronStoreLoadError = new Error("SQLITE_CORRUPT: database disk image is malformed");
98+
99+
const summary = await runSessionRegistryMaintenance({ apply: true });
100+
101+
expect(summary.skippedReason).toContain("cron store unreadable");
102+
expect(summary.pruned).toBe(0);
103+
// The possibly-running cron transcript survives until cron facts are readable.
104+
expect(loadSessionEntry({ sessionKey: staleCronKey, storePath })).toBeDefined();
105+
});
56106
});
57107

58108
it("prunes stale rows when the cron store is readable", async () => {
59-
await withOpenClawTestState(
60-
{ layout: "state-only", prefix: "openclaw-session-registry-maintenance-" },
61-
async (state) => {
62-
resetConfigRuntimeState();
63-
const storePath = path.join(state.sessionsDir("main"), "sessions.json");
64-
const staleKey = "agent:main:cron:done-job:run:old-run";
65-
await replaceSessionEntry(
66-
{ sessionKey: staleKey, storePath },
67-
{ sessionId: "old-run", updatedAt: Date.now() - 8 * 24 * 60 * 60_000 },
68-
);
69-
70-
const summary = await runSessionRegistryMaintenance({ apply: true });
71-
72-
expect(summary.skippedReason).toBeUndefined();
73-
expect(summary.pruned).toBe(1);
74-
expect(loadSessionEntry({ sessionKey: staleKey, storePath })).toBeUndefined();
75-
},
76-
);
109+
await withMaintenanceState(async (state) => {
110+
const storePath = path.join(state.sessionsDir("main"), "sessions.json");
111+
const staleKey = "agent:main:cron:done-job:run:old-run";
112+
await replaceSessionEntry(
113+
{ sessionKey: staleKey, storePath },
114+
{ sessionId: "old-run", updatedAt: Date.now() - 8 * DAY_MS },
115+
);
116+
117+
const summary = await runSessionRegistryMaintenance({ apply: true });
118+
119+
expect(summary.skippedReason).toBeUndefined();
120+
expect(summary.pruned).toBe(1);
121+
expect(loadSessionEntry({ sessionKey: staleKey, storePath })).toBeUndefined();
122+
});
123+
});
124+
125+
it.each([
126+
{ apply: false, mainEntrySurvives: true },
127+
{ apply: true, mainEntrySurvives: false },
128+
])(
129+
"reports completed agent deletions while maintaining healthy stores (apply=$apply)",
130+
async ({ apply, mainEntrySurvives }) => {
131+
await withMaintenanceState(async (state) => {
132+
const mainStorePath = path.join(state.sessionsDir("main"), "sessions.json");
133+
const retiredStorePath = path.join(state.sessionsDir("retired"), "sessions.json");
134+
const mainKey = await writeStaleCronSession(mainStorePath, "main");
135+
await writeStaleCronSession(retiredStorePath, "retired");
136+
writeAgentDeletion(state, "retired", true);
137+
closeOpenClawAgentDatabasesForTest();
138+
139+
const summary = await runSessionRegistryMaintenance({ apply });
140+
141+
expect(summary).toMatchObject({
142+
pruned: 1,
143+
skippedStores: 1,
144+
stores: expect.arrayContaining([
145+
expect.objectContaining({ agentId: "main", pruned: 1 }),
146+
{
147+
agentId: "retired",
148+
storePath: retiredStorePath,
149+
skippedReason: "agent-deletion-complete",
150+
},
151+
]),
152+
});
153+
expect(
154+
loadSessionEntry({ sessionKey: mainKey, storePath: mainStorePath }) !== undefined,
155+
).toBe(mainEntrySurvives);
156+
if (!apply) {
157+
const jsonRuntime = createRuntime();
158+
await tasksMaintenanceCommand({ json: true }, jsonRuntime);
159+
expect(JSON.parse(String(vi.mocked(jsonRuntime.log).mock.calls[0]?.[0]))).toMatchObject({
160+
maintenance: {
161+
sessions: {
162+
skippedStores: 1,
163+
stores: expect.arrayContaining([
164+
{
165+
agentId: "retired",
166+
storePath: retiredStorePath,
167+
skippedReason: "agent-deletion-complete",
168+
},
169+
]),
170+
},
171+
},
172+
});
173+
const textRuntime = createRuntime();
174+
await tasksMaintenanceCommand({}, textRuntime);
175+
expect(vi.mocked(textRuntime.log).mock.calls.flat().join("\n")).toContain(
176+
"1 skipped store",
177+
);
178+
}
179+
});
180+
},
181+
);
182+
183+
it("keeps incomplete agent deletions terminal", async () => {
184+
await withMaintenanceState(async (state) => {
185+
const retiredStorePath = path.join(state.sessionsDir("retired"), "sessions.json");
186+
await writeStaleCronSession(retiredStorePath, "retired");
187+
writeAgentDeletion(state, "retired", false);
188+
closeOpenClawAgentDatabasesForTest();
189+
190+
await expect(runSessionRegistryMaintenance({ apply: false })).rejects.toThrow(
191+
"OpenClaw agent database is unavailable while agent retired is deleted.",
192+
);
193+
});
194+
});
195+
196+
it("keeps corrupt discovered stores terminal", async () => {
197+
await withMaintenanceState(async (state) => {
198+
const retiredStorePath = path.join(state.sessionsDir("retired"), "sessions.json");
199+
const sqlitePath = resolveSqliteTargetFromSessionStorePath(retiredStorePath).path;
200+
if (!sqlitePath) {
201+
throw new Error("expected retired store to resolve to SQLite");
202+
}
203+
await fs.mkdir(path.dirname(sqlitePath), { recursive: true });
204+
await fs.writeFile(sqlitePath, "not a sqlite database");
205+
206+
await expect(runSessionRegistryMaintenance({ apply: false })).rejects.toThrow();
207+
});
77208
});
78209
});

‎src/commands/tasks-session-registry-maintenance.ts‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,31 @@ import {
77
} from "../config/sessions.js";
88
import { loadCronJobsStoreSync, resolveCronJobsStorePath } from "../cron/store.js";
99
import { formatErrorMessage } from "../infra/errors.js";
10+
import { readAgentDeletionJournal } from "../state/agent-deletion-journal.js";
1011

1112
const SESSION_REGISTRY_RETENTION_MS = 7 * 24 * 60 * 60_000;
1213

13-
type SessionRegistryMaintenanceStoreSummary = {
14+
type SessionRegistryMaintenanceStoreIdentity = {
1415
agentId: string;
1516
storePath: string;
16-
beforeCount: number;
17-
afterCount: number;
18-
pruned: number;
19-
preservedRunning: number;
2017
};
2118

19+
type SessionRegistryMaintenanceStoreSummary =
20+
| (SessionRegistryMaintenanceStoreIdentity & {
21+
beforeCount: number;
22+
afterCount: number;
23+
pruned: number;
24+
preservedRunning: number;
25+
})
26+
| (SessionRegistryMaintenanceStoreIdentity & {
27+
skippedReason: "agent-deletion-complete";
28+
});
29+
2230
type SessionRegistryMaintenanceSummary = {
2331
retentionMs: number;
2432
runningCronJobs: number;
2533
pruned: number;
34+
skippedStores: number;
2635
stores: SessionRegistryMaintenanceStoreSummary[];
2736
/** Set when the sweep did not run; pruning without cron facts would archive live transcripts. */
2837
skippedReason?: string;
@@ -78,12 +87,20 @@ export async function runSessionRegistryMaintenance(params: {
7887
retentionMs: SESSION_REGISTRY_RETENTION_MS,
7988
runningCronJobs: 0,
8089
pruned: 0,
90+
skippedStores: 0,
8191
stores: [],
8292
skippedReason: `cron store unreadable: ${runningCronJobs.reason}`,
8393
};
8494
}
8595
const stores: SessionRegistryMaintenanceStoreSummary[] = [];
8696
for (const target of resolveAllAgentSessionStoreTargetsSync(cfg)) {
97+
const deletion = readAgentDeletionJournal(target.agentId);
98+
if (deletion?.cleanupCompleted) {
99+
// Completed tombstones intentionally keep retired stores unavailable.
100+
// Record that lifecycle outcome instead of reopening the fenced database.
101+
stores.push({ ...target, skippedReason: "agent-deletion-complete" });
102+
continue;
103+
}
87104
const result = await runSessionRegistryMaintenanceForStore({
88105
apply: params.apply,
89106
retentionMs: SESSION_REGISTRY_RETENTION_MS,
@@ -102,7 +119,8 @@ export async function runSessionRegistryMaintenance(params: {
102119
return {
103120
retentionMs: SESSION_REGISTRY_RETENTION_MS,
104121
runningCronJobs: runningCronJobs.count,
105-
pruned: stores.reduce((total, store) => total + store.pruned, 0),
122+
pruned: stores.reduce((total, store) => total + ("pruned" in store ? store.pruned : 0), 0),
123+
skippedStores: stores.filter((store) => "skippedReason" in store).length,
106124
stores,
107125
};
108126
}

‎src/commands/tasks.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,7 @@ export async function tasksMaintenanceCommand(
651651
info(
652652
sessionMaintenance.skippedReason
653653
? `Session registry: sweep skipped (${sessionMaintenance.skippedReason})`
654-
: `Session registry: ${sessionMaintenance.pruned} prune · ${sessionMaintenance.runningCronJobs} running automations`,
654+
: `Session registry: ${sessionMaintenance.pruned} prune · ${sessionMaintenance.runningCronJobs} running automations · ${sessionMaintenance.skippedStores} skipped ${sessionMaintenance.skippedStores === 1 ? "store" : "stores"}`,
655655
),
656656
);
657657
runtime.log(

0 commit comments

Comments
 (0)