Skip to content

Commit 33dbf03

Browse files
committed
perf(update): reuse dev preflight build cache
1 parent 6922ddd commit 33dbf03

7 files changed

Lines changed: 120 additions & 27 deletions

File tree

‎docs/cli/update.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -251,16 +251,16 @@ returns the latest sentinel.
251251
Dev only.
252252
</Step>
253253
<Step title="Preflight build (dev only)">
254-
Runs the TypeScript build in a temp worktree. If the tip fails, walks back up to 10 commits to find the newest buildable commit. Set `OPENCLAW_UPDATE_PREFLIGHT_LINT=1` to also run lint during this preflight; lint runs in constrained serial mode because user update hosts are often smaller than CI runners.
254+
Runs the TypeScript build in a temp worktree. If the tip fails, walks back up to 10 commits to find the newest buildable commit. Content-addressed declaration outputs from the successful candidate are reused by the final checkout build; rebased source changes automatically invalidate the affected cache groups. Set `OPENCLAW_UPDATE_PREFLIGHT_LINT=1` to also run lint during this preflight; lint runs in constrained serial mode because user update hosts are often smaller than CI runners.
255255
</Step>
256256
<Step title="Rebase">
257257
Rebases onto the selected commit (dev only).
258258
</Step>
259259
<Step title="Install dependencies">
260260
Uses the repo package manager. For pnpm checkouts, the updater bootstraps `pnpm` on demand (via `corepack` first, then a temporary `npm install pnpm@11` fallback) instead of running `npm run build` inside a pnpm workspace. If pnpm bootstrap still fails, the updater stops early with a package-manager-specific error instead of trying `npm run build` in the checkout.
261261
</Step>
262-
<Step title="Build Control UI">
263-
Builds the gateway and the Control UI.
262+
<Step title="Build checkout">
263+
Builds the gateway and Control UI once in the final checkout. The updater runs the standalone Control UI build only when a target build omitted those assets or doctor later removes them.
264264
</Step>
265265
<Step title="Run doctor">
266266
`openclaw doctor` runs as the final safe-update check.

‎scripts/build-all.mjs‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -635,9 +635,21 @@ function normalizePortablePath(filePath) {
635635
return filePath.replaceAll("\\", "/");
636636
}
637637

638-
function resolveCachePaths(rootDir, step) {
638+
function resolveBuildCacheRoot(rootDir, env) {
639+
// Dev update preflight and final builds run in separate worktrees. A shared
640+
// root lets content signatures decide reuse without relocating built trees.
641+
const configuredRoot = env?.BUILD_ALL_CACHE_ROOT?.trim();
642+
if (!configuredRoot) {
643+
return path.resolve(rootDir, ".artifacts/build-all-cache");
644+
}
645+
return path.isAbsolute(configuredRoot)
646+
? path.normalize(configuredRoot)
647+
: path.resolve(rootDir, configuredRoot);
648+
}
649+
650+
function resolveCachePaths(rootDir, step, env) {
639651
const safeLabel = step.label.replace(/[^a-zA-Z0-9._-]+/g, "_");
640-
const cacheDir = path.resolve(rootDir, ".artifacts/build-all-cache", safeLabel);
652+
const cacheDir = path.join(resolveBuildCacheRoot(rootDir, env), safeLabel);
641653
return {
642654
cacheDir,
643655
outputRoot: path.join(cacheDir, "outputs"),
@@ -703,7 +715,7 @@ export function resolveBuildAllStepCacheState(step, params = {}) {
703715
step.cache.env ?? [],
704716
params.env ?? process.env,
705717
);
706-
const { outputRoot, stampPath } = resolveCachePaths(rootDir, step);
718+
const { outputRoot, stampPath } = resolveCachePaths(rootDir, step, params.env ?? process.env);
707719
const stamp = readCacheStamp(stampPath, fsImpl);
708720
const outputFiles = listCacheFiles(rootDir, step.cache.outputs, fsImpl);
709721
const relativeOutputFiles = outputFiles.map((file) => portableRelativePath(rootDir, file));

‎src/infra/update-runner-git-commands.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,20 @@ function resolveBuildNodeOptions(baseOptions: string | undefined): string {
4242
return current.replace(/(?:^|\s)--max-old-space-size=\d+(?=\s|$)/, ` ${desired}`).trim();
4343
}
4444

45-
export function resolveBuildEnv(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv | undefined {
45+
export function resolveBuildEnv(
46+
env?: NodeJS.ProcessEnv,
47+
buildCacheRoot?: string,
48+
): NodeJS.ProcessEnv | undefined {
4649
const currentNodeOptions = env?.NODE_OPTIONS ?? process.env.NODE_OPTIONS;
4750
const nextNodeOptions = resolveBuildNodeOptions(currentNodeOptions);
48-
if (nextNodeOptions === currentNodeOptions) {
51+
if (nextNodeOptions === currentNodeOptions && !buildCacheRoot) {
4952
return env;
5053
}
51-
return { ...env, NODE_OPTIONS: nextNodeOptions };
54+
return {
55+
...env,
56+
NODE_OPTIONS: nextNodeOptions,
57+
...(buildCacheRoot ? { BUILD_ALL_CACHE_ROOT: buildCacheRoot } : {}),
58+
};
5259
}
5360

5461
export function resolveInstallEnv(

‎src/infra/update-runner-git-preflight.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ async function testPreflightCandidates(params: {
392392
`preflight build (${shortSha})`,
393393
managerScriptArgs(manager.manager, "build"),
394394
params.worktreeDir,
395-
resolveBuildEnv(manager.env),
395+
resolveBuildEnv(manager.env, path.join(params.gitRoot, ".artifacts", "build-all-cache")),
396396
),
397397
);
398398
params.steps.push(buildStep);

‎src/infra/update-runner-git.ts‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ export async function runGitUpdate(params: {
7070
const branch = await readBranchName(runCommand, gitRoot, timeoutMs);
7171
const hasDevTargetRef = channel === "dev" && Boolean(opts.devTargetRef?.trim());
7272
const needsCheckoutMain = channel === "dev" && !hasDevTargetRef && branch !== DEV_BRANCH;
73-
const totalSteps = channel === "dev" ? (needsCheckoutMain ? 12 : 11) : 10;
73+
const totalSteps = channel === "dev" ? (needsCheckoutMain ? 11 : 10) : 9;
7474
const steps: UpdateStepResult[] = [];
7575
let stepIndex = 0;
7676
const step = (
@@ -389,7 +389,10 @@ export async function runGitUpdate(params: {
389389
"build",
390390
managerScriptArgs(manager.manager, "build"),
391391
gitRoot,
392-
resolveBuildEnv(manager.env),
392+
resolveBuildEnv(
393+
manager.env,
394+
channel === "dev" ? path.join(gitRoot, ".artifacts", "build-all-cache") : undefined,
395+
),
393396
),
394397
);
395398
steps.push(buildStep);
@@ -410,12 +413,20 @@ export async function runGitUpdate(params: {
410413
if (buildCleanCheck.stdoutTail?.trim()) {
411414
return await rollbackError("build-dirty");
412415
}
413-
const uiBuildStep = await runStep(
414-
step("ui:build", managerScriptArgs(manager.manager, "ui:build"), gitRoot, manager.env),
415-
);
416-
steps.push(uiBuildStep);
417-
if (uiBuildStep.exitCode !== 0) {
418-
return await rollbackError("ui-build-failed");
416+
const builtUiIndexHealth = await resolveControlUiDistIndexHealth({ root: gitRoot });
417+
if (!builtUiIndexHealth.exists) {
418+
const uiBuildStep = await runStep(
419+
step(
420+
"ui:build (build fallback)",
421+
managerScriptArgs(manager.manager, "ui:build"),
422+
gitRoot,
423+
manager.env,
424+
),
425+
);
426+
steps.push(uiBuildStep);
427+
if (uiBuildStep.exitCode !== 0) {
428+
return await rollbackError("ui-build-failed");
429+
}
419430
}
420431

421432
const doctorEntry = path.join(gitRoot, "openclaw.mjs");

‎src/infra/update-runner.test.ts‎

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1849,7 +1849,7 @@ describe("runGatewayUpdate", () => {
18491849
expect(calls).toContain("pnpm install");
18501850
expect(calls).toContain("pnpm build");
18511851
expect(calls).not.toContain("pnpm lint");
1852-
expect(calls).toContain("pnpm ui:build");
1852+
expect(calls).not.toContain("pnpm ui:build");
18531853
expect(pnpmEnvPaths.filter((envPath) => envPath.includes("openclaw-update-pnpm-"))).not.toEqual(
18541854
[],
18551855
);
@@ -2262,10 +2262,11 @@ describe("runGatewayUpdate", () => {
22622262
expect(cleanupStep?.stderrTail ?? "").toContain("fallback cleanup removed preflight tree");
22632263
});
22642264

2265-
it("adds heap headroom to pnpm build steps during dev updates", async () => {
2265+
it("shares the build cache while adding heap headroom to dev builds", async () => {
22662266
await setupGitPackageManagerFixture();
22672267
const upstreamSha = "upstream123";
22682268
const buildNodeOptions: string[] = [];
2269+
const buildCacheRoots: string[] = [];
22692270
const doctorNodePath = await resolveStableNodePath(process.execPath);
22702271
const doctorCommand = `${doctorNodePath} ${path.join(tempDir, "openclaw.mjs")} doctor --non-interactive --fix`;
22712272

@@ -2327,6 +2328,7 @@ describe("runGatewayUpdate", () => {
23272328
}
23282329
if (key === "pnpm build") {
23292330
buildNodeOptions.push(options?.env?.NODE_OPTIONS ?? "");
2331+
buildCacheRoots.push(options?.env?.BUILD_ALL_CACHE_ROOT ?? "");
23302332
return { stdout: "", stderr: "", code: 0 };
23312333
}
23322334
if (
@@ -2352,6 +2354,10 @@ describe("runGatewayUpdate", () => {
23522354
expect(result.status).toBe("ok");
23532355
expect(buildNodeOptions).toHaveLength(2);
23542356
expect(buildNodeOptions).toEqual(["--max-old-space-size=8192", "--max-old-space-size=8192"]);
2357+
expect(buildCacheRoots).toEqual([
2358+
path.join(tempDir, ".artifacts", "build-all-cache"),
2359+
path.join(tempDir, ".artifacts", "build-all-cache"),
2360+
]);
23552361
});
23562362
it("pins dev updates to an explicit target ref when requested", async () => {
23572363
await setupGitPackageManagerFixture();
@@ -3314,11 +3320,31 @@ describe("runGatewayUpdate", () => {
33143320
const result = await runWithCommand(runCommand, { channel: "stable" });
33153321

33163322
expect(result.status).toBe("ok");
3317-
expect(getUiBuildCount()).toBe(2);
3323+
expect(getUiBuildCount()).toBe(1);
33183324
expect(await pathExists(uiIndexPath)).toBe(true);
33193325
expect(calls).toContain(doctorKey);
33203326
});
33213327

3328+
it("builds Control UI separately only when the checkout build omitted it", async () => {
3329+
await setupGitCheckout({ packageManager: "[email protected]" });
3330+
const uiIndexPath = path.join(tempDir, "dist", "control-ui", "index.html");
3331+
const stableTag = "v1.0.1-1";
3332+
const { runCommand, calls, doctorKey, getUiBuildCount } = await createStableTagRunner({
3333+
stableTag,
3334+
uiIndexPath,
3335+
onUiBuild: async () => {
3336+
await fs.mkdir(path.dirname(uiIndexPath), { recursive: true });
3337+
await fs.writeFile(uiIndexPath, "<html>built</html>", "utf-8");
3338+
},
3339+
});
3340+
3341+
const result = await runWithCommand(runCommand, { channel: "stable" });
3342+
3343+
expect(result.status).toBe("ok");
3344+
expect(getUiBuildCount()).toBe(1);
3345+
expect(calls.indexOf("pnpm ui:build")).toBeLessThan(calls.indexOf(doctorKey));
3346+
});
3347+
33223348
it("fails when UI assets are still missing after post-doctor repair", async () => {
33233349
await setupGitCheckout({ packageManager: "[email protected]" });
33243350
const uiIndexPath = await setupUiIndex();
@@ -3327,12 +3353,6 @@ describe("runGatewayUpdate", () => {
33273353
const { runCommand } = await createStableTagRunner({
33283354
stableTag,
33293355
uiIndexPath,
3330-
onUiBuild: async (count) => {
3331-
if (count === 1) {
3332-
await fs.mkdir(path.dirname(uiIndexPath), { recursive: true });
3333-
await fs.writeFile(uiIndexPath, "<html>built</html>", "utf-8");
3334-
}
3335-
},
33363356
onDoctor: removeControlUiAssets,
33373357
});
33383358

‎test/scripts/build-all.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,6 +736,49 @@ describe("build-all timing output", () => {
736736
});
737737

738738
describe("resolveBuildAllStepCacheState", () => {
739+
it("shares content-addressed outputs across checkout roots", () => {
740+
const cacheRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-shared-build-cache-"));
741+
const firstRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-build-cache-source-"));
742+
const secondRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-build-cache-target-"));
743+
const step = {
744+
label: "cached",
745+
cache: {
746+
inputs: ["src"],
747+
outputs: ["dist"],
748+
restore: "always" as const,
749+
},
750+
};
751+
const env = { BUILD_ALL_CACHE_ROOT: cacheRoot };
752+
753+
try {
754+
for (const rootDir of [firstRoot, secondRoot]) {
755+
fs.mkdirSync(path.join(rootDir, "src"), { recursive: true });
756+
fs.writeFileSync(path.join(rootDir, "src/input.ts"), "same input");
757+
}
758+
fs.mkdirSync(path.join(firstRoot, "dist"), { recursive: true });
759+
fs.writeFileSync(path.join(firstRoot, "dist/output.js"), "cached output");
760+
761+
const sourceState = resolveBuildAllStepCacheState(step, { rootDir: firstRoot, env });
762+
writeBuildAllStepCacheStamp(
763+
step,
764+
resolveBuildAllStepCacheStampState(step, sourceState, { rootDir: firstRoot }),
765+
{ rootDir: firstRoot },
766+
);
767+
768+
const targetState = resolveBuildAllStepCacheState(step, { rootDir: secondRoot, env });
769+
expect(targetState).toMatchObject({ fresh: true, restorable: true });
770+
expect(targetState.outputRoot).toBe(path.join(cacheRoot, "cached", "outputs"));
771+
expect(restoreBuildAllStepCacheOutputs(targetState, { rootDir: secondRoot })).toBe(true);
772+
expect(fs.readFileSync(path.join(secondRoot, "dist/output.js"), "utf8")).toBe(
773+
"cached output",
774+
);
775+
} finally {
776+
fs.rmSync(cacheRoot, { force: true, recursive: true });
777+
fs.rmSync(firstRoot, { force: true, recursive: true });
778+
fs.rmSync(secondRoot, { force: true, recursive: true });
779+
}
780+
});
781+
739782
it("invalidates only declaration groups that depend on the changed module", () => {
740783
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-tsdown-group-cache-"));
741784
const ai = getBuildAllStep("tsdown-ai");

0 commit comments

Comments
 (0)