Skip to content

Commit 2320230

Browse files
axisrowclaude
andcommitted
fix: bound the broker client's close() against a peer that ignores FIN
Codex review of PR #48 (issue #47 finding 2) caught that interruptAppServerTurn's onTimeout handler called client.close(), but BrokerCodexAppServerClient.close() sent socket.end() and awaited exitPromise with no fallback. A peer that accepts the FIN but never reciprocates leaves exitPromise unresolved forever, so close() could hang indefinitely — defeating the request-level timeoutMs the previous commit added, since the cleanup path it triggers wasn't itself bounded. Add a 50ms grace period before force-destroying the socket, mirroring the pattern the spawned client's close() already uses (stdin.end() + killChildNow() fallback). New fixture spawnStubbornBroker() completes the handshake and answers requests, but (via allowHalfOpen: true) never reciprocates the FIN -- reproducing the exact wedge Codex described. Verified red without the fix (hangs ~3s) and green with it (~56ms, matching the grace period). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013hBHjrDA8DzzY2SEq4ieiS
1 parent 1e41e55 commit 2320230

3 files changed

Lines changed: 127 additions & 0 deletions

File tree

‎plugins/codex/scripts/lib/app-server.mjs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,17 @@ const BROKER_CONNECT_TIMEOUT_MS = 2000;
3333
const BROKER_INITIALIZE_TIMEOUT_MS = 5000;
3434
const SPAWNED_INITIALIZE_TIMEOUT_MS = 10000;
3535

36+
// Bound the broker socket's graceful close the same way the spawned client
37+
// already bounds its own (close()'s 50ms killChildNow() fallback below).
38+
// socket.end() sends FIN and waits for the peer to also close — if the peer
39+
// stays alive and ignores it, exitPromise never resolves and close() hangs
40+
// indefinitely. destroy()ing after a short grace period forces the "close"
41+
// event (-> handleExit) so close() always returns, mirroring the spawned
42+
// client's kill fallback. See #47 finding 2 (Codex review on PR #48): a
43+
// caller's own request-level timeoutMs is not a real bound if close() itself
44+
// can hang past it.
45+
const BROKER_CLOSE_GRACE_MS = 50;
46+
3647
/** @type {ClientInfo} */
3748
const DEFAULT_CLIENT_INFO = {
3849
title: "Codex Plugin",
@@ -399,6 +410,11 @@ class BrokerCodexAppServerClient extends AppServerClientBase {
399410
this.closed = true;
400411
if (this.socket) {
401412
this.socket.end();
413+
setTimeout(() => {
414+
if (!this.exitResolved) {
415+
this.socket?.destroy();
416+
}
417+
}, BROKER_CLOSE_GRACE_MS).unref?.();
402418
}
403419
await this.exitPromise;
404420
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import test from "node:test";
2+
import assert from "node:assert/strict";
3+
4+
import { CodexAppServerClient } from "../plugins/codex/scripts/lib/app-server.mjs";
5+
import { makeTempDir } from "./helpers.mjs";
6+
import { spawnStubbornBroker } from "./broker-controller-helpers.mjs";
7+
8+
// Codex-review finding on PR #48 (#47 finding 2): BrokerCodexAppServerClient
9+
// .close() called socket.end() and awaited exitPromise with no fallback. A
10+
// peer that completes the handshake, answers requests, but then stays alive
11+
// and ignores the client's FIN (socket.end()) left close() -- and therefore
12+
// any onTimeout handler in codex.mjs that calls client.close() -- hanging
13+
// indefinitely. A caller's own request-level timeoutMs is not a real bound
14+
// if close() itself can hang past it. This is the regression test for the
15+
// BROKER_CLOSE_GRACE_MS fallback in app-server.mjs's close().
16+
test("close() does not hang when the broker peer ignores the FIN (#47 finding 2 follow-up)", async () => {
17+
const stubborn = await spawnStubbornBroker();
18+
const cwd = makeTempDir();
19+
20+
let client;
21+
try {
22+
client = await CodexAppServerClient.connect(cwd, {
23+
brokerEndpoint: `unix:${stubborn.socketPath}`,
24+
brokerConnectTimeoutMs: 2000,
25+
brokerInitializeTimeoutMs: 2000
26+
});
27+
assert.equal(client.transport, "broker", "must have connected over the broker transport");
28+
29+
// A normal request completes -- the peer is not wedged, just stubborn
30+
// about closing.
31+
await client.request("turn/interrupt", { threadId: "t1", turnId: "r1" }, { timeoutMs: 2000 });
32+
33+
const outcome = await Promise.race([
34+
client.close().then(() => "closed"),
35+
new Promise((resolve) => setTimeout(() => resolve("HANG"), 3000))
36+
]);
37+
38+
assert.notEqual(outcome, "HANG", "close() hung forever on a peer that never reciprocates FIN");
39+
assert.equal(outcome, "closed", "close() must resolve once the grace-period fallback force-destroys the socket");
40+
} finally {
41+
stubborn.cleanup();
42+
}
43+
});

‎tests/broker-controller-helpers.mjs‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,3 +290,71 @@ export async function spawnBusyBroker() {
290290
}
291291
};
292292
}
293+
294+
/**
295+
* A real net.createServer that completes the handshake and answers every
296+
* subsequent request normally, but never reciprocates a TCP half-close: on
297+
* receiving FIN (the client's socket.end()) it does not also end/destroy its
298+
* side. Reproduces the #47/PR-48 Codex-review finding that
299+
* BrokerCodexAppServerClient.close() called socket.end() and awaited
300+
* exitPromise with no fallback -- a peer that stays alive and ignores the FIN
301+
* left close() (and any onTimeout handler that calls it) hanging forever.
302+
*/
303+
export async function spawnStubbornBroker() {
304+
const sessionDir = makeTempDir("broker-stubborn-");
305+
const socketPath = path.join(sessionDir, "broker.sock");
306+
const connections = new Set();
307+
// allowHalfOpen: true is load-bearing. Node's default (false) auto-ends
308+
// the accepted socket's write side as soon as it sees the client's FIN --
309+
// which would make this fixture indistinguishable from a normal close and
310+
// silently defeat the regression test. true keeps the connection genuinely
311+
// half-open so the fixture can deliberately never reciprocate.
312+
const server = net.createServer({ allowHalfOpen: true }, (socket) => {
313+
socket.setEncoding("utf8");
314+
connections.add(socket);
315+
socket.on("error", () => {});
316+
// Deliberately do NOT end/destroy on "end" (FIN received) -- that is the
317+
// wedge this fixture reproduces. Track close purely for cleanup.
318+
socket.on("close", () => connections.delete(socket));
319+
let buffer = "";
320+
socket.on("data", (chunk) => {
321+
buffer += chunk;
322+
let newlineIndex = buffer.indexOf("\n");
323+
while (newlineIndex !== -1) {
324+
const line = buffer.slice(0, newlineIndex);
325+
buffer = buffer.slice(newlineIndex + 1);
326+
newlineIndex = buffer.indexOf("\n");
327+
let message;
328+
try {
329+
message = JSON.parse(line);
330+
} catch {
331+
continue;
332+
}
333+
if (message.id === undefined) {
334+
continue;
335+
}
336+
if (message.method === "initialize") {
337+
socket.write(`${JSON.stringify({ id: message.id, result: { userAgent: "stubborn-broker" } })}\n`);
338+
} else {
339+
socket.write(`${JSON.stringify({ id: message.id, result: {} })}\n`);
340+
}
341+
}
342+
});
343+
});
344+
await new Promise((resolve) => server.listen(socketPath, resolve));
345+
return {
346+
socketPath,
347+
cleanup() {
348+
for (const socket of connections) {
349+
socket.destroy();
350+
}
351+
connections.clear();
352+
try {
353+
server.close();
354+
} catch {}
355+
try {
356+
fs.unlinkSync(socketPath);
357+
} catch {}
358+
}
359+
};
360+
}

0 commit comments

Comments
 (0)