Skip to content

Commit 7fceb85

Browse files
committed
fix: bump first-byte timeout, env override, stderr note, NPE safety
Addresses suryaiyer95's review of `cc222db2a`: - Default first-byte timeout bumped from 100ms to 500ms. The previous value was aggressive against realistic slow-to-first-byte producers (DB queries that need to plan, decompression headers, network calls with DNS+TLS handshake). 500ms is generous for those without sacri- ficing the inherited-idle wedge fix. - New `ALTIMATE_STDIN_TIMEOUT_MS=N` env override so a user hitting an even slower pipeline can bump it without code changes. - Stderr note when fd 0 looked like real input (FIFO / file / socket) but readStdin came back empty. Silent drop was the original UX failure that motivated this whole review thread. The note fires on the dominant inherited-idle path too; that's intentional since stderr is captured but not surfaced for most subprocess callers (Claude Code's Bash tool, CI), and a single line of noise per call is worth the explicitness for the slow-producer case. - `process.stdin` null-safety folded into `readStdinIfAvailable`: in embedded / child runtimes (dev-punia review on PR #937) accessing `process.stdin.isTTY` could throw. Treat undefined stdin as "no input to read". - 6 new injection tests: env override + invalid env fallback, warning fires/doesn't fire across each gate, undefined-stdin guard. - E2E thresholds adjusted for the 500ms timeout (idle-exit assertion bumped to 1500ms, post-timeout sleep bumped to 1200ms).
1 parent bf0aab2 commit 7fceb85

3 files changed

Lines changed: 186 additions & 24 deletions

File tree

‎packages/opencode/src/util/stdin.ts‎

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import fs from "fs"
22
import type { Stats } from "fs"
33

4-
const FIRST_BYTE_TIMEOUT_MS = 100
4+
const STDIN_TIMEOUT_ENV = "ALTIMATE_STDIN_TIMEOUT_MS"
5+
const DEFAULT_FIRST_BYTE_TIMEOUT_MS = 500
56

67
type Stat = Pick<Stats, "isFIFO" | "isFile" | "isSocket">
78

@@ -15,6 +16,25 @@ export interface ReadStdinDeps {
1516
// implementation in tests.
1617
readStdin?: (timeoutMs: number) => Promise<string>
1718
timeoutMs?: number
19+
// Called once with a human-readable note when fd 0 looked like a real
20+
// input source (FIFO / file / socket) but no first byte arrived within
21+
// the timeout — so a user whose pipe was silently dropped finds out.
22+
// Default writes to stderr; tests inject a no-op to silence.
23+
warn?: (msg: string) => void
24+
}
25+
26+
function resolveTimeoutMs(): number {
27+
const raw = process.env[STDIN_TIMEOUT_ENV]
28+
if (raw === undefined) return DEFAULT_FIRST_BYTE_TIMEOUT_MS
29+
const parsed = Number.parseInt(raw, 10)
30+
if (!Number.isFinite(parsed) || parsed < 0) return DEFAULT_FIRST_BYTE_TIMEOUT_MS
31+
return parsed
32+
}
33+
34+
function defaultWarn(msg: string): void {
35+
try {
36+
process.stderr?.write(msg + "\n")
37+
} catch {}
1838
}
1939

2040
// Read piped/redirected stdin without wedging on an inherited-but-idle fd.
@@ -35,16 +55,36 @@ export interface ReadStdinDeps {
3555
// wait up to `timeoutMs` for the first readable byte. If no byte
3656
// arrives in that window, we treat stdin as inherited-idle and skip.
3757
// If a byte arrives, we drain to EOF without further deadline — so a
38-
// slow producer that takes >100ms total but flushes its first chunk
39-
// within the window is not truncated. This avoids the two pitfalls of
40-
// a whole-stream race: (a) the orphaned `Bun.stdin.text()` continuing
41-
// to hold fd 0 open after the loser is abandoned, and (b) silent
42-
// mid-stream truncation of legitimate slow / large producers.
58+
// slow producer that takes >500ms total but flushes its first chunk
59+
// within the window is not truncated. The 500ms default is chosen to
60+
// cover realistic slow-to-first-byte producers (DB queries that need
61+
// to plan, decompression headers, network calls with DNS+TLS handshake)
62+
// while still failing fast enough to keep the inherited-idle wedge fix
63+
// effective. Users can override via `ALTIMATE_STDIN_TIMEOUT_MS=N` (ms)
64+
// for environments with even slower producers. This avoids the two
65+
// pitfalls of a whole-stream race: (a) the orphaned `Bun.stdin.text()`
66+
// continuing to hold fd 0 open after the loser is abandoned, and
67+
// (b) silent mid-stream truncation of legitimate slow / large producers.
68+
//
69+
// 3. Stderr note on silent drop: if we got past the fstat gate (fd 0
70+
// looked like real input) but the read came back empty, we write one
71+
// line to stderr so a user whose pipe was dropped finds out instead
72+
// of silently getting no input. The note also tells them how to bump
73+
// the timeout. This fires on the dominant inherited-idle path too —
74+
// that's intentional, since stderr is captured but not surfaced for
75+
// most subprocess callers (Claude Code's Bash tool, CI) and a single
76+
// line of noise per call is worth the explicitness for the
77+
// slow-producer case.
4378
export async function readStdinIfAvailable(deps: ReadStdinDeps = {}): Promise<string> {
79+
// `process.stdin` can be undefined in embedded / child runtimes (flagged
80+
// by dev-punia on PR #937). Treat absence as "no stdin to read."
81+
if (deps.isTTY === undefined && !process.stdin) return ""
82+
4483
const isTTY = deps.isTTY ?? Boolean(process.stdin.isTTY)
4584
const fstat = deps.fstat ?? (() => fs.fstatSync(0) as Stat)
4685
const readStdin = deps.readStdin ?? defaultReadStdin
47-
const timeoutMs = deps.timeoutMs ?? FIRST_BYTE_TIMEOUT_MS
86+
const timeoutMs = deps.timeoutMs ?? resolveTimeoutMs()
87+
const warn = deps.warn ?? defaultWarn
4888

4989
if (isTTY) return ""
5090

@@ -55,7 +95,16 @@ export async function readStdinIfAvailable(deps: ReadStdinDeps = {}): Promise<st
5595
return ""
5696
}
5797

58-
return readStdin(timeoutMs)
98+
const result = await readStdin(timeoutMs)
99+
100+
if (result === "") {
101+
warn(
102+
`altimate-code: stdin appears piped but no data received within ${timeoutMs}ms; ` +
103+
`proceeding without it. Set ${STDIN_TIMEOUT_ENV}=N (ms) to wait longer.`,
104+
)
105+
}
106+
107+
return result
59108
}
60109

61110
// Compose the final prompt from a positional message and stdin input.

‎packages/opencode/test/util/stdin-e2e.test.ts‎

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -50,22 +50,24 @@ describe("readStdinIfAvailable (spawned subprocess)", () => {
5050
"exits promptly with empty result when stdin is an inherited-but-idle pipe",
5151
async () => {
5252
const { code, result, elapsed } = await runFixture({
53-
// Don't write — leave the pipe open and silent. Close after 1s so
53+
// Don't write — leave the pipe open and silent. Close after 3s so
5454
// the parent's writer isn't garbage-collected; by then the child
55-
// should have already exited via the first-byte timeout.
55+
// should have already exited via the 500ms first-byte timeout.
5656
writeStdin: async (sink) => {
57-
await new Promise((r) => setTimeout(r, 1000))
57+
await new Promise((r) => setTimeout(r, 3000))
5858
try {
5959
await sink.end()
6060
} catch {}
6161
},
62-
killAfterMs: 5000,
62+
killAfterMs: 8000,
6363
})
6464
expect(code).toBe(0)
6565
expect(result).toBe("")
66-
expect(elapsed).toBeLessThan(500)
66+
// 1500 = timeout (500ms) × 3 for CI scheduler headroom. Well under
67+
// "infinite hang" — the assertion guards the wedge fix, not perf.
68+
expect(elapsed).toBeLessThan(1500)
6769
},
68-
10000,
70+
15000,
6971
)
7072

7173
// MAJOR-regression from PR #935: `echo ctx | run "prompt"` must still
@@ -85,18 +87,16 @@ describe("readStdinIfAvailable (spawned subprocess)", () => {
8587
10000,
8688
)
8789

88-
// M2-regression: a producer that takes >100ms to flush first byte was
89-
// truncated by the old Promise.race timeout. The first-byte gate must
90-
// accept the byte once it arrives and then drain the rest without a
91-
// deadline.
90+
// Sury PR #935 review #2: 500ms must cover realistic slow-first-byte
91+
// producers (DB queries that need to plan, decompression, network calls
92+
// with DNS+TLS handshake). 300ms is comfortably under the 500ms budget;
93+
// the previous 100ms config would have truncated this.
9294
test(
93-
"preserves data from slow producer (first byte arrives just before timeout)",
95+
"preserves data from slow producer (first byte arrives ~300ms after spawn)",
9496
async () => {
9597
const { code, result } = await runFixture({
9698
writeStdin: async (sink) => {
97-
// Sleep close to but under the 100ms first-byte budget, then
98-
// flush. The whole-stream-race fix would have returned "".
99-
await new Promise((r) => setTimeout(r, 60))
99+
await new Promise((r) => setTimeout(r, 300))
100100
sink.write("slow ctx")
101101
await sink.end()
102102
},
@@ -109,12 +109,13 @@ describe("readStdinIfAvailable (spawned subprocess)", () => {
109109

110110
// Negative control: a producer slow enough to miss the first-byte window
111111
// should yield "" (intentional cutoff, no truncation of in-flight data).
112+
// 1200ms > 500ms timeout with margin for CI scheduler latency.
112113
test(
113114
"returns empty when first byte arrives after the first-byte timeout",
114115
async () => {
115116
const { code, result } = await runFixture({
116117
writeStdin: async (sink) => {
117-
await new Promise((r) => setTimeout(r, 400))
118+
await new Promise((r) => setTimeout(r, 1200))
118119
try {
119120
sink.write("too late")
120121
await sink.end()
@@ -124,6 +125,6 @@ describe("readStdinIfAvailable (spawned subprocess)", () => {
124125
expect(code).toBe(0)
125126
expect(result).toBe("")
126127
},
127-
10000,
128+
15000,
128129
)
129130
})

‎packages/opencode/test/util/stdin.test.ts‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ describe("readStdinIfAvailable", () => {
8484
isTTY: false,
8585
fstat: () => fifo,
8686
readStdin: async () => "", // simulates first-byte timeout
87+
warn: () => {}, // silence the stderr note in test output
8788
})
8889
expect(out).toBe("")
8990
})
@@ -107,6 +108,7 @@ describe("readStdinIfAvailable", () => {
107108
isTTY: false,
108109
fstat: () => fifo,
109110
readStdin: async () => "",
111+
warn: () => {},
110112
})
111113
expect(out).toBe("")
112114
})
@@ -119,6 +121,116 @@ describe("readStdinIfAvailable", () => {
119121
})
120122
expect(out).toBe(" \n\t ")
121123
})
124+
125+
// PR #937 / dev-punia review: `process.stdin` can be undefined in
126+
// embedded/child runtimes. The helper must not throw when accessing
127+
// `process.stdin.isTTY` in that case.
128+
test("returns empty when process.stdin is undefined (embedded/child runtime)", async () => {
129+
const original = process.stdin
130+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
131+
;(process as any).stdin = undefined
132+
try {
133+
const out = await readStdinIfAvailable()
134+
expect(out).toBe("")
135+
} finally {
136+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
137+
;(process as any).stdin = original
138+
}
139+
})
140+
141+
// Sury PR #935 review #2: silent drop is bad UX. When fd 0 looked like
142+
// real input but no first byte arrived, warn so the user knows.
143+
test("warns when stdin looked like input but readStdin returned empty (silent-drop fix)", async () => {
144+
const seen: string[] = []
145+
const out = await readStdinIfAvailable({
146+
isTTY: false,
147+
fstat: () => fifo,
148+
readStdin: async () => "",
149+
warn: (msg) => seen.push(msg),
150+
})
151+
expect(out).toBe("")
152+
expect(seen).toHaveLength(1)
153+
expect(seen[0]).toContain("stdin appears piped")
154+
expect(seen[0]).toContain("ALTIMATE_STDIN_TIMEOUT_MS")
155+
})
156+
157+
test("does NOT warn when isTTY (no pipe to drop in the first place)", async () => {
158+
const seen: string[] = []
159+
const out = await readStdinIfAvailable({
160+
isTTY: true,
161+
readStdin: async () => "",
162+
warn: (msg) => seen.push(msg),
163+
})
164+
expect(out).toBe("")
165+
expect(seen).toHaveLength(0)
166+
})
167+
168+
test("does NOT warn when fstat says char device (/dev/null) — intentional skip", async () => {
169+
const seen: string[] = []
170+
const out = await readStdinIfAvailable({
171+
isTTY: false,
172+
fstat: () => charDev,
173+
readStdin: async () => "",
174+
warn: (msg) => seen.push(msg),
175+
})
176+
expect(out).toBe("")
177+
expect(seen).toHaveLength(0)
178+
})
179+
180+
test("does NOT warn when stdin delivered data (no drop happened)", async () => {
181+
const seen: string[] = []
182+
const out = await readStdinIfAvailable({
183+
isTTY: false,
184+
fstat: () => fifo,
185+
readStdin: async () => "ctx",
186+
warn: (msg) => seen.push(msg),
187+
})
188+
expect(out).toBe("ctx")
189+
expect(seen).toHaveLength(0)
190+
})
191+
192+
// Sury PR #935 review #2: env override for slow-pipeline users.
193+
test("ALTIMATE_STDIN_TIMEOUT_MS env override is forwarded to readStdin", async () => {
194+
const original = process.env["ALTIMATE_STDIN_TIMEOUT_MS"]
195+
process.env["ALTIMATE_STDIN_TIMEOUT_MS"] = "2500"
196+
let observed: number | undefined
197+
try {
198+
await readStdinIfAvailable({
199+
isTTY: false,
200+
fstat: () => fifo,
201+
readStdin: async (ms) => {
202+
observed = ms
203+
return "data"
204+
},
205+
warn: () => {},
206+
})
207+
} finally {
208+
if (original === undefined) delete process.env["ALTIMATE_STDIN_TIMEOUT_MS"]
209+
else process.env["ALTIMATE_STDIN_TIMEOUT_MS"] = original
210+
}
211+
expect(observed).toBe(2500)
212+
})
213+
214+
test("ALTIMATE_STDIN_TIMEOUT_MS falls back to default when unparseable", async () => {
215+
const original = process.env["ALTIMATE_STDIN_TIMEOUT_MS"]
216+
process.env["ALTIMATE_STDIN_TIMEOUT_MS"] = "not-a-number"
217+
let observed: number | undefined
218+
try {
219+
await readStdinIfAvailable({
220+
isTTY: false,
221+
fstat: () => fifo,
222+
readStdin: async (ms) => {
223+
observed = ms
224+
return "data"
225+
},
226+
warn: () => {},
227+
})
228+
} finally {
229+
if (original === undefined) delete process.env["ALTIMATE_STDIN_TIMEOUT_MS"]
230+
else process.env["ALTIMATE_STDIN_TIMEOUT_MS"] = original
231+
}
232+
expect(observed).toBe(500)
233+
})
122234
})
123235

124236
describe("assembleStdinMessage", () => {

0 commit comments

Comments
 (0)