Skip to content

fix: break logger EPIPE feedback loop — async stderr error re-enters uncaughtException (#1233) - #1240

Merged
ranxianglei merged 1 commit into
masterfrom
2026-09-24_fix-logger-epipe-loop
Sep 24, 2026
Merged

ranxianglei merged 1 commit into
masterfrom
2026-09-24_fix-logger-epipe-loop

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Sep 24, 2026 •

Copy link
Copy Markdown
Owner

Fixes #1233

Root cause (verified with minimal repro)

On Linux process.stderr over a pipe is an async stream: EPIPE surfaces as an error event, not a sync throw, so the try { process.stderr.write(line) } catch {} guard in src/logger.ts never saw it. No error listener was attached, so each event rethrew as uncaughtException → the top-level handler (src/server.ts) logged it through the logger → another stderr write → another EPIPE event — a tight feedback loop.

Repro A/B (child process emulating the proxy: real logger + same uncaughtException handler shape; parent destroys the stderr pipe mid-run):

before after
uncaughtException handler fired 31,836× in ~2.8s 0
log file growth 42,595 lines / 3MB in ~4s 40 lines / 1.8KB
EPIPE spam lines in file thousands 0
degradation [warn] lines 0 exactly 1

Fix (root cause)

Invariant enforced: the logger's error path must never re-enter the writer that produced the error.

  • src/logger.ts: module-init process.stderr.on("error", …) listener flips logging to file-only once, with a single [warn] stderr unavailable (write EPIPE); continuing with file-only logging. Sync write failures (Windows sync stderr) take the same path via the existing catch. After the flip, log() skips stderr entirely — no re-entry, no repeated throws.
  • src/server.ts: belt-and-suspenders — the uncaughtException handler classifies stream-write errors (isStreamWriteError: EPIPE/EIO/EBADF/ERR_STREAM_DESTROYED), logs the first one, suppresses repeats. Protects against any writer outside the logger hitting a dead stream.

Behavior change (intended — flagged per policy)

When the stderr consumer closes (client crash, terminal closed, piped reader exit):

  • Old: unbounded uncaughtException: Error: write EPIPE spam loop — every iteration wrote to the log file (77MB in minutes observed), churning 10MB rotation until the forensic window was wiped; CPU pegged per closed pipe.
  • New: one [warn] line in the log file, then silent file-only logging; the process keeps running normally. Non-logger stream-write uncaughtExceptions: first is logged, repeats suppressed (previously every one was logged).

No wire/message-shape change; both compression modes unaffected (logger + crash-handler scope only).

Pre-flight (rebased head on current master)

  • npm run typecheck — green
  • npm test — 2397 pass / 0 fail / 2 skipped, except 4 failures in tests/claude-native.test.ts that are pre-existing environment issues (live-ps-walk / spawned-host e2e): verified the identical failure set on pristine master without this PR.
  • npm run build — green
  • New regression test (tests/logger-epipe.test.ts) verified red on unpatched code, green with the fix.
  • E2E suite not run from this sandbox (needs the documented local upstream default, unreachable here); the diff touches no request-path/wire code — module-init listener + crash-handler branch only.

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-24_fix-logger-epipe-loop (d57a087)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-1240

Each push to this PR publishes a new version under the pr-1240 npm tag.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr1240.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到。这是带 ework-agent-pr 标记的已完成工作,我不重做——当前在按 PR Review 规范核验:拉取分支核对代码、验证回归测试红/绿、重跑 pre-flight(typecheck/test/build)、检查 CI 状态与 diff 整洁度,随后给出结论。

…uncaughtException (#1233)

On Linux, stderr over a pipe is an async stream: EPIPE surfaces as an 'error' event, not a sync throw, so the try/catch around process.stderr.write() never saw it. Unhandled, each event rethrew as uncaughtException, the top-level handler logged it through the logger, and the loop spammed bili.log (77MB in minutes observed) until 10MB rotation wiped the forensic window.

- logger.ts: module-init 'error' listener on process.stderr flips logging to file-only once (single [warn]); sync write failures (Windows) take the same path; log() skips stderr after the flip so the logger's error path never re-enters the writer that produced the error.
- server.ts: uncaughtException handler logs the first stream-write error and suppresses repeats (belt-and-suspenders for non-logger writers).
- tests/logger-epipe.test.ts: spawn-based regression (closed stderr pipe -> no storm, durable record intact, exactly one warn) + predicate unit test. Red on unpatched code, green with the fix.
@ranxianglei
ranxianglei force-pushed the 2026-09-24_fix-logger-epipe-loop branch from 728f4ac to d57a087 Compare September 24, 2026 03:08
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Review complete — verified, rebased to current master, mergeable.

Per the agent-PR protocol I did not redo the work; I audited code + behavior against #1233 and re-ran everything on the live master. Summary by review gate:

① Direction (issue first). Root cause, not mask ✓. I reproduced the mechanism on unpatched code: piped Linux stderr is an async stream, so EPIPE arrives as an error event that the old try { write } catch {} never sees; with no listener it rethrows as uncaughtException, the top-level handler logs through the logger, which writes stderr again — the loop. The fix enforces the right invariant (the logger's error path never re-enters the writer that produced the error) at the source (module-init listener + once-flag), not by filtering payload in transit. Both compression modes and wire shape are untouched (logger + crash-handler scope only).

② Regression review. Inventoried every existing behavior the diff touches:

  • log() file path, rotation, log format: unchanged.
  • Sync stderr failure (Windows): previously swallowed silently forever → now emits exactly one [warn] then file-only. Intended, already flagged in the PR body.
  • Global side effect: any process importing logger.ts (proxy, CLI commands, MCP children) now absorbs stderr stream errors instead of dying via uncaughtException. Consistent with the "logging can never crash" contract; grep confirms no code depends on stderr errors surfacing.
  • Non-stream-write uncaughtExceptions: logging unchanged.
  • src/preflight.ts:675 EPIPE is an unrelated network-code set; tests/proxy-stream-error.test.ts throws plain Error("write EPIPE") without .code, so the new classifier can't misfire there.

③ Code. Listener is idempotent (stderrDead guard), attached once at module init before any write; warnReopenFailed correctly skips stderr when dead; the uncaughtException dedup (src/server.ts:579) logs the first stream-write error, suppresses repeats, and only matches the four dead-stream codes (EPIPE/EIO/EBADF/ERR_STREAM_DESTROYED) — a genuinely novel stream error still gets its first log line. No silent clobbering of diagnostics.

④ Tests. Real teeth, independently verified:

  • Red: with the logger reverted to pre-patch (only the export shim added), the new test fails with FIRED 35181 — it reproduces the actual storm from logger EPIPE feedback loop: async stream error re-enters uncaughtException handler — 77MB spam, rotation destroys forensic logs #1233. Green: patched code → FIRED 0, exit 0, exactly one [warn] matching both /stderr unavailable/ and /file-only/. A tautological test couldn't have produced that delta.
  • Full suite on the rebased head: 2440 tests / 2435 pass / 3 fail / 2 skipped. The 3 failures are all in tests/claude-native.test.ts (live-ps-walk / spawned-host e2e) — I ran pristine master in a separate worktree and got the identical failure set, so they are pre-existing sandbox environment issues, not caused by this PR. Typecheck green, build green.
  • CI on the original head was fully green (ubuntu+windows × node 22/24, version-guard, codex e2e zero-token, build-artifact).

⑤ Diff. Single commit, 3 files, 160+/14-, every line in scope; no version/lockfile/generated churn.

One action taken: master moved several commits during review (v0.1.145 release, image-compression work landed), so I rebased the branch onto current master (3767e9eb) and force-pushed the updated head d57a087a — clean rebase, identical diff content, full pre-flight re-run on the new head (all green except the known env failures above). Fresh CI is running on it.

Minor observation (non-blocking, no change made): the unhandledRejection handler doesn't get the same repeat-suppression for stream-write rejections. It's not a feedback loop — the logger flips file-only on the first stderr error event regardless of which writer hit the pipe — so any such spam is bounded by an external writer's failure rate. If you want symmetric treatment there it's a ~5-line follow-up; left out of this PR deliberately to keep scope tight.

Verdict: root cause correctly identified and fixed at the source, regression test has teeth, no unintended behavior drift beyond what's flagged, clean diff, green on current master. Mergeable.

中文摘要:修复了日志器 stderr EPIPE 反馈环(异步管道的 EPIPE 以 error 事件重抛为 uncaughtException,处理器再写日志形成死循环、数分钟刷爆 77MB 日志并冲掉取证窗口)——根因是缺少 stderr error 监听器,修复在模块初始化时挂监听并一次性降级为纯文件日志(仅一条 [warn]),另在崩溃处理器里对死流写错误做首记后抑制;已独立验证回归测试红绿差异(未修复代码 FIRED 35181 vs 修复后 0)、rebase 到当前 master 后全量测试通过(仅有的 3 个失败为沙箱预存环境问题,与 PR 无关),可以合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Follow-up: fresh CI on the rebased head d57a087a is all green — test matrix (ubuntu+windows × node 22/24), version-guard, codex e2e zero-token, pi package-native lane, codex CODEX_HOME overlay, build-artifact. Nothing outstanding on this PR; ready for human merge whenever.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

logger EPIPE feedback loop: async stream error re-enters uncaughtException handler — 77MB spam, rotation destroys forensic logs

1 participant