Skip to content

Commit 61bed1c

Browse files
axisrowclaude
andauthored
fix: make the spawned app-server handshake deadline overridable (#55) (#56)
Смерджено в ручную * fix: make the spawned app-server handshake deadline overridable (#55) The spawned `codex app-server` initialize had a hard 10s deadline. The `spawnedInitializeTimeoutMs` option existed but nothing in production set it — the only caller was a test — so on a cold start, a CPU-quota'd container or a loaded CI runner, `/codex:*` failed with a message the user could neither act on nor tune. Add `CODEX_COMPANION_SPAWNED_INITIALIZE_TIMEOUT_MS`, mirroring the existing `CODEX_COMPANION_BROKER_IDLE_TIMEOUT_MS` resolver in app-server-broker.mjs (same env-name shape, same lenient parse, same fall-back-to-default on garbage). It rejects `<= 0` rather than treating 0 as "disabled": a 0ms handshake budget would just fail instantly. Also name the deadline that fired and the knob that raises it in the error message, via an optional `timeoutMessage` on request(). The shared request() default is unchanged, so the broker transport keeps its generic wording. Deliberately not implemented: the progress-based deadline (option 3 in the issue). Keeping this minimal. Closes #55 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LA3HNpq2wRzWpRDBnHusvw * fix: reject sub-millisecond initialize timeout overrides The `parsed <= 0` guard ran before `Math.floor`, so a positive fraction such as `0.5` passed validation and then floored to `0`. request() only arms its timer when `timeoutMs > 0`, so that silently disarmed the handshake deadline entirely and a wedged spawned app-server would hang forever — exactly the failure mode this deadline exists to prevent (fork #29/#31). Floor first, then validate. A sub-millisecond budget is unusable input, so it falls back to the 10s default rather than clamping to an instantly-failing 1ms. Math.floor(NaN)/Math.floor(Infinity) stay non-finite, so the existing garbage-input cases are unaffected. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LA3HNpq2wRzWpRDBnHusvw * fix: reject initialize timeout overrides above Node's timer ceiling Node stores a timer's delay in a 32-bit signed int, so setTimeout silently reduces any delay above 2^31-1 to 1ms (with a TimeoutOverflowWarning). The resolver accepted such values, so a user raising the deadline to something enormous got a handshake that failed almost instantly — the opposite of what they asked for. This is the mirror image of the sub-millisecond case fixed in the previous commit. Both extremes are unusable input, so both fall back to the 10s default rather than clamping: clamping would silently run a deadline that means the opposite of what the user typed, while the default is the documented behaviour. The ceiling itself remains valid. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LA3HNpq2wRzWpRDBnHusvw --------- Co-authored-by: axisrow <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
1 parent 9d0bac5 commit 61bed1c

3 files changed

Lines changed: 185 additions & 5 deletions

File tree

‎plugins/codex/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
- Stop an orphaned shared Codex app-server broker after 15 minutes with no connected clients. Active foreground and background jobs keep their broker connection open, and the timeout can be configured with `CODEX_COMPANION_BROKER_IDLE_TIMEOUT_MS` (`0` disables the safety timer).
66
- Close the broker listener before asynchronous child cleanup and safely reject reconnects already queued during shutdown.
7+
- Allow the spawned `codex app-server` handshake deadline (default 10 seconds) to be raised with `CODEX_COMPANION_SPAWNED_INITIALIZE_TIMEOUT_MS`, for cold starts and heavily loaded or CPU-limited machines, and name both the deadline and that override in the timeout error message.
78

89
## 1.0.0
910

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

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,42 @@ export const BROKER_BUSY_RPC_CODE = -32001;
3131
export const REQUEST_TIMEOUT_CODE = "EBROKERTIMEOUT";
3232
const BROKER_CONNECT_TIMEOUT_MS = 2000;
3333
const BROKER_INITIALIZE_TIMEOUT_MS = 5000;
34-
const SPAWNED_INITIALIZE_TIMEOUT_MS = 10000;
34+
35+
// Escape hatch for the spawned handshake deadline (fork #55). A cold start, a
36+
// container with a tight CPU quota, or a loaded CI runner can genuinely need
37+
// more than 10s, and until now nothing in production set the
38+
// `spawnedInitializeTimeoutMs` option — the only caller was a test, so the
39+
// failure was untunable. Mirrors CODEX_COMPANION_BROKER_IDLE_TIMEOUT_MS in
40+
// app-server-broker.mjs: same env-name shape, same lenient parse, same
41+
// fall-back-to-default-on-garbage behaviour.
42+
export const SPAWNED_INITIALIZE_TIMEOUT_ENV = "CODEX_COMPANION_SPAWNED_INITIALIZE_TIMEOUT_MS";
43+
export const DEFAULT_SPAWNED_INITIALIZE_TIMEOUT_MS = 10000;
44+
// Node stores a timer's delay in a 32-bit signed int; anything larger is
45+
// silently reduced to 1ms with a TimeoutOverflowWarning. Values above this are
46+
// unusable input, not a bigger budget.
47+
export const MAX_SPAWNED_INITIALIZE_TIMEOUT_MS = 2147483647;
48+
49+
export function resolveSpawnedInitializeTimeoutMs(env = process.env) {
50+
const rawValue = env?.[SPAWNED_INITIALIZE_TIMEOUT_ENV];
51+
if (rawValue == null || rawValue === "") {
52+
return DEFAULT_SPAWNED_INITIALIZE_TIMEOUT_MS;
53+
}
54+
55+
// Validate *after* flooring: a positive fraction like 0.5 passes a `parsed > 0`
56+
// check but floors to 0, and request() only arms its timer when timeoutMs > 0.
57+
// That would silently disarm the handshake deadline and let a wedged spawned
58+
// app-server hang forever — the failure mode this deadline exists to prevent
59+
// (fork #29/#31). At the other end, a value above MAX_* is reduced by
60+
// setTimeout to 1ms, so asking for a huge budget would fail almost instantly.
61+
// Both extremes are unusable input: fall back to the default rather than
62+
// clamping, so the user sees the documented 10s behaviour instead of a
63+
// deadline that silently means the opposite of what they typed.
64+
const parsed = Math.floor(Number(rawValue));
65+
if (!Number.isFinite(parsed) || parsed <= 0 || parsed > MAX_SPAWNED_INITIALIZE_TIMEOUT_MS) {
66+
return DEFAULT_SPAWNED_INITIALIZE_TIMEOUT_MS;
67+
}
68+
return parsed;
69+
}
3570

3671
// Bound the broker socket's graceful close the same way the spawned client
3772
// already bounds its own (close()'s 50ms killChildNow() fallback below).
@@ -106,7 +141,7 @@ class AppServerClientBase {
106141
* @template {AppServerMethod} M
107142
* @param {M} method
108143
* @param {import("./app-server-protocol").AppServerRequestParams<M>} params
109-
* @param {{ timeoutMs?: number, onTimeout?: () => void }} [options]
144+
* @param {{ timeoutMs?: number, onTimeout?: () => void, timeoutMessage?: string }} [options]
110145
* @returns {Promise<import("./app-server-protocol").AppServerResponse<M>>}
111146
*/
112147
request(method, params, options = {}) {
@@ -116,7 +151,7 @@ class AppServerClientBase {
116151

117152
const id = this.nextId;
118153
this.nextId += 1;
119-
const { timeoutMs, onTimeout } = options;
154+
const { timeoutMs, onTimeout, timeoutMessage } = options;
120155

121156
return new Promise((resolve, reject) => {
122157
let timer = null;
@@ -130,7 +165,9 @@ class AppServerClientBase {
130165
try {
131166
onTimeout?.();
132167
} catch {}
133-
const error = /** @type {ProtocolError} */ (new Error(`codex app-server ${method} timed out.`));
168+
const error = /** @type {ProtocolError} */ (new Error(
169+
timeoutMessage ?? `codex app-server ${method} timed out.`
170+
));
134171
error.code = REQUEST_TIMEOUT_CODE;
135172
reject(error);
136173
}
@@ -272,12 +309,22 @@ class SpawnedCodexAppServerClient extends AppServerClientBase {
272309
this.handleLine(line);
273310
});
274311

312+
const initializeTimeoutMs =
313+
this.options.spawnedInitializeTimeoutMs ??
314+
resolveSpawnedInitializeTimeoutMs(this.options.env ?? process.env);
315+
275316
try {
276317
await this.request("initialize", {
277318
clientInfo: this.options.clientInfo ?? DEFAULT_CLIENT_INFO,
278319
capabilities: this.options.capabilities ?? DEFAULT_CAPABILITIES
279320
}, {
280-
timeoutMs: this.options.spawnedInitializeTimeoutMs ?? SPAWNED_INITIALIZE_TIMEOUT_MS
321+
timeoutMs: initializeTimeoutMs,
322+
// Name both the deadline that fired and the knob that raises it — the
323+
// bare "initialize timed out." told the user nothing actionable (#55).
324+
timeoutMessage:
325+
`codex app-server initialize timed out after ${initializeTimeoutMs}ms. ` +
326+
`If this machine is slow or heavily loaded, raise the deadline with ` +
327+
`${SPAWNED_INITIALIZE_TIMEOUT_ENV}=<milliseconds>.`
281328
});
282329
} catch (error) {
283330
// A handshake failure (timeout, app-server crash) must not orphan the
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import test from "node:test";
2+
import assert from "node:assert/strict";
3+
4+
import {
5+
SPAWNED_INITIALIZE_TIMEOUT_ENV,
6+
DEFAULT_SPAWNED_INITIALIZE_TIMEOUT_MS,
7+
MAX_SPAWNED_INITIALIZE_TIMEOUT_MS,
8+
resolveSpawnedInitializeTimeoutMs
9+
} from "../plugins/codex/scripts/lib/app-server.mjs";
10+
import { CodexAppServerClient } from "../plugins/codex/scripts/lib/app-server.mjs";
11+
import { buildEnv, installFakeCodex } from "./fake-codex-fixture.mjs";
12+
import { makeTempDir } from "./helpers.mjs";
13+
14+
// fork #55: the spawned app-server handshake had a hard 10s deadline with no
15+
// user-facing escape hatch. On a loaded CI runner or a cold start this fails
16+
// with a message the user can neither act on nor tune. The override mirrors
17+
// CODEX_COMPANION_BROKER_IDLE_TIMEOUT_MS (app-server-broker.mjs).
18+
19+
test("resolveSpawnedInitializeTimeoutMs honours the env override", () => {
20+
assert.equal(
21+
resolveSpawnedInitializeTimeoutMs({ [SPAWNED_INITIALIZE_TIMEOUT_ENV]: "45000" }),
22+
45000
23+
);
24+
assert.equal(
25+
resolveSpawnedInitializeTimeoutMs({ [SPAWNED_INITIALIZE_TIMEOUT_ENV]: "1500.9" }),
26+
1500
27+
);
28+
});
29+
30+
// A positive fraction passes a `parsed > 0` check but floors to 0, and request()
31+
// only installs its timer when timeoutMs > 0 — so a sub-millisecond override
32+
// would silently disarm the handshake deadline entirely and let a wedged
33+
// spawned app-server hang forever (the #29/#31 class this deadline exists to
34+
// prevent). Never resolve to 0.
35+
test("resolveSpawnedInitializeTimeoutMs never resolves a positive override to 0", () => {
36+
for (const rawValue of ["0.5", "0.9", "1e-9", "0.0001"]) {
37+
const resolved = resolveSpawnedInitializeTimeoutMs({
38+
[SPAWNED_INITIALIZE_TIMEOUT_ENV]: rawValue
39+
});
40+
assert.ok(resolved > 0, `${rawValue} resolved to ${resolved}, which disarms the deadline`);
41+
// Sub-millisecond is unusable input, so it falls back to the default rather
42+
// than becoming a 1ms deadline that would fail instantly.
43+
assert.equal(resolved, DEFAULT_SPAWNED_INITIALIZE_TIMEOUT_MS);
44+
}
45+
});
46+
47+
// The mirror image of the sub-millisecond case: Node's setTimeout stores its
48+
// delay in a 32-bit signed int, so any value above 2^31-1 is silently reduced
49+
// to 1ms (with a TimeoutOverflowWarning). A user raising the deadline to
50+
// something enormous would get a near-instant handshake failure — the opposite
51+
// of what they asked for. Never resolve above the timer ceiling.
52+
test("resolveSpawnedInitializeTimeoutMs rejects values above Node's timer ceiling", () => {
53+
for (const rawValue of ["2147483648", "2147483648.7", "9999999999", "1e21"]) {
54+
const resolved = resolveSpawnedInitializeTimeoutMs({
55+
[SPAWNED_INITIALIZE_TIMEOUT_ENV]: rawValue
56+
});
57+
assert.ok(
58+
resolved <= MAX_SPAWNED_INITIALIZE_TIMEOUT_MS,
59+
`${rawValue} resolved to ${resolved}, which setTimeout would reduce to 1ms`
60+
);
61+
assert.equal(resolved, DEFAULT_SPAWNED_INITIALIZE_TIMEOUT_MS);
62+
}
63+
64+
// The ceiling itself is still a usable value.
65+
assert.equal(
66+
resolveSpawnedInitializeTimeoutMs({
67+
[SPAWNED_INITIALIZE_TIMEOUT_ENV]: String(MAX_SPAWNED_INITIALIZE_TIMEOUT_MS)
68+
}),
69+
MAX_SPAWNED_INITIALIZE_TIMEOUT_MS
70+
);
71+
});
72+
73+
test("resolveSpawnedInitializeTimeoutMs falls back to the default on unusable values", () => {
74+
for (const rawValue of [undefined, "", " ", "abc", "-1", "NaN", "Infinity"]) {
75+
assert.equal(
76+
resolveSpawnedInitializeTimeoutMs({ [SPAWNED_INITIALIZE_TIMEOUT_ENV]: rawValue }),
77+
DEFAULT_SPAWNED_INITIALIZE_TIMEOUT_MS,
78+
`expected default for ${JSON.stringify(rawValue)}`
79+
);
80+
}
81+
assert.equal(resolveSpawnedInitializeTimeoutMs({}), DEFAULT_SPAWNED_INITIALIZE_TIMEOUT_MS);
82+
});
83+
84+
test("explicit spawnedInitializeTimeoutMs wins over the env override", async () => {
85+
const binDir = makeTempDir();
86+
const cwd = makeTempDir();
87+
installFakeCodex(binDir, "stalled-initialize");
88+
const env = { ...buildEnv(binDir), [SPAWNED_INITIALIZE_TIMEOUT_ENV]: "60000" };
89+
90+
const error = await CodexAppServerClient.connect(cwd, {
91+
disableBroker: true,
92+
env,
93+
// The explicit option must still win, otherwise this test would wait 60s.
94+
spawnedInitializeTimeoutMs: 300
95+
}).then(
96+
(client) => {
97+
client.close().catch(() => {});
98+
return null;
99+
},
100+
(err) => err
101+
);
102+
103+
assert.ok(error, "expected the handshake to time out");
104+
assert.equal(error.code, "EBROKERTIMEOUT");
105+
});
106+
107+
test("the spawned initialize timeout message names the deadline and the override knob", async () => {
108+
const binDir = makeTempDir();
109+
const cwd = makeTempDir();
110+
installFakeCodex(binDir, "stalled-initialize");
111+
const env = { ...buildEnv(binDir), [SPAWNED_INITIALIZE_TIMEOUT_ENV]: "300" };
112+
113+
const error = await CodexAppServerClient.connect(cwd, {
114+
disableBroker: true,
115+
env
116+
}).then(
117+
(client) => {
118+
client.close().catch(() => {});
119+
return null;
120+
},
121+
(err) => err
122+
);
123+
124+
assert.ok(error, "expected the handshake to time out");
125+
assert.equal(error.code, "EBROKERTIMEOUT");
126+
assert.match(error.message, /300ms/, `deadline missing from: ${error.message}`);
127+
assert.match(
128+
error.message,
129+
new RegExp(SPAWNED_INITIALIZE_TIMEOUT_ENV),
130+
`override knob missing from: ${error.message}`
131+
);
132+
});

0 commit comments

Comments
 (0)