Skip to content

Commit 81c203a

Browse files
committed
refactor(gateway): carry exact worker claims
1 parent a0278af commit 81c203a

43 files changed

Lines changed: 520 additions & 820 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/agents/admitted-run-context.ts‎

Lines changed: 7 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -42,31 +42,16 @@ export type PreparedAgentRunAdmission = Readonly<{
4242
type DelegatedAuthorityLease = {
4343
authority: AgentRunDelegatedAuthority;
4444
foregroundClosed: boolean;
45-
nativeHookRecoveryRetained: boolean;
4645
};
4746

4847
const delegatedAuthorityLeases = new WeakMap<AdmittedRunContext, DelegatedAuthorityLease>();
4948
const activeNativeHookRecoveryLeases = new Map<string, DelegatedAuthorityLease>();
5049

51-
function bindAdmittedRunDelegatedAuthority(
52-
context: AdmittedRunContext,
53-
): AgentRunDelegatedAuthority {
50+
function bindAdmittedRunDelegatedAuthority(context: AdmittedRunContext): void {
51+
activeNativeHookRecoveryLeases.delete(context.operationalRunInstance.runId);
5452
const authority = claimAgentRunDelegatedAuthority(context.operationalRunInstance);
55-
const lease = {
56-
authority,
57-
foregroundClosed: false,
58-
nativeHookRecoveryRetained: false,
59-
};
60-
activeNativeHookRecoveryLeases.set(context.operationalRunInstance.runId, lease);
53+
const lease = { authority, foregroundClosed: false };
6154
delegatedAuthorityLeases.set(context, lease);
62-
return authority;
63-
}
64-
65-
function releaseNativeHookRecoveryLease(lease: DelegatedAuthorityLease): void {
66-
const runId = lease.authority.operationalRunInstance.runId;
67-
if (activeNativeHookRecoveryLeases.get(runId) === lease) {
68-
activeNativeHookRecoveryLeases.delete(runId);
69-
}
7055
}
7156

7257
/** Reads the immutable outer-run authority without reviving a closed claim. */
@@ -87,9 +72,6 @@ export function closeAdmittedRunDelegatedAuthority(context: AdmittedRunContext):
8772
}
8873
lease.foregroundClosed = true;
8974
releaseAgentRunDelegatedAuthority(lease.authority);
90-
if (!lease.nativeHookRecoveryRetained) {
91-
releaseNativeHookRecoveryLease(lease);
92-
}
9375
return true;
9476
}
9577

@@ -107,18 +89,14 @@ export function retainAdmittedRunBeforeToolCallRecovery(
10789
if (
10890
!lease ||
10991
lease.foregroundClosed ||
110-
lease.nativeHookRecoveryRetained ||
111-
activeNativeHookRecoveryLeases.get(runId) !== lease ||
92+
activeNativeHookRecoveryLeases.has(runId) ||
11293
!validateAgentRunDelegatedAuthority(lease.authority)
11394
) {
11495
return undefined;
11596
}
116-
lease.nativeHookRecoveryRetained = true;
117-
let released = false;
97+
activeNativeHookRecoveryLeases.set(runId, lease);
11898
const assertActive = () => {
11999
if (
120-
released ||
121-
!lease.nativeHookRecoveryRetained ||
122100
getAgentRunLifecycleGeneration() !== lease.authority.lifecycleGeneration ||
123101
activeNativeHookRecoveryLeases.get(runId) !== lease
124102
) {
@@ -128,13 +106,8 @@ export function retainAdmittedRunBeforeToolCallRecovery(
128106
return Object.freeze({
129107
assertActive,
130108
release: () => {
131-
if (released) {
132-
return;
133-
}
134-
released = true;
135-
lease.nativeHookRecoveryRetained = false;
136-
if (lease.foregroundClosed) {
137-
releaseNativeHookRecoveryLease(lease);
109+
if (activeNativeHookRecoveryLeases.get(runId) === lease) {
110+
activeNativeHookRecoveryLeases.delete(runId);
138111
}
139112
},
140113
});

‎src/agents/harness/host-capability.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,23 @@ describe("agent harness host capability", () => {
346346
retained.release();
347347
});
348348

349+
it("fences a retained native policy lease after lifecycle rotation", async () => {
350+
const { attempt } = await admittedAttempt("run-retained-policy-lifecycle");
351+
const host = createAgentHarnessHostCapabilities({ attempt, pluginId: "codex" });
352+
const retained = retainBeforeToolCallForNativeHookRelay(host.capabilities.runBeforeToolCall);
353+
if (!retained) {
354+
throw new Error("expected retained native policy lease");
355+
}
356+
expect(closeAdmittedRunDelegatedAuthority(attempt.admittedRunContext)).toBe(true);
357+
358+
rotateAgentRunRegistryLifecycleGeneration();
359+
360+
await expect(
361+
retained.runBeforeToolCall({ toolName: "exec", params: { command: "true" } }),
362+
).rejects.toThrow("no longer active");
363+
retained.release();
364+
});
365+
349366
it.each([
350367
{
351368
name: "lexical host closure",

‎src/agents/harness/host-capability.ts‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,6 @@ export function createAgentHarnessHostCapabilities(params: {
231231
await withGatewayToolCallerIdentity(callerIdentity, run);
232232
const runBeforeToolCallWithAssertion = async (
233233
assertCurrent: () => void,
234-
callerBinding: "foreground" | "recovery",
235234
{
236235
nativeOperation,
237236
approvalMode,
@@ -247,18 +246,16 @@ export function createAgentHarnessHostCapabilities(params: {
247246
const actionHookContext = actionCwd
248247
? Object.freeze({ ...hookContext, cwd: actionCwd })
249248
: hookContext;
250-
const runPolicy = async () =>
251-
await runBeforeToolCallHook({
252-
...request,
253-
approvalMode: hostApprovalMode,
254-
ctx: actionHookContext,
255-
});
256-
const result = callerBinding === "foreground" ? await withCaller(runPolicy) : await runPolicy();
249+
const result = await runBeforeToolCallHook({
250+
...request,
251+
approvalMode: hostApprovalMode,
252+
ctx: actionHookContext,
253+
});
257254
assertCurrent();
258255
return result;
259256
};
260257
const runBeforeToolCall: AgentHarnessHostCapabilities["runBeforeToolCall"] = async (request) =>
261-
await runBeforeToolCallWithAssertion(assertActive, "foreground", request);
258+
await withCaller(async () => await runBeforeToolCallWithAssertion(assertActive, request));
262259
retainedBeforeToolCallRunners.set(runBeforeToolCall, () => {
263260
const recovery = retainAdmittedRunBeforeToolCallRecovery(attempt.admittedRunContext);
264261
if (!recovery) {
@@ -277,7 +274,7 @@ export function createAgentHarnessHostCapabilities(params: {
277274
assertActive: assertRecoveryActive,
278275
release: recovery.release,
279276
runBeforeToolCall: async (request) =>
280-
await runBeforeToolCallWithAssertion(assertRecoveryActive, "recovery", request),
277+
await runBeforeToolCallWithAssertion(assertRecoveryActive, request),
281278
});
282279
});
283280

‎src/gateway/server-methods/approval-run-cancellation.ts‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ import type { AgentRunDelegatedAuthority } from "../../infra/agent-run-registry.
22
// Settles run-bound approvals when their active agent run is aborted.
33
import type { ExecApprovalManager, ExecApprovalRecord } from "../exec-approval-manager.js";
44
import type { OperatorApprovalRecord } from "../operator-approval-store.js";
5-
import type { WorkerSessionTurnClaim } from "../worker-environments/placement-record.js";
5+
import {
6+
sameWorkerSessionTurnClaim,
7+
type WorkerSessionTurnClaim,
8+
} from "../worker-environments/placement-record.js";
69

710
function cancelMatchingApprovals<TPayload>(params: {
811
manager: ExecApprovalManager<TPayload>;
@@ -49,19 +52,6 @@ export function cancelAgentRuntimeBoundApprovals<TPayload>(params: {
4952
});
5053
}
5154

52-
function sameWorkerTurnClaim(left: WorkerSessionTurnClaim, right: WorkerSessionTurnClaim): boolean {
53-
return (
54-
left.sessionId === right.sessionId &&
55-
left.claimId === right.claimId &&
56-
left.runId === right.runId &&
57-
left.placementGeneration === right.placementGeneration &&
58-
left.owner.kind === "worker" &&
59-
right.owner.kind === "worker" &&
60-
left.owner.environmentId === right.owner.environmentId &&
61-
left.owner.ownerEpoch === right.owner.ownerEpoch
62-
);
63-
}
64-
6555
/** Settles approvals whose authoritative worker turn claim has been fenced. */
6656
export function cancelWorkerTurnClaimBoundApprovals<TPayload>(params: {
6757
claim: WorkerSessionTurnClaim;
@@ -73,7 +63,11 @@ export function cancelWorkerTurnClaimBoundApprovals<TPayload>(params: {
7363
publish: params.publish,
7464
matches: (pending) => {
7565
const authority = pending.agentRuntimeDelegatedAuthority;
76-
return authority?.kind === "worker" && sameWorkerTurnClaim(authority.turnClaim, params.claim);
66+
return (
67+
authority?.kind === "worker" &&
68+
params.claim.owner.kind === "worker" &&
69+
sameWorkerSessionTurnClaim(authority.turnClaim, params.claim)
70+
);
7771
},
7872
});
7973
}

‎src/gateway/server.preauth-hardening.test.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,8 +255,7 @@ describe("gateway pre-auth hardening", () => {
255255
bundleHash: "a".repeat(64),
256256
sessionId: null,
257257
runId: null,
258-
claimId: null,
259-
placementGeneration: null,
258+
turnClaim: null,
260259
ownerEpoch: 1,
261260
rpcSetVersion: 1,
262261
protocolFeatures: [],

‎src/gateway/server/ws-connection/message-handler.worker.test.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,7 @@ const IDENTITY: WorkerConnectionIdentity = {
7070
bundleHash: HANDSHAKE.bundleHash,
7171
sessionId: null,
7272
runId: null,
73-
claimId: null,
74-
placementGeneration: null,
73+
turnClaim: null,
7574
ownerEpoch: 1,
7675
rpcSetVersion: 1,
7776
protocolFeatures: [...HANDSHAKE.protocolFeatures],
@@ -100,8 +99,13 @@ const ATTACHED_IDENTITY: WorkerConnectionIdentity = {
10099
...IDENTITY,
101100
sessionId: "session-1",
102101
runId: "run-1",
103-
claimId: "claim-1",
104-
placementGeneration: 1,
102+
turnClaim: {
103+
sessionId: "session-1",
104+
claimId: "claim-1",
105+
runId: "run-1",
106+
placementGeneration: 1,
107+
owner: { kind: "worker", environmentId: "worker-1", ownerEpoch: 1 },
108+
},
105109
};
106110
const INFERENCE_IDS = {
107111
runEpoch: 1,

‎src/gateway/session-message-events.test.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2514,8 +2514,13 @@ describe("session.message websocket events", () => {
25142514
bundleHash: "f".repeat(64),
25152515
sessionId,
25162516
runId: "run-fanout",
2517-
claimId: "claim-fanout",
2518-
placementGeneration: 4,
2517+
turnClaim: {
2518+
sessionId,
2519+
claimId: "claim-fanout",
2520+
runId: "run-fanout",
2521+
placementGeneration: 4,
2522+
owner: { kind: "worker", environmentId: "environment-fanout", ownerEpoch: 4 },
2523+
},
25192524
ownerEpoch: 4,
25202525
rpcSetVersion: 1,
25212526
protocolFeatures: ["worker-live-event-v1", "worker-transcript-commit-v1"],

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,8 +153,7 @@ export function admitWorkerConnection(params: {
153153
bundleHash: credential.bundleHash,
154154
sessionId: credential.sessionId,
155155
runId: admission.runId,
156-
claimId: turnClaim?.claimId ?? null,
157-
placementGeneration: turnClaim?.placementGeneration ?? null,
156+
turnClaim: turnClaim ?? null,
158157
ownerEpoch: credential.ownerEpoch,
159158
rpcSetVersion: credential.rpcSetVersion,
160159
protocolFeatures: [...environment.bootstrapReceipt.protocolFeatures],

‎src/gateway/worker-environments/connection-identity.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1+
import type { WorkerSessionTurnClaim } from "./placement-record.js";
2+
13
/** Hash-only worker identity retained after admission. */
24
export type WorkerConnectionIdentity = {
35
environmentId: string;
46
credentialHash: string;
57
bundleHash: string;
68
sessionId: string | null;
79
runId: string | null;
8-
claimId: string | null;
9-
placementGeneration: number | null;
10+
turnClaim: WorkerSessionTurnClaim | null;
1011
ownerEpoch: number;
1112
rpcSetVersion: number;
1213
protocolFeatures: string[];

‎src/gateway/worker-environments/credential-broker.test.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,7 @@ describe("worker environment service", () => {
3232
});
3333
const liveEvents = support.createLiveEvents();
3434
const placementStore = {
35-
hasWorkerTurn: vi.fn(() => true),
3635
readWorkerTurnClaim: vi.fn(),
37-
resolveWorkerTurn: vi.fn(),
3836
validateWorkerTurn: vi.fn(() => true),
3937
isWorkerTurnToolAuthorized: vi.fn(() => true),
4038
updateAckCursors: vi.fn(),

0 commit comments

Comments
 (0)