Skip to content

Commit 65b6654

Browse files
committed
fix(agents): keep overlapping native hook relay registrations routable
Codex native runs share one stable per-session relayId, and the single registration slot let an overlapping sibling run (new turn, nested run, or bound-thread resume reusing the persisted generation) evict the active registration at register time. Every later PreToolUse hook of the still-live run then failed closed with the stale-registration error mid-turn, and a retained relay guarding direct-child hooks could be torn down by the next turn's registration on the same session. Track every live registration per relayId in registration order and route invocations to the newest registration matching the presented generation, falling back to the current registration only for the bootstrap generation-mismatch grace. Unregister now removes only the caller's own registration; relayId-wide state (loopback bridge, SQLite locator record, invocation history, approval and permission state) is torn down only when the last registration goes. The bridge is reused across overlapping registrations, its record expiry covers the longest-lived registration, and renew works for non-current siblings so long turns no longer lose their relay at the original TTL. Retained-relay and foreground liveness checks key off slot membership instead of map currency, so a sibling registering or unregistering cannot invalidate an in-flight invocation binding. Registrations are capped per relayId, and at the cap the new registration is rejected instead of evicting a live sibling. Exact-generation authorization is preserved: a generation that was unregistered or expired still fails closed with the stale registration error. Shared-state objects written by older module copies are upgraded in place, and their relays-only registrations stay routable, expirable, and sweepable. Slot bookkeeping, lifetime teardown, and invocation-binding resolution move to native-hook-relay-registrations.ts to keep the relay facade under the max-lines cap.
1 parent 4431033 commit 65b6654

10 files changed

Lines changed: 1975 additions & 419 deletions

‎extensions/codex/src/app-server/native-hook-relay.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,7 @@ function createRelay(options?: {
442442
? " --pre-tool-use-unavailable noop"
443443
: ""
444444
}${commandOptions?.timeoutMs ? ` --timeout ${commandOptions.timeoutMs}` : ""}`,
445+
claimTurn: () => undefined,
445446
renew: () => undefined,
446447
unregister: () => undefined,
447448
};

‎extensions/codex/src/app-server/run-attempt-turn-request.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,14 @@ export async function prepareCodexAttemptTurnRequest(
148148
}),
149149
);
150150
acceptedTurnId = startedTurn.turn.id;
151+
// Bind this turn's native hook traffic to this run's relay registration
152+
// immediately: an overlapping same-generation sibling (bound-thread
153+
// resume) must never consume this turn's hooks or policy context, and
154+
// unclaimed hooks on a contested generation fail closed. Codex
155+
// turn/start is start-or-steer — when it steered a sibling's live turn
156+
// it returns THAT turn's id, and the relay refuses the duplicate claim
157+
// so hook ownership stays with the original claimant.
158+
resourceState.nativeHookRelay?.claimTurn(acceptedTurnId);
151159
throwIfTurnStartAcceptedAfterAbort();
152160
return startedTurn;
153161
} catch (error) {

‎extensions/codex/src/app-server/side-question.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -836,6 +836,9 @@ export async function runCodexAppServerSideQuestion(
836836
}),
837837
);
838838
turnId = turnResponse.turn.id;
839+
// Bind the side turn's hooks to this side relay so they can never fall
840+
// through to a session sibling's registration.
841+
nativeHookRelay?.claimTurn(turnId);
839842
collector.setTurn(childThreadId, turnId);
840843
nativeToolLifecycleProjector = new CodexNativeToolLifecycleProjector(
841844
{ ...sideRunParams, agentId: sessionAgentId },

‎src/agents/harness/native-hook-relay-bridge.ts‎

Lines changed: 109 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,13 @@ import { createSubsystemLogger } from "../../logging/subsystem.js";
44
import { isPidDefinitelyDead } from "../../shared/pid-alive.js";
55
import {
66
isNativeHookRelayBridgeStaleRegistrationError,
7+
NATIVE_HOOK_BRIDGE_REPLACEMENT_RECORD_GRACE_MS,
78
NATIVE_HOOK_RELAY_BRIDGE_STALE_REGISTRATION_ERROR,
89
} from "./native-hook-relay-client.js";
9-
import { nativeHookRelayState } from "./native-hook-relay-state.js";
10+
import {
11+
nativeHookRelayRegistrationsById,
12+
nativeHookRelayState,
13+
} from "./native-hook-relay-state.js";
1014
import {
1115
clearNativeHookRelayBridgeRecordsForTests,
1216
deleteNativeHookRelayBridgeRecordIfOwned,
@@ -34,11 +38,11 @@ const log = createSubsystemLogger("agents/harness/native-hook-relay");
3438

3539
export {
3640
isRetryableNativeHookRelayBridgeLookupError,
37-
NATIVE_HOOK_BRIDGE_REPLACEMENT_RECORD_GRACE_MS,
3841
NATIVE_HOOK_RELAY_BRIDGE_STALE_REGISTRATION_ERROR,
3942
} from "./native-hook-relay-client.js";
4043

4144
const { relays, relayBridges } = nativeHookRelayState;
45+
const relayRegistrationsById = nativeHookRelayRegistrationsById;
4246

4347
type InvokeNativeHookRelay = (
4448
params: InvokeNativeHookRelayParams,
@@ -48,7 +52,6 @@ type NativeHookRelayBridgeRequestAuth = {
4852
provider: NativeHookRelayProvider;
4953
relayId: string;
5054
token: string;
51-
registration: ActiveNativeHookRelayRegistration;
5255
bridge: NativeHookRelayBridgeRegistration;
5356
invokeRelay: InvokeNativeHookRelay;
5457
};
@@ -58,89 +61,155 @@ export function registerNativeHookRelayBridge(
5861
stateDbPath: string,
5962
invokeRelay: InvokeNativeHookRelay,
6063
): void {
61-
// Liveness checks stay outside the write transaction. The store rereads each
62-
// authoritative row before deletion so renewal or replacement wins the race.
63-
try {
64-
const pruned = pruneNativeHookRelayBridgeRecords({
65-
currentPid: process.pid,
66-
isPidDead: isPidDefinitelyDead,
67-
stateDbPath,
64+
const relayId = registration.relayId;
65+
const existing = relayBridges.get(relayId);
66+
if (existing) {
67+
if (existing.server.listening) {
68+
// Reuse the live bridge so re-registration never interrupts in-flight
69+
// hook subprocesses from sibling runs on the same relayId. Refresh the
70+
// record so its expiry covers the new registration.
71+
refreshNativeHookRelayBridgeRecord(relayId);
72+
return;
73+
}
74+
if (existing.pendingListen) {
75+
// Server is still starting; its listen callback publishes the record
76+
// with relay-wide expiry once bound.
77+
return;
78+
}
79+
// The previous bridge server closed or failed. Replace it, leaving the old
80+
// record in place briefly so racing hook subprocesses retry instead of
81+
// observing a missing relay.
82+
unregisterNativeHookRelayBridge(relayId, {
83+
deferBridgeRecordRemovalMs: NATIVE_HOOK_BRIDGE_REPLACEMENT_RECORD_GRACE_MS,
84+
expectedBridge: existing,
6885
});
69-
for (const row of pruned) {
70-
log.debug("pruned stale native hook relay bridge record", {
71-
relayId: row.relayId,
72-
stalePid: row.pid,
86+
} else {
87+
// Liveness checks stay outside the write transaction. The store rereads
88+
// each authoritative row before deletion so renewal or replacement wins
89+
// the race.
90+
try {
91+
const pruned = pruneNativeHookRelayBridgeRecords({
7392
currentPid: process.pid,
74-
reason: row.reason,
93+
isPidDead: isPidDefinitelyDead,
94+
stateDbPath,
7595
});
96+
for (const row of pruned) {
97+
log.debug("pruned stale native hook relay bridge record", {
98+
relayId: row.relayId,
99+
stalePid: row.pid,
100+
currentPid: process.pid,
101+
reason: row.reason,
102+
});
103+
}
104+
} catch (error) {
105+
log.debug("native hook relay bridge record prune skipped", { error });
76106
}
77-
} catch (error) {
78-
log.debug("native hook relay bridge record prune skipped", { error });
79107
}
80-
unregisterNativeHookRelayBridge(registration.relayId);
81108
const token = randomUUID();
82109
const server = createServer();
83110
const bridge: NativeHookRelayBridgeRegistration = {
84-
relayId: registration.relayId,
111+
relayId,
85112
stateDbPath,
86113
token,
87114
server,
115+
pendingListen: true,
88116
};
89117
server.on("request", (req, res) => {
90118
void handleNativeHookRelayBridgeRequest(req, res, {
91119
provider: registration.provider,
92-
relayId: registration.relayId,
120+
relayId,
93121
token,
94-
registration,
95122
bridge,
96123
invokeRelay,
97124
});
98125
});
99-
relayBridges.set(registration.relayId, bridge);
126+
relayBridges.set(relayId, bridge);
100127
server.on("error", (error) => {
101-
log.debug("native hook relay bridge server error", { error, relayId: registration.relayId });
128+
bridge.pendingListen = false;
129+
log.debug("native hook relay bridge server error", { error, relayId });
102130
});
103131
server.listen(0, "127.0.0.1", () => {
104-
if (relayBridges.get(registration.relayId) !== bridge) {
132+
bridge.pendingListen = false;
133+
if (relayBridges.get(relayId) !== bridge) {
105134
return;
106135
}
107136
try {
108-
writeNativeHookRelayBridgeRecordForRegistration(registration, bridge);
137+
writeNativeHookRelayBridgeRecordForRelay(relayId, bridge);
109138
} catch (error) {
110139
log.debug("failed to publish native hook relay bridge record", {
111140
error,
112-
relayId: registration.relayId,
141+
relayId,
113142
});
114143
}
115144
});
116145
server.unref();
117146
}
118147

119-
function writeNativeHookRelayBridgeRecordForRegistration(
120-
registration: ActiveNativeHookRelayRegistration,
148+
/**
149+
* One bridge serves every live registration for the relayId, so the record
150+
* must outlive the longest-lived one. A shared-state registration written by
151+
* an older module copy lives only in `relays`; keep the record alive for it
152+
* too.
153+
*/
154+
export function resolveNativeHookRelayBridgeRecordExpiresAtMs(
155+
relayId: string,
156+
floorExpiresAtMs?: number,
157+
): number | undefined {
158+
let expiresAtMs = floorExpiresAtMs;
159+
for (const registration of relayRegistrationsById.get(relayId) ?? []) {
160+
if (expiresAtMs === undefined || registration.expiresAtMs > expiresAtMs) {
161+
expiresAtMs = registration.expiresAtMs;
162+
}
163+
}
164+
const current = relays.get(relayId);
165+
if (current && (expiresAtMs === undefined || current.expiresAtMs > expiresAtMs)) {
166+
expiresAtMs = current.expiresAtMs;
167+
}
168+
return expiresAtMs;
169+
}
170+
171+
function writeNativeHookRelayBridgeRecordForRelay(
172+
relayId: string,
121173
bridge: NativeHookRelayBridgeRegistration,
122174
): void {
123-
const record = resolveNativeHookRelayBridgeRecord(registration, bridge);
175+
const expiresAtMs = resolveNativeHookRelayBridgeRecordExpiresAtMs(relayId);
176+
if (expiresAtMs === undefined) {
177+
return;
178+
}
179+
const record = resolveNativeHookRelayBridgeRecord(relayId, bridge, expiresAtMs);
124180
if (!record) {
125181
return;
126182
}
127183
writeNativeHookRelayBridgeRecord({ record, stateDbPath: bridge.stateDbPath });
128184
}
129185

186+
/** Republish the shared record after registration-set changes on a live bridge. */
187+
export function refreshNativeHookRelayBridgeRecord(relayId: string): void {
188+
const bridge = relayBridges.get(relayId);
189+
if (!bridge || !bridge.server.listening) {
190+
return;
191+
}
192+
try {
193+
writeNativeHookRelayBridgeRecordForRelay(relayId, bridge);
194+
} catch (error) {
195+
log.debug("failed to publish native hook relay bridge record", { error, relayId });
196+
}
197+
}
198+
130199
function resolveNativeHookRelayBridgeRecord(
131-
registration: ActiveNativeHookRelayRegistration,
200+
relayId: string,
132201
bridge: NativeHookRelayBridgeRegistration,
133-
expiresAtMs = registration.expiresAtMs,
202+
expiresAtMs: number,
134203
): NativeHookRelayBridgeRecord | undefined {
135204
const address = bridge.server.address();
136205
if (!address || typeof address === "string") {
137206
log.debug("native hook relay bridge server address unavailable", {
138-
relayId: registration.relayId,
207+
relayId,
139208
});
140209
return undefined;
141210
}
142211
return {
143-
relayId: registration.relayId,
212+
relayId,
144213
pid: process.pid,
145214
hostname: "127.0.0.1",
146215
port: address.port,
@@ -154,7 +223,7 @@ export function renewNativeHookRelayBridgeRecord(
154223
bridge: NativeHookRelayBridgeRegistration,
155224
expiresAtMs: number,
156225
): "renewed" | "unavailable" | "ownership-changed" {
157-
const record = resolveNativeHookRelayBridgeRecord(registration, bridge, expiresAtMs);
226+
const record = resolveNativeHookRelayBridgeRecord(registration.relayId, bridge, expiresAtMs);
158227
if (!record) {
159228
return "unavailable";
160229
}
@@ -251,8 +320,13 @@ async function handleNativeHookRelayBridgeRequest(
251320
}
252321

253322
function isCurrentNativeHookRelayBridgeRequest(auth: NativeHookRelayBridgeRequestAuth): boolean {
323+
// The bridge outlives individual registrations; a request is current while
324+
// this bridge is still installed and any registration is live. Per-request
325+
// generation resolution happens in invokeNativeHookRelay and fails closed.
326+
// `relays` alone can hold a registration written by an older module copy.
254327
return (
255-
relays.get(auth.relayId) === auth.registration && relayBridges.get(auth.relayId) === auth.bridge
328+
relayBridges.get(auth.relayId) === auth.bridge &&
329+
((relayRegistrationsById.get(auth.relayId)?.size ?? 0) > 0 || relays.has(auth.relayId))
256330
);
257331
}
258332

0 commit comments

Comments
 (0)