Skip to content

Commit 1232090

Browse files
committed
fix(plugins): reclaim retained npm generations safely
1 parent a50a9ae commit 1232090

5 files changed

Lines changed: 221 additions & 10 deletions

File tree

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

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,93 @@ describe("commitConfigWithPendingPluginInstalls", () => {
392392
}
393393
});
394394

395+
it("removes earlier retained markers when a later marker creation fails", async () => {
396+
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-record-commit-"));
397+
const firstPreviousInstallPath = path.join(
398+
stateDir,
399+
"npm",
400+
"projects",
401+
"codex-v1",
402+
"node_modules",
403+
"@openclaw",
404+
"codex",
405+
);
406+
const firstNextInstallPath = path.join(
407+
stateDir,
408+
"npm",
409+
"projects",
410+
"codex-v2",
411+
"node_modules",
412+
"@openclaw",
413+
"codex",
414+
);
415+
const secondPreviousInstallPath = path.join(
416+
stateDir,
417+
"npm",
418+
"projects",
419+
"voice-call-v1",
420+
"node_modules",
421+
"@openclaw",
422+
"voice-call",
423+
);
424+
const secondNextInstallPath = path.join(
425+
stateDir,
426+
"npm",
427+
"projects",
428+
"voice-call-v2",
429+
"node_modules",
430+
"@openclaw",
431+
"voice-call",
432+
);
433+
fs.mkdirSync(firstPreviousInstallPath, { recursive: true });
434+
fs.mkdirSync(firstNextInstallPath, { recursive: true });
435+
fs.mkdirSync(secondPreviousInstallPath, { recursive: true });
436+
fs.mkdirSync(secondNextInstallPath, { recursive: true });
437+
fs.writeFileSync(
438+
path.join(stateDir, "npm", "projects", "voice-call-v1", ".openclaw-retained-npm-installs"),
439+
"not a directory",
440+
"utf8",
441+
);
442+
443+
try {
444+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
445+
await expect(
446+
commitPluginInstallRecordsWithConfig({
447+
previousInstallRecords: {
448+
codex: {
449+
source: "npm",
450+
spec: "@openclaw/[email protected]",
451+
installPath: firstPreviousInstallPath,
452+
},
453+
"voice-call": {
454+
source: "npm",
455+
spec: "@openclaw/[email protected]",
456+
installPath: secondPreviousInstallPath,
457+
},
458+
},
459+
nextInstallRecords: {
460+
codex: {
461+
source: "npm",
462+
spec: "@openclaw/[email protected]",
463+
installPath: firstNextInstallPath,
464+
},
465+
"voice-call": {
466+
source: "npm",
467+
spec: "@openclaw/[email protected]",
468+
installPath: secondNextInstallPath,
469+
},
470+
},
471+
nextConfig: {},
472+
}),
473+
).rejects.toThrow();
474+
});
475+
476+
expect(hasRetainedManagedNpmInstallMarker(firstPreviousInstallPath)).toBe(false);
477+
} finally {
478+
fs.rmSync(stateDir, { recursive: true, force: true });
479+
}
480+
});
481+
395482
it("clears retained npm markers for active committed install records", async () => {
396483
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-record-commit-"));
397484
const installPath = path.join(

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

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -177,8 +177,8 @@ function findReplacementNpmRecordForRemovedRecord(params: {
177177
async function markRetainedReplacedManagedNpmInstallRecords(params: {
178178
previousInstallRecords: Record<string, PluginInstallRecord>;
179179
nextInstallRecords: Record<string, PluginInstallRecord>;
180-
}): Promise<string[]> {
181-
const createdMarkerPaths: string[] = [];
180+
createdMarkerPaths: string[];
181+
}): Promise<void> {
182182
const markedPreviousPluginIds = new Set<string>();
183183
const markReplacement = async (
184184
pluginId: string,
@@ -201,7 +201,8 @@ async function markRetainedReplacedManagedNpmInstallRecords(params: {
201201
reason: "replaced-by-managed-npm-generation-update",
202202
});
203203
if (marked && !markerAlreadyExisted) {
204-
createdMarkerPaths.push(markerPath);
204+
// Record each marker immediately so a later filesystem failure can roll it back.
205+
params.createdMarkerPaths.push(markerPath);
205206
}
206207
markedPreviousPluginIds.add(pluginId);
207208
};
@@ -222,7 +223,6 @@ async function markRetainedReplacedManagedNpmInstallRecords(params: {
222223
}) ?? undefined,
223224
);
224225
}
225-
return createdMarkerPaths;
226226
}
227227

228228
async function removeCreatedRetainedManagedNpmInstallMarkers(markerPaths: string[]): Promise<void> {
@@ -285,12 +285,12 @@ async function commitPluginInstallRecordsWithWriter(params: {
285285
try {
286286
await writePersistedInstalledPluginIndexInstallRecords(params.nextInstallRecords);
287287
try {
288-
retainedMarkerPaths.push(
289-
...(await markRetainedReplacedManagedNpmInstallRecords({
290-
previousInstallRecords,
291-
nextInstallRecords: params.nextInstallRecords,
292-
})),
293-
);
288+
await markRetainedReplacedManagedNpmInstallRecords({
289+
previousInstallRecords,
290+
nextInstallRecords: params.nextInstallRecords,
291+
// Keep partial progress visible to the outer rollback path.
292+
createdMarkerPaths: retainedMarkerPaths,
293+
});
294294
clearedMarkerSnapshots.push(
295295
...(await clearActiveRetainedManagedNpmInstallMarkers(params.nextInstallRecords)),
296296
);

‎src/gateway/server.impl.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ import { startDiagnosticHeartbeat, stopDiagnosticHeartbeat } from "../logging/di
4646
import { createSubsystemLogger, runtimeForLogger } from "../logging/subsystem.js";
4747
import { setCurrentPluginMetadataSnapshot } from "../plugins/current-plugin-metadata-snapshot.js";
4848
import type { PluginHookGatewayCronService } from "../plugins/hook-types.js";
49+
import { loadInstalledPluginIndexInstallRecordsSync } from "../plugins/installed-plugin-index-records.js";
50+
import { cleanupRetainedManagedNpmInstallGenerations } from "../plugins/managed-npm-retention.js";
4951
import { clearPluginMetadataLifecycleCaches } from "../plugins/plugin-metadata-lifecycle.js";
5052
import {
5153
pinActivePluginChannelRegistry,
@@ -551,6 +553,23 @@ export async function startGatewayServer(
551553
opts: GatewayServerOptions = {},
552554
): Promise<GatewayServer> {
553555
normalizeStateDirEnv(process.env);
556+
// runGatewayLoop calls this after closing the previous server on both fresh
557+
// and in-process restarts, making retired plugin generations safe to remove.
558+
try {
559+
const installRecords = loadInstalledPluginIndexInstallRecordsSync();
560+
const removedGenerations = await cleanupRetainedManagedNpmInstallGenerations({
561+
activeInstallPaths: Object.values(installRecords).flatMap((record) =>
562+
record.installPath ? [record.installPath] : [],
563+
),
564+
onError: (error, projectRoot) =>
565+
log.warn(`failed to clean retained npm generation ${projectRoot}: ${String(error)}`),
566+
});
567+
if (removedGenerations > 0) {
568+
log.info(`cleaned ${removedGenerations} retained npm plugin generation(s)`);
569+
}
570+
} catch (error) {
571+
log.warn(`retained npm generation cleanup unavailable: ${String(error)}`);
572+
}
554573
const { bootstrapGatewayNetworkRuntime } = await import("./server-network-runtime.js");
555574
bootstrapGatewayNetworkRuntime();
556575

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { describe, expect, it } from "vitest";
5+
import { resolvePluginNpmGenerationProjectDir } from "./install-paths.js";
6+
import {
7+
cleanupRetainedManagedNpmInstallGenerations,
8+
hasRetainedManagedNpmInstallMarker,
9+
markRetainedManagedNpmInstall,
10+
} from "./managed-npm-retention.js";
11+
12+
describe("managed npm retention", () => {
13+
it("cleans retired generations while preserving the active install root", async () => {
14+
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-retention-"));
15+
const npmDir = path.join(stateDir, "npm");
16+
const packageName = "@openclaw/codex";
17+
const oldProjectRoot = resolvePluginNpmGenerationProjectDir({
18+
npmDir,
19+
packageName,
20+
generationKey: "codex-v1",
21+
});
22+
const activeProjectRoot = resolvePluginNpmGenerationProjectDir({
23+
npmDir,
24+
packageName,
25+
generationKey: "codex-v2",
26+
});
27+
const oldPackageDir = path.join(oldProjectRoot, "node_modules", "@openclaw", "codex");
28+
const activePackageDir = path.join(activeProjectRoot, "node_modules", "@openclaw", "codex");
29+
fs.mkdirSync(oldPackageDir, { recursive: true });
30+
fs.mkdirSync(activePackageDir, { recursive: true });
31+
await markRetainedManagedNpmInstall({
32+
packageDir: oldPackageDir,
33+
pluginId: "codex",
34+
reason: "test-retired-generation",
35+
});
36+
37+
try {
38+
await expect(
39+
cleanupRetainedManagedNpmInstallGenerations({
40+
npmDir,
41+
activeInstallPaths: [activePackageDir],
42+
}),
43+
).resolves.toBe(1);
44+
expect(fs.existsSync(oldProjectRoot)).toBe(false);
45+
expect(fs.existsSync(activeProjectRoot)).toBe(true);
46+
expect(hasRetainedManagedNpmInstallMarker(activePackageDir)).toBe(false);
47+
} finally {
48+
fs.rmSync(stateDir, { recursive: true, force: true });
49+
}
50+
});
51+
});

‎src/plugins/managed-npm-retention.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import fs from "node:fs";
33
import path from "node:path";
44
import { safePathSegmentHashed } from "../infra/install-safe-path.js";
5+
import { resolveDefaultPluginNpmDir, resolvePluginNpmProjectsDir } from "./install-paths.js";
6+
import { listManagedPluginNpmProjectRootsSync } from "./npm-project-roots.js";
57

68
export const RETAINED_MANAGED_NPM_INSTALL_MARKER = ".openclaw-retained-npm-install.json";
79
const RETAINED_MANAGED_NPM_INSTALL_MARKER_DIR = ".openclaw-retained-npm-installs";
@@ -109,3 +111,55 @@ export async function markRetainedManagedNpmInstall(params: {
109111
);
110112
return true;
111113
}
114+
115+
function isPathEqualOrInside(parentPath: string, childPath: string): boolean {
116+
const relative = path.relative(path.resolve(parentPath), path.resolve(childPath));
117+
return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`));
118+
}
119+
120+
export async function cleanupRetainedManagedNpmInstallGenerations(
121+
params: {
122+
activeInstallPaths?: Iterable<string>;
123+
env?: NodeJS.ProcessEnv;
124+
npmDir?: string;
125+
onError?: (error: unknown, projectRoot: string) => void;
126+
} = {},
127+
): Promise<number> {
128+
// Callers run this after the previous gateway server has closed and before
129+
// the next one loads plugins, so retired module graphs no longer need these trees.
130+
const npmDir = params.npmDir ?? resolveDefaultPluginNpmDir(params.env);
131+
const projectsDir = resolvePluginNpmProjectsDir(npmDir);
132+
const activeInstallPaths = Array.from(params.activeInstallPaths ?? [], (installPath) =>
133+
path.resolve(installPath),
134+
);
135+
let removed = 0;
136+
for (const projectRoot of listManagedPluginNpmProjectRootsSync(npmDir)) {
137+
const markerDir = path.join(projectRoot, RETAINED_MANAGED_NPM_INSTALL_MARKER_DIR);
138+
let markerEntries: fs.Dirent[];
139+
try {
140+
markerEntries = fs
141+
.readdirSync(markerDir, { withFileTypes: true })
142+
.filter((entry) => entry.isFile());
143+
} catch (error) {
144+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
145+
continue;
146+
}
147+
params.onError?.(error, projectRoot);
148+
continue;
149+
}
150+
if (
151+
markerEntries.length === 0 ||
152+
!isPathEqualOrInside(projectsDir, projectRoot) ||
153+
activeInstallPaths.some((installPath) => isPathEqualOrInside(projectRoot, installPath))
154+
) {
155+
continue;
156+
}
157+
try {
158+
await fs.promises.rm(projectRoot, { recursive: true, force: true });
159+
removed += 1;
160+
} catch (error) {
161+
params.onError?.(error, projectRoot);
162+
}
163+
}
164+
return removed;
165+
}

0 commit comments

Comments
 (0)