Skip to content

Commit e537819

Browse files
committed
fix(crabbox): make warm-image lifecycle recovery-safe
Delete least-recently-used provider snapshots before image index admission. Recover stale empty capture reservations without breaking single-flight. Persist effective machine classes across restarts and revert heartbeat coupling. Align the hibernation plan with the exact-class warm-image key policy.
1 parent e6eb51b commit e537819

5 files changed

Lines changed: 163 additions & 32 deletions

File tree

‎docs/plan/worker-hibernation.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -218,12 +218,12 @@ falls back to the cold `warmup` path — never dead-end a dispatch on a
218218
missing, stale, or still-pending snapshot. (Fallback contract: product
219219
behavior per the doctrine, not a compat shim.)
220220

221-
**Image key and staleness.** Record key = hash of (backend provider, region,
222-
architecture, profile `setup`, `desktop`, machine-class _architecture family_).
223-
Cross-class reuse within the same architecture is deliberately allowed — a
224-
snapshot boots on any same-arch instance type; accepted tradeoff noted here so
225-
it is a decision. A key change (edited setup command, backend switch) simply
226-
misses the record and cold-provisions; the stale image ages out.
221+
**Image key and staleness.** Record key = hash of (backend provider, profile
222+
`setup`, sorted `setupEnv` names, `desktop`, exact machine class). Exact-class
223+
matching is the accepted conservative decision; cross-class and cross-region
224+
reuse are future work. A key change (edited setup command, backend switch, or
225+
machine class) simply misses the record and cold-provisions; the stale image
226+
ages out.
227227

228228
**Storage.** Plugin KV in the shared state DB (the sanctioned plugin-scratch
229229
store — no new tables, no sidecar files): one record per image key holding

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

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ type HeartbeatContext = {
99
heartbeatTimeoutMs: number;
1010
id: string;
1111
idleTimeout: string;
12-
machineClass?: string;
1312
provider: string;
1413
};
1514

@@ -102,17 +101,16 @@ export function createCrabboxHeartbeatManager(dependencies: {
102101
schedule(entry);
103102
};
104103

105-
const stop = (leaseId: string): HeartbeatContext | undefined => {
104+
const stop = (leaseId: string): void => {
106105
const entry = entries.get(leaseId);
107106
if (!entry) {
108-
return undefined;
107+
return;
109108
}
110109
entries.delete(leaseId);
111110
if (entry.timer) {
112111
clearTimeout(entry.timer);
113112
}
114113
entry.controller?.abort();
115-
return entry;
116114
};
117115

118116
return {

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

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
type WorkerProfile,
77
type WorkerProvider,
88
} from "openclaw/plugin-sdk/plugin-entry";
9+
import { createPluginStateSyncKeyedStore } from "openclaw/plugin-sdk/plugin-state-store-runtime";
910
import { runCommandWithTimeout } from "openclaw/plugin-sdk/process-runtime";
1011
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
1112
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
@@ -214,7 +215,7 @@ const isTerminalState = (state: string) => DESTROYED_STATES.has(state.toLowerCas
214215
const isUnusableProvisionState = (state: string) =>
215216
UNUSABLE_PROVISION_STATES.has(state.toLowerCase());
216217

217-
function crabboxLeaseRunArgs(
218+
function leaseRunArgs(
218219
context: LeaseCommandContext,
219220
forwardedEnvNames: readonly string[] = [],
220221
envProfilePath?: string,
@@ -316,7 +317,7 @@ async function runProvisionSetupAndWaitReady(
316317
(names, profilePath, childEnv) =>
317318
runCrabboxCommand({
318319
action: "setup",
319-
args: crabboxLeaseRunArgs({ ...params, id: params.inspect.id }, names, profilePath),
320+
args: leaseRunArgs({ ...params, id: params.inspect.id }, names, profilePath),
320321
binary: params.binary,
321322
env: childEnv,
322323
input: params.setup,
@@ -469,11 +470,16 @@ export function createCrabboxWorkerProvider(
469470
runCommand,
470471
warn,
471472
});
472-
const warmImages = createCrabboxWarmImageManager({
473-
runCommand,
474-
runArgs: crabboxLeaseRunArgs,
475-
warn,
476-
});
473+
const warmImages = createCrabboxWarmImageManager({ runCommand, runArgs: leaseRunArgs, warn });
474+
let warmLeases:
475+
| ReturnType<typeof createPluginStateSyncKeyedStore<{ machineClass: string }>>
476+
| undefined;
477+
const openWarmLeases = () =>
478+
(warmLeases ??= createPluginStateSyncKeyedStore<{ machineClass: string }>("crabbox", {
479+
namespace: "warm-leases",
480+
maxEntries: 256,
481+
overflowPolicy: "evict-oldest",
482+
}));
477483
const resolveLeaseContext = (
478484
lease: Parameters<WorkerProvider["inspect"]>[0],
479485
): { context: LeaseHeartbeatContext; profile: CrabboxProfile } => {
@@ -665,7 +671,7 @@ export function createCrabboxWorkerProvider(
665671
// Read node evidence before cleanup destroys its only copy on the leased machine.
666672
const evidence = await collectCrabboxNodeEnrollmentEvidence({
667673
...leaseContext,
668-
args: crabboxLeaseRunArgs(leaseContext),
674+
args: leaseRunArgs(leaseContext),
669675
...(enrollment.signal ? { signal: enrollment.signal } : {}),
670676
});
671677
enrollment.signal?.throwIfAborted();
@@ -675,13 +681,15 @@ export function createCrabboxWorkerProvider(
675681
new Error(`${message}; ${evidence}`, { cause: error }),
676682
);
677683
}
684+
if (parsed.warmImage) {
685+
openWarmLeases().register(leaseId, { machineClass: parsed.class });
686+
}
678687
heartbeats.start({
679688
binary,
680689
heartbeatIntervalMs: parsed.heartbeatIntervalMs,
681690
heartbeatTimeoutMs: parsed.heartbeatTimeoutMs,
682691
id: leaseId,
683692
idleTimeout: parsed.idleTimeout,
684-
machineClass: parsed.class,
685693
provider: parsed.provider,
686694
});
687695
return {
@@ -714,11 +722,11 @@ export function createCrabboxWorkerProvider(
714722
async destroy(lease): Promise<void> {
715723
const { context, profile } = resolveLeaseContext(lease);
716724
// Fence the provider keepalive before teardown so an in-flight touch cannot reschedule.
717-
const heartbeat = heartbeats.stop(context.id);
725+
heartbeats.stop(context.id);
718726
if (profile.warmImage) {
719727
// Lifecycle profiles omit placement class overrides; only successful
720-
// provisioning can attest which class owns this reusable image.
721-
const machineClass = heartbeat?.machineClass;
728+
// provisioning can durably attest which class owns this reusable image.
729+
const machineClass = openWarmLeases().lookup(context.id)?.machineClass;
722730
await warmImages.capture({
723731
...context,
724732
profile: machineClass ? { ...profile, class: machineClass } : profile,
@@ -730,6 +738,7 @@ export function createCrabboxWorkerProvider(
730738
runCommand,
731739
timeoutMs: resolveCrabboxLifecycleTimeoutMs(context.provider),
732740
});
741+
warmLeases?.delete(context.id);
733742
},
734743
};
735744
}

‎extensions/crabbox/src/crabbox-worker-warm-image.test.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import fs from "node:fs";
33
import path from "node:path";
44
import { fileURLToPath } from "node:url";
55
import type { WorkerProfile, WorkerProvider } from "openclaw/plugin-sdk/plugin-entry";
6+
import { createPluginStateSyncKeyedStoreForTests } from "openclaw/plugin-sdk/plugin-state-test-runtime";
67
import type { SpawnResult } from "openclaw/plugin-sdk/process-runtime";
78
import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env";
89
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -114,6 +115,16 @@ function createWarmProvider(
114115
return { provider, calls, stateDir, warn };
115116
}
116117

118+
function openWarmImageStore() {
119+
return createPluginStateSyncKeyedStoreForTests<{
120+
checkpointId: string;
121+
kind: string;
122+
state: "pending" | "available";
123+
createdAtMs: number;
124+
lastUsedAtMs: number;
125+
}>("crabbox", { namespace: "warm-images", maxEntries: 128, overflowPolicy: "evict-oldest" });
126+
}
127+
117128
async function provisionWarmProfile(
118129
provider: WorkerProvider,
119130
profile: WorkerProfile = PROFILE,
@@ -351,6 +362,33 @@ describe("Crabbox profile warm images", () => {
351362
expect(fork?.[fork.indexOf("--class") + 1]).toBe("fast");
352363
});
353364

365+
it("captures the persisted effective machine class after a Gateway restart rearms heartbeat", async () => {
366+
const initial = createWarmProvider();
367+
const lease = await provisionWarmProfile(initial.provider, PROFILE, OPERATION_ID, "fast");
368+
initial.provider.dispose();
369+
370+
const restarted = createWarmProvider(undefined, initial.stateDir);
371+
await restarted.provider.inspect({ leaseId: lease.leaseId, profile: PROFILE });
372+
await restarted.provider.destroy({ leaseId: lease.leaseId, profile: PROFILE });
373+
374+
expect(restarted.calls.filter(({ argv }) => argv[2] === "create")).toHaveLength(1);
375+
376+
restarted.calls.length = 0;
377+
await provisionWarmProfile(restarted.provider, PROFILE, `provision:v2:${"1".repeat(64)}`);
378+
expect(restarted.calls.some(({ argv }) => argv[1] === "warmup")).toBe(true);
379+
expect(restarted.calls.some(({ argv }) => argv[2] === "fork")).toBe(false);
380+
381+
restarted.calls.length = 0;
382+
await provisionWarmProfile(
383+
restarted.provider,
384+
PROFILE,
385+
`provision:v2:${"2".repeat(64)}`,
386+
"fast",
387+
);
388+
const fork = restarted.calls.find(({ argv }) => argv[2] === "fork")?.argv;
389+
expect(fork?.[fork.indexOf("--class") + 1]).toBe("fast");
390+
});
391+
354392
it("never snapshots an inspected lease whose effective machine class is unknown", async () => {
355393
const { provider, calls } = createWarmProvider();
356394
const lease = { leaseId: LEASE_ID, profile: PROFILE };
@@ -469,6 +507,53 @@ describe("Crabbox profile warm images", () => {
469507
expect(calls.some(({ argv }) => argv[2] === "fork")).toBe(false);
470508
});
471509

510+
it("deletes the least-recently-used provider snapshot before admitting a 129th image", async () => {
511+
const { provider, calls } = createWarmProvider();
512+
const store = openWarmImageStore();
513+
const now = Date.now();
514+
for (let index = 0; index < 128; index += 1) {
515+
store.register(`image-${index}`, {
516+
checkpointId: `chk_image_${index}`,
517+
kind: "aws-ebs-snapshot",
518+
state: "available",
519+
createdAtMs: now,
520+
lastUsedAtMs: now - (index === 42 ? 1_000 : 0),
521+
});
522+
}
523+
524+
await captureWarmImage(provider);
525+
526+
const deleted = calls.findIndex(({ argv }) => argv[2] === "delete");
527+
const created = calls.findIndex(({ argv }) => argv[2] === "create");
528+
expect(calls[deleted]?.argv.slice(1)).toEqual(["checkpoint", "delete", "chk_image_42"]);
529+
expect(deleted).toBeLessThan(created);
530+
expect(store.lookup("image-42")).toBeUndefined();
531+
expect(store.lookup("image-0")?.checkpointId).toBe("chk_image_0");
532+
expect(store.entries()).toHaveLength(128);
533+
});
534+
535+
it("replaces an abandoned empty reservation after a manager restart", async () => {
536+
const initial = createWarmProvider();
537+
await captureWarmImage(initial.provider);
538+
const store = openWarmImageStore();
539+
const [image] = store.entries();
540+
if (!image) {
541+
throw new Error("Expected a captured warm image");
542+
}
543+
store.register(image.key, {
544+
...image.value,
545+
checkpointId: "",
546+
createdAtMs: Date.now() - 360_001,
547+
});
548+
549+
const restarted = createWarmProvider(undefined, initial.stateDir);
550+
await captureWarmImage(restarted.provider);
551+
552+
expect(restarted.calls.filter(({ argv }) => argv[2] === "create")).toHaveLength(1);
553+
expect(restarted.calls.some(({ argv }) => argv[2] === "delete")).toBe(false);
554+
expect(store.lookup(image.key)?.checkpointId).toBe(CHECKPOINT_ID);
555+
});
556+
472557
it("reserves one capture when enrolled leases with the same profile stop concurrently", async () => {
473558
let releaseScrub!: () => void;
474559
const scrubBlocked = new Promise<void>((resolve) => {

‎extensions/crabbox/src/crabbox-worker-warm-image.ts‎

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ const WARM_IMAGE_COMMAND_TIMEOUT_MS = 60_000;
3535
// owner, coordinator posts); 60s starves them under coordinator latency and the
3636
// capture silently degrades to cold-only. Live-measured on AWS 2026-08-26.
3737
const WARM_IMAGE_CAPTURE_TIMEOUT_MS = 180_000;
38+
const WARM_IMAGE_CAPTURE_RESERVATION_TIMEOUT_MS = 2 * WARM_IMAGE_CAPTURE_TIMEOUT_MS;
39+
const WARM_IMAGE_MAX_ENTRIES = 128;
3840
const CHECKPOINT_ID_PATTERN = /^chk_[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u;
3941

4042
// Enrollment roots its identity, device token, bundles, and node-host workspaces
@@ -124,7 +126,7 @@ export function createCrabboxWarmImageManager(dependencies: {
124126
const openStore = () =>
125127
(store ??= createPluginStateSyncKeyedStore<WarmImageRecord>("crabbox", {
126128
namespace: "warm-images",
127-
maxEntries: 128,
129+
maxEntries: WARM_IMAGE_MAX_ENTRIES,
128130
overflowPolicy: "evict-oldest",
129131
}));
130132

@@ -172,11 +174,38 @@ export function createCrabboxWarmImageManager(dependencies: {
172174
timeoutMs,
173175
);
174176
}
175-
// Delete the provider snapshot before its index; store eviction alone can
176-
// orphan a resource, a residual risk bounded by `crabbox checkpoint prune`.
177+
// Delete the provider snapshot before its index; losing the index first
178+
// would orphan a billed resource outside warm-image retention cleanup.
177179
openStore().delete(key);
178180
};
179181

182+
const makeRoomForCapture = async (context: LeaseContext): Promise<boolean> => {
183+
const deadline = Date.now() + WARM_IMAGE_COMMAND_TIMEOUT_MS;
184+
for (let remainingEntries = WARM_IMAGE_MAX_ENTRIES; remainingEntries > 0; remainingEntries--) {
185+
const entries = openStore().entries();
186+
if (entries.length < WARM_IMAGE_MAX_ENTRIES) {
187+
return true;
188+
}
189+
const remainingTime = deadline - Date.now();
190+
if (remainingTime <= 0) {
191+
return false;
192+
}
193+
// Evicting a live reservation would break its capture's single-flight ownership.
194+
const oldest = entries
195+
.filter(
196+
({ value }) =>
197+
value.checkpointId ||
198+
Date.now() - value.createdAtMs >= WARM_IMAGE_CAPTURE_RESERVATION_TIMEOUT_MS,
199+
)
200+
.toSorted((left, right) => left.value.lastUsedAtMs - right.value.lastUsedAtMs)[0];
201+
if (!oldest) {
202+
return false;
203+
}
204+
await deleteImage(context, oldest.key, oldest.value, remainingTime);
205+
}
206+
return openStore().entries().length < WARM_IMAGE_MAX_ENTRIES;
207+
};
208+
180209
const collectExpiredImages = async (context: LeaseContext): Promise<void> => {
181210
const deadline = Date.now() + WARM_IMAGE_COMMAND_TIMEOUT_MS;
182211
for (const { key, value } of openStore().entries()) {
@@ -269,15 +298,25 @@ export function createCrabboxWarmImageManager(dependencies: {
269298
await collectExpiredImages(context);
270299
const existing = openStore().lookup(key);
271300
if (existing) {
272-
if (
273-
!existing.checkpointId ||
274-
(await verifyImage(context, existing.checkpointId)) !== "missing"
275-
) {
276-
return;
301+
if (!existing.checkpointId) {
302+
const staleBefore = Date.now() - WARM_IMAGE_CAPTURE_RESERVATION_TIMEOUT_MS;
303+
if (
304+
existing.createdAtMs > staleBefore ||
305+
!openStore().deleteIf?.(
306+
key,
307+
(current) => !current.checkpointId && current.createdAtMs <= staleBefore,
308+
)
309+
) {
310+
return;
311+
}
312+
} else {
313+
if ((await verifyImage(context, existing.checkpointId)) !== "missing") {
314+
return;
315+
}
316+
await deleteImage(context, key, existing);
277317
}
278-
await deleteImage(context, key, existing);
279318
}
280-
if (!context.eligible) {
319+
if (!context.eligible || !(await makeRoomForCapture(context))) {
281320
return;
282321
}
283322
const now = Date.now();

0 commit comments

Comments
 (0)