Skip to content

Commit 18412b3

Browse files
committed
fix(gateway): restrict failed-placement recovery to pre-worker failures
Address review (#114850): reclaiming every failed placement to local also covered failures reached from reconciling, where a worker may have produced unreconciled workspace changes. Guard the recovery on activeOwnerEpoch so only pre-worker (dispatch/bootstrap) failures auto-reclaim to local; post-worker failures keep worker ownership and recover via drain/reconcile instead of a local reset that could discard remote work. Encode the invariant in reclaimFailedToLocal and add regression coverage for post-worker failures.
1 parent b6eefe2 commit 18412b3

5 files changed

Lines changed: 152 additions & 9 deletions

File tree

‎docs/gateway/cloud-workers.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ Placement moves through a durable state machine (`local → requested → provis
133133
- **"Worker bootstrap requires Node.js on the leased host"** — add a Node install to `settings.setup` (see above).
134134
- **AWS instance-role attestation fails** — clear `aws.instanceProfile` (and `CRABBOX_AWS_INSTANCE_PROFILE`, if set). Install Crabbox 0.38.1 or newer; older binaries do not expose the authoritative `providerMetadata.instanceProfileAttached` contract required for AWS admission.
135135
- **Dispatch fails with a provider error** — the placement record and `environments.list` keep the last error, including the setup/bootstrap stderr tail. Boxes are destroyed on failure, so that tail is the primary forensic.
136-
- **Placement is `failed` after a dispatch or bootstrap failure** — `failed` keeps the last error but is not a dead end: the next turn reclaims the placement to `local` and runs locally so the session keeps working, and `sessions.dispatch` accepts `local` again once the underlying cause is fixed.
136+
- **Placement is `failed` after a dispatch or bootstrap failure** — a `failed` placement reached before the worker took ownership (no active worker yet) is not a dead end: the next turn reclaims it to `local` and runs locally so the session keeps working, and `sessions.dispatch` accepts `local` again once the underlying cause is fixed. A failure reached after the worker ran (during reconciliation) still holds worker ownership and recovers through drain/reconcile so remote workspace changes are not discarded.
137137
- **Client timeout while dispatching** — `openclaw gateway call` defaults to a 10s timeout; pass `--timeout` generously (dispatch keeps running server-side either way, and a retry while provisioning is rejected with `session cannot dispatch from placement provisioning`).
138138
- **Worker reclaimed after upgrading from a 2026.7.2 beta** — those betas used the older worker launch contract. On restart, OpenClaw destroys an idle incompatible worker, keeps the session and workspace, marks the placement reclaimed, and provisions a current worker on the next dispatch or turn. A beta worker interrupted while still starting is marked failed after cleanup; retry the dispatch to provision it with the current contract.
139139
- **Cloud workspace conflict notice** — the turn completed and kept the local version of each listed path. Use the staged-ref commands in the notice to inspect or take the cloud version; no retry is required for the non-conflicting changes, which are already applied.

‎src/gateway/worker-environments/placement-store-reclaim.test.ts‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,45 @@ const SESSION: WorkerSessionPlacementIdentity = {
1919
sessionKey: "agent:main:placement",
2020
};
2121

22+
const ENVIRONMENT_ID = "environment-placement";
23+
const BUNDLE_HASH = "a".repeat(64);
24+
const MANIFEST_REF = `sha256:${"b".repeat(64)}`;
25+
const OWNER_EPOCH = 7;
26+
27+
// Reaches `active` worker ownership so a later failure carries worker state
28+
// (activeOwnerEpoch set), the case that must NOT bypass reconciliation.
29+
function advanceToActive(s: WorkerSessionPlacementStore, identity = SESSION) {
30+
let placement = s.startDispatch(identity);
31+
placement = s.transition({
32+
sessionId: identity.sessionId,
33+
from: "requested",
34+
to: "provisioning",
35+
expectedGeneration: placement.generation,
36+
patch: { environmentId: ENVIRONMENT_ID },
37+
});
38+
placement = s.transition({
39+
sessionId: identity.sessionId,
40+
from: "provisioning",
41+
to: "syncing",
42+
expectedGeneration: placement.generation,
43+
patch: { workerBundleHash: BUNDLE_HASH },
44+
});
45+
placement = s.transition({
46+
sessionId: identity.sessionId,
47+
from: "syncing",
48+
to: "starting",
49+
expectedGeneration: placement.generation,
50+
patch: { remoteWorkspaceDir: "/worker/workspace", workspaceBaseManifestRef: MANIFEST_REF },
51+
});
52+
return s.transition({
53+
sessionId: identity.sessionId,
54+
from: "starting",
55+
to: "active",
56+
expectedGeneration: placement.generation,
57+
patch: { activeOwnerEpoch: OWNER_EPOCH },
58+
});
59+
}
60+
2261
describe("worker session placement failed recovery", () => {
2362
let root: string;
2463
let database: OpenClawStateDatabase;
@@ -72,4 +111,37 @@ describe("worker session placement failed recovery", () => {
72111
}),
73112
).toThrow("Cannot reclaim failed worker placement");
74113
});
114+
115+
it("refuses to reclaim a failed placement that reached worker ownership", () => {
116+
const active = advanceToActive(store);
117+
const draining = store.startDrain({
118+
sessionId: SESSION.sessionId,
119+
environmentId: active.environmentId,
120+
ownerEpoch: active.activeOwnerEpoch,
121+
expectedGeneration: active.generation,
122+
});
123+
const reconciling = store.startReconcile({
124+
sessionId: SESSION.sessionId,
125+
environmentId: active.environmentId,
126+
ownerEpoch: active.activeOwnerEpoch,
127+
expectedGeneration: draining.generation,
128+
});
129+
const failed = store.transition({
130+
sessionId: SESSION.sessionId,
131+
from: "reconciling",
132+
to: "failed",
133+
expectedGeneration: reconciling.generation,
134+
patch: { recoveryError: "reconcile failed with remote work in flight" },
135+
});
136+
expect(failed).toMatchObject({ state: "failed", activeOwnerEpoch: active.activeOwnerEpoch });
137+
138+
// A post-worker failure may carry unreconciled remote workspace changes, so
139+
// it must not be reset to local; recovery has to go through drain/reconcile.
140+
expect(() =>
141+
store.reclaimFailedToLocal({
142+
sessionId: SESSION.sessionId,
143+
expectedGeneration: failed.generation,
144+
}),
145+
).toThrow("worker ownership was reached");
146+
});
75147
});

‎src/gateway/worker-environments/placement-store.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,16 @@ export function createWorkerSessionPlacementStore(
495495
`Cannot reclaim failed worker placement for session ${sessionId}: expected failed@${input.expectedGeneration}, found ${current.state}@${current.generation}`,
496496
);
497497
}
498+
// Only pre-worker failures are safe to reclaim to local. A failed
499+
// placement that still holds worker ownership (activeOwnerEpoch set, i.e.
500+
// it reached `active` and failed from reconciling) may carry unreconciled
501+
// remote workspace changes and must recover via drain/reconcile instead
502+
// of an unconditional local reset that would discard that work.
503+
if (current.activeOwnerEpoch !== null) {
504+
throw new Error(
505+
`Cannot reclaim failed worker placement for session ${sessionId}: worker ownership was reached, reconcile before local recovery`,
506+
);
507+
}
498508
if (current.turnClaim) {
499509
throw new Error(
500510
`Cannot reclaim failed worker placement for session ${sessionId} during an active turn`,

‎src/gateway/worker-environments/worker-turn-launcher.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,37 @@ describe("worker turn launcher", () => {
233233
return reclaimed;
234234
}
235235

236+
function seedFailedAfterWorkerPlacement() {
237+
seedActivePlacement();
238+
const active = placements.get(SESSION_ID);
239+
if (active?.state !== "active") {
240+
throw new Error("expected active placement to fail after worker ownership");
241+
}
242+
const draining = placements.startDrain({
243+
sessionId: SESSION_ID,
244+
environmentId: active.environmentId,
245+
ownerEpoch: active.activeOwnerEpoch,
246+
expectedGeneration: active.generation,
247+
});
248+
const reconciling = placements.startReconcile({
249+
sessionId: SESSION_ID,
250+
environmentId: active.environmentId,
251+
ownerEpoch: active.activeOwnerEpoch,
252+
expectedGeneration: draining.generation,
253+
});
254+
const failed = placements.transition({
255+
sessionId: SESSION_ID,
256+
from: "reconciling",
257+
to: "failed",
258+
expectedGeneration: reconciling.generation,
259+
patch: { recoveryError: "reconcile failed with remote work in flight" },
260+
});
261+
if (failed.state !== "failed") {
262+
throw new Error("expected failed placement after worker ownership");
263+
}
264+
return failed;
265+
}
266+
236267
function attachedEnvironment(): WorkerTurnEnvironmentRecord {
237268
return {
238269
environmentId: ENVIRONMENT_ID,
@@ -372,6 +403,33 @@ describe("worker turn launcher", () => {
372403
expect(after?.recoveryError).toBeNull();
373404
});
374405

406+
it("does not reclaim a post-worker failed placement that may hold unreconciled work", async () => {
407+
const environments = unusedEnvironments();
408+
const provider = createWorkerSessionTurnPlacementProvider({ environments, placements });
409+
const failed = seedFailedAfterWorkerPlacement();
410+
expect(failed.activeOwnerEpoch).not.toBeNull();
411+
412+
// A failed placement reached after worker ownership may carry unreconciled
413+
// remote workspace changes; it must recover via drain/reconcile, not a
414+
// silent local reset, so the turn is rejected and the placement stays failed.
415+
await expect(
416+
provider.executeTurn(
417+
{
418+
sessionId: SESSION_ID,
419+
sessionKey: SESSION_KEY,
420+
agentId: "main",
421+
runId: "run-postworker",
422+
},
423+
turn("run-postworker"),
424+
async () => ({ payloads: [{ text: "must not run" }], meta: { durationMs: 1 } }),
425+
),
426+
).rejects.toThrow("Worker turn rejected in placement failed");
427+
expect(placements.get(SESSION_ID)).toMatchObject({
428+
state: "failed",
429+
activeOwnerEpoch: failed.activeOwnerEpoch,
430+
});
431+
});
432+
375433
it("leaves no placement row for an auxiliary model run without a session key", async () => {
376434
const provider = createWorkerSessionTurnPlacementProvider({
377435
environments: unusedEnvironments(),

‎src/gateway/worker-environments/worker-turn-launcher.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -573,18 +573,21 @@ export function createWorkerSessionTurnPlacementProvider(
573573
return await executeLocalTurn({ claim, placements: options.placements, runLocal });
574574
},
575575
async executeTurn(claim, turn, runLocal) {
576-
let current = options.placements.get(claim.sessionId);
577-
if (current?.state === "failed") {
578-
// `failed` is otherwise a terminal sink: turns reject it via
579-
// requireActivePlacement, and sessions.dispatch/sessions.reclaim both
580-
// refuse it, so one bootstrap or dispatch failure would brick the
581-
// session until a manual state-store repair. Degrade it to local so the
582-
// turn keeps working; cloud dispatch can be requested again from `local`.
576+
const current = options.placements.get(claim.sessionId);
577+
// Recover only pre-worker failures: a `failed` placement that never reached
578+
// active worker ownership (activeOwnerEpoch is null) has no worker state to
579+
// reconcile, so the next turn can safely reclaim it to local instead of
580+
// rejecting every turn until a manual state-store repair. A `failed`
581+
// placement reached from reconciling still holds worker ownership and may
582+
// have unreconciled remote workspace changes; recovering those must go
583+
// through the drain/reconcile path, not an unconditional local reset, so
584+
// leave them to the existing recovery machinery instead of discarding work.
585+
if (current?.state === "failed" && current.activeOwnerEpoch === null) {
583586
options.placements.reclaimFailedToLocal({
584587
sessionId: current.sessionId,
585588
expectedGeneration: current.generation,
586589
});
587-
current = options.placements.get(claim.sessionId);
590+
return await executeLocalTurn({ claim, placements: options.placements, runLocal });
588591
}
589592
if (
590593
!current &&

0 commit comments

Comments
 (0)