|
| 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