Skip to content

Commit 5ac88c5

Browse files
committed
test(gateway): model exact worker claim lifecycle
1 parent 81c203a commit 5ac88c5

4 files changed

Lines changed: 265 additions & 86 deletions

File tree

‎src/worker/worker-fault-injection.test-support.ts‎

Lines changed: 54 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import type { WorkerConnectionIdentity } from "../gateway/worker-environments/co
2323
import { hashWorkerCredential } from "../gateway/worker-environments/credential.js";
2424
import { createWorkerInferenceStore } from "../gateway/worker-environments/inference-store.js";
2525
import * as liveEvents from "../gateway/worker-environments/live-events.js";
26+
import { projectWorkerSessionTurnClaim } from "../gateway/worker-environments/placement-record.js";
2627
import * as placements from "../gateway/worker-environments/placement-store.js";
2728
import {
2829
createWorkerSessionPlacementGate,
@@ -37,6 +38,7 @@ import type { WorkerProvider, WorkerSshEndpoint } from "../plugins/types.js";
3738
import * as stateDb from "../state/openclaw-state-db.js";
3839
import { buildWorkerConnectParams, type WorkerLaunchDescriptor } from "./launch-descriptor.js";
3940
import { createWorkerConnection, type WorkerConnection } from "./worker-connection.js";
41+
import { WorkerFaultPlacementLifecycle } from "./worker-fault-placement-lifecycle.test-support.js";
4042
import * as workerRpc from "./worker-rpc-clients.js";
4143

4244
export const SESSION_ID = "fault-session";
@@ -164,8 +166,6 @@ export class ComposedGatewayHarness {
164166
readonly admissions: WorkerConnectionIdentity[] = [];
165167
readonly liveDeltas: string[] = [];
166168
readonly abandonedServices: workerEnv.WorkerEnvironmentService[] = [];
167-
readonly placementWrites: Array<Parameters<WorkerSessionPlacementGate["updateAckCursors"]>[0]> =
168-
[];
169169
providerCalls = 0;
170170
replacementProviderCalls = 0;
171171
connectionCount = 0;
@@ -181,6 +181,7 @@ export class ComposedGatewayHarness {
181181
private readonly liveEventGates: LiveEventGate[] = [];
182182
private serviceValue!: workerEnv.WorkerEnvironmentService;
183183
private liveEventsValue!: liveEvents.WorkerLiveEventReceiver;
184+
private readonly placementLifecycle: WorkerFaultPlacementLifecycle;
184185
private placementGateValue: WorkerSessionPlacementGate | undefined;
185186
private useReplacementExecutor = false;
186187
private unsubscribeLive: (() => void) | undefined;
@@ -226,6 +227,19 @@ export class ComposedGatewayHarness {
226227
});
227228
this.seedAttachedEnvironment();
228229
this.liveEventsValue = this.createLiveEvents(true);
230+
this.placementLifecycle = new WorkerFaultPlacementLifecycle({
231+
agentId: "main",
232+
bundleHash: BUNDLE_HASH,
233+
environmentId: ENVIRONMENT_ID,
234+
environmentStore: this.store,
235+
getLiveEvents: () => this.liveEventsValue,
236+
getOwnerEpoch: () => this.epoch,
237+
placementStore: this.placementStore,
238+
rpcSetVersion: WORKER_RPC_SET_VERSION,
239+
sessionId: SESSION_ID,
240+
sessionKey: SESSION_KEY,
241+
});
242+
this.placementGateValue = this.createPlacementGate();
229243
this.serviceValue = this.createService();
230244
this.httpServer = createServer();
231245
this.webSocketServer = new WebSocketServer({ server: this.httpServer });
@@ -267,55 +281,18 @@ export class ComposedGatewayHarness {
267281
return gate;
268282
}
269283

270-
enablePlacement(runId: string): void {
271-
let placement = this.placementStore.startDispatch({
272-
sessionId: SESSION_ID,
273-
agentId: "main",
274-
sessionKey: SESSION_KEY,
275-
});
276-
const transitions = [
277-
{ to: "provisioning", patch: { environmentId: ENVIRONMENT_ID } },
278-
{ to: "syncing", patch: { workerBundleHash: BUNDLE_HASH } },
279-
{
280-
to: "starting",
281-
patch: {
282-
workspaceBaseManifestRef: `sha256:${"c".repeat(64)}`,
283-
remoteWorkspaceDir: "/workspace/fault-session",
284-
},
285-
},
286-
{ to: "active", patch: { activeOwnerEpoch: this.epoch } },
287-
] as const;
288-
for (const transition of transitions) {
289-
placement = this.placementStore.transition({
290-
sessionId: SESSION_ID,
291-
from: placement.state,
292-
expectedGeneration: placement.generation,
293-
...transition,
294-
});
295-
}
296-
this.placementStore.claimTurn({
297-
sessionId: SESSION_ID,
298-
agentId: "main",
299-
sessionKey: SESSION_KEY,
300-
claimId: `claim:${runId}`,
301-
runId,
302-
owner: { kind: "worker", environmentId: ENVIRONMENT_ID, ownerEpoch: this.epoch },
303-
});
304-
const placementGate = createWorkerSessionPlacementGate(this.placementStore);
305-
this.placementGateValue = {
306-
...placementGate,
307-
updateAckCursors: (binding) => {
308-
this.placementWrites.push(structuredClone(binding));
309-
placementGate.updateAckCursors(binding);
310-
},
311-
};
312-
this.abandonedServices.push(this.serviceValue);
313-
this.serviceValue = this.createService();
284+
settleRun(runId: string): void {
285+
this.placementLifecycle.settleRun(runId);
314286
}
315287

316288
createDescriptor(params: WorkerClientOptions = {}): WorkerLaunchDescriptor {
317289
const epoch = params.epoch ?? this.epoch;
318290
const credential = params.admissionProof ?? CREDENTIAL;
291+
const runId = params.runId ?? RUN_ID;
292+
const claim = this.placementLifecycle.prepareRun(runId, credential);
293+
if (claim.owner.ownerEpoch !== epoch) {
294+
throw new Error("fault descriptor epoch does not match its exact placement claim");
295+
}
319296
return {
320297
version: 3,
321298
connectionEndpoint: { kind: "unix", socketPath: this.socketPath },
@@ -329,8 +306,8 @@ export class ComposedGatewayHarness {
329306
},
330307
assignment: {
331308
agentId: "worker-agent",
332-
runId: params.runId ?? RUN_ID,
333-
operationalRunInstance: createOperationalRunInstanceRef(params.runId ?? RUN_ID),
309+
runId,
310+
operationalRunInstance: createOperationalRunInstanceRef(runId),
334311
agentRuntimeIdentityToken: "test-agent-runtime-token",
335312
turnId: "fault-turn",
336313
prompt: "fault injection",
@@ -377,10 +354,11 @@ export class ComposedGatewayHarness {
377354
};
378355
}
379356

380-
hardRestart(options: { corroborateLiveOwner: boolean }): void {
357+
hardRestart(): void {
381358
this.abandonedServices.push(this.serviceValue);
382359
this.liveEventsValue.clear();
383-
this.liveEventsValue = this.createLiveEvents(options.corroborateLiveOwner);
360+
this.liveEventsValue = this.createLiveEvents(false);
361+
this.placementGateValue = this.createPlacementGate({ rejectExistingWorkerClaims: true });
384362
this.useReplacementExecutor = true;
385363
this.serviceValue = this.createService();
386364
this.terminateSockets();
@@ -390,7 +368,24 @@ export class ComposedGatewayHarness {
390368
this.terminateSockets();
391369
}
392370

393-
reclaimWithCredential(credential: string): number {
371+
reclaimWithCredential(credential: string, runId: string): number {
372+
const placement = this.placementStore.get(SESSION_ID);
373+
const staleClaim = placement ? projectWorkerSessionTurnClaim(placement) : undefined;
374+
if (
375+
!placement ||
376+
placement.state !== "active" ||
377+
!staleClaim ||
378+
staleClaim.owner.kind !== "worker"
379+
) {
380+
throw new Error("fault placement has no active worker claim to reclaim");
381+
}
382+
this.settleRun(staleClaim.runId);
383+
this.placementStore.finishReclaim({
384+
sessionId: SESSION_ID,
385+
environmentId: ENVIRONMENT_ID,
386+
ownerEpoch: staleClaim.owner.ownerEpoch,
387+
expectedGeneration: placement.generation,
388+
});
394389
const attached = this.store.get(ENVIRONMENT_ID);
395390
if (!attached || attached.state !== "attached") {
396391
throw new Error("fault environment is not attached");
@@ -426,6 +421,7 @@ export class ComposedGatewayHarness {
426421
) {
427422
throw new Error("replacement live-event binding failed");
428423
}
424+
this.placementLifecycle.prepareRun(runId, credential);
429425
return next.ownerEpoch;
430426
}
431427

@@ -609,6 +605,12 @@ export class ComposedGatewayHarness {
609605
});
610606
}
611607

608+
private createPlacementGate(
609+
options: { rejectExistingWorkerClaims?: boolean } = {},
610+
): WorkerSessionPlacementGate {
611+
return createWorkerSessionPlacementGate(this.placementStore, options);
612+
}
613+
612614
private matchesLiveEventGate(gate: LiveEventGate, request: WorkerLiveEventParams): boolean {
613615
if (gate.target === "preview") {
614616
return request.event.kind === "assistant" || request.event.kind === "thinking";
@@ -706,7 +708,7 @@ export class ComposedGatewayHarness {
706708
const fault = faultIndex >= 0 ? this.faults.splice(faultIndex, 1)[0] : undefined;
707709
if (fault?.kind === "drop-response") {
708710
if (fault.restart) {
709-
this.hardRestart({ corroborateLiveOwner: false });
711+
this.hardRestart();
710712
} else {
711713
socket.terminate();
712714
}
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
import { hashWorkerCredential } from "../gateway/worker-environments/credential.js";
2+
import type { WorkerLiveEventReceiver } from "../gateway/worker-environments/live-events.js";
3+
import {
4+
projectWorkerSessionTurnClaim,
5+
type WorkerSessionTurnClaim,
6+
} from "../gateway/worker-environments/placement-record.js";
7+
import type {
8+
WorkerSessionPlacementRecord,
9+
WorkerSessionPlacementStore,
10+
} from "../gateway/worker-environments/placement-store.js";
11+
import type { WorkerEnvironmentStore } from "../gateway/worker-environments/store.js";
12+
13+
type WorkerFaultPlacementLifecycleOptions = {
14+
agentId: string;
15+
bundleHash: string;
16+
environmentId: string;
17+
environmentStore: WorkerEnvironmentStore;
18+
getLiveEvents: () => Pick<WorkerLiveEventReceiver, "rotateCredential">;
19+
getOwnerEpoch: () => number;
20+
placementStore: WorkerSessionPlacementStore;
21+
rpcSetVersion: number;
22+
sessionId: string;
23+
sessionKey: string;
24+
};
25+
26+
export class WorkerFaultPlacementLifecycle {
27+
private claimSequence = 0;
28+
29+
constructor(private readonly options: WorkerFaultPlacementLifecycleOptions) {}
30+
31+
prepareRun(runId: string, credential: string): WorkerSessionTurnClaim {
32+
const current = this.options.placementStore.get(this.options.sessionId);
33+
const placement = current?.state === "active" ? current : this.activatePlacement();
34+
const activeClaim = projectWorkerSessionTurnClaim(placement);
35+
if (activeClaim) {
36+
if (activeClaim.runId !== runId) {
37+
throw new Error(`fault placement is already claimed by ${activeClaim.runId}`);
38+
}
39+
this.bindCredentialToClaim(credential, activeClaim);
40+
return activeClaim;
41+
}
42+
const claim = this.options.placementStore.claimTurn({
43+
sessionId: this.options.sessionId,
44+
agentId: this.options.agentId,
45+
sessionKey: this.options.sessionKey,
46+
claimId: `claim:${runId}:${++this.claimSequence}`,
47+
runId,
48+
owner: {
49+
kind: "worker",
50+
environmentId: this.options.environmentId,
51+
ownerEpoch: this.options.getOwnerEpoch(),
52+
},
53+
});
54+
this.bindCredentialToClaim(credential, claim);
55+
return claim;
56+
}
57+
58+
settleRun(runId: string): void {
59+
const placement = this.options.placementStore.get(this.options.sessionId);
60+
const claim = placement ? projectWorkerSessionTurnClaim(placement) : undefined;
61+
if (!claim || claim.runId !== runId) {
62+
throw new Error(`fault run ${runId} does not own the active placement`);
63+
}
64+
const pending = this.options.placementStore
65+
.listPendingWorkspaceResults()
66+
.some(
67+
(result) =>
68+
result.sessionId === claim.sessionId &&
69+
result.claimId === claim.claimId &&
70+
result.runId === claim.runId,
71+
);
72+
if (pending) {
73+
this.options.placementStore.acceptWorkspaceResult(claim);
74+
this.options.placementStore.completeWorkspaceResultAndReleaseTurn(claim);
75+
return;
76+
}
77+
this.options.placementStore.releaseTurn(claim);
78+
}
79+
80+
private activatePlacement(): Extract<WorkerSessionPlacementRecord, { state: "active" }> {
81+
let placement = this.options.placementStore.startDispatch({
82+
sessionId: this.options.sessionId,
83+
agentId: this.options.agentId,
84+
sessionKey: this.options.sessionKey,
85+
});
86+
const transitions = [
87+
{ to: "provisioning", patch: { environmentId: this.options.environmentId } },
88+
{ to: "syncing", patch: { workerBundleHash: this.options.bundleHash } },
89+
{
90+
to: "starting",
91+
patch: {
92+
workspaceBaseManifestRef: `sha256:${"c".repeat(64)}`,
93+
remoteWorkspaceDir: `/workspace/${this.options.sessionId}`,
94+
},
95+
},
96+
{ to: "active", patch: { activeOwnerEpoch: this.options.getOwnerEpoch() } },
97+
] as const;
98+
for (const transition of transitions) {
99+
placement = this.options.placementStore.transition({
100+
sessionId: this.options.sessionId,
101+
from: placement.state,
102+
expectedGeneration: placement.generation,
103+
...transition,
104+
});
105+
}
106+
if (placement.state !== "active") {
107+
throw new Error("fault placement activation failed");
108+
}
109+
return placement;
110+
}
111+
112+
private bindCredentialToClaim(credential: string, claim: WorkerSessionTurnClaim): void {
113+
if (claim.owner.kind !== "worker") {
114+
throw new Error("fault worker credential requires a worker-owned claim");
115+
}
116+
const previous = this.options.environmentStore.getCredential(this.options.environmentId);
117+
const credentialHash = hashWorkerCredential(credential, claim);
118+
this.options.environmentStore.renewCredential({
119+
environmentId: this.options.environmentId,
120+
expectedOwnerEpoch: claim.owner.ownerEpoch,
121+
credentialHash,
122+
sessionId: this.options.sessionId,
123+
rpcSetVersion: this.options.rpcSetVersion,
124+
expiresAtMs: Date.now() + 60_000,
125+
});
126+
if (previous && previous.credentialHash !== credentialHash) {
127+
this.options.getLiveEvents().rotateCredential({
128+
credentialHash,
129+
environmentId: this.options.environmentId,
130+
newProcessTurn: true,
131+
previousCredentialHash: previous.credentialHash,
132+
runEpoch: claim.owner.ownerEpoch,
133+
sessionId: this.options.sessionId,
134+
});
135+
}
136+
}
137+
}

0 commit comments

Comments
 (0)