Skip to content

Commit ddabf26

Browse files
axisrowclaude
andcommitted
fix(broker): restore post-handshake broker/busy direct fallback (cycle-review critical)
Codex adversarial review caught that collapsing withAppServer's fallback onto error.transport broke the #29 path: broker/busy (-32001) arrives AFTER a successful handshake, while the error is created by createProtocolError with rpcCode but NO transport (transport is tagged only on handshake failure in connect()'s catch). So every overlapping /codex:* command failed for the duration of a long-running broker turn instead of falling back to direct. Restore client?.transport === "broker" for the busy branch (post-handshake, client is assigned); keep error.brokerFatal for handshake failures (client is null, tagged in connect). Adds spawnBusyBroker helper + an end-to-end test that drives a successful initialize, then -32001 on the first RPC, and verifies the operation completes via the direct fallback. Co-Authored-By: Claude <[email protected]>
1 parent dc8b5da commit ddabf26

3 files changed

Lines changed: 110 additions & 5 deletions

File tree

‎plugins/codex/scripts/lib/codex.mjs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -688,11 +688,14 @@ export async function withAppServer(cwd, fn, clientOptions = {}) {
688688
return result;
689689
} catch (error) {
690690
// Fall back to a direct (non-broker) app-server when the broker transport
691-
// is unusable: either it is busy with another in-flight request (-32001),
692-
// or it failed fatally during the handshake (timeout / ENOENT /
693-
// ECONNREFUSED — tagged brokerFatal in CodexAppServerClient.connect).
691+
// is unusable. Two distinct shapes:
692+
// - broker/busy (-32001) arrives AFTER a successful handshake, while
693+
// `client` is assigned — read the transport off the client.
694+
// - a handshake failure (timeout / ENOENT / ECONNREFUSED) rejects inside
695+
// connect() before `client` is assigned — tagged brokerFatal in
696+
// CodexAppServerClient.connect.
694697
const shouldRetryDirect =
695-
(error?.transport === "broker" && error?.rpcCode === BROKER_BUSY_RPC_CODE) ||
698+
(client?.transport === "broker" && error?.rpcCode === BROKER_BUSY_RPC_CODE) ||
696699
error?.brokerFatal === true;
697700

698701
if (client) {

‎tests/broker-client-initialize-timeout.test.mjs‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { CodexAppServerClient } from "../plugins/codex/scripts/lib/app-server.mj
55
import { withAppServer } from "../plugins/codex/scripts/lib/codex.mjs";
66
import { buildEnv, installFakeCodex } from "./fake-codex-fixture.mjs";
77
import { makeTempDir } from "./helpers.mjs";
8-
import { spawnWedgedServer } from "./broker-controller-helpers.mjs";
8+
import { spawnBusyBroker, spawnWedgedServer } from "./broker-controller-helpers.mjs";
99

1010
// Reproduces fork #29 / upstream openai#509: when the shared broker is wedged
1111
// (busy with a long-running request and never reaching the second socket), the
@@ -82,3 +82,46 @@ test("withAppServer falls back to a direct app-server when the broker wedges (#2
8282
wedged.cleanup();
8383
}
8484
});
85+
86+
// Drives the post-handshake busy fallback: the broker accepts initialize, then
87+
// returns BROKER_BUSY_RPC_CODE (-32001) for the operation's first request.
88+
// withAppServer must fall back to a direct app-server. Codex review of PR #32
89+
// caught that collapsing the OR-chain onto error.transport broke this path
90+
// (transport is tagged only on handshake failure, not on post-handshake busy).
91+
test("withAppServer falls back to a direct app-server on broker/busy after a successful handshake (#32)", async () => {
92+
const busy = await spawnBusyBroker();
93+
const cwd = makeTempDir();
94+
const binDir = makeTempDir();
95+
installFakeCodex(binDir);
96+
const env = buildEnv(binDir);
97+
98+
let calls = 0;
99+
try {
100+
const result = await Promise.race([
101+
withAppServer(
102+
cwd,
103+
async (client) => {
104+
calls += 1;
105+
// Any real RPC: on the broker client this hits broker/busy (-32001)
106+
// and must trigger the direct fallback; on the direct client it
107+
// resolves normally via the fake-codex app-server.
108+
await client.request("account/read", {});
109+
return { transport: client.transport };
110+
},
111+
{
112+
brokerEndpoint: `unix:${busy.socketPath}`,
113+
env
114+
}
115+
),
116+
new Promise((resolve) => setTimeout(() => resolve({ HANG: true }), 5000))
117+
]);
118+
119+
assert.ok(!result.HANG, "withAppServer hung instead of falling back to direct on broker/busy");
120+
// The broker attempt hits -32001, withAppServer retries on direct — so fn
121+
// runs at least once on the broker (which fails) and succeeds on direct.
122+
assert.ok(calls >= 1, "the operation must run via the direct fallback after broker/busy");
123+
assert.equal(result.transport, "direct", "the operation must complete on the direct transport after a busy broker");
124+
} finally {
125+
busy.cleanup();
126+
}
127+
});

‎tests/broker-controller-helpers.mjs‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,3 +231,62 @@ export async function spawnWedgedServer() {
231231
}
232232
};
233233
}
234+
235+
/**
236+
* A real net.createServer that speaks just enough JSON-RPC to pass the broker
237+
* handshake, then returns BROKER_BUSY_RPC_CODE (-32001) for every subsequent
238+
* request — simulates a shared broker that accepted initialize while busy with
239+
* another in-flight stream. Drives withAppServer's post-handshake busy
240+
* fallback, which must retry the operation on a direct (non-broker) client.
241+
*/
242+
export async function spawnBusyBroker() {
243+
const sessionDir = makeTempDir("broker-busy-");
244+
const socketPath = path.join(sessionDir, "broker.sock");
245+
const connections = new Set();
246+
const server = net.createServer((socket) => {
247+
socket.setEncoding("utf8");
248+
connections.add(socket);
249+
socket.on("close", () => connections.delete(socket));
250+
socket.on("error", () => {});
251+
let buffer = "";
252+
socket.on("data", (chunk) => {
253+
buffer += chunk;
254+
let newlineIndex = buffer.indexOf("\n");
255+
while (newlineIndex !== -1) {
256+
const line = buffer.slice(0, newlineIndex);
257+
buffer = buffer.slice(newlineIndex + 1);
258+
newlineIndex = buffer.indexOf("\n");
259+
let message;
260+
try {
261+
message = JSON.parse(line);
262+
} catch {
263+
continue;
264+
}
265+
if (message.id === undefined) {
266+
continue;
267+
}
268+
if (message.method === "initialize") {
269+
socket.write(`${JSON.stringify({ id: message.id, result: { userAgent: "busy-broker" } })}\n`);
270+
} else {
271+
socket.write(`${JSON.stringify({ id: message.id, error: { code: -32001, message: "Shared Codex broker is busy." } })}\n`);
272+
}
273+
}
274+
});
275+
});
276+
await new Promise((resolve) => server.listen(socketPath, resolve));
277+
return {
278+
socketPath,
279+
cleanup() {
280+
for (const socket of connections) {
281+
socket.destroy();
282+
}
283+
connections.clear();
284+
try {
285+
server.close();
286+
} catch {}
287+
try {
288+
fs.unlinkSync(socketPath);
289+
} catch {}
290+
}
291+
};
292+
}

0 commit comments

Comments
 (0)