Skip to content

Commit 7637143

Browse files
committed
fix(cloud): recover accepted reclaim results after restart
1 parent 4bc8c08 commit 7637143

6 files changed

Lines changed: 139 additions & 52 deletions

File tree

‎docs/gateway/cloud-workers.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,7 @@ To publish the finished work, the agent calls `github_publish` as its final acti
354354

355355
Apply uses the latest accepted manifest as the merge base, initialized at dispatch and advanced after each accepted reconciliation. Cloud-only changes are applied, local-only changes stay in place, and paths changed on both sides use a three-way keep-local policy. A conflicted turn still finishes: the transcript reports the bounded path summary and staged result ref, the placement exposes the same conflict for the Control UI, and non-conflicting cloud changes remain applied. The notice includes `git show <ref>:<path>` to inspect a present cloud file and a top-level literal-pathspec `git checkout <ref> -- <path>` command to take it from any workspace directory. Run the commands in Bash or zsh (Git Bash on Windows). If inspect says the path does not exist, the cloud result deleted it; verify and remove the retained local path manually. If checkout reports a file/directory obstruction, move or remove the blocking local path and retry. If the staged ref itself is gone, treat the notice as stale and do not change the local path. Conflicted staged refs remain available after the normal turn fence is released; a later clean result clears the notice and retires the old ref, while explicit fence removal is the final cleanup boundary.
356356

357-
While a fenced result is still reconciling, a new turn waits up to 15 seconds for the prior claim to release. If it is still busy, the turn fails with an actionable “previous cloud turn's workspace result is still reconciling” message and can be retried shortly. On restart, recovery discovers pending and staged results before stale-claim cleanup, completes or retries their local apply, and reclaims dead environments only after preserving the result. The bounded SQLite rollback journal makes an interrupted filesystem apply recoverable without replaying already accepted mutations.
357+
While a fenced result is still reconciling, a new turn waits up to 15 seconds for the prior claim to release. If it is still busy, the turn fails with an actionable “previous cloud turn's workspace result is still reconciling” message and can be retried shortly. On restart, recovery discovers pending and staged results before stale-claim cleanup, completes or retries their local apply, and reclaims dead environments only after preserving the result. An accepted Stop result can finish cleanup after restart even when its cloud environment is already destroyed; this does not restore the old turn's live authority. The bounded SQLite rollback journal makes an interrupted filesystem apply recoverable without replaying already accepted mutations.
358358

359359
To continue the same session somewhere else, open the **Runs on Cloud** chip and choose **Move session…**. An operator with `operator.write` can select the Gateway or an eligible paired device; selecting a configured cloud profile requires `operator.admin`. Profiles may also offer a machine class. Moving to the current profile with a different effective class replaces its worker; it is not an in-place resize, and native size overrides may take precedence over classes. The Gateway closes new admission, interrupts any active turn, reconciles the source workspace, destroys the old environment, and then activates the destination. An interrupted turn is never replayed: partial output may disappear, and you send the next turn again after the move. The exact target, including a machine override, and bounded errors are durable, so the Control UI shows **Moving to…** or the recovery error after a reconnect. If the Gateway restarts before the destination becomes active, request-bound authority is lost: recovery finishes safe source cleanup, marks the placement failed with a retry message, and does not provision the destination. Reconnect, then choose **Move session…** again.
360360

‎src/gateway/worker-environments/placement-dispatch-staged-results.test.ts‎

Lines changed: 68 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { type PlacementStore, REQUEST } from "./placement-dispatch-test-fixtures
1313
import { createHarness } from "./placement-dispatch-test-harness.js";
1414
import { createWorkerSessionPlacementStore } from "./placement-store.js";
1515
import {
16+
cleanupWorkerWorkspaceResultRef,
1617
workerWorkspaceResultRef,
1718
workerWorkspaceResultStaging,
1819
} from "./workspace-result-staging.js";
@@ -348,11 +349,14 @@ describe("staged worker placement result recovery", () => {
348349
expect(restartedHarness.log).not.toContain("placement:failed");
349350
});
350351

351-
it.each(["active", "draining"] as const)(
352+
it.each(["active", "draining", "draining-reclaim", "accepted-reclaim"] as const)(
352353
"recovers a staged remote-exec %s result after restart clears its local claim",
353354
async (placementState) => {
354355
const workspacePath = path.join(root, `remote-exec-restart-${placementState}-result`);
355-
const originalHarness = createHarness(placementStore, { workspacePath });
356+
const originalHarness = createHarness(placementStore, {
357+
workspacePath,
358+
destroyFailureCount: placementState === "accepted-reclaim" ? 1 : 0,
359+
});
356360
const active = originalHarness.placements.seedActive(2, "remote-exec");
357361
if (active.state !== "active") {
358362
throw new Error("active placement fixture was not active");
@@ -368,11 +372,7 @@ describe("staged worker placement result recovery", () => {
368372
ownerEpoch: active.activeOwnerEpoch,
369373
},
370374
};
371-
const claim =
372-
placementState === "active"
373-
? placementStore.claimReclaimWorkspaceResult(claimInput)
374-
: placementStore.claimTurn(claimInput);
375-
if (placementState === "draining") {
375+
const drain = () => {
376376
expect(
377377
placementStore.startDrain({
378378
sessionId: active.sessionId,
@@ -381,6 +381,16 @@ describe("staged worker placement result recovery", () => {
381381
expectedGeneration: active.generation,
382382
}),
383383
).toMatchObject({ state: "draining" });
384+
};
385+
if (placementState === "draining-reclaim" || placementState === "accepted-reclaim") {
386+
drain();
387+
}
388+
const claim =
389+
placementState === "draining"
390+
? placementStore.claimTurn(claimInput)
391+
: placementStore.claimReclaimWorkspaceResult(claimInput);
392+
if (placementState === "draining") {
393+
drain();
384394
}
385395
const staged = await stagePendingResult({
386396
store: placementStore,
@@ -389,21 +399,40 @@ describe("staged worker placement result recovery", () => {
389399
base: "base\n",
390400
current: "remote exec\n",
391401
});
402+
if (placementState === "accepted-reclaim") {
403+
originalHarness.markEnvironmentOwnerEpoch(active.activeOwnerEpoch);
404+
placementStore.handoffWorkspaceResultRecovery(claim);
405+
await originalHarness.service.reconcile();
406+
expect(placementStore.listPendingWorkspaceResults()).toMatchObject([
407+
{ workspaceAcceptedAtMs: 1_000, placementGeneration: claim.placementGeneration },
408+
]);
409+
expect(originalHarness.environments.destroy).toHaveBeenCalledOnce();
410+
}
392411

393412
closeOpenClawStateDatabaseForTest();
394413
database = openOpenClawStateDatabase({ env: { OPENCLAW_STATE_DIR: root } });
395414
const restartedStore = createWorkerSessionPlacementStore({ database, now: () => 2_000 });
396415
expect(restartedStore.clearLocalTurnClaimsAfterRestart()).toBe(1);
397416
expect(restartedStore.get(active.sessionId)).toMatchObject({
398-
state: placementState,
417+
state: placementState === "active" ? "active" : "draining",
399418
turnClaim: null,
400419
});
401420
expect(restartedStore.validateTurnClaim(claim)).toBe(false);
402421
expect(restartedStore.validateWorkspaceResultClaim(claim)).toBe(true);
403422
for (const staleClaim of [
404423
{ ...claim, claimId: `${claim.claimId}-stale` },
405424
{ ...claim, runId: `${claim.runId}-stale` },
425+
{ ...claim, placementGeneration: claim.placementGeneration - 1 },
406426
{ ...claim, placementGeneration: claim.placementGeneration + 1 },
427+
{ ...claim, placementGeneration: claim.placementGeneration + 2 },
428+
{
429+
...claim,
430+
owner: {
431+
kind: "worker" as const,
432+
environmentId: active.environmentId,
433+
ownerEpoch: active.activeOwnerEpoch,
434+
},
435+
},
407436
{
408437
...claim,
409438
owner: { ...claim.owner, environmentId: `${claim.owner.environmentId}-stale` },
@@ -418,8 +447,23 @@ describe("staged worker placement result recovery", () => {
418447
"Cannot update stale worker workspace result",
419448
);
420449
}
450+
expect(() =>
451+
restartedStore.claimReclaimWorkspaceResult({
452+
...claimInput,
453+
claimId: "reclaim-replacement",
454+
runId: "reclaim-replacement",
455+
}),
456+
).toThrow("Worker workspace result is already pending");
457+
expect(restartedStore.validateWorkspaceResultClaim(claim)).toBe(true);
421458
const restartedHarness = createHarness(restartedStore, { workspacePath });
422459
restartedHarness.markEnvironmentOwnerEpoch(active.activeOwnerEpoch);
460+
if (placementState === "accepted-reclaim") {
461+
restartedHarness.markEnvironmentDestroyed();
462+
expect(restartedHarness.environments.get(active.environmentId)).toMatchObject({
463+
state: "destroyed",
464+
ownerEpoch: active.activeOwnerEpoch + 1,
465+
});
466+
}
423467

424468
await restartedHarness.service.reconcile();
425469

@@ -433,6 +477,22 @@ describe("staged worker placement result recovery", () => {
433477
workspaceBaseManifestRef: staged.currentManifestRef,
434478
});
435479
expect(restartedHarness.environments.startTunnel).not.toHaveBeenCalled();
480+
if (placementState === "accepted-reclaim") {
481+
expect(restartedHarness.environments.destroy).not.toHaveBeenCalled();
482+
expect(
483+
await runCommandWithTimeout(
484+
[
485+
"git",
486+
"-C",
487+
workspacePath,
488+
"show-ref",
489+
"--verify",
490+
cleanupWorkerWorkspaceResultRef(staged.stagedResultRef),
491+
],
492+
{ timeoutMs: 10_000 },
493+
),
494+
).not.toMatchObject({ code: 0 });
495+
}
436496
},
437497
);
438498

‎src/gateway/worker-environments/placement-workspace-result.ts‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,19 @@ export type WorkerWorkspacePendingResult = {
3232
stagedResultRef: string | null;
3333
};
3434

35+
function matchesWorkspaceResultGeneration(
36+
placement: WorkerSessionPlacementRecord,
37+
generation: number,
38+
): boolean {
39+
// Reclaim reserves after drain; ordinary turns reserve before it. Both exact
40+
// durable result generations remain recoverable without restoring live authority.
41+
return (
42+
(placement.state === "active" || placement.state === "draining") &&
43+
(placement.generation === generation ||
44+
(placement.state === "draining" && placement.generation === generation + 1))
45+
);
46+
}
47+
3548
export function isCurrentWorkerWorkspacePendingResultOwner(
3649
placement: WorkerSessionPlacementRecord | undefined,
3750
pending: WorkerWorkspacePendingResult,
@@ -55,10 +68,7 @@ export function isCurrentWorkerWorkspacePendingResultOwner(
5568
owner: placementTurnOwner(placement),
5669
});
5770
}
58-
return (
59-
placement.generation ===
60-
(placement.state === "active" ? pending.placementGeneration : pending.placementGeneration + 1)
61-
);
71+
return matchesWorkspaceResultGeneration(placement, pending.placementGeneration);
6272
}
6373

6474
function matchesWorkspaceResultClaim(
@@ -70,10 +80,6 @@ function matchesWorkspaceResultClaim(
7080
placement.state === "active" || placement.state === "draining"
7181
? placementTurnOwner(placement)
7282
: undefined;
73-
const recoveryGenerationMatches =
74-
placement.state === "active"
75-
? placement.generation === claim.placementGeneration
76-
: placement.state === "draining" && placement.generation === claim.placementGeneration + 1;
7783
return (
7884
row.session_id === claim.sessionId &&
7985
row.environment_id === placement.environmentId &&
@@ -83,7 +89,7 @@ function matchesWorkspaceResultClaim(
8389
row.run_id === claim.runId &&
8490
(isCurrentPlacementTurnClaim(placement, claim) ||
8591
// Restart revokes local authority; only the exact durable result may finish.
86-
(recoveryGenerationMatches &&
92+
(matchesWorkspaceResultGeneration(placement, claim.placementGeneration) &&
8793
placement.turnClaim === null &&
8894
recoveryOwner?.kind === "local" &&
8995
claim.owner.kind === "local" &&

‎ui/src/i18n/locales/en.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1239,7 +1239,7 @@ export const en: TranslationMap = {
12391239
stopCloudWorkerConfirm: 'Stop the cloud worker for "{session}"?',
12401240
stopCloudWorkerConfirmAction: "Stop worker",
12411241
initialTurnPausedByWorkerStop:
1242-
"Cloud worker stop requested. Review the initial message before retrying.",
1242+
"Worker stop requested. Review the initial message before retrying.",
12431243
stopCloudWorkerStale:
12441244
'Gateway connection replaced before the cloud worker for "{session}" was stopped. Try again.',
12451245
deleteSessionMenu: "Delete…",

‎ui/src/pages/chat/chat-pane-placement.test.ts‎

Lines changed: 52 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -168,38 +168,59 @@ describe("chat pane placement", () => {
168168
);
169169
});
170170

171-
it("reclaims an active placement after the operator confirms", async () => {
172-
vi.stubGlobal(
173-
"confirm",
174-
vi.fn(() => {
175-
throw new Error("native confirm must not be used");
176-
}),
177-
);
178-
const request = vi.fn(async () => ({ ok: true }));
179-
const refreshReplacement = vi.fn(async () => undefined);
180-
const { pane } = createTestChatPane({
181-
client: { request } as unknown as GatewayBrowserClient,
182-
sessions: { refreshReplacement } as unknown as SessionCapability,
183-
});
184-
pane.context.gateway.snapshot.hello = {
185-
features: { methods: ["sessions.reclaim"] },
186-
auth: { role: "operator", scopes: ["operator.read", "operator.write"] },
187-
} as never;
188-
const session = activePlacementSession();
189-
190-
const reclaim = pane.reclaimHeaderPlacement(session);
191-
const actions = await waitForConfirmDialogActions();
192-
expect(actions.textContent).toContain("Stop worker");
193-
answerConfirmDialog(actions, "confirm");
194-
await reclaim;
171+
it.each(["cloud", "device"] as const)(
172+
"reclaims an active %s placement after the operator confirms",
173+
async (runner) => {
174+
vi.stubGlobal(
175+
"confirm",
176+
vi.fn(() => {
177+
throw new Error("native confirm must not be used");
178+
}),
179+
);
180+
const request = vi.fn(async () => ({ ok: true }));
181+
const refreshReplacement = vi.fn(async () => undefined);
182+
const { pane } = createTestChatPane({
183+
client: { request } as unknown as GatewayBrowserClient,
184+
sessions: { refreshReplacement } as unknown as SessionCapability,
185+
});
186+
pane.context.gateway.snapshot.hello = {
187+
features: { methods: ["sessions.reclaim"] },
188+
auth: { role: "operator", scopes: ["operator.read", "operator.write"] },
189+
} as never;
190+
const session = activePlacementSession();
191+
if (runner === "device") {
192+
session.placement.runner = { kind: "device", status: "available" };
193+
}
195194

196-
expect(request).toHaveBeenCalledWith(
197-
"sessions.reclaim",
198-
{ key: session.key, agentId: "main" },
199-
{ timeoutMs: 10 * 60_000 },
200-
);
201-
expect(refreshReplacement).toHaveBeenCalledWith("main");
202-
});
195+
const reclaim = pane.reclaimHeaderPlacement(session);
196+
const actions = await waitForConfirmDialogActions();
197+
expect(actions.textContent).toContain(
198+
runner === "device" ? "Stop device worker" : "Stop worker",
199+
);
200+
expect(document.body.querySelector("openclaw-modal-dialog")?.textContent).toContain(
201+
runner === "device" ? "Stop the device worker" : "Stop the cloud worker",
202+
);
203+
expect(pane.context.placementStartup.pause).not.toHaveBeenCalled();
204+
answerConfirmDialog(actions, "confirm");
205+
await reclaim;
206+
207+
expect(request).toHaveBeenCalledWith(
208+
"sessions.reclaim",
209+
{ key: session.key, agentId: "main" },
210+
{ timeoutMs: 10 * 60_000 },
211+
);
212+
expect(pane.context.placementStartup.pause).toHaveBeenCalledExactlyOnceWith(
213+
session.key,
214+
"Worker stop requested. Review the initial message before retrying.",
215+
expect.objectContaining({
216+
readSessionPlacementRecovery: expect.any(Function),
217+
pauseSessionPlacementRecovery: expect.any(Function),
218+
}),
219+
);
220+
expect(pane.context.placementStartup.pause).toHaveBeenCalledBefore(request);
221+
expect(refreshReplacement).toHaveBeenCalledWith("main");
222+
},
223+
);
203224

204225
it("shows authoritative device targets to writers and moves to the selected device", async () => {
205226
const request = vi.fn(async (method: string) => {

‎ui/src/test-helpers/app-sidebar-cases/session-mutations.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ describe("AppSidebar session mutation feedback", () => {
285285
await waitForFast(() => expect(request).toHaveBeenCalledOnce());
286286
expect(context.placementStartup.pause).toHaveBeenCalledExactlyOnceWith(
287287
"agent:main:a",
288-
"Cloud worker stop requested. Review the initial message before retrying.",
288+
"Worker stop requested. Review the initial message before retrying.",
289289
{ readSessionPlacementRecovery, pauseSessionPlacementRecovery },
290290
);
291291
expect(context.placementStartup.pause).toHaveBeenCalledBefore(request);
@@ -329,7 +329,7 @@ describe("AppSidebar session mutation feedback", () => {
329329
await waitForFast(() => expect(request).toHaveBeenCalledOnce());
330330
expect(context.placementStartup.pause).toHaveBeenCalledExactlyOnceWith(
331331
"agent:main:a",
332-
"Cloud worker stop requested. Review the initial message before retrying.",
332+
"Worker stop requested. Review the initial message before retrying.",
333333
{ readSessionPlacementRecovery, pauseSessionPlacementRecovery },
334334
);
335335
expect(context.placementStartup.pause).toHaveBeenCalledBefore(request);

0 commit comments

Comments
 (0)