Skip to content

[PR] fix(hermes): stop losing /acp and all tools on cold start — move the slow proxy boot off register() - #4645

Closed
ranxianglei wants to merge 14 commits into
masterfrom
2026-10-25_4641-hermes-cold-start-register-budget
Closed

ranxianglei wants to merge 14 commits into
masterfrom
2026-10-25_4641-hermes-cold-start-register-budget

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Summary

Hermes cold start (no running bili proxy to attach to) loses /acp, /acp-cache and every bili tool entirely. The host gives each plugin a fixed load budget (plugins.load_timeout_seconds, default 10s) around import+register; a cold register() always exceeds it (health-poll up to SPAWN_WAIT_S=10s, then GET /manifest up to 5s), so the host discards the whole plugin (disposes every registration) and later register_tool calls become no-ops. Attaching to an already-running proxy is millisecond-level — which is exactly why "start bili manually first, then hermes" always worked.

Fix

Split register() into a fast path and a background path:

  • register() now only wires the cheap always-on surfaces (llm_request middleware, pre_api_request hook, /acp + /acp-cache, an unload hook), starts the slow work on a daemon thread, and returns inside a bounded wait (REGISTER_WAIT_S = 4.0) — comfortably under the host's 10s budget.
  • _bootstrap() (daemon thread) runs attach-or-spawn + manifest fetch + tool registration under one monotonic deadline (BOOTSTRAP_BUDGET_S = 90.0), replacing the old per-stage waits that summed in the worst case.
  • First LLM request blocks a bounded window (FIRST_REQUEST_WAIT_S = BOOTSTRAP_BUDGET_S + 15.0) for readiness, then rides wire mode only if the boot has not landed — never a silent direct-connect.
  • Each register()/re-enable mints a fresh bootstrap generation (stop/ready threading.Events): an unload aborts an in-flight boot, and a re-enable boots fresh instead of dying on a stale stop signal.

Also fixes latent defects on this path: two never-defined constants (BOOTSTRAP_SPAWN_WAIT_S would have been a NameError; the other caused the silent direct-connect), and the TOCTOU where an unload could still land a late register_tool / apply_env on a dead plugin.

Behavior change (old → new)

Before After
register() latency (cold) blocks up to ~15s; over 10s ⇒ whole plugin discarded returns within ~4s; slow boot continues in the background
Round 1 (first LLM request) always wire mode (returns None immediately) waits a bounded window for a fast boot; wire mode only if the boot has not landed
Cold-start outcome /acp + all tools silently gone plugin survives; tools arrive once the background boot finishes
Registrations tools only + an unload hook (best-effort; skipped on hosts that reject it)

All intentional — this is the fix. Worst case (boot genuinely stuck) the first request waits at most FIRST_REQUEST_WAIT_S then proceeds in wire mode, so availability is preserved.

Tests

tests/hermes-native.test.ts (targeted; runs the real plugin in a subprocess):

  • slow-boot: a proxy that comes up ~4s after spawn (slower than the shrunk REGISTER_WAIT_S). Asserts register() returns in <4s (stays under the host budget) and the tools land once the background boot finishes — the regression pin.
  • re-enable: register → unload → register again; asserts the second enable boots a fresh generation and restores the tools. Negative control verified: forcing the new epoch to reuse the previous (already-stopped) stop event makes this test red.
  • Existing attach/spawn/discover/gate/no-sidecar scenarios stay green; the hooks assertion now includes the new unload hook.

Local, on the rebased head (current master): node --import tsx --test tests/hermes-native.test.ts → 40/40; npm run typecheck clean; python -m py_compile hermes-plugin/__init__.py clean.

Scope

  • Hermes plugin lane only (hermes-plugin/__init__.py + its test). No other client lanes touched.
  • No config schema / env var / CLI flag change (the three timeouts are module constants, not user-configurable). No wire/message-shape change, no kernel/ change, no persistence change.

Closes #4641

…kground bootstrap (#4641)

The host gives each plugin a fixed load budget (plugins.load_timeout_seconds,
default 10s) around import+register; exceeding it makes the host discard the
ENTIRE plugin (every registration disposed), so a cold-start whose proxy took
longer than 10s silently lost /acp, /acp-cache and every tool.

register() now only wires the cheap always-on surfaces (llm_request middleware,
pre_api_request hook, /acp + /acp-cache, unload hook) and returns inside a bounded
wait; the attach-or-spawn + manifest + tool registration runs on a daemon thread
under ONE monotonic deadline (BOOTSTRAP_BUDGET_S). Each register()/re-enable mints
a fresh bootstrap generation (stop/ready Events) so an unload aborts an in-flight
boot and a re-enable boots fresh. The first LLM request blocks a bounded window for
the boot, then rides wire mode only if it has not landed.
@ranxianglei ranxianglei changed the title fix(hermes): stop losing /acp and all tools on cold start — move the slow proxy boot off register() [PR] fix(hermes): stop losing /acp and all tools on cold start — move the slow proxy boot off register() Oct 25, 2026
@github-actions

github-actions Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-10-25_4641-hermes-cold-start-register-budget (0d5b1d3)

Latest build — install this exact version

npm install -g billion-context@0.0.5976-pr.4645.5b4292b

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
0d5b1d3 billion-context@0.0.5976-pr.4645.5b4292b build
b2a4921 billion-context@0.0.5687-pr.4645.7980c1d build
8694b20 billion-context@0.0.5681-pr.4645.6cfca26 build

Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr4645.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

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

查重: 不重复。#4645 是修复 #4641(hermes 冷启动后 /acp + 全部 bili 工具消失)的 PR。与既有 hermes 条目 #2714(spawn 临时端口后 HTTPS_PROXY 指向死端口)、#4282(全局自更新不刷新 Python 侧插件副本)症状/机制都不同——本 PR 针对的是「冷启动时 register() 同步阻塞超过宿主 10s 加载预算,整个插件被宿主回收」。

标签: 已打 bug hermes scope/wiring p1(缺陷;hermes 接入层;冷启动时 bili 在 hermes 上核心能力整体静默失效 = 可用性缺陷 p1)。

独立审核(不复读 issue/PR 描述,逐行读了 diff;base=bd29924d4,单 commit 8694b20):

方向对、主修复成立。把 register() 拆成「廉价快注册 + 后台 bootstrap 线程」正是对的——它解决的是根因(宿主固定 10s 预算内 register() 必须返回),不是把某个工具提前注册来碰运气。warm attach 仍在有界等待内完成,各 fail-open 场景终态一致。slow-boot / re-enable 两个测试是真测试(子进程驱动、断言真实工具注册+时序+env),slow-boot 那个钉住前修复会红。

但发现一个真实的正确性缺口——本 PR 自己宣称的机制没完全兑现:

register() 铸造新 bootstrap 代的守卫是:

epoch = _state.get("epoch")
if epoch is None or epoch["ready"].is_set():
    epoch = _new_epoch(); start_thread(...)

竞态:第一次冷启动还在后台跑(ready 未 set)→ 宿主 unload(_on_unload 只 set stop,不 set ready)→ 立刻 re-enable。此时旧代 ready 还没 set、stop 已 set → 守卫判 False → 不铸新代、不起新线程,只是 wait(4s)。等旧线程被 stop 中止后 ready 才 set,但那时已经不会再起 boot 了。结果这次 re-enable 之后 ACP 工具永远不上线、流量走 wire 模式,直到下一次 re-enable 才自愈(下一轮 ready 已 set → 铸新代)。

现有 re-enable 测试用 fast attach(首启瞬间 settle),unload 时 ready 早已 set,恰好绕开这个窗口——测试绿 ≠ 覆盖到 in-flight 情形。PR 描述的「re-enable boots fresh instead of dying on a stale stop signal」在这个 race 里不成立。

修法很小且无决策依赖:守卫加一项 or epoch["stop"].is_set()——unload 一旦 set stop,后续任何 register 都铸新代起新线程;健康在途(未 stop)仍不误铸(避免双 boot)。我会直接在本 PR 分支补这一行 + 一个确定性回归测试(伪造「stop 已 set、ready 未 set」的旧代,断言 register() 铸了新代并落地工具;无此修复即红)。

另两处小问题(非阻塞):

  1. PR 描述说「顺带修掉两个从未定义的常量(BOOTSTRAP_SPAWN_WAIT_S 会 NameError…)」——我核对了 base 的实际代码:旧代码只有 SPAWN_WAIT_S(有定义且在用),根本没有未定义常量这回事。这些符号来自上游 AI 设计稿(bug(hermes): /acp and plugin tools disappear entirely after cold start — register() blocks beyond the host's 10s load bu | bug(hermes): 冷启动后 /acp 与插件工具整体消失——register() 阻塞超过宿主 10s 加载预算被丢弃 #4641)的臆造,不是 shipped 代码里的真缺陷。代码本身没问题(新引用的三个常量都有定义),只是描述把不存在的问题写成了「已修复」。(正文属用户输入我不改,仅在此指出,建议按事实收敛。)
  2. 中止-重启会在极短窗口内出现 T1(被中止)+T2(新代)并发 ensure_origin;T1 因 stop 已 set 不会 spawn、且会 terminate 自己的 child,T2 独立进行,最终收敛到 fail-open。可接受,记录一下。

CI: head 8694b20 上 static gates/guards/build 全绿;test 分片里失败的 shard 全部落在 node-22(ubuntu+windows 都有),node-24 分片在跑——这个分布不像 hermes 改动引起(那会让含 hermes-native.test.ts 的分片在两个 Node 版本上都红),更像 node-22 级或继承性红。推完修复后复核 #4599/master 确认归因。

下一步: 先在本 PR 分支落 epoch 守卫修复 + 回归测试,本地定向跑 tests/hermes-native.test.ts + py_compile,push additive commit,然后给完整八问结论。

@ranxianglei ranxianglei added bug Something isn't working hermes 改动范围:内核之外的主机侧接线(src/agent 适配器、server 路由、注入拦截)/范围兜底/客户端标签 p1 scope/wiring labels Oct 25, 2026
…ap generation (#4641)

Review of #4645: register()'s generation-mint guard only fired on
`epoch is None or epoch["ready"].is_set()`. An unload sets stop but NOT ready,
so when a re-enable lands while the aborted boot has not yet settled (ready
still unset), no fresh generation was minted and no bootstrap thread started —
the re-enabled plugin sat in wire mode with no ACP tools until the NEXT
re-enable. The existing re-enable test used fast attach (boot settles before
unload), so it never covered this window.

Add `or epoch["stop"].is_set()` so an aborted-but-unsettled generation also
triggers a fresh mint+thread; a healthy in-flight boot (stop unset) still does
not double-boot. Deterministic regression test seeds exactly that state and
asserts a new generation is minted and the tools land; verified red without the
one-line change.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

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

独立审核完成(查重结论见上一条回复:不重复)。结论:代码方向对、可合,但我发现并已在 PR 分支修掉一处 PR 自身引入的新竞态。以下为结构化八问。

结构化八问

  1. 是什么问题:Hermes 冷启动(没有已运行的 bili 代理可挂接)时,/acp、/acp-cache 和所有 bili 工具全部丢失。宿主给每个插件 import+register 一个固定加载预算(默认 10s),而冷启动的 register() 同步阻塞(health-poll 最多 10s + manifest 最多 5s)必然超预算,宿主便把整个插件丢弃(注销所有注册),后续 register_tool 全成空操作。挂到已运行代理只要毫秒级——这正是「先手动起 bili 再起 hermes」一直可用的原因。

  2. 什么原因导致的:根本原因是 register() 的同步时序模型与宿主的固定 10s 预算不匹配:它把慢操作(attach-or-spawn + manifest + 注册工具)全塞进调用栈内同步执行,而且是 all-or-nothing(只有全部成功才注册任何东西),冷启动一旦超时,连中间件/命令都没注册。PR 的修法方向正确(把慢活挪到后台线程);但我在独立审核中发现 PR 自身引入了一处新竞争,已修(见第 4 问)。

  3. 影响范围与严重程度:影响所有走「hermes 冷启动拉起代理」的用户(未预先手动起 bili 的)。严重度 p1——静默彻底丢能力:不是报错,是 /acp 和工具直接消失、流量裸连上游无压缩,用户多半会以为 hermes 坏了。触发条件:冷启动且 spawn+manifest 总耗时超过宿主 10s 预算。

  4. 怎么修复的:

    • PR 原方案(方向正确):register() 拆成快路径(只注册廉价常驻面:llm_request 中间件、pre_api_request hook、/acp+/acp-cache、unload hook)+ 后台守护线程 _bootstrap()(attach-or-spawn+manifest+工具注册,单一 monotonic deadline BOOTSTRAP_BUDGET_S=90s)+ 首个 LLM 请求有界等待(FIRST_REQUEST_WAIT_S=105s)后仅在未就绪时走 wire mode;每次 register()/重新启用铸造一个 bootstrap generation(stop/ready 两个 Event)。
    • 我补的一处修复(review 发现的真 bug):generation 铸造守卫原来只判 epoch is None or epoch["ready"].is_set()。竞态链:首次冷启动还在飞(ready 未置位)→ 宿主 unload(_on_unload 置 stop、不置 ready)→ 立刻重新启用 → 守卫看到 epoch 存在且 ready 未置位 → 不铸新代、不起线程,只干等 4s;被中止的 boot 的 finally 稍后才置 ready,为时已晚 → ACP 工具永不出现,流量 wire-mode 直到下一次重新启用才自愈。既有 re-enable 测试用的是快速 attach(boot 在 unload 前就 settle 了),恰好绕开了这个窗口。修法:守卫加 or epoch["stop"].is_set()——被中止但未 settle 的代也触发新铸造+线程;健康在飞的 boot(stop 未置位)仍不会双启。已加确定性回归测试钉住该窗口。
  5. 是否有回归问题:逐项清点触碰路径的既有行为——

    • 热挂载(attach 到已运行代理):毫秒级,行为不变,仍立即 active。✅
    • Round 1(首请求):有意变更——旧:总是立即 wire mode(返回 None);新:有界等待快速 boot,仅当 boot 未落地才 wire mode。这是修复本身(让首请求有机会吃到压缩),最坏等满 FIRST_REQUEST_WAIT_S 后仍 wire mode,可用性保留。
    • 注册内容:有意变更——新增一个 unload hook(best-effort,宿主拒绝则跳过)。
    • 我加的 stop.is_set() 分支:健康在飞 boot 不受影响(不双启),只在中止场景多铸一代——正是目的。✅
    • apply_env/env_applied:env_applied 是只写簿记(无任何逻辑读取),清除无害。✅
    • 高危模式逐项过:无语义漂移(除上述两处已披露的有意变更)、无 fail-fast 变吞错、无阈值/时序漂移(REGISTER_WAIT_S 从「隐性 ~15s」→ 显式 4s 是修复目标,非漂移)、输出/wire 格式不变。
  6. 是否破坏缓存:不涉及。改动在 hermes 插件生命周期层,不碰前缀缓存接缝/账本/ref/存储布局。

  7. 是否改了设计方向:插件生命周期从「register() 同步全或无」转向「快路径 + 后台 generation 协调」——这是本次修复的必要设计方向(否则无法同时满足「register 快速返回」与「慢 boot 最终完成」)。我补的 fix 在该方向内收口一处竞态,未改方向。

  8. 是否引入了新的配置:无用户可见配置变更。三个超时(REGISTER_WAIT_S/BOOTSTRAP_BUDGET_S/FIRST_REQUEST_WAIT_S)是模块常量,非配置项(符合 Environment Variable Discipline)。

审核补充

  • 测试有效性:本地定向跑 tests/hermes-native.test.ts 41/41 通过(真实子进程跑真插件);tsc --noEmit exit 0;py_compile OK。负控制验证:把我加的那一行还原掉,新测试即红(register() did not mint a fresh generation over an aborted-unsettled epoch (before=7 after=7))——证明该测试真有牙、能抓住这个 bug。既有 slow-boot / re-enable / attach / spawn / discover / gate / no-sidecar 场景保持绿。
  • 描述勘误(非代码问题):PR 正文称「修了两个从未定义的常量(BOOTSTRAP_SPAWN_WAIT_S 会 NameError)」——对照 base bd29924d4 核实:旧代码只有 SPAWN_WAIT_S(已定义),并无 BOOTSTRAP_SPAWN_WAIT_S 或其它未定义常量;这些符号是当初写 bug(hermes): /acp and plugin tools disappear entirely after cold start — register() blocks beyond the host's 10s load bu | bug(hermes): 冷启动后 /acp 与插件工具整体消失——register() 阻塞超过宿主 10s 加载预算被丢弃 #4641 spec 的外部模型幻觉。代码本身没问题(新常量都定义了),只是 PR 描述夸大。按规则我不改写 PR 正文,仅在此标注。
  • 次要(可接受,不处理):abort-restart 会短暂让 T1(被中止)+T2(新)并发跑 ensure_origin;T1 的 stop 置位后不再 spawn 并自行清理子进程,收敛 fail-open。
  • CI:head 上静态门禁(guards/build-artifact/kernel-guard/lane-guard/version-guard 等)全绿;红的都是 node-22 的 test shard(node-24 shard 当时仍在跑)——模式不像 hermes 专属破坏,更像继承性/node-22 红。我已 push 修复到新 head,CI 会重跑;若仍红且明确指向 hermes,再定向排查。

交付状态

  • 我已在 PR 分支追加一个修复 commit b2a492184(fix(hermes): re-enable after an in-flight abort mints a fresh bootstrap generation (#4641)),push 成功(8694b2089..b2a492184 fast-forward)。只动 hermes-plugin/__init__.py + tests/hermes-native.test.ts,无 kernel/、无 config、无 version bump。
  • 判定:代码可合——方向正确、回归受控、测试有牙、CI 继承红待新 head 重跑确认。合并动作按仓库规则由你执行。

ci-check and others added 12 commits October 25, 2026 23:02
…ment

#4316 PR3/3 (restampRefsToLedger) re-homes citation numbers once on every
full-mode cold load; goldens pinning exact ref numbers are born-red. Re-pin
the 7 storage-lane tests (engine-proofs x6 + orphan-recovery x1) modulo that
renumbering — zero production code touched.

- golden-storage-drive.ts: per-turn citation-normalized digest (shaCiteNorm)
  and state digest modulo stripOneTimeAlignment (stateDigestAligned); the
  deep-sort helper is hoisted into golden-canonical.ts for sharing.
- corrupt-index-child.ts: new stripOneTimeAlignment normalizer — strips the
  refLedgerAligned stamp and re-homes refs onto canonical raw-id order so a
  clean full-mode read and the legacy fallback load compare equal.
- storage-engine-proofs.test.ts: wire legs assert shaCiteNorm equality vs
  the legacy restart leg and the committed goldens; state legs assert
  stateDigestAligned; rollback leg now spells BILI_STORAGE_UNIFIED=legacy
  explicitly (#3818 flip: absent resolves to full, deleting the env would
  vacate the legacy path).
- storage-orphan-recovery.test.ts: pins the content-addressable
  byRaw->byRef round-trip instead of a counter-era m00003 literal.
- golden/storage-render/*.json regenerated with shaCiteNorm/stateDigestAligned.

Converges the master-red storage-lane family (#4599 plan A, owner directive).
…dger parity masks

The #4316 one-time renumbering restamped messageRefs but left
state.tokenSnapshot keyed by the OLD refs, so post-restart bodies
carried stale per-message token counts (1.3K vs 1.4K) and the
full-mode-restart wire drifted off the legacy baseline (#4599).

persist.ts: two-pass remap (stage moves, delete old keys, then write
new keys) so entries whose new ref collides with another move's old
ref survive; fires only when superseded refs exist.

Aligned normalizer (corrupt-index-child.ts): the cacheLedger's
segment bookkeeping (be/bl/bs, unfinalized tail line), the derived
agg block, and per-line miss-attribution (prov/seam) are restart
experience, not content — no-restart and restart legs legitimately
differ there. Masked in the aligned view only; raw digests keep
full accounting. Goldens regenerated (stateDigest + aligned).

storage-engine-proofs 12/12, golden-storage-render 5/5 locally.
…persisted state (#4599)

The fork-survival test asserted immediately after the compress tool
response, but the fold lands in the live session state asynchronously
(#3573 replay semantics). Slow CI runners persisted the pre-fold state
('0 block(s) (compressions=0)' cold load) and the deepEqual diverged.
Bounded 5s wait on the in-memory fold; fast machines exit on the first
iteration. Product semantics unchanged.
The #4316 cold-load alignment reads the unified sidecar; its ingest of
just-flushed records completes asynchronously. Slow runners compared
the pre-ingest state and saw refLedgerAligned missing while the fold
itself had landed. Poll (bounded 5s) until the loaded state carries
the flag; fast machines exit on the first probe.
Git-for-Windows autocrlf checks the bundled .md posts out with CRLF;
the exact-match '---' fences then failed to parse and every post lost
its title/excerpt/date frontmatter (Windows CI: 'bundled meet-bili post
found' assertion). Normalize CRLF to LF inside parseFrontmatter when
the fence is CRLF-shaped; LF content is byte-identical as before.
Regression test with a CRLF fixture.
… storage mode (#4599)

The #4316 cold-load alignment sets refLedgerAligned only when the
unified store is available; config-clean machines (CI runners) run
legacy mode where it is an honest skip. The test asserted the flag
unconditionally, so every shard carrying this file was born-red on CI
while unified-config machines passed. Expectation now mirrors
store.replicasAvailable(); verified 49/49 in BOTH modes locally.
The ci-check lane's expectation change (c496cfb) exposed a real Windows
bug: stripInheritedProxy builds inlineEnv as a spread copy of process.env,
which keeps the original key casing (ComSpec) — Windows env vars are
case-insensitive but plain objects are not. planClientSpawn's exact
env.COMSPEC probe then missed it and silently degraded every wrapped spawn
to the bare-name 'cmd.exe' fallback (verified by repro on a real win32 box:
childEnv.COMSPEC=undefined while process.env.COMSPEC was set).

Fix: probe COMSPEC/ComSpec/comspec in planClientSpawn and planDshSpawn.
Verified on real Windows (Node 22): launcher-opencode-inline + fix-679 +
dsh-refresh 37/37; host tsc clean, 35 pass / 2 win32-skips.
…OMSPEC case-probe

c496cfb re-derived the win32 expectation from ambient process.env, which
still mismatches production: Node's process.env member access is
case-insensitive on Windows while the child env handed to the planner is a
plain object whose key keeps the OS casing (ComSpec), so the exact
env.COMSPEC probe fell through to the bare-name fallback. The assertion now
derives from the child's OWN captured env/options and probes
COMSPEC/ComSpec/comspec exactly like planClientSpawn does post-dfeea8a11 —
self-contained under any concurrent-test env churn in single-process CI
shards — and additionally pins windowsVerbatimArguments=true on the wrap.
@ranxianglei

Copy link
Copy Markdown
Owner Author

closing as superseded by #4646. this variant lacks the tools-visibility gate (_plugin_tools_visible): stamping plugin-mode headers whenever tools_ready is true lets sessions whose tool snapshot predates registration run silently uncompressed — the exact #4641 defect class. the per-epoch generation design is worth a follow-up refactor if desired.

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

Labels

bug Something isn't working hermes 改动范围:内核之外的主机侧接线(src/agent 适配器、server 路由、注入拦截)/范围兜底/客户端标签 p1 scope/wiring

Projects

None yet

1 participant