Skip to content

[PR] fix: event-loop-watchdog survives an OS freeze instead of self-exiting into a dead port - #7493

Open
ranxianglei wants to merge 6 commits into
masterfrom
2026-11-22_watchdog-freeze-detection
Open

ranxianglei wants to merge 6 commits into
masterfrom
2026-11-22_watchdog-freeze-detection

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

What

On an unattended suspending device (phone, NAS, deep-sleep laptop) the OS freezes the WHOLE process — main thread AND worker. The event-loop watchdog's worker could not tell that freeze apart from a genuine main-thread wedge, so it tripped on the accumulated silence and SIGKILLed the lane into a dead port with no spawner left to respawn it. The port then sat dead for hours until the next session started (the reporter's repro: a Claude Code native lane on an Android chroot, frozen overnight, ECONNREFUSED on the next-morning first request).

A second, independent defect surfaced in the same thread: when the /proc walk misses the claude host (e.g. under herdr/tmux/mosh session holders on Android chroot), the watcher pins to the direct parent — a long-lived ancestor (interactive bash, herdr-core) that outlives the claude session. The anti-orphan contract is voided: the lane survives the session exit indefinitely (21h observed).

Why this fix

Freeze detection: The worker's OWN tick interval is the signal that separates the two cases:

  • Real wedge (main thread blocked, worker fine): the worker keeps ticking on schedule, so its tick gap stays near checkIntervalMs.
  • OS freeze (whole process suspended): the worker misses its own ticks, so its tick gap jumps.

When the tick gap exceeds 2× checkIntervalMs the worker now resets lastBeat/warned/tripped and logs an info line instead of tripping, so the lane survives the freeze and is still alive when the device wakes — the next session attaches to it instead of racing a cold spawn. A genuine wedge that happens to span a freeze is delayed by one freeze cycle, never masked permanently: after the reset the heartbeat gap grows again from the fresh baseline and trips as before.

Anti-orphan: When the walk misses and the direct parent is not a transient shell, chooseWatchdogParentPid now returns undefined instead of the parent pid. The watcher arms without a parent pid (gated on BILI_LAUNCHER_LANE so daemons stay daemons) and relies on the MCP child to register itself via POST /__bili/watcher. The lane dies when the MCP child dies (session end), which is the correct anti-orphan behavior. The startup gap (set empty before the MCP child registers) is handled with an everHadWatcher flag that defers the idle grace period until the first registration.

Changes

  • src/event-loop-watchdog.ts: add watchdogFreezeVerdict (pure, unit-tested) + the worker-side isFrozen check in tick(); store checkIntervalMs and track lastWorkerTick in the worker; document the behavior in the module header.
  • tests/event-loop-watchdog.test.ts: add the watchdogFreezeVerdict boundary test. The existing wedge test still trips, confirming no false-positive on a real wedge.
  • src/claude-native-bootstrap.ts: chooseWatchdogParentPid returns number|undefined — undefined when the walk misses and the direct parent is not a transient shell (was: the parent pid). Debug log updated.
  • src/launcher.ts: watchPid = opts.parentPid (no fallback to process.pid); BILI_PARENT_PID = String(opts.parentPid ?? ""); registerOwner returns "refused" when watchPid is undefined; all startOwnerHeartbeat calls guarded with watchPid !== undefined; markWatcherPendingRecovery cast.
  • src/server.ts: laneWatcherArmed = initialWatcherPid !== null || BILI_LAUNCHER_LANE !== undefined; everHadWatcher flag defers idle grace until first watcher registration.
  • src/server/admin.ts: POST /__bili/watcher allows registration when BILI_LAUNCHER_LANE is set (even if initialWatcherPid is null).
  • tests/claude-native.test.ts: updated the legacy direct-parent test to expect undefined (new behavior).
  • docs/configuration.{md,zh-CN.md,ja.md} + docs/lifecycle.md: clarify BILI_NATIVE_CLAUDE=0 is passthrough (the lane still starts, compression off) — it does NOT prevent the lane from starting, unlike the other BILI_NATIVE_* lanes where =0 turns the lane off entirely. (Drive-by: the lifecycle line lumped claude in with the others as =0 整体退出, which was wrong for claude.)
  • docs/technical-notes.{md,zh-CN.md,ja.md}: note the unattended/suspending-device behavior — the lane now survives an OS freeze, but its self-heal after a genuine wedge still depends on a session being present; for maximum robustness on such devices the daemon posture + external supervisor is still the safest choice.

Behavior change

Freeze detection:

  • Old: on an OS freeze longer than the 300s hard threshold, the lane self-exited (SIGKILL), leaving its port dead with no spawner to respawn it (hours of ECONNREFUSED on an unattended device).
  • New: on an OS freeze, the worker resets its baseline and the lane stays alive; it only trips on a genuine main-thread wedge (worker tick gap stays on schedule). A genuine wedge spanning a freeze is detected one freeze cycle later, not never.

Anti-orphan:

  • Old: when the /proc walk missed the claude host, the watcher pinned to the direct parent (long-lived ancestor → lane survives indefinitely).
  • New: when the walk misses, the watcher arms without a parent pid → lane dies at session end (MCP child death). This is the intended fix for the 21h lane survival observed in the thread.

Not in this PR (needs owner decision)

What the watchdog should do on a genuine wedge + no spawner (not an OS freeze, e.g. a real deadlock on an unattended host): keep self-exiting (status quo) / self re-exec / a built-in bili supervise. Tracked in a separate decision-request issue; this PR does not change that path.

Closes #7482

ci-check added 3 commits November 22, 2026 02:00
…ck gap and resets its baseline instead of self-exiting (#7482)

On an unattended suspending device (phone, NAS, deep-sleep laptop) the OS
freezes the WHOLE process — main thread AND worker. The watchdog worker could
not tell that freeze apart from a genuine main-thread wedge, so it tripped on
the accumulated silence and SIGKILLed the lane into a dead port with no
spawner left to respawn it (the port then sat dead for hours).

The worker's OWN tick interval is the signal: on a real wedge the worker keeps
ticking on schedule, but on a freeze it misses its own ticks. When the tick
gap exceeds 2x checkIntervalMs the worker now resets lastBeat/warned/tripped
and logs an info line instead of tripping, so the lane survives the freeze and
is still alive when the device wakes. A genuine wedge spanning a freeze is
delayed by one freeze cycle, never masked: the heartbeat gap grows again from
the fresh baseline and trips as before.

Adds watchdogFreezeVerdict (pure, unit-tested) and the worker-side isFrozen
check. The existing wedge test still trips, confirming no false-positive on a
real wedge.
…, not off (#7482)

BILI_NATIVE_CLAUDE=0 opts the claude lane into passthrough mode (compression
fully off) — the lane STILL starts and binds its port. It does NOT prevent the
lane from starting, unlike the other BILI_NATIVE_* lanes where =0 turns the
lane off entirely. The configuration table (en/zh/ja) said only 'marks a
claude-native plugin process' with no =0 semantics, and lifecycle.md lumped
claude in with the others as '=0 整体退出' — both wrong for claude. Split the
lifecycle row to state claude's passthrough behavior separately.
…#7482)

Adds a note to the claude-native section (en/zh/ja): the lane's watchdog now
survives an OS freeze (the worker resets its baseline instead of self-exiting),
so a lane alive when the device slept is still alive when it wakes. But the
lane's self-heal still depends on a session being present to trigger a respawn
after a genuine (non-freeze) wedge — on an unattended device with no session,
a wedged lane leaves its port dead until the next session. For maximum
robustness on such devices, the daemon posture (bili start + an external
supervisor) is still the safest choice.
@ranxianglei ranxianglei added bug Something isn't working claude p2 scope/other labels Nov 21, 2026
@ranxianglei ranxianglei changed the title fix: event-loop-watchdog survives an OS freeze instead of self-exiting into a dead port [PR] fix: event-loop-watchdog survives an OS freeze instead of self-exiting into a dead port Nov 21, 2026
@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-11-22_watchdog-freeze-detection (9d627b1)

Latest build — install this exact version

npm install -g billion-context@0.0.11462-pr.7493.41d621c

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Recent builds (commit → version)

commit version build
9d627b1 billion-context@0.0.11462-pr.7493.41d621c build
6740711 billion-context@0.0.11391-pr.7493.d36f90c build
66dd04c billion-context@0.0.11265-pr.7493.f64ce33 build
2b2301a billion-context@0.0.11259-pr.7493.721c436 build

Download artifact

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

Install instructions are refreshed on each push.

… so docs-sync regeneration is drift-free (#7482)

The passthrough clarification landed as a hand-edit of the GENERATED
docs/configuration.{md,zh-CN.md,ja.md} tables, while the yaml seed kept
the old one-line description — docs-sync regenerates from the seed and
fails on the drift. Move the text into the seed (verified against
src/claude-native-bootstrap.ts:71 and src/agent/native-bootstrap.ts:22);
regeneration now reproduces the committed tables byte-for-byte.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

Reviewed PR #7493 (event-loop-watchdog OS-freeze detection, fixes #7482). The core fix is sound and correct; the one CI red (docs-sync) is already resolved.

Core fix — correct. The discriminator is the worker's own tick interval, which is valid because the watchdog is a worker_threads Worker with an independent event loop:

  • Real wedge (main thread blocked): the worker keeps ticking on schedule (tick gap ≈ checkIntervalMs); only the main-thread heartbeat stops → gap grows → trips. ✓
  • OS freeze (whole process suspended): the worker's own timer is frozen too, so on wake its tick gap jumps → detected as a freeze → baseline reset, no trip. ✓

The 2× threshold (10s default) is far below the 300s hard timeout, so any freeze long enough to cause a false trip is caught first. A genuine wedge spanning a freeze is delayed one freeze cycle, never masked permanently. Verified by reading the code and running the targeted test: watchdogFreezeVerdict passes, and the existing wedge test still trips (no false-positive on a real wedge). (The one local test failure is the exit mode child-spawn test, which needs tsx installed — a local-env artifact, not a code bug; it runs on CI.)

docs-sync — was red, now fixed. The PR's drive-by doc change edited the generated docs/configuration.*.md directly without updating the seed (website/config-reference/env-only.yaml), so the docs-sync drift guard (#2107) went red and cancelled all downstream test lanes. A parallel agent already pushed the correct seed fix (66dd04cea22); I independently reproduced it and confirmed it is byte-identical to mine and that docs-sync now passes. I did not push my duplicate.

CI state (live, head 66dd04cea22): docs-sync green; the full test lanes are running (3 in progress, 8 queued, no failures). The watchdog test is covered by those lanes.

结构化八问

  1. 是什么问题: 无人值守的休眠设备(手机/NAS/深睡笔记本)上,OS 冻结整个进程(主线程+worker)。watchdog 的 worker 分不清「OS 冻结」和「真·主线程 wedge」,在累积静默上 trip,SIGKILL 掉 lane,留下没有 spawner 能重生的死端口(唤醒后数小时 ECONNREFUSED)。
  2. 什么原因导致的: 判据只看主线程心跳 gap,缺了「worker 自身是否还在正常 tick」这一维。OS 冻结时主线程当然也不发心跳,gap 累积到 300s 就误 trip——但进程没死,只是被挂起,自退反而杀死了活着的 lane。
  3. 影响范围与严重程度: 仅影响无人值守 + 会休眠/冻结设备上的 native lane。触发条件:冻结时长 > 300s 硬阈值。p1 级可用性(该场景下 lane 直接不可用、端口死到下个会话);有会话在场的常规桌面场景不受影响(那种 wedge 自退是设计本意)。
  4. 怎么修复的: 用 worker 自身 tick 间隔判别——真 wedge 时 worker 独立 tick 照常、只有心跳停;冻结时 worker 自己的 tick 也漏、醒来间隔跳变。间隔 > 2×checkIntervalMs 判为冻结,重置 lastBeat/warned/tripped 基线 + 记一条 info 日志,不 trip。
  5. 是否有回归问题: 无。逐项过:真 wedge 仍 trip(现有测试本地实跑确认)、健康流不 trip、300s/30s/5s 阈值与心跳时序全未动、冻结是「重置基线+记日志」而非吞 wedge 信号(真 wedge 在新基线上重新累积仍会 trip)、warn/FATAL 行格式未变(只新增一条 info 行)。
  6. 是否破坏缓存: 不涉及。watchdog 是进程级安全定时器,与 prompt/压缩缓存、增量游标无关。
  7. 是否改了设计方向: 不涉及。watchdog 本意(检测真 wedge、自退让 spawner 重生)不变,只是「冻结 vs 真 wedge」判别更准。genuine wedge + 无 spawner(真死锁、非冻结)本 PR 不改,已单独立 decision-request 等 owner 拍板。
  8. 是否引入了新的配置: 不涉及。阈值仍硬编码(模块头明确不为内部安全定时器开 owner-gated 配置面)。唯一「行为变更」是 docs 侧把 BILI_NATIVE_CLAUDE=0 澄清为 passthrough(lane 仍启动、压缩关)——文档勘误,非新配置。

合并判定: 核心修复正确、无回归、测试到位;docs-sync 红已修(并行 agent 已推入、与我独立复现逐字节一致)。等全量 test lane 跑完(CI 当前无失败)即可合。

ranxianglei pushed a commit that referenced this pull request Nov 21, 2026
Review of the PR diff: all 11 cross-references added by the fix point at
#7493, which is a different PR (event-loop-watchdog OS-freeze fix). The
issue this PR closes is #7491 (hermes pid registered without owner
heartbeats). Comments and docs-only change, no behavior.
Field instrumentation for the anti-orphan gap: on hosts where the /proc
walk and the sh -c fallback both miss the claude host, the parent watcher
silently points at a long-lived ancestor and the lane outlives every
session. Record the chosen pid (and the direct parent for comparison) in
the hook log so the exact fallback can be pinned with one instrumented
spawn.
… undefined instead of the direct parent (#7482)

The chooseWatchdogParentPid fallback returned the direct parent pid when
the /proc walk missed the claude host. On Android chroot and other
session-holder environments (herdr, tmux, mosh), the direct parent is a
long-lived ancestor (interactive bash, herdr-core) that outlives the
claude session — the watcher pins to it and the anti-orphan contract is
voided: the lane survives the session exit indefinitely.

Fix: return undefined when the walk misses and the direct parent is not
a transient shell. The watcher arms without a parent pid (gated on
BILI_LAUNCHER_LANE so daemons stay daemons) and relies on the MCP child
to register itself via POST /__bili/watcher. The startup gap (set empty
before the MCP child registers) is handled with an everHadWatcher flag
that defers the idle grace period until the first registration.

Files:
- src/claude-native-bootstrap.ts: chooseWatchdogParentPid returns
  number|undefined; debug log updated.
- src/launcher.ts: watchPid = opts.parentPid (no fallback to process.pid);
  BILI_PARENT_PID = String(opts.parentPid ?? ); registerOwner returns
  "refused" when watchPid is undefined; all startOwnerHeartbeat calls
  guarded with watchPid !== undefined; markWatcherPendingRecovery cast.
- src/server.ts: laneWatcherArmed = initialWatcherPid !== null ||
  BILI_LAUNCHER_LANE !== undefined; everHadWatcher flag defers idle
  grace until first watcher registration.
- src/server/admin.ts: POST /__bili/watcher allows registration when
  BILI_LAUNCHER_LANE is set (even if initialWatcherPid is null).
- tests/claude-native.test.ts: updated the legacy direct-parent test to
  expect undefined (new behavior).

This branch has not been deployed

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

Labels

bug Something isn't working claude p2 scope/other

Projects

None yet

1 participant