Skip to content

Commit f81afb2

Browse files
ruel225claudesteipete
authored
fix(state-migrations): isolate a throwing channel plan callback into a warning (#119200) (#119201)
* fix(state-migrations): isolate a throwing channel plan callback into a warning runLegacyMigrationPlans ran the plugin-state-import plan without a try/catch, so a throwing shouldReplaceExistingEntry (a channel plugin contract callback) escaped through runLegacyStateMigrationSteps and config-guard, crashing doctor/gateway startup and skipping every unrelated migration plan. Wrap the import plan in the same per-plan isolation sibling migratePluginDoctorStatePlans already uses: record a warning and continue so the remaining plans still run. Re-applied on top of the plugin-state import rewrite, which grew rename/remove source cleanup and archive-on-cover handling around the same withPluginStateImportEnv call. Co-Authored-By: Claude <[email protected]> * fix(doctor): preserve shared migration sources on failure Keep each migration plan's failure boundary in the executor so earlier change reports survive and unrelated sources can continue in order. Defer plans sharing an incomplete source and retire import sources only after their last consumer succeeds, preserving the import state scope. This protects durable counters and expiring caches derived from one file. Absorb source-lifecycle tracking by consolidating duplicate key sets, baseline maps, and per-entry cleanup-failure state. Preserve warning-based startup refusal without configuration, API, schema, or retention changes. Replace the narrow callback test with ordered throw/rejection, shared source read/capacity failures, cleanup ordering/scope, retry, and no-op regressions. Existing Doctor and SDK migration coverage remains green. Related: #119200 Co-authored-by: ruel225 <[email protected]> --------- Co-authored-by: ruel225 <[email protected]> Co-authored-by: Claude <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
1 parent a226416 commit f81afb2

3 files changed

Lines changed: 522 additions & 224 deletions

File tree

‎docs/gateway/doctor.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,8 @@ That stages grounded durable candidates into the short-term dreaming store while
427427

428428
Legacy session-file import and repair belong to explicit Doctor runs. Gateway and local CLI startup use SQLite; they do not import, restore, or rewrite session JSON/JSONL files. When startup finds a legacy session store, it refuses readiness and prints the Doctor command for the active profile instead of serving empty history. Stop the Gateway, back up its state, and run `openclaw doctor --fix` before restarting it to upgrade old session history. The [targeted migration sequence](/cli/doctor#session-sqlite-migration) provides inspection and validation evidence. Current SQLite maintenance does not require legacy files to remain on disk.
429429

430+
Doctor reports individual channel migration-plan failures while continuing plans for unrelated sources, including those from the same plugin. Plans sharing the failed source are deferred, and source cleanup waits for its last consumer to finish without reported failures or incomplete imports. A startup migration warning still blocks Gateway readiness; resolve the reported failure and run `openclaw doctor --fix` before retrying startup.
431+
430432
Doctor emits warnings when migrations leave legacy folders behind as backups. WhatsApp auth is intentionally only migrated via `openclaw doctor`. Talk provider/provider-map normalization compares by structural equality, so key-order-only diffs no longer trigger repeat no-op `doctor --fix` changes.
431433

432434
When an explicit roster no longer contains `main`, OpenClaw migrates durable `agent:main:*` SQLite rows only if the replacement owner is unambiguous: the sole roster member or the configured upgrade owner in `agents.defaults.sessionStore.agentId`. The explicit owner works for both per-agent and fixed session stores; fixed-store runtime ownership remains scoped to that physical store. Conflicting canonical or alias rows are preserved during startup and reported with a Doctor hint. `openclaw doctor --fix` first imports any legacy JSON session store, then keeps the winning canonical claim and renames each losing claim to `agent:<owner>:legacy-main-conflict-<n>` in its original database. Quarantine changes only the key; the entry and full transcript remain available for inspection or archival.
Lines changed: 294 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,294 @@
1+
import fs from "node:fs";
2+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
3+
import type { ChannelLegacyStateMigrationPlan } from "../channels/plugins/legacy-state-migration.types.js";
4+
import {
5+
createPluginStateKeyedStore,
6+
resetPluginStateStoreForTests,
7+
} from "../plugin-state/plugin-state-store.js";
8+
import {
9+
createOpenClawTestState,
10+
type OpenClawTestState,
11+
} from "../test-utils/openclaw-test-state.js";
12+
import { runLegacyMigrationPlans } from "./state-migrations.plugin-state.js";
13+
14+
describe("legacy migration plan failure isolation", () => {
15+
let state: OpenClawTestState;
16+
17+
beforeEach(async () => {
18+
state = await createOpenClawTestState({ label: "migration-plan-isolation" });
19+
});
20+
21+
afterEach(async () => {
22+
resetPluginStateStoreForTests();
23+
await state.cleanup();
24+
});
25+
26+
it.each(["throw", "reject"] as const)(
27+
"retains completed work, continues later plans, and retries a failed import (%s)",
28+
async (failure) => {
29+
const importStateDir = state.statePath("import-owner");
30+
const sourcePath = await state.writeText("legacy-import.json", "legacy source\n");
31+
const earlierPath = await state.writeText("earlier.txt", "earlier artifact\n");
32+
const laterPath = await state.writeText("later.txt", "later artifact\n");
33+
const env = { ...state.env, OPENCLAW_STATE_DIR: importStateDir };
34+
const store = createPluginStateKeyedStore<string>("migration-fixture", {
35+
namespace: "failure-isolation",
36+
maxEntries: 4,
37+
env,
38+
});
39+
await store.register("scope:conflict", "canonical");
40+
let shouldFail = true;
41+
const plans: ChannelLegacyStateMigrationPlan[] = [
42+
{
43+
kind: "move",
44+
label: "Earlier artifact",
45+
sourcePath: earlierPath,
46+
targetPath: `${earlierPath}.moved`,
47+
},
48+
{
49+
kind: "plugin-state-import",
50+
label: "Replacement import",
51+
sourcePath,
52+
targetPath: "plugin state:failure-isolation",
53+
pluginId: "migration-fixture",
54+
namespace: "failure-isolation",
55+
maxEntries: 4,
56+
scopeKey: "scope",
57+
stateDir: importStateDir,
58+
cleanupSource: "rename",
59+
readEntries: () => [{ key: "conflict", value: "incoming" }],
60+
shouldReplaceExistingEntry: () => {
61+
if (!shouldFail) {
62+
return true;
63+
}
64+
const error = new Error("synthetic callback failure");
65+
if (failure === "reject") {
66+
return Promise.reject(error);
67+
}
68+
throw error;
69+
},
70+
},
71+
{
72+
kind: "copy",
73+
label: "Later artifact",
74+
sourcePath: laterPath,
75+
targetPath: `${laterPath}.copied`,
76+
},
77+
];
78+
const run = () =>
79+
runLegacyMigrationPlans(plans.filter((plan) => fs.existsSync(plan.sourcePath)));
80+
81+
const failed = await run();
82+
83+
expect(failed.changes).toEqual([
84+
expect.stringContaining("Moved Earlier artifact"),
85+
expect.stringContaining("Copied Later artifact"),
86+
]);
87+
expect(failed.warnings).toEqual([
88+
expect.stringMatching(/Failed migrating Replacement import.*synthetic callback failure/),
89+
]);
90+
expect(fs.readFileSync(`${earlierPath}.moved`, "utf8")).toBe("earlier artifact\n");
91+
expect(fs.readFileSync(`${laterPath}.copied`, "utf8")).toBe("later artifact\n");
92+
expect(fs.readFileSync(sourcePath, "utf8")).toBe("legacy source\n");
93+
expect(fs.existsSync(`${sourcePath}.migrated`)).toBe(false);
94+
expect(await store.lookup("scope:conflict")).toBe("canonical");
95+
expect(process.env.OPENCLAW_STATE_DIR).toBe(state.stateDir);
96+
97+
shouldFail = false;
98+
const repaired = await run();
99+
100+
expect(repaired.warnings).toEqual([]);
101+
expect(repaired.changes).toContainEqual(
102+
expect.stringContaining("Migrated 1 Replacement import entry"),
103+
);
104+
expect(await store.lookup("scope:conflict")).toBe("incoming");
105+
expect(fs.existsSync(sourcePath)).toBe(false);
106+
expect(fs.readFileSync(`${sourcePath}.migrated`, "utf8")).toBe("legacy source\n");
107+
expect(process.env.OPENCLAW_STATE_DIR).toBe(state.stateDir);
108+
await expect(run()).resolves.toEqual({ changes: [], warnings: [] });
109+
},
110+
);
111+
112+
it.each([
113+
{ failure: "predicate", cleanupFirst: false },
114+
{ failure: "reader", cleanupFirst: false },
115+
{ failure: "capacity", cleanupFirst: false },
116+
{ failure: "predicate", cleanupFirst: true },
117+
{ failure: "empty", cleanupFirst: false },
118+
] as const)(
119+
"retires a shared source only after every consumer completes ($failure, cleanup first: $cleanupFirst)",
120+
async ({ failure, cleanupFirst }) => {
121+
// iMessage derives a durable short-id counter and an expiring cache from one JSONL file.
122+
const original = `${JSON.stringify({ shortId: failure === "empty" ? "0" : "9000", timestamp: 0 })}\n`;
123+
const sourcePath = await state.writeText("reply-cache.jsonl", original);
124+
const unrelatedPath = await state.writeText("unrelated.txt", "independent artifact\n");
125+
const importStateDir = state.statePath("shared-source-owner");
126+
const env = { ...state.env, OPENCLAW_STATE_DIR: importStateDir };
127+
const counter = createPluginStateKeyedStore<{ counter: number }>("migration-fixture", {
128+
namespace: "shared-counter",
129+
maxEntries: 1,
130+
env,
131+
});
132+
await counter.register(failure === "capacity" ? "occupied" : "counter", { counter: 1 });
133+
let shouldFail = true;
134+
const counterObservedMove: boolean[] = [];
135+
const counterPlan: ChannelLegacyStateMigrationPlan = {
136+
kind: "plugin-state-import",
137+
label: "Reply counter",
138+
sourcePath,
139+
targetPath: "plugin state:shared-counter",
140+
pluginId: "migration-fixture",
141+
namespace: "shared-counter",
142+
maxEntries: 1,
143+
scopeKey: "",
144+
stateDir: importStateDir,
145+
readEntries: () => {
146+
counterObservedMove.push(fs.existsSync(`${unrelatedPath}.moved`));
147+
if (failure === "reader" && shouldFail) {
148+
throw new Error("synthetic counter read failure");
149+
}
150+
const entry = JSON.parse(fs.readFileSync(sourcePath, "utf8")) as { shortId: string };
151+
const value = Number.parseInt(entry.shortId, 10);
152+
return value > 0 ? [{ key: "counter", value: { counter: value } }] : [];
153+
},
154+
shouldReplaceExistingEntry: () => {
155+
if (failure === "predicate" && shouldFail) {
156+
throw new Error("synthetic counter callback failure");
157+
}
158+
return true;
159+
},
160+
};
161+
const cachePlan: ChannelLegacyStateMigrationPlan = {
162+
kind: "plugin-state-import",
163+
label: "Expired reply cache",
164+
sourcePath,
165+
targetPath: "plugin state:shared-cache",
166+
pluginId: "migration-fixture",
167+
namespace: "shared-cache",
168+
maxEntries: 4,
169+
scopeKey: "",
170+
stateDir: importStateDir,
171+
cleanupSource: "rename",
172+
cleanupWhenEmpty: true,
173+
readEntries: () => [],
174+
};
175+
const unrelatedPlan: ChannelLegacyStateMigrationPlan = {
176+
kind: "move",
177+
label: "Unrelated artifact",
178+
sourcePath: unrelatedPath,
179+
targetPath: `${unrelatedPath}.moved`,
180+
};
181+
const plans = cleanupFirst
182+
? [cachePlan, unrelatedPlan, counterPlan]
183+
: [counterPlan, cachePlan, unrelatedPlan];
184+
const run = () =>
185+
runLegacyMigrationPlans(plans.filter((plan) => fs.existsSync(plan.sourcePath)));
186+
187+
const first = await run();
188+
189+
expect(counterObservedMove).toEqual([cleanupFirst]);
190+
expect(fs.readFileSync(`${unrelatedPath}.moved`, "utf8")).toBe("independent artifact\n");
191+
expect(process.env.OPENCLAW_STATE_DIR).toBe(state.stateDir);
192+
expect(await counter.lookup("counter")).toEqual(
193+
failure === "capacity" ? undefined : { counter: 1 },
194+
);
195+
if (failure === "empty") {
196+
expect(first.warnings).toEqual([]);
197+
expect(fs.existsSync(sourcePath)).toBe(false);
198+
expect(fs.readFileSync(`${sourcePath}.migrated`, "utf8")).toBe(original);
199+
await expect(run()).resolves.toEqual({ changes: [], warnings: [] });
200+
return;
201+
}
202+
203+
expect(fs.existsSync(sourcePath), "the incomplete counter still needs its source").toBe(true);
204+
expect(fs.readFileSync(sourcePath, "utf8")).toBe(original);
205+
expect(fs.existsSync(`${sourcePath}.migrated`)).toBe(false);
206+
expect(first.warnings).toContainEqual(expect.stringContaining("Reply counter"));
207+
expect(first.changes).not.toContainEqual(expect.stringContaining("Archived"));
208+
209+
shouldFail = false;
210+
if (failure === "capacity") {
211+
await counter.delete("occupied");
212+
}
213+
const repaired = await run();
214+
215+
expect(repaired.warnings).toEqual([]);
216+
expect(await counter.lookup("counter")).toEqual({ counter: 9000 });
217+
expect(fs.existsSync(sourcePath)).toBe(false);
218+
expect(fs.readFileSync(`${sourcePath}.migrated`, "utf8")).toBe(original);
219+
expect(process.env.OPENCLAW_STATE_DIR).toBe(state.stateDir);
220+
await expect(run()).resolves.toEqual({ changes: [], warnings: [] });
221+
},
222+
);
223+
224+
it.each([false, true])(
225+
"keeps source cleanup scoped and before unrelated imports (cleanup throws: %s)",
226+
async (cleanupThrows) => {
227+
const importStateDir = state.statePath("cleanup-owner");
228+
const env = { ...state.env, OPENCLAW_STATE_DIR: importStateDir };
229+
const storeOptions = { namespace: "old-rows", maxEntries: 4 };
230+
const ambient = createPluginStateKeyedStore<string>("migration-fixture", {
231+
...storeOptions,
232+
env: state.env,
233+
});
234+
const owner = createPluginStateKeyedStore<string>("migration-fixture", {
235+
...storeOptions,
236+
env,
237+
});
238+
await ambient.register("legacy", "ambient");
239+
await owner.register("legacy", "owner");
240+
const cleanupScopes: Array<string | undefined> = [];
241+
const laterObservedCleanup: boolean[] = [];
242+
const plans: ChannelLegacyStateMigrationPlan[] = [
243+
{
244+
kind: "plugin-state-import",
245+
label: "Scoped rows",
246+
sourcePath: "plugin state:old-rows",
247+
targetPath: "plugin state:first-import",
248+
pluginId: "migration-fixture",
249+
namespace: "first-import",
250+
maxEntries: 4,
251+
scopeKey: "",
252+
stateDir: importStateDir,
253+
readEntries: () => [{ key: "first", value: "imported" }],
254+
removeSource: async () => {
255+
cleanupScopes.push(process.env.OPENCLAW_STATE_DIR);
256+
if (cleanupThrows) {
257+
throw new Error("synthetic cleanup failure");
258+
}
259+
const scopedStore = createPluginStateKeyedStore("migration-fixture", storeOptions);
260+
await scopedStore.delete("legacy");
261+
},
262+
},
263+
{
264+
kind: "plugin-state-import",
265+
label: "Later rows",
266+
sourcePath: "plugin state:unrelated-rows",
267+
targetPath: "plugin state:later-import",
268+
pluginId: "migration-fixture",
269+
namespace: "later-import",
270+
maxEntries: 4,
271+
scopeKey: "",
272+
stateDir: importStateDir,
273+
readEntries: async () => {
274+
const scopedStore = createPluginStateKeyedStore("migration-fixture", storeOptions);
275+
laterObservedCleanup.push((await scopedStore.lookup("legacy")) === undefined);
276+
return [{ key: "later", value: "completed" }];
277+
},
278+
},
279+
];
280+
281+
const result = await runLegacyMigrationPlans(plans);
282+
283+
expect(cleanupScopes).toEqual([importStateDir]);
284+
expect(laterObservedCleanup).toEqual([!cleanupThrows]);
285+
expect(await ambient.lookup("legacy")).toBe("ambient");
286+
expect(await owner.lookup("legacy")).toBe(cleanupThrows ? "owner" : undefined);
287+
expect(process.env.OPENCLAW_STATE_DIR).toBe(state.stateDir);
288+
expect(result.changes).toContainEqual(expect.stringContaining("Migrated 1 Later rows entry"));
289+
expect(result.warnings).toEqual(
290+
cleanupThrows ? [expect.stringContaining("synthetic cleanup failure")] : [],
291+
);
292+
},
293+
);
294+
});

0 commit comments

Comments
 (0)