Skip to content

Commit 9c824b2

Browse files
committed
perf(crabbox): streamline warm project activation
Reuse the successful snapshot fork attestation and finish trusted runtime preparation and enrollment through the shared command cleanup owner. Keep provider readiness refreshes for arbitrary setup and native capture. Allow Daytona to perform its required snapshot stop/capture/restore cycle. Validated with 372 Linux tests, canonical changed-surface checks, and the full QA-enabled build. The only later test edit removes an unused import.
1 parent ace8a13 commit 9c824b2

7 files changed

Lines changed: 157 additions & 81 deletions

‎docs/gateway/cloud-workers.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,8 @@ Forwarded host environment values reach setup, so whatever setup derives from th
114114

115115
For a project with a Git commit, capture happens during provisioning, before node enrollment. After profile setup, OpenClaw prepares a pristine checkout of the admitted commit, installs the verified node runtime, and captures the machine when an image is needed. The first dispatch includes that work; subsequent sessions can reuse the image without waiting for the first session to stop. Session edits, eligible untracked files, and node enrollment credentials arrive only after capture. Provisioning without a prepared Git project retains capture at an eligible enrolled worker's teardown.
116116

117+
Daytona requires a stopped source for filesystem snapshots. OpenClaw allows Crabbox to stop the scrubbed worker for capture. A successful capture waits for snapshot completion and restores a previously running source before project enrollment continues.
118+
117119
Image reuse is keyed by the backend, setup command, sorted `setupEnv` variable names (not their values), desktop setting, exact effective machine class, and project identity when present. Project identity comes from the Gateway's namespace and the canonical shared Git directory. Linked session worktrees from the same repository share it; a new session or commit does not create another project identity. Separate repository clones have separate identities. Each prepared seed also records its exact commit, so a changed commit can refresh the same project's image.
118120

119121
Before its first provider allocation command, OpenClaw records whether the lease starts cold or from a specific checkpoint, along with its resolved class. Retries and Gateway restart reuse that exact choice; a lost response cannot switch a cold allocation to a newly available image or select a different checkpoint. The record advances through preparation and enrollment, and a selected checkpoint remains protected from deletion until the provider confirms the lease has stopped. A failed fork reports an error instead of silently changing the recorded allocation.

‎extensions/crabbox/src/crabbox-worker-node-enrollment.test.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import https from "node:https";
77
import path from "node:path";
88
import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env";
99
import * as tar from "tar";
10-
import { afterEach, describe, expect, it, vi } from "vitest";
10+
import { afterEach, describe, expect, it } from "vitest";
1111
import {
1212
createCrabboxNodeEnrollmentSetup,
1313
createCrabboxNodeRuntimeSetup,
@@ -248,7 +248,23 @@ echo 123
248248

249249
async function readLaunch(stateDir: string) {
250250
const target = path.join(stateDir, "launch.json");
251-
await vi.waitFor(() => expect(fs.existsSync(target)).toBe(true));
251+
// Child startup follows the test deadline, not waitFor's shorter polling deadline.
252+
const watcher = fs.watch(stateDir, { persistent: false });
253+
cleanups.push(() => watcher.close());
254+
try {
255+
await new Promise<void>((resolve, reject) => {
256+
const inspect = () => {
257+
if (fs.existsSync(target)) {
258+
resolve();
259+
}
260+
};
261+
watcher.on("change", inspect);
262+
watcher.once("error", reject);
263+
inspect();
264+
});
265+
} finally {
266+
watcher.close();
267+
}
252268
return JSON.parse(fs.readFileSync(target, "utf8")) as {
253269
build: string;
254270
cli: string;

‎extensions/crabbox/src/crabbox-worker-project.test.ts‎

Lines changed: 82 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -62,66 +62,109 @@ function projectOptions(events: string[], controller = new AbortController()) {
6262
}
6363

6464
describe("Crabbox project snapshot provisioning", () => {
65-
it("captures the checked-out project and runtime before enrollment, then forks without another capture", async () => {
66-
const events: string[] = [];
67-
let current = projectOptions(events);
68-
const { provider, calls } = createWarmProvider((call) => current.observe(call));
69-
70-
await provider.provision(PROFILE, "project-first", current.options);
71-
72-
expect(events).toEqual([
73-
"project-prepared",
74-
"runtime-granted",
75-
"runtime-install",
76-
"capture",
77-
"enrollment-begun",
78-
"enrollment-install",
79-
]);
80-
expect(listCrabboxWarmImages()[0]).toMatchObject({
81-
projectKey: PROJECT_KEY,
82-
checkpointId: CHECKPOINT_ID,
83-
allocations: {
84-
[operationLeaseId("project-first")]: { phase: "enrolled", baseCommit: BASE_COMMIT },
85-
},
86-
});
87-
// The first worker is still running: a new session can already use its clean image.
88-
calls.length = 0;
89-
events.length = 0;
90-
current = projectOptions(events);
91-
await provider.provision(PROFILE, "project-second", current.options);
92-
expect(calls.find(({ argv }) => argv[2] === "fork")?.argv[3]).toBe(CHECKPOINT_ID);
93-
expect(calls.some(({ argv }) => argv[1] === "warmup" || argv[2] === "create")).toBe(false);
94-
expect(events).toEqual(["project-prepared", "enrollment-begun", "enrollment-install"]);
95-
expect(current.options.prepareNodeRuntime).not.toHaveBeenCalled();
96-
// Allocation and normal enrollment each inspect once; a cache hit causes no native restart.
97-
expect(calls.filter(({ argv }) => argv[1] === "inspect")).toHaveLength(2);
98-
});
65+
it.each(["runtime-install", "enrollment-install"])(
66+
"completes internal %s without another provider readiness request",
67+
async (phase) => {
68+
const events: string[] = [];
69+
const { options, observe } = projectOptions(events);
70+
const { provider, calls } = createWarmProvider((call) => {
71+
observe(call);
72+
if ((call.argv[1] === "inspect" || call.argv[1] === "status") && events.at(-1) === phase) {
73+
return commandResult({ termination: "timeout", code: null, killed: true });
74+
}
75+
return undefined;
76+
});
77+
78+
await expect(
79+
provider.provision(PROFILE, `internal-${phase}`, options),
80+
).resolves.toMatchObject({
81+
node: { deviceId: "project-node" },
82+
});
83+
expect(events).toContain(phase);
84+
expect(calls.some(({ argv }) => argv[1] === "stop")).toBe(false);
85+
},
86+
);
87+
88+
it.each(["aws", "daytona"])(
89+
"captures the prepared %s project before enrollment and reuses it",
90+
async (backend) => {
91+
const profile = { ...PROFILE, provider: backend };
92+
const events: string[] = [];
93+
let current = projectOptions(events);
94+
const { provider, calls } = createWarmProvider((call) => {
95+
current.observe(call);
96+
if (
97+
backend === "daytona" &&
98+
call.argv[2] === "create" &&
99+
!call.argv.includes("--no-reboot=false")
100+
) {
101+
return commandResult({
102+
code: 2,
103+
stderr:
104+
"Daytona filesystem snapshots require a stopped source; rerun with --no-reboot=false",
105+
});
106+
}
107+
return undefined;
108+
});
109+
110+
await provider.provision(profile, "project-first", current.options);
111+
112+
expect(events).toEqual([
113+
"project-prepared",
114+
"runtime-granted",
115+
"runtime-install",
116+
"capture",
117+
"enrollment-begun",
118+
"enrollment-install",
119+
]);
120+
expect(listCrabboxWarmImages()[0]).toMatchObject({
121+
projectKey: PROJECT_KEY,
122+
checkpointId: CHECKPOINT_ID,
123+
allocations: {
124+
[operationLeaseId("project-first")]: { phase: "enrolled", baseCommit: BASE_COMMIT },
125+
},
126+
});
127+
// The first worker is still running: a new session can already use its clean image.
128+
calls.length = 0;
129+
events.length = 0;
130+
current = projectOptions(events);
131+
await provider.provision(profile, "project-second", current.options);
132+
expect(calls.find(({ argv }) => argv[2] === "fork")?.argv[3]).toBe(CHECKPOINT_ID);
133+
expect(calls.some(({ argv }) => argv[1] === "warmup" || argv[2] === "create")).toBe(false);
134+
// Pending images need verification before the fork; a successful fork already attests reuse.
135+
expect(calls.filter(({ argv }) => argv[2] === "inspect")).toHaveLength(1);
136+
expect(events).toEqual(["project-prepared", "enrollment-begun", "enrollment-install"]);
137+
expect(current.options.prepareNodeRuntime).not.toHaveBeenCalled();
138+
// A cache hit does not restart the machine; only allocation needs provider readiness.
139+
expect(calls.filter(({ argv }) => argv[1] === "inspect")).toHaveLength(1);
140+
},
141+
);
99142

100143
it.each(["grant", "setup", "readiness"] as const)(
101-
"preserves runtime %s failure ownership without starting capture or enrollment",
144+
"preserves preparation %s failure ownership without enrollment",
102145
async (failure) => {
103146
const events: string[] = [];
104147
const { options, observe } = projectOptions(events);
105148
if (failure === "grant") {
106149
options.prepareNodeRuntime.mockRejectedValueOnce(new Error("runtime grant failed"));
107150
}
108-
let installed = false;
151+
let captured = false;
109152
const { provider, calls } = createWarmProvider((call) => {
110153
observe(call);
111154
if (call.argv[1] === "run" && call.argv.includes("CRABBOX_WORKER_BOOTSTRAP_TOKEN")) {
112-
installed = true;
113155
if (failure === "setup") {
114156
return commandResult({ code: 7, stderr: "runtime setup failed" });
115157
}
116158
}
117-
if (installed && failure === "readiness" && call.argv[1] === "inspect") {
159+
captured ||= call.argv[2] === "create";
160+
if (captured && failure === "readiness" && call.argv[1] === "inspect") {
118161
return commandResult({ termination: "timeout", code: null, killed: true });
119162
}
120163
return undefined;
121164
});
122165
await expect(provider.provision(PROFILE, `runtime-${failure}`, options)).rejects.toThrow();
123166
expect(options.beginNodeEnrollment).not.toHaveBeenCalled();
124-
expect(calls.some(({ argv }) => argv[2] === "create")).toBe(false);
167+
expect(calls.some(({ argv }) => argv[2] === "create")).toBe(failure === "readiness");
125168
expect(calls.filter(({ argv }) => argv[1] === "stop")).toHaveLength(
126169
failure === "readiness" ? 0 : 1,
127170
);

‎extensions/crabbox/src/crabbox-worker-provider.test.ts‎

Lines changed: 23 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1288,7 +1288,6 @@ describe("Crabbox worker provider", () => {
12881288
"inspect",
12891289
"inspect",
12901290
"run",
1291-
"inspect",
12921291
]);
12931292
});
12941293

@@ -1764,7 +1763,7 @@ describe("Crabbox worker provider", () => {
17641763
},
17651764
],
17661765
expectedError: null,
1767-
expectedCommands: ["warmup", "inspect", "inspect", "run", "inspect"],
1766+
expectedCommands: ["warmup", "inspect", "inspect", "run"],
17681767
},
17691768
{
17701769
state: "pending-forbidden",
@@ -2258,13 +2257,25 @@ describe("Crabbox worker provider", () => {
22582257
expect(hasLoneSurrogate(message)).toBe(false);
22592258
});
22602259

2261-
it.each(["preparation", "completion", "diagnostics"] as const)(
2260+
it.each(["preparation", "setup", "completion", "diagnostics"] as const)(
22622261
"preserves its fixed lease when the Gateway aborts enrollment %s",
22632262
async (phase) => {
22642263
const calls: string[][] = [];
22652264
const controller = new AbortController();
2265+
const waitForDeviceId = vi.fn(async () => {
2266+
if (phase === "diagnostics") {
2267+
throw new Error("Worker node did not connect before the enrollment deadline");
2268+
}
2269+
controller.abort();
2270+
controller.signal.throwIfAborted();
2271+
return "device-bound";
2272+
});
22662273
const provider = providerWithRunner(async (argv, options) => {
22672274
calls.push(argv);
2275+
if (phase === "setup" && argv[1] === "run") {
2276+
controller.abort();
2277+
return commandResult();
2278+
}
22682279
if (
22692280
phase === "diagnostics" &&
22702281
argv[1] === "run" &&
@@ -2292,20 +2303,16 @@ describe("Crabbox worker provider", () => {
22922303
nodeBootstrap: createNodeBootstrapFixture(),
22932304
displayName: "Bound worker",
22942305
signal: controller.signal,
2295-
waitForDeviceId: async () => {
2296-
if (phase === "diagnostics") {
2297-
throw new Error("Worker node did not connect before the enrollment deadline");
2298-
}
2299-
controller.abort();
2300-
controller.signal.throwIfAborted();
2301-
return "device-bound";
2302-
},
2306+
waitForDeviceId,
23032307
};
23042308
},
23052309
}),
23062310
).rejects.toMatchObject({ name: "AbortError" });
23072311

23082312
expect(calls.some((argv) => argv[1] === "stop")).toBe(false);
2313+
if (phase === "setup") {
2314+
expect(waitForDeviceId).not.toHaveBeenCalled();
2315+
}
23092316
},
23102317
);
23112318

@@ -2344,7 +2351,7 @@ describe("Crabbox worker provider", () => {
23442351
await expect(provider.provision(profile, OPERATION_ID)).resolves.toMatchObject({
23452352
leaseId: LEASE_ID,
23462353
});
2347-
expect(calls).toHaveLength(4);
2354+
expect(calls).toHaveLength(3);
23482355
expect(calls[0]?.argv).toEqual([
23492356
SIBLING_BINARY,
23502357
"warmup",
@@ -2411,13 +2418,10 @@ describe("Crabbox worker provider", () => {
24112418
expect.arrayContaining(["--allow-env", "CRABBOX_WORKER_SETUP_CODE"]),
24122419
);
24132420
expect(calls[2]?.argv.join(" ")).not.toContain("setup-code");
2414-
expect(calls[3]?.argv[1]).toBe(readinessAction);
2415-
expect(calls[3]?.options.timeoutMs).toBe(lifecycleTimeoutMs);
2416-
24172421
const lease = lifecycleLease(LEASE_ID, profile);
24182422
await expect(provider.inspect(lease)).resolves.toEqual({ status: "active" });
24192423
await expect(provider.destroy(lease)).resolves.toBeUndefined();
2420-
expect(calls.slice(4).map(({ argv, options }) => [argv[1], options.timeoutMs])).toEqual([
2424+
expect(calls.slice(3).map(({ argv, options }) => [argv[1], options.timeoutMs])).toEqual([
24212425
["inspect", lifecycleTimeoutMs],
24222426
["stop", lifecycleTimeoutMs],
24232427
]);
@@ -2622,14 +2626,9 @@ describe("Crabbox worker provider", () => {
26222626
});
26232627
expect(live.size).toBe(0);
26242628
expect(calls.filter((argv) => argv[1] === "warmup")).toHaveLength(2);
2625-
expect(calls.filter((argv) => argv[1] === "inspect")).toHaveLength(3);
2626-
expect(calls.filter((argv) => argv[1] === "inspect")).toEqual(
2627-
expect.arrayContaining([
2628-
expect.arrayContaining(["--id", LEASE_ID]),
2629-
expect.arrayContaining(["--id", LEASE_ID]),
2630-
expect.arrayContaining(["--id", LEASE_ID]),
2631-
]),
2632-
);
2629+
expect(
2630+
calls.filter((argv) => argv[1] === "inspect").map((argv) => argv[argv.indexOf("--id") + 1]),
2631+
).toEqual([LEASE_ID, LEASE_ID]);
26332632
expect(calls.at(-1)).toEqual([SIBLING_BINARY, "stop", "--provider", "aws", "--id", LEASE_ID]);
26342633
});
26352634

@@ -2686,7 +2685,6 @@ describe("Crabbox worker provider", () => {
26862685
"warmup",
26872686
"inspect",
26882687
"run",
2689-
"inspect",
26902688
"stop",
26912689
]);
26922690
});

‎extensions/crabbox/src/crabbox-worker-provider.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import {
4545
isNonRunnableState,
4646
leaseRunArgs,
4747
remainingProvisionTimeout,
48+
runProvisionSetup,
4849
runProvisionSetupAndWaitReady,
4950
waitForProvisionReady,
5051
type InspectCommandResult,
@@ -365,7 +366,7 @@ export function createCrabboxWorkerProvider(
365366
}
366367
}
367368

368-
await warmImages.allocate({
369+
const allocationChoice = await warmImages.allocate({
369370
...context,
370371
id: leaseId,
371372
profile: parsed,
@@ -453,6 +454,9 @@ export function createCrabboxWorkerProvider(
453454
profile: parsed,
454455
signal: project.signal,
455456
assertCurrent: project.assertCurrent,
457+
...(allocationChoice.kind === "checkpoint"
458+
? { forkedCheckpointId: allocationChoice.checkpointId }
459+
: {}),
456460
},
457461
async () => {
458462
if (!options?.prepareNodeRuntime) {
@@ -465,19 +469,16 @@ export function createCrabboxWorkerProvider(
465469
leaseId,
466470
});
467471
try {
468-
inspectedParams.inspect = await runProvisionSetupAndWaitReady({
472+
await runProvisionSetup({
469473
...inspectedParams,
470474
phase: "node runtime preparation",
471475
setup: setup.command,
472476
forwardedEnv: setup.forwardedEnv,
473477
timeoutMs: CRABBOX_NODE_ENROLLMENT_TIMEOUT_MS,
474478
signal: runtime.signal,
475-
sleep,
476479
});
477-
runtime.signal?.throwIfAborted();
478480
} catch (error) {
479-
// Setup already owns cleanup; an indeterminate readiness error deliberately
480-
// keeps the lease for replay. Neither outcome permits a second stop here.
481+
// The command owner settles setup failure and cleanup; do not stop it twice.
481482
preparationFailed = true;
482483
throw error;
483484
}
@@ -521,7 +522,8 @@ export function createCrabboxWorkerProvider(
521522
desktop: parsed.desktop,
522523
leaseId,
523524
});
524-
inspectedParams.inspect = await runProvisionSetupAndWaitReady({
525+
// These owned scripts do not restart SSH; authenticated enrollment proves node readiness.
526+
await runProvisionSetup({
525527
...inspectedParams,
526528
phase: "node enrollment setup",
527529
signal: enrollment.signal,
@@ -530,7 +532,6 @@ export function createCrabboxWorkerProvider(
530532
...(nodeEnrollmentSetup.forwardedEnv
531533
? { forwardedEnv: nodeEnrollmentSetup.forwardedEnv }
532534
: {}),
533-
sleep,
534535
});
535536
let deviceId: string;
536537
try {

0 commit comments

Comments
 (0)