Skip to content

Commit 82f6280

Browse files
authored
fix(cloud-workers): retain provider operation ownership (#120661)
Keep per-environment provider work serialized through actual settlement after caller-visible timeouts, so replay, destroy, and shutdown cannot overlap a still-running setup.\n\nCloses #120651
1 parent 5e66d9e commit 82f6280

2 files changed

Lines changed: 179 additions & 16 deletions

File tree

‎src/gateway/worker-environments/service.test.ts‎

Lines changed: 146 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1260,26 +1260,48 @@ describe("worker environment service", () => {
12601260
});
12611261

12621262
it("bounds worker identity resolution as a provider operation", async () => {
1263-
bootstrapWorker = vi.fn(async ({ installation, resolveIdentity }) => {
1263+
const events: string[] = [];
1264+
let finishIdentity: (() => void) | undefined;
1265+
const identityPending = new Promise<void>((resolve) => {
1266+
finishIdentity = resolve;
1267+
});
1268+
bootstrapWorker = vi.fn(async ({ installation, resolveIdentity, signal }) => {
1269+
signal.addEventListener("abort", () => void events.push("abort"), { once: true });
12641270
await resolveIdentity(SSH_ENDPOINT.keyRef);
12651271
return {
12661272
bundleHash: installation.bundleHash,
12671273
openclawVersion: installation.openclawVersion,
12681274
protocolFeatures: [...installation.protocolFeatures],
12691275
};
12701276
});
1271-
const destroy = vi.fn(async () => {});
1277+
const destroy = vi.fn(async () => {
1278+
events.push("destroy");
1279+
});
12721280
const workerService = createService(createProvider({ destroy }), {
12731281
providerCallTimeoutMs: 5,
1274-
resolveSshIdentity: async () => await new Promise<never>(() => {}),
1282+
resolveSshIdentity: async () => {
1283+
events.push("identity:start");
1284+
await identityPending;
1285+
events.push("identity:end");
1286+
return { kind: "path", path: "/keys/worker" };
1287+
},
12751288
});
12761289

1277-
await expect(
1278-
workerService.create("development", "request-identity-timeout"),
1279-
).rejects.toMatchObject({
1290+
const creation = workerService.create("development", "request-identity-timeout");
1291+
const creationResult = expect(creation).rejects.toMatchObject({
12801292
code: "bootstrap_failure",
12811293
} satisfies Partial<WorkerEnvironmentServiceError>);
1294+
try {
1295+
await waitForFast(() => expect(store.list()[0]).toMatchObject({ state: "destroying" }));
1296+
expect(events).toEqual(["identity:start", "abort"]);
1297+
expect(destroy).not.toHaveBeenCalled();
1298+
} finally {
1299+
finishIdentity?.();
1300+
}
1301+
1302+
await creationResult;
12821303
expect(destroy).toHaveBeenCalledOnce();
1304+
expect(events).toEqual(["identity:start", "abort", "identity:end", "destroy"]);
12831305
expect(store.list()[0]).toMatchObject({ state: "failed", leaseId: null });
12841306
});
12851307

@@ -1353,6 +1375,83 @@ describe("worker environment service", () => {
13531375
expect(new Set(calls).size).toBe(1);
13541376
});
13551377

1378+
it("serializes destroy and provision replay behind a timed-out provider operation", async () => {
1379+
const events: string[] = [];
1380+
const operationIds: string[] = [];
1381+
let active = 0;
1382+
let maxActive = 0;
1383+
let originalProvisionCalls = 0;
1384+
let finishFirstProvision: (() => void) | undefined;
1385+
const firstProvisionPending = new Promise<void>((resolve) => {
1386+
finishFirstProvision = resolve;
1387+
});
1388+
const destroy = vi.fn(async () => {
1389+
events.push("destroy:start");
1390+
active += 1;
1391+
maxActive = Math.max(maxActive, active);
1392+
active -= 1;
1393+
events.push("destroy:end");
1394+
});
1395+
const provider = createProvider({
1396+
provision: async (_profile, operationId) => {
1397+
originalProvisionCalls += 1;
1398+
const call = originalProvisionCalls;
1399+
operationIds.push(operationId);
1400+
events.push(`provision:${call}:start`);
1401+
active += 1;
1402+
maxActive = Math.max(maxActive, active);
1403+
if (call === 1) {
1404+
await firstProvisionPending;
1405+
}
1406+
active -= 1;
1407+
events.push(`provision:${call}:end`);
1408+
return { leaseId: "lease-timeout-replay", ssh: SSH_ENDPOINT };
1409+
},
1410+
destroy,
1411+
});
1412+
const workerService = createService(provider, { providerCallTimeoutMs: 20 });
1413+
const creation = workerService.create("development", "request-provider-timeout-race");
1414+
const creationResult = expect(creation).rejects.toMatchObject({
1415+
code: "provider_failure",
1416+
} satisfies Partial<WorkerEnvironmentServiceError>);
1417+
let environmentId: string | undefined;
1418+
let teardownResult: Promise<void> | undefined;
1419+
try {
1420+
await waitForFast(() => expect(events).toEqual(["provision:1:start"]));
1421+
const queuedEnvironmentId = expectDefined(
1422+
store.list()[0],
1423+
"timed-out provision row",
1424+
).environmentId;
1425+
environmentId = queuedEnvironmentId;
1426+
const teardown = workerService.destroy(queuedEnvironmentId);
1427+
teardownResult = expect(teardown).resolves.toMatchObject({ state: "destroyed" });
1428+
await creationResult;
1429+
await waitForFast(() =>
1430+
expect(store.get(queuedEnvironmentId)?.destroyRequestedAtMs).not.toBeNull(),
1431+
);
1432+
expect(originalProvisionCalls).toBe(1);
1433+
expect(destroy).not.toHaveBeenCalled();
1434+
expect(maxActive).toBe(1);
1435+
} finally {
1436+
finishFirstProvision?.();
1437+
}
1438+
1439+
await teardownResult;
1440+
const finalEnvironmentId = expectDefined(environmentId, "timed-out provision environment id");
1441+
expect(operationIds).toHaveLength(2);
1442+
expect(new Set(operationIds).size).toBe(1);
1443+
expect(maxActive).toBe(1);
1444+
expect(events).toEqual([
1445+
"provision:1:start",
1446+
"provision:1:end",
1447+
"provision:2:start",
1448+
"provision:2:end",
1449+
"destroy:start",
1450+
"destroy:end",
1451+
]);
1452+
expect(store.get(finalEnvironmentId)).toMatchObject({ state: "destroyed" });
1453+
});
1454+
13561455
it("adopts an indeterminate allocation before a replay preparation failure", async () => {
13571456
const events: string[] = [];
13581457
let preparationFails = false;
@@ -2186,6 +2285,47 @@ describe("worker environment service", () => {
21862285
);
21872286
});
21882287

2288+
it("waits for timed-out provider work during shutdown", async () => {
2289+
let finishProvision: (() => void) | undefined;
2290+
const provisionPending = new Promise<void>((resolve) => {
2291+
finishProvision = resolve;
2292+
});
2293+
const provision = vi.fn(async () => {
2294+
await provisionPending;
2295+
return { leaseId: "lease-stop-timeout", ssh: SSH_ENDPOINT };
2296+
});
2297+
const stopAll = vi.fn(async () => {});
2298+
const tunnelManager = {
2299+
stopAll,
2300+
} as unknown as WorkerTunnelManager;
2301+
const workerService = createService(createProvider({ provision }), {
2302+
providerCallTimeoutMs: 5,
2303+
tunnelManager,
2304+
});
2305+
const creation = workerService.create("development", "request-stop-provider-timeout");
2306+
const creationResult = expect(creation).rejects.toMatchObject({
2307+
code: "provider_failure",
2308+
} satisfies Partial<WorkerEnvironmentServiceError>);
2309+
let stopped = false;
2310+
let stopping: Promise<void> | undefined;
2311+
2312+
try {
2313+
await waitForFast(() => expect(provision).toHaveBeenCalledOnce());
2314+
await creationResult;
2315+
stopping = workerService.stop().then(() => {
2316+
stopped = true;
2317+
});
2318+
await waitForFast(() => expect(stopAll).toHaveBeenCalledOnce());
2319+
await Promise.resolve();
2320+
expect(stopped).toBe(false);
2321+
} finally {
2322+
finishProvision?.();
2323+
}
2324+
2325+
await stopping;
2326+
expect(stopped).toBe(true);
2327+
});
2328+
21892329
it("owns and clears one periodic reconciliation timer", async () => {
21902330
vi.useFakeTimers();
21912331
const liveEvents = createLiveEvents();

‎src/gateway/worker-environments/service.ts‎

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ export function createWorkerEnvironmentService(options: WorkerEnvironmentService
218218
const tunnels = options.tunnelManager;
219219
const warn = (message: string) => options.logger?.warn(message);
220220
const operations = new KeyedAsyncQueue();
221+
const providerOperations = new KeyedAsyncQueue();
221222
const activeOperations = new Set<Promise<unknown>>();
222223
const pendingCredentials = new Map<string, MintedWorkerCredential>();
223224
const observedAckCursors = new Map<string, WorkerTerminalTurnFence>();
@@ -351,20 +352,34 @@ export function createWorkerEnvironmentService(options: WorkerEnvironmentService
351352

352353
const inState = (r: WorkerEnvironmentRecord, ...states: WorkerEnvironmentState[]) =>
353354
states.includes(r.state);
354-
const withLock = <T>(environmentId: string, task: () => Promise<T>) => {
355-
const operation = operations.enqueue(environmentId, task);
355+
const trackOperation = <T>(operation: Promise<T>) => {
356356
activeOperations.add(operation);
357357
const release = () => activeOperations.delete(operation);
358358
void operation.then(release, release);
359359
return operation;
360360
};
361+
const withLock = <T>(environmentId: string, task: () => Promise<T>) =>
362+
trackOperation(operations.enqueue(environmentId, task));
361363

362-
const callProvider = <T>(run: () => Promise<T>) =>
363-
withTimeout(
364-
Promise.resolve().then(run),
364+
const callProvider = async <T>(environmentId: string, run: () => Promise<T>): Promise<T> => {
365+
let signalStarted!: () => void;
366+
const started = new Promise<void>((resolve) => {
367+
signalStarted = resolve;
368+
});
369+
const operation = trackOperation(
370+
providerOperations.enqueue(environmentId, async () => {
371+
signalStarted();
372+
return await run();
373+
}),
374+
);
375+
await started;
376+
// Timeout completion must not release provider ownership or permit replay/destroy overlap.
377+
return await withTimeout(
378+
operation,
365379
options.providerCallTimeoutMs ?? 300_000,
366380
"Worker provider operation",
367381
);
382+
};
368383

369384
const callBootstrap = async <T>(run: (signal: AbortSignal) => Promise<T>): Promise<T> => {
370385
const controller = new AbortController();
@@ -401,7 +416,9 @@ export function createWorkerEnvironmentService(options: WorkerEnvironmentService
401416
if (!resolveSshIdentity) {
402417
throw new Error("Worker SSH identity resolution is unavailable");
403418
}
404-
return await callProvider(() => resolveSshIdentity({ provider, leaseId, profile, keyRef }));
419+
return await callProvider(record.environmentId, () =>
420+
resolveSshIdentity({ provider, leaseId, profile, keyRef }),
421+
);
405422
};
406423
};
407424

@@ -518,7 +535,9 @@ export function createWorkerEnvironmentService(options: WorkerEnvironmentService
518535
await tunnels?.stop(record.environmentId);
519536
const destroying = move(draining, "destroying", { lastError: detail });
520537
try {
521-
await callProvider(() => provider.destroy(lifecycleLease(record, leaseId)));
538+
await callProvider(record.environmentId, () =>
539+
provider.destroy(lifecycleLease(record, leaseId)),
540+
);
522541
} catch (cleanupError) {
523542
// An indeterminate destroy must remain retryable; never hide a possibly-live paid lease
524543
// behind terminal failed state.
@@ -585,7 +604,9 @@ export function createWorkerEnvironmentService(options: WorkerEnvironmentService
585604
try {
586605
const profile = requireWorkerProfile(record.profileSnapshot.settings);
587606
lease = requireWorkerLease(
588-
await callProvider(() => provider.provision(profile, record.provisionOperationId)),
607+
await callProvider(record.environmentId, () =>
608+
provider.provision(profile, record.provisionOperationId),
609+
),
589610
);
590611
} catch (error) {
591612
if (
@@ -670,7 +691,7 @@ export function createWorkerEnvironmentService(options: WorkerEnvironmentService
670691
const owningProvider = provider ?? providerFor(r.providerId);
671692
const destroying = beginDestroy(draining);
672693
try {
673-
await callProvider(() => owningProvider.destroy(lifecycleLease(r, leaseId)));
694+
await callProvider(r.environmentId, () => owningProvider.destroy(lifecycleLease(r, leaseId)));
674695
} catch (error) {
675696
saveError(destroying, error);
676697
throw serviceError("provider_failure", "Worker provider operation failed");
@@ -753,7 +774,9 @@ export function createWorkerEnvironmentService(options: WorkerEnvironmentService
753774
}
754775
return;
755776
}
756-
const status = await callProvider(() => provider.inspect(lifecycleLease(record, leaseId)))
777+
const status = await callProvider(record.environmentId, () =>
778+
provider.inspect(lifecycleLease(record, leaseId)),
779+
)
757780
.then(inspectionStatus)
758781
.catch((error: unknown) => {
759782
saveError(record, error);

0 commit comments

Comments
 (0)