Skip to content

Commit 5fb5eef

Browse files
steipeteampagent
andauthored
refactor(cloud-workers): centralize placement lifecycle fences (#121658)
* refactor(cloud-workers): centralize placement ownership fences Amp-Thread-ID: https://ampcode.com/threads/T-019feaaa-c7ed-769e-9f29-a3612bec72e7 * test: restore core test typechecking Amp-Thread-ID: https://ampcode.com/threads/T-019feaaa-c7ed-769e-9f29-a3612bec72e7 * test: repair current-main CI regressions Amp-Thread-ID: https://ampcode.com/threads/T-019feaaa-c7ed-769e-9f29-a3612bec72e7 * test: align shared main contracts Amp-Thread-ID: https://ampcode.com/threads/T-019feaaa-c7ed-769e-9f29-a3612bec72e7 * docs(cloud-workers): document placement fence Amp-Thread-ID: https://ampcode.com/threads/T-019feaaa-c7ed-769e-9f29-a3612bec72e7 * test(approvals): align account routing fixtures Amp-Thread-ID: https://ampcode.com/threads/T-019feaaa-c7ed-769e-9f29-a3612bec72e7 * fix(protocol): refresh Swift approval resolve models Amp-Thread-ID: https://ampcode.com/threads/T-019feaaa-c7ed-769e-9f29-a3612bec72e7 * test(approvals): use scoped event kind fixtures Amp-Thread-ID: https://ampcode.com/threads/T-019feaaa-c7ed-769e-9f29-a3612bec72e7 --------- Co-authored-by: Amp <[email protected]>
1 parent 1263450 commit 5fb5eef

3 files changed

Lines changed: 110 additions & 119 deletions

File tree

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15742,21 +15742,25 @@ public struct ApprovalResolveParams: Codable, Sendable {
1574215742
public let id: String
1574315743
public let kind: ApprovalKind
1574415744
public let decision: ApprovalDecision
15745+
public let reviewer: [String: AnyCodable]?
1574515746

1574615747
public init(
1574715748
id: String,
1574815749
kind: ApprovalKind,
15749-
decision: ApprovalDecision)
15750+
decision: ApprovalDecision,
15751+
reviewer: [String: AnyCodable]? = nil)
1575015752
{
1575115753
self.id = id
1575215754
self.kind = kind
1575315755
self.decision = decision
15756+
self.reviewer = reviewer
1575415757
}
1575515758

1575615759
private enum CodingKeys: String, CodingKey {
1575715760
case id
1575815761
case kind
1575915762
case decision
15763+
case reviewer
1576015764
}
1576115765
}
1576215766

@@ -16143,18 +16147,22 @@ public struct ExecApprovalRequestParams: Codable, Sendable {
1614316147
public struct ExecApprovalResolveParams: Codable, Sendable {
1614416148
public let id: String
1614516149
public let decision: String
16150+
public let reviewer: [String: AnyCodable]?
1614616151

1614716152
public init(
1614816153
id: String,
16149-
decision: String)
16154+
decision: String,
16155+
reviewer: [String: AnyCodable]? = nil)
1615016156
{
1615116157
self.id = id
1615216158
self.decision = decision
16159+
self.reviewer = reviewer
1615316160
}
1615416161

1615516162
private enum CodingKeys: String, CodingKey {
1615616163
case id
1615716164
case decision
16165+
case reviewer
1615816166
}
1615916167
}
1616016168

@@ -16513,18 +16521,22 @@ public struct PluginApprovalRequestParams: Codable, Sendable {
1651316521
public struct PluginApprovalResolveParams: Codable, Sendable {
1651416522
public let id: String
1651516523
public let decision: String
16524+
public let reviewer: [String: AnyCodable]?
1651616525

1651716526
public init(
1651816527
id: String,
16519-
decision: String)
16528+
decision: String,
16529+
reviewer: [String: AnyCodable]? = nil)
1652016530
{
1652116531
self.id = id
1652216532
self.decision = decision
16533+
self.reviewer = reviewer
1652316534
}
1652416535

1652516536
private enum CodingKeys: String, CodingKey {
1652616537
case id
1652716538
case decision
16539+
case reviewer
1652816540
}
1652916541
}
1653016542

‎src/gateway/server-worker-placement-startup.ts‎

Lines changed: 95 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,58 @@ class WorkerDispatchTargetChangedError extends Error {
5656
readonly code = "invalid_state";
5757
}
5858

59+
type WorkerPlacementSessionRuntime = Awaited<
60+
ReturnType<typeof loadWorkerPlacementSessionRuntimeModule>
61+
>;
62+
type WorkerPlacementSessionTarget = ReturnType<
63+
WorkerPlacementSessionRuntime["resolveGatewaySessionStoreTargetWithStore"]
64+
>;
65+
66+
/** Keeps store identity, session incarnation, canonical ownership, and the live worktree
67+
* in one cross-phase fence. Initial resolution throws normally; barrier revalidation
68+
* supplies expectedTarget and yields an invalid_state retry when the target changed. */
69+
function resolveWorkerPlacementSessionTarget(params: {
70+
sessionRuntime: WorkerPlacementSessionRuntime;
71+
config: ReturnType<typeof getRuntimeConfig>;
72+
sessionId: string;
73+
sessionKey: string;
74+
agentId: string;
75+
expectedTarget?: WorkerPlacementSessionTarget;
76+
errorMessage: string;
77+
}) {
78+
const target = params.sessionRuntime.resolveGatewaySessionStoreTargetWithStore({
79+
cfg: params.config,
80+
key: params.sessionKey,
81+
agentId: params.agentId,
82+
clone: false,
83+
});
84+
const entry = params.sessionRuntime.resolveCanonicalSessionEntryFromStoreKeys(
85+
target.store,
86+
target.storeKeys,
87+
);
88+
const worktree = params.sessionRuntime.managedWorktrees.findLiveByOwner(
89+
"session",
90+
target.canonicalKey,
91+
);
92+
const expected = params.expectedTarget;
93+
if (
94+
(expected &&
95+
(target.storePath !== expected.storePath ||
96+
target.canonicalKey !== expected.canonicalKey ||
97+
target.agentId !== expected.agentId)) ||
98+
entry?.sessionId !== params.sessionId ||
99+
!entry.worktree?.id ||
100+
!worktree ||
101+
worktree.id !== entry.worktree.id ||
102+
worktree.ownerId !== target.canonicalKey
103+
) {
104+
throw expected
105+
? new WorkerDispatchTargetChangedError(params.errorMessage)
106+
: new Error(params.errorMessage);
107+
}
108+
return { config: params.config, target, entry, worktree };
109+
}
110+
59111
/** Serializes reconciliation sweeps against in-flight dispatches so a sweep never
60112
* observes a placement mid-transition. Dispatches wait out any pending sweep. */
61113
export function coordinateWorkerPlacementDispatch(
@@ -200,28 +252,15 @@ export function createGatewayWorkerPlacementRuntime(params: GatewayWorkerPlaceme
200252
sessionKey: string;
201253
agentId: string;
202254
}): Promise<string> => {
203-
const {
204-
managedWorktrees,
205-
resolveCanonicalSessionEntryFromStoreKeys,
206-
resolveGatewaySessionStoreTargetWithStore,
207-
} = await loadWorkerPlacementSessionRuntimeModule();
208-
const target = resolveGatewaySessionStoreTargetWithStore({
209-
cfg: getRuntimeConfig(),
210-
key: sessionKey,
255+
const sessionRuntime = await loadWorkerPlacementSessionRuntimeModule();
256+
const { worktree } = resolveWorkerPlacementSessionTarget({
257+
sessionRuntime,
258+
config: getRuntimeConfig(),
259+
sessionId,
260+
sessionKey,
211261
agentId,
212-
clone: false,
262+
errorMessage: `Session ${sessionKey} dispatch requires a session-owned managed worktree`,
213263
});
214-
const sessionEntry = resolveCanonicalSessionEntryFromStoreKeys(target.store, target.storeKeys);
215-
const worktree = managedWorktrees.findLiveByOwner("session", target.canonicalKey);
216-
if (
217-
sessionEntry?.sessionId !== sessionId ||
218-
!sessionEntry.worktree?.id ||
219-
!worktree ||
220-
worktree.id !== sessionEntry.worktree.id ||
221-
worktree.ownerId !== target.canonicalKey
222-
) {
223-
throw new Error(`Session ${sessionKey} dispatch requires a session-owned managed worktree`);
224-
}
225264
return worktree.path;
226265
};
227266
const dispatchService = coordinateWorkerPlacementDispatch(
@@ -230,13 +269,12 @@ export function createGatewayWorkerPlacementRuntime(params: GatewayWorkerPlaceme
230269
environments: params.environments,
231270
...workspaceConflictHandlers,
232271
runLocalBarrier: async ({ sessionId, sessionKey, agentId, startDispatch }) => {
272+
const sessionRuntime = await loadWorkerPlacementSessionRuntimeModule();
233273
const {
234274
isWorkerPlacementSessionRuntimeSupported,
235-
managedWorktrees,
236-
resolveCanonicalSessionEntryFromStoreKeys,
237275
resolveGatewaySessionStoreTargetWithStore,
238276
resolveWorkerPlacementSessionRuntime,
239-
} = await loadWorkerPlacementSessionRuntimeModule();
277+
} = sessionRuntime;
240278
const target = resolveGatewaySessionStoreTargetWithStore({
241279
cfg: getRuntimeConfig(),
242280
key: sessionKey,
@@ -254,35 +292,20 @@ export function createGatewayWorkerPlacementRuntime(params: GatewayWorkerPlaceme
254292
scope: target.storePath,
255293
identities: lifecycleIdentities,
256294
prepare: async () => {
257-
const currentConfig = getRuntimeConfig();
258-
const currentTarget = resolveGatewaySessionStoreTargetWithStore({
259-
cfg: currentConfig,
260-
key: sessionKey,
295+
const {
296+
config: currentConfig,
297+
target: currentTarget,
298+
entry: currentEntry,
299+
worktree,
300+
} = resolveWorkerPlacementSessionTarget({
301+
sessionRuntime,
302+
config: getRuntimeConfig(),
303+
sessionId,
304+
sessionKey,
261305
agentId,
262-
clone: false,
306+
expectedTarget: target,
307+
errorMessage: `Session ${sessionKey} changed before cloud worker dispatch. Retry.`,
263308
});
264-
const currentEntry = resolveCanonicalSessionEntryFromStoreKeys(
265-
currentTarget.store,
266-
currentTarget.storeKeys,
267-
);
268-
const worktree = managedWorktrees.findLiveByOwner(
269-
"session",
270-
currentTarget.canonicalKey,
271-
);
272-
if (
273-
currentTarget.storePath !== target.storePath ||
274-
currentTarget.canonicalKey !== target.canonicalKey ||
275-
currentTarget.agentId !== target.agentId ||
276-
currentEntry?.sessionId !== sessionId ||
277-
!currentEntry.worktree?.id ||
278-
!worktree ||
279-
worktree.id !== currentEntry.worktree.id ||
280-
worktree.ownerId !== currentTarget.canonicalKey
281-
) {
282-
throw new WorkerDispatchTargetChangedError(
283-
`Session ${sessionKey} changed before cloud worker dispatch. Retry.`,
284-
);
285-
}
286309
if (currentEntry.archivedAt !== undefined) {
287310
throw new WorkerDispatchTargetChangedError(
288311
`Session ${sessionKey} was archived before cloud worker dispatch. Retry.`,
@@ -334,13 +357,12 @@ export function createGatewayWorkerPlacementRuntime(params: GatewayWorkerPlaceme
334357
return placement;
335358
},
336359
runActivationBarrier: async ({ sessionId, sessionKey, agentId, activate }) => {
360+
const sessionRuntime = await loadWorkerPlacementSessionRuntimeModule();
337361
const {
338362
isWorkerPlacementSessionRuntimeSupported,
339-
managedWorktrees,
340-
resolveCanonicalSessionEntryFromStoreKeys,
341363
resolveGatewaySessionStoreTargetWithStore,
342364
resolveWorkerPlacementSessionRuntime,
343-
} = await loadWorkerPlacementSessionRuntimeModule();
365+
} = sessionRuntime;
344366
const target = resolveGatewaySessionStoreTargetWithStore({
345367
cfg: getRuntimeConfig(),
346368
key: sessionKey,
@@ -358,35 +380,19 @@ export function createGatewayWorkerPlacementRuntime(params: GatewayWorkerPlaceme
358380
scope: target.storePath,
359381
identities: lifecycleIdentities,
360382
run: async () => {
361-
const currentConfig = getRuntimeConfig();
362-
const currentTarget = resolveGatewaySessionStoreTargetWithStore({
363-
cfg: currentConfig,
364-
key: sessionKey,
383+
const {
384+
config: currentConfig,
385+
target: currentTarget,
386+
entry: currentEntry,
387+
} = resolveWorkerPlacementSessionTarget({
388+
sessionRuntime,
389+
config: getRuntimeConfig(),
390+
sessionId,
391+
sessionKey,
365392
agentId,
366-
clone: false,
393+
expectedTarget: target,
394+
errorMessage: `Session ${sessionKey} changed before cloud worker activation. Retry.`,
367395
});
368-
const currentEntry = resolveCanonicalSessionEntryFromStoreKeys(
369-
currentTarget.store,
370-
currentTarget.storeKeys,
371-
);
372-
const worktree = managedWorktrees.findLiveByOwner(
373-
"session",
374-
currentTarget.canonicalKey,
375-
);
376-
if (
377-
currentTarget.storePath !== target.storePath ||
378-
currentTarget.canonicalKey !== target.canonicalKey ||
379-
currentTarget.agentId !== target.agentId ||
380-
currentEntry?.sessionId !== sessionId ||
381-
!currentEntry.worktree?.id ||
382-
!worktree ||
383-
worktree.id !== currentEntry.worktree.id ||
384-
worktree.ownerId !== currentTarget.canonicalKey
385-
) {
386-
throw new WorkerDispatchTargetChangedError(
387-
`Session ${sessionKey} changed before cloud worker activation. Retry.`,
388-
);
389-
}
390396
if (currentEntry.archivedAt !== undefined) {
391397
throw new WorkerDispatchTargetChangedError(
392398
`Session ${sessionKey} was archived before cloud worker activation. Retry.`,
@@ -412,11 +418,8 @@ export function createGatewayWorkerPlacementRuntime(params: GatewayWorkerPlaceme
412418
return activePlacement;
413419
},
414420
runReclaimBarrier: async ({ sessionId, sessionKey, agentId, reclaim }) => {
415-
const {
416-
managedWorktrees,
417-
resolveCanonicalSessionEntryFromStoreKeys,
418-
resolveGatewaySessionStoreTargetWithStore,
419-
} = await loadWorkerPlacementSessionRuntimeModule();
421+
const sessionRuntime = await loadWorkerPlacementSessionRuntimeModule();
422+
const { resolveGatewaySessionStoreTargetWithStore } = sessionRuntime;
420423
const target = resolveGatewaySessionStoreTargetWithStore({
421424
cfg: getRuntimeConfig(),
422425
key: sessionKey,
@@ -435,34 +438,15 @@ export function createGatewayWorkerPlacementRuntime(params: GatewayWorkerPlaceme
435438
scope: target.storePath,
436439
identities: lifecycleIdentities,
437440
prepare: async () => {
438-
const currentTarget = resolveGatewaySessionStoreTargetWithStore({
439-
cfg: getRuntimeConfig(),
440-
key: sessionKey,
441+
const { worktree } = resolveWorkerPlacementSessionTarget({
442+
sessionRuntime,
443+
config: getRuntimeConfig(),
444+
sessionId,
445+
sessionKey,
441446
agentId,
442-
clone: false,
447+
expectedTarget: target,
448+
errorMessage: `Session ${sessionKey} changed before cloud worker stop. Retry.`,
443449
});
444-
const currentEntry = resolveCanonicalSessionEntryFromStoreKeys(
445-
currentTarget.store,
446-
currentTarget.storeKeys,
447-
);
448-
const worktree = managedWorktrees.findLiveByOwner(
449-
"session",
450-
currentTarget.canonicalKey,
451-
);
452-
if (
453-
currentTarget.storePath !== target.storePath ||
454-
currentTarget.canonicalKey !== target.canonicalKey ||
455-
currentTarget.agentId !== target.agentId ||
456-
currentEntry?.sessionId !== sessionId ||
457-
!currentEntry.worktree?.id ||
458-
!worktree ||
459-
worktree.id !== currentEntry.worktree.id ||
460-
worktree.ownerId !== currentTarget.canonicalKey
461-
) {
462-
throw new WorkerDispatchTargetChangedError(
463-
`Session ${sessionKey} changed before cloud worker stop. Retry.`,
464-
);
465-
}
466450
const placement = params.placements.get(sessionId);
467451
if (placement?.state !== "active" || placement.turnClaim) {
468452
throw new Error(

‎src/gateway/worker-environments/placement-dispatch-failure.ts‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -232,11 +232,6 @@ export function createPlacementFailureActions(deps: {
232232
environment: ReturnType<WorkerEnvironmentService["get"]>,
233233
claimedTurnError: Error,
234234
): Promise<void> => {
235-
if (placement.turnClaim) {
236-
const draining = startDrain(placement);
237-
await failDraining(draining, claimedTurnError, { forceClaimFence: true });
238-
return;
239-
}
240235
const draining = startDrain(placement);
241236
if (draining.turnClaim) {
242237
await failDraining(draining, claimedTurnError, { forceClaimFence: true });

0 commit comments

Comments
 (0)