Skip to content

Commit da86bfc

Browse files
committed
fix(plugins): serialize install rollback with config commit
1 parent 4b21c4a commit da86bfc

3 files changed

Lines changed: 187 additions & 100 deletions

File tree

‎src/plugins/install-persistence.test.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
runtimeLogs,
1818
setInstalledPluginIndexInstallRecords,
1919
writeConfigFile,
20-
writePersistedInstalledPluginIndexInstallRecords,
20+
writePersistedInstalledPluginIndexInstallRecordsWithLease,
2121
applyPluginUninstallDirectoryRemoval,
2222
} from "../cli/plugins-cli-test-helpers.js";
2323
import type { OpenClawConfig } from "../config/config.js";
@@ -109,8 +109,8 @@ describe("persistPluginInstall", () => {
109109

110110
expect(next).toEqual(enabledConfig);
111111
const persistedRecords = requireMockCallArg(
112-
writePersistedInstalledPluginIndexInstallRecords,
113-
"writePersistedInstalledPluginIndexInstallRecords",
112+
writePersistedInstalledPluginIndexInstallRecordsWithLease,
113+
"writePersistedInstalledPluginIndexInstallRecordsWithLease",
114114
);
115115
expect(persistedRecords.alpha).toEqual({
116116
source: "npm",
@@ -881,8 +881,8 @@ describe("persistPluginInstall", () => {
881881
'Installed plugin "needs-config" without enabling it because it requires configuration first.',
882882
);
883883
const persistedRecords = requireMockCallArg(
884-
writePersistedInstalledPluginIndexInstallRecords,
885-
"writePersistedInstalledPluginIndexInstallRecords",
884+
writePersistedInstalledPluginIndexInstallRecordsWithLease,
885+
"writePersistedInstalledPluginIndexInstallRecordsWithLease",
886886
);
887887
expect(persistedRecords["needs-config"]).toMatchObject({
888888
source: "npm",
@@ -937,7 +937,7 @@ describe("persistPluginInstall", () => {
937937
).rejects.toThrow("has invalid configured settings");
938938

939939
expect(enablePluginInConfig).not.toHaveBeenCalled();
940-
expect(writePersistedInstalledPluginIndexInstallRecords).not.toHaveBeenCalled();
940+
expect(writePersistedInstalledPluginIndexInstallRecordsWithLease).not.toHaveBeenCalled();
941941
expect(writeConfigFile).not.toHaveBeenCalled();
942942
});
943943

@@ -969,8 +969,8 @@ describe("persistPluginInstall", () => {
969969
expect(enablePluginInConfig).not.toHaveBeenCalled();
970970
expect(applyExclusiveSlotSelection).not.toHaveBeenCalled();
971971
const persistedRecords = requireMockCallArg(
972-
writePersistedInstalledPluginIndexInstallRecords,
973-
"writePersistedInstalledPluginIndexInstallRecords",
972+
writePersistedInstalledPluginIndexInstallRecordsWithLease,
973+
"writePersistedInstalledPluginIndexInstallRecordsWithLease",
974974
);
975975
expect(persistedRecords["memory-lancedb"]).toEqual({
976976
source: "path",

‎src/plugins/install-record-commit.sqlite.test.ts‎

Lines changed: 138 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
import { spawn } from "node:child_process";
2+
import fs from "node:fs";
23
import path from "node:path";
4+
import { setTimeout as delay } from "node:timers/promises";
35
import { pathToFileURL } from "node:url";
46
import { afterEach, describe, expect, it } from "vitest";
57
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
68
import { withEnvAsync } from "../test-utils/env.js";
79
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
8-
import { commitConfigWriteWithPendingPluginInstalls } from "./install-record-commit.js";
10+
import { writePersistedInstalledPluginIndexInstallRecordsWithLease } from "./installed-plugin-index-records.js";
911
import { readPersistedInstalledPluginIndex } from "./installed-plugin-index-store.js";
1012
import { resolveInstalledPluginIndexPolicyHash } from "./installed-plugin-index.js";
13+
import { withPluginLifecycleLease } from "./plugin-lifecycle-lease.js";
1114

1215
afterEach(() => {
1316
closeOpenClawStateDatabaseForTest();
@@ -25,74 +28,162 @@ function runChild(scriptPath: string, args: string[]): Promise<void> {
2528
if (code === 0) {
2629
resolve();
2730
} else {
28-
reject(new Error(`install-record successor child exited ${code}: ${output}`));
31+
reject(new Error(`install-record commit child exited ${code}: ${output}`));
2932
}
3033
});
3134
});
3235
}
3336

37+
async function fileExists(filePath: string): Promise<boolean> {
38+
try {
39+
await fs.promises.access(filePath);
40+
return true;
41+
} catch (error) {
42+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
43+
return false;
44+
}
45+
throw error;
46+
}
47+
}
48+
49+
async function waitForFile(filePath: string, timeoutMs = 15_000): Promise<void> {
50+
const deadline = Date.now() + timeoutMs;
51+
while (Date.now() < deadline) {
52+
if (await fileExists(filePath)) {
53+
return;
54+
}
55+
await delay(10);
56+
}
57+
throw new Error(`timed out waiting for ${filePath}`);
58+
}
59+
60+
async function expectFileToStayAbsent(filePath: string, durationMs = 500): Promise<void> {
61+
const deadline = Date.now() + durationMs;
62+
while (Date.now() < deadline) {
63+
expect(await fileExists(filePath)).toBe(false);
64+
await delay(10);
65+
}
66+
}
67+
3468
describe("plugin install record commit rollback", () => {
35-
it("keeps a successor index when config commit fails after another process writes", async () => {
36-
await withOpenClawTestState({ label: "plugin-record-successor" }, async (state) => {
37-
const leaseModuleUrl = pathToFileURL(
38-
path.resolve("src/plugins/plugin-lifecycle-lease.ts"),
39-
).href;
40-
const recordsModuleUrl = pathToFileURL(
41-
path.resolve("src/plugins/installed-plugin-index-records.ts"),
69+
it("serializes two failing direct config commits and restores the original index", async () => {
70+
await withOpenClawTestState({ label: "plugin-record-failing-commits" }, async (state) => {
71+
const commitModuleUrl = pathToFileURL(
72+
path.resolve("src/plugins/install-record-commit.ts"),
4273
).href;
4374
const childScript = await state.writeText(
44-
"write-successor.mts",
75+
"fail-config-commit.mts",
4576
`
46-
import { withPluginLifecycleLease } from ${JSON.stringify(leaseModuleUrl)};
47-
import { writePersistedInstalledPluginIndexInstallRecordsWithLease } from ${JSON.stringify(recordsModuleUrl)};
48-
const [stateDir] = process.argv.slice(2);
49-
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
50-
await withPluginLifecycleLease({ env, leaseMs: 1_000, waitMs: 5_000 }, async (lease) => {
51-
await writePersistedInstalledPluginIndexInstallRecordsWithLease(
52-
{
53-
successor: {
54-
source: "path",
55-
spec: "successor",
56-
sourcePath: "/tmp/successor",
57-
installPath: "/tmp/successor",
77+
import fs from "node:fs";
78+
import { setTimeout as delay } from "node:timers/promises";
79+
import { commitConfigWriteWithPendingPluginInstalls } from ${JSON.stringify(commitModuleUrl)};
80+
const [stateDir, pluginId, startedPath, enteredPath, releasePath] = process.argv.slice(2);
81+
process.env.OPENCLAW_STATE_DIR = stateDir;
82+
await fs.promises.writeFile(startedPath, "started");
83+
try {
84+
await commitConfigWriteWithPendingPluginInstalls({
85+
nextConfig: {
86+
plugins: {
87+
installs: {
88+
[pluginId]: {
89+
source: "path",
90+
spec: pluginId,
91+
sourcePath: "/tmp/" + pluginId,
92+
installPath: "/tmp/" + pluginId,
93+
},
94+
},
5895
},
5996
},
60-
{ env, config: {}, lease },
61-
);
62-
});
97+
commit: async () => {
98+
await fs.promises.writeFile(enteredPath, "entered");
99+
while (true) {
100+
try {
101+
await fs.promises.access(releasePath);
102+
break;
103+
} catch (error) {
104+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
105+
throw error;
106+
}
107+
}
108+
await delay(10);
109+
}
110+
throw new Error("config failed " + pluginId);
111+
},
112+
});
113+
throw new Error("config commit unexpectedly succeeded");
114+
} catch (error) {
115+
if (!(error instanceof Error) || error.message !== "config failed " + pluginId) {
116+
throw error;
117+
}
118+
}
63119
`,
64120
);
121+
const firstStarted = path.join(state.stateDir, "first-started");
122+
const firstEntered = path.join(state.stateDir, "first-entered");
123+
const firstRelease = path.join(state.stateDir, "first-release");
124+
const secondStarted = path.join(state.stateDir, "second-started");
125+
const secondEntered = path.join(state.stateDir, "second-entered");
126+
const secondRelease = path.join(state.stateDir, "second-release");
65127

66128
await withEnvAsync(state.env, async () => {
67-
await expect(
68-
commitConfigWriteWithPendingPluginInstalls({
69-
nextConfig: {
70-
plugins: {
71-
installs: {
72-
tentative: {
73-
source: "path",
74-
spec: "tentative",
75-
sourcePath: "/tmp/tentative",
76-
installPath: "/tmp/tentative",
77-
},
78-
},
129+
await withPluginLifecycleLease({}, async (lease) => {
130+
await writePersistedInstalledPluginIndexInstallRecordsWithLease(
131+
{
132+
original: {
133+
source: "path",
134+
spec: "original",
135+
sourcePath: "/tmp/original",
136+
installPath: "/tmp/original",
79137
},
80138
},
81-
commit: async () => {
82-
await runChild(childScript, [state.stateDir]);
83-
throw new Error("config changed");
84-
},
85-
}),
86-
).rejects.toThrow("config changed");
139+
{ config: {}, lease },
140+
);
141+
});
142+
143+
const firstDone = runChild(childScript, [
144+
state.stateDir,
145+
"first",
146+
firstStarted,
147+
firstEntered,
148+
firstRelease,
149+
]);
150+
let secondDone: Promise<void> | undefined;
151+
try {
152+
await waitForFile(firstEntered);
153+
secondDone = runChild(childScript, [
154+
state.stateDir,
155+
"second",
156+
secondStarted,
157+
secondEntered,
158+
secondRelease,
159+
]);
160+
await waitForFile(secondStarted);
161+
162+
// The second writer must stay outside its config commit until the
163+
// first writer rolls its tentative index state back.
164+
await expectFileToStayAbsent(secondEntered);
165+
166+
await fs.promises.writeFile(firstRelease, "release");
167+
await firstDone;
168+
await waitForFile(secondEntered);
169+
await fs.promises.writeFile(secondRelease, "release");
170+
await secondDone;
171+
} finally {
172+
await Promise.all([
173+
fs.promises.writeFile(firstRelease, "release"),
174+
fs.promises.writeFile(secondRelease, "release"),
175+
]);
176+
await Promise.allSettled([firstDone, ...(secondDone ? [secondDone] : [])]);
177+
}
87178
});
88179

89180
const persisted = await readPersistedInstalledPluginIndex({ env: state.env });
90181
expect(persisted?.installRecords).toEqual({
91-
successor: {
182+
original: {
92183
source: "path",
93-
spec: "successor",
94-
sourcePath: "/tmp/successor",
95-
installPath: "/tmp/successor",
184+
spec: "original",
185+
sourcePath: "/tmp/original",
186+
installPath: "/tmp/original",
96187
},
97188
});
98189
expect(persisted?.policyHash).toBe(resolveInstalledPluginIndexPolicyHash({}));

‎src/plugins/install-record-commit.ts‎

Lines changed: 41 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -289,51 +289,48 @@ async function commitPluginInstallRecordsWithWriter(params: {
289289
committed: ConfigReplaceResult | void;
290290
nextInstallRecords: Record<string, PluginInstallRecord>;
291291
}> {
292-
let tentativeWrite: InstalledPluginIndexWriteReceipt | undefined;
293-
const retainedMarkerPaths: string[] = [];
294-
const clearedMarkerSnapshots: Array<{ markerPath: string; contents: string }> = [];
295-
try {
296-
const prepared = await withPluginLifecycleLease({}, async (lease) => {
292+
return await withPluginLifecycleLease({}, async (lease) => {
293+
let tentativeWrite: InstalledPluginIndexWriteReceipt | undefined;
294+
const retainedMarkerPaths: string[] = [];
295+
const clearedMarkerSnapshots: Array<{ markerPath: string; contents: string }> = [];
296+
try {
297297
const storeOptions = { filePath: lease.databasePath };
298-
const installRecords = await params.prepareInstallRecords(storeOptions);
298+
const prepared = await params.prepareInstallRecords(storeOptions);
299299
tentativeWrite = await writePersistedInstalledPluginIndexInstallRecordsWithLease(
300-
installRecords.nextInstallRecords,
300+
prepared.nextInstallRecords,
301301
{
302302
...storeOptions,
303303
config: params.nextConfig,
304304
lease,
305305
},
306306
);
307307
await markRetainedReplacedManagedNpmInstallRecords({
308-
previousInstallRecords: installRecords.previousInstallRecords,
309-
nextInstallRecords: installRecords.nextInstallRecords,
308+
previousInstallRecords: prepared.previousInstallRecords,
309+
nextInstallRecords: prepared.nextInstallRecords,
310310
// Keep partial progress visible to the rollback path.
311311
createdMarkerPaths: retainedMarkerPaths,
312312
});
313313
clearedMarkerSnapshots.push(
314-
...(await clearActiveRetainedManagedNpmInstallMarkers(installRecords.nextInstallRecords)),
314+
...(await clearActiveRetainedManagedNpmInstallMarkers(prepared.nextInstallRecords)),
315315
);
316-
return installRecords;
317-
});
318-
const installRecordsChanged = !isDeepStrictEqual(
319-
prepared.previousInstallRecords,
320-
prepared.nextInstallRecords,
321-
);
322-
const committed = await params.commit(params.nextConfig, {
323-
...params.writeOptions,
324-
...(installRecordsChanged && params.writeOptions?.afterWrite === undefined
325-
? { afterWrite: { mode: "restart", reason: PLUGIN_SOURCE_CHANGED_RESTART_REASON } }
326-
: {}),
327-
unsetPaths: mergeUnsetPaths(params.writeOptions?.unsetPaths, [
328-
Array.from(PLUGIN_INSTALLS_CONFIG_PATH),
329-
]),
330-
});
331-
return { committed, nextInstallRecords: prepared.nextInstallRecords };
332-
} catch (error) {
333-
const tentative = tentativeWrite;
334-
if (tentative) {
335-
try {
336-
await withPluginLifecycleLease({}, async (lease) => {
316+
const installRecordsChanged = !isDeepStrictEqual(
317+
prepared.previousInstallRecords,
318+
prepared.nextInstallRecords,
319+
);
320+
const committed = await params.commit(params.nextConfig, {
321+
...params.writeOptions,
322+
...(installRecordsChanged && params.writeOptions?.afterWrite === undefined
323+
? { afterWrite: { mode: "restart", reason: PLUGIN_SOURCE_CHANGED_RESTART_REASON } }
324+
: {}),
325+
unsetPaths: mergeUnsetPaths(params.writeOptions?.unsetPaths, [
326+
Array.from(PLUGIN_INSTALLS_CONFIG_PATH),
327+
]),
328+
});
329+
return { committed, nextInstallRecords: prepared.nextInstallRecords };
330+
} catch (error) {
331+
const tentative = tentativeWrite;
332+
if (tentative) {
333+
try {
337334
const restored = await restorePersistedInstalledPluginIndexIfCurrent(
338335
tentative.previous,
339336
tentative.revision,
@@ -342,23 +339,22 @@ async function commitPluginInstallRecordsWithWriter(params: {
342339
lease,
343340
},
344341
);
345-
if (!restored) {
346-
return;
342+
if (restored) {
343+
// Marker compensation belongs to the same tentative revision. A newer
344+
// index owner may rely on the current marker state.
345+
await restoreClearedRetainedManagedNpmInstallMarkers(clearedMarkerSnapshots);
346+
await removeCreatedRetainedManagedNpmInstallMarkers(retainedMarkerPaths);
347347
}
348-
// Marker compensation belongs to the same tentative revision. A newer
349-
// index owner may rely on the current marker state.
350-
await restoreClearedRetainedManagedNpmInstallMarkers(clearedMarkerSnapshots);
351-
await removeCreatedRetainedManagedNpmInstallMarkers(retainedMarkerPaths);
352-
});
353-
} catch (rollbackError) {
354-
throw new Error(
355-
"Failed to commit plugin install records and could not roll back tentative plugin state",
356-
{ cause: rollbackError },
357-
);
348+
} catch (rollbackError) {
349+
throw new Error(
350+
"Failed to commit plugin install records and could not roll back tentative plugin state",
351+
{ cause: rollbackError },
352+
);
353+
}
358354
}
355+
throw error;
359356
}
360-
throw error;
361-
}
357+
});
362358
}
363359

364360
/** Persist plugin install records and commit the matching config update to disk. */

0 commit comments

Comments
 (0)