Proxy heartbeat loop dies permanently on any pre-fetch exception; stuck at 30-min backoff cap with no wake-up path
概要
src/proxy/lifecycle/manager.js 的 heartbeat 循环存在两个独立但会相互放大的缺陷。用户视角的现象是:daemon 首次启动后第一次 heartbeat 正常,闲置一段时间(机器睡眠 / 网络抖动)后,无论怎么继续使用,evolver 都处于「死掉」状态,不重启进程无法恢复。
下面附完整复现脚本(不需要 hub、不需要凭证)。
Bug 1: heartbeat() 在 try/catch 之外有可抛代码,一次异常即可彻底打死循环
heartbeat() 的 try 块从第 416 行 hubFetch 才开始。前面 393–414 行有多处同步调用并不在 try 内:
// src/proxy/lifecycle/manager.js:390-416
async heartbeat({ _skipReauth = false } = {}) {
if (!this.hubUrl) return { ok: false, error: 'no_hub_url' };
const nodeId = this.nodeId; // L393 <- 在 try 之外
if (!nodeId) {
const helloResult = await this.hello(); // L395
if (!helloResult.ok) return helloResult;
}
const endpoint = `${this.hubUrl}/a2a/heartbeat`;
const taskMeta = typeof this.getTaskMeta === 'function'
? this.getTaskMeta() // L400 <- 在 try 之外
: {};
const fp = _getEnvFingerprint(); // L401
const body = {
...
meta: {
...
outbound_pending: this.store.countPending({ direction: 'outbound' }), // L410
inbound_pending: this.store.countPending({ direction: 'inbound' }), // L411
...
},
};
try { // L416 <- try 在这里才开始
const res = await hubFetch(endpoint, ...);
...
} catch (err) {
this._consecutiveFailures++;
return { ok: false, error: err.message };
}
}
并且 startHeartbeatLoop 里的 tick 闭包也没有 try/catch:
// src/proxy/lifecycle/manager.js:489-509
startHeartbeatLoop(intervalMs) {
if (this._running) return;
this._running = true;
...
const tick = async () => {
if (!this._running) return;
await this.heartbeat(); // <- reject 直接逃逸
if (this._running) {
const backoff = ...;
this._heartbeatTimer = setTimeout(tick, backoff); // <- 永远不会执行
if (this._heartbeatTimer.unref) this._heartbeatTimer.unref();
}
};
tick(); // <- fire-and-forget,没人 catch
}
只要 store.countPending() / getTaskMeta() / _getEnvFingerprint() 中任何一次抛异常(store 文件损坏、外部 hook throw、mailbox 锁占用、磁盘满等),heartbeat() reject → tick reject → 下一个 setTimeout(tick) 永远不会被注册 → heartbeat 循环彻底死透。_running 仍为 true,但已没有任何机制能把它救活,必须重启进程。
Bug 2: backoff 6 次失败就撞 30 分钟上限,且无任何手动唤醒入口
// src/proxy/lifecycle/manager.js:500-501
const backoff = this._consecutiveFailures > 0
? Math.min(interval * Math.pow(2, this._consecutiveFailures), 30 * 60_000)
: interval;
叠加 reAuthenticate() 自己的 30min → 1h → 2h → 4h backoff(L339-349),形成死锁:
- 连续失败 6 次后,timer backoff 稳定在 30 min 天花板
- 同时 reAuth backoff 也激活(30 min ~ 4h)
- 每 30 min 一次 heartbeat → 401/403 → reAuth 在 backoff 内 直接
return false→_consecutiveFailures继续涨 - LifecycleManager 没有
pokeHeartbeat()这种「用户来活动了,立刻试一次」的入口 - 没有 system wake / network change 监听
reAuthenticate()成功路径(L326)只重置了_consecutiveReauthFailures,没把_reauthBackoffUntil = 0
用户体验:完全没反应,要等几个小时窗口过去 reAuth 才肯再试。
复现脚本
保存为仓库根目录的 repro-heartbeat.js,确保 pnpm install 已跑过,然后 node repro-heartbeat.js。不需要 hub、不需要凭证。
repro-heartbeat.js(点击展开)
'use strict';
/*
* Reproduce two suspected bugs in evolver's LifecycleManager.
*
* B1) heartbeat() has code BEFORE its try/catch (nodeId getter,
* getTaskMeta(), store.countPending(), _getEnvFingerprint()).
* Any exception there escapes heartbeat() -> escapes the tick
* closure in startHeartbeatLoop -> setTimeout(tick, ...) is
* never called -> the heartbeat loop dies permanently. Only
* a daemon restart recovers.
*
* B2) Repeated failures escalate the loop's exponential backoff
* up to a 30-minute cap. Combined with reAuthenticate()'s own
* 30min..4h backoff, every 30 minutes you get one heartbeat
* attempt, reAuth refuses to try, _consecutiveFailures keeps
* growing. No pokeHeartbeat() / system-wake / activity hook
* exists to reset the state earlier.
*
* Usage: drop this file at the repo root and run with the project's
* dependencies installed:
*
* pnpm install
* node repro-heartbeat.js # both scenarios
* node repro-heartbeat.js b1 # B1 only
* node repro-heartbeat.js b2 # B2 only
*/
const path = require('path');
const Module = require('module');
const ROOT = __dirname;
const MANAGER_PATH = path.join(ROOT, 'src/proxy/lifecycle/manager.js');
const HUBFETCH_PATH = path.join(ROOT, 'src/gep/hubFetch.js');
// Intercept the require of '../../gep/hubFetch' inside manager.js so we can
// stub network behaviour without standing up a real hub.
let hubFetchImpl = async () => { throw new Error('hubFetchImpl not set'); };
const origLoad = Module._load;
Module._load = function (request, parent, ...rest) {
if (parent && parent.filename) {
try {
const abs = require.resolve(request, { paths: [path.dirname(parent.filename)] });
if (abs === HUBFETCH_PATH) {
return { hubFetch: (...args) => hubFetchImpl(...args) };
}
} catch { /* fall through */ }
}
return origLoad.call(this, request, parent, ...rest);
};
const { LifecycleManager } = require(MANAGER_PATH);
function makeStore() {
const state = new Map();
state.set('node_id', 'node_aaaaaaaaaaaa');
state.set('node_secret', 'a'.repeat(64));
return {
getState: (k) => state.get(k) ?? null,
setState: (k, v) => state.set(k, v),
countPending: () => 0,
writeInbound: () => {},
writeInboundBatch: () => {},
};
}
// Count only setTimeout calls that look like the `tick` closure from
// startHeartbeatLoop. Heuristic on the source matches both the original and
// any future small refactors that keep _running + heartbeat in scope.
const realSetTimeout = global.setTimeout;
let scheduledTicks = 0;
global.setTimeout = function (fn, ms, ...rest) {
try {
const src = fn && fn.toString ? fn.toString() : '';
if (src.includes('_running') && src.includes('heartbeat')) {
scheduledTicks++;
console.log(` [spy] setTimeout(tick, ${ms}ms) -> scheduledTicks=${scheduledTicks}`);
}
} catch { /* noop */ }
return realSetTimeout(fn, ms, ...rest);
};
let unhandled = 0;
process.on('unhandledRejection', (err) => {
unhandled++;
console.log(` [spy] unhandledRejection: ${err && err.message}`);
});
async function scenarioB1() {
console.log('\n=== B1: store.countPending throws BEFORE try/catch in heartbeat ===');
const store = makeStore();
let calls = 0;
store.countPending = () => {
calls++;
throw new Error(`simulated store error (call #${calls})`);
};
hubFetchImpl = async () => ({
ok: true, status: 200,
json: async () => ({}), text: async () => '',
headers: new Map(),
});
const lc = new LifecycleManager({
hubUrl: 'http://127.0.0.1:1',
store,
logger: { log: () => {}, warn: () => {}, error: (m) => console.log(' [mgr]', m) },
getTaskMeta: () => ({}),
});
scheduledTicks = 0;
lc.startHeartbeatLoop(30_000); // 30s is the floor enforced by manager.js
await new Promise((r) => realSetTimeout(r, 500));
console.log(` -> store.countPending calls: ${calls}`);
console.log(` -> setTimeout(tick) scheduled: ${scheduledTicks}`);
console.log(` -> unhandled rejections: ${unhandled}`);
console.log(` -> _heartbeatTimer set? ${lc._heartbeatTimer ? 'YES' : 'NO'}`);
console.log(` -> _running? ${lc._running}`);
console.log(` EXPECTED (if bug present): countPending=1, scheduledTicks=0, _heartbeatTimer=NO`);
lc.stopHeartbeatLoop();
}
async function scenarioB2() {
console.log('\n=== B2: hubFetch always 401 -> backoff escalation ===');
const store = makeStore();
let hits = 0;
hubFetchImpl = async () => {
hits++;
return {
ok: false, status: 401,
json: async () => ({ error: 'unauthorized' }),
text: async () => 'unauthorized',
headers: new Map(),
};
};
const lc = new LifecycleManager({
hubUrl: 'http://127.0.0.1:1',
store,
logger: { log: () => {}, warn: () => {}, error: () => {} },
getTaskMeta: () => ({}),
});
// Drive heartbeat() directly (rather than waiting on real 30s timers) and
// print what backoff the loop WOULD apply on the next tick.
const interval = 30_000;
for (let i = 1; i <= 8; i++) {
await lc.heartbeat();
const f = lc._consecutiveFailures;
const backoff = f > 0
? Math.min(interval * Math.pow(2, f), 30 * 60_000)
: interval;
const reauth = lc._reauthBackoffUntil > Date.now()
? `${Math.round((lc._reauthBackoffUntil - Date.now()) / 60_000)}min from now`
: 'inactive';
console.log(
` call #${i}: _consecutiveFailures=${f} next backoff=${(backoff / 1000).toFixed(0)}s ` +
`(~${(backoff / 60_000).toFixed(2)} min) reauthBackoffUntil=${reauth}`,
);
}
console.log(` -> total hub hits: ${hits}`);
}
(async () => {
const which = (process.argv[2] || 'all').toLowerCase();
if (which === 'b1' || which === 'all') await scenarioB1();
if (which === 'b2' || which === 'all') await scenarioB2();
process.exit(0);
})();
实际输出(main HEAD = 3d5386c, v1.86.0, Node 26.0.0, macOS)
=== B1: store.countPending throws BEFORE try/catch in heartbeat ===
[spy] unhandledRejection: simulated store error (call #1)
-> store.countPending calls: 1
-> setTimeout(tick) scheduled: 0 <- 下一个 tick 永远没排上
-> _heartbeatTimer set? NO
-> _running? true <- manager 自以为还在跑
=== B2: hubFetch always 401 -> backoff escalation ===
call #1: _consecutiveFailures=1 next backoff= 60s reauthBackoffUntil=30min from now
call #2: _consecutiveFailures=2 next backoff= 120s
call #3: _consecutiveFailures=3 next backoff= 240s
call #4: _consecutiveFailures=4 next backoff= 480s
call #5: _consecutiveFailures=5 next backoff= 960s
call #6: _consecutiveFailures=6 next backoff=1800s <- 撞 30min 上限
call #7: _consecutiveFailures=7 next backoff=1800s
call #8: _consecutiveFailures=8 next backoff=1800s
建议修复方向
try提前:heartbeat()的 try 块覆盖从 L393this.nodeId起的全部代码tick闭包加 try/catch:不管heartbeat()怎么失败,下一次setTimeout(tick, ...)总能被调度- 新增
pokeHeartbeat():清_consecutiveFailures+_reauthBackoffUntil,clearTimeout 当前 timer,立刻 fire 一次。proxy HTTP 收到任何请求时调一下 reAuthenticate()成功路径加this._reauthBackoffUntil = 0
如需 PR,我可以接着出补丁。
环境
- evolver: v1.86.0 (
mainHEAD3d5386c) - Node.js: v26.0.0
- macOS Darwin 25.5.0
我一会先修一下 @autogame-17
@bjw9808 复核完毕,两个 bug 都坐实,#548 的方向也是对的。下面分条对照,另外有一条建议修复项我觉得可以删掉。
Bug 1 — heartbeat loop 完全停摆:确认
heartbeat() 的 try 块是从 manager.js:417 的 hubFetch 才开始的,前面的调用全部裸露在外:
startHeartbeatLoop 的 tick 闭包里:
await this.heartbeat()
而:
setTimeout(tick, ...)
是排在 await 后面的,同时没有 try/catch 包裹,所以一旦 reject,下一次调度就直接没了。
tick() 末尾 fire-and-forget 那段外层也没有 .catch()。
_running 仍然保持 true,所以从外部看会像“没死”,但 heartbeat 实际已经彻底停掉。
复现脚本逻辑没有问题。
Bug 2 — 30min backoff cap + 无唤醒路径:确认
manager.js:500-501:
Math.min(interval * 2^n, 30 * 60_000)
配合:
DEFAULT_HEARTBEAT_INTERVAL = 360_000
(6 分钟)后,只要连续失败 3 次,就会直接贴到 30min 上限:
360s · 2³ = 2880s → 截断到 1800s
全仓 grep:
pokeHeartbeat
wake
system-resume
main 上都是 0 命中。
确认当前不存在:
手动唤醒入口
system resume listener
wall-clock drift / 网络变化监听
再叠加 reAuthenticate() 自己的 30min → 4h backoff,确实能进入“永久沉睡”状态。
复现脚本里 8 次调用跑出来的 backoff 表和源码逻辑完全一致。
顺手补充(不在 issue 范围内,但相关)
src/gep/a2aProtocol.js 那条 heartbeat 路径走的是:
sendHeartbeat()
.catch(...)
.then(_scheduleNextHeartbeat)
(a2aProtocol.js:729-744)
因为 .then 永远会重新排程:
那条路径没有 Bug 1
也没有指数 backoff
所以同样没有 Bug 2
因此 #548 把修复范围限定在:
proxy/lifecycle/manager.js
是合理的,不是漏修。
对建议修复方向 #4 的勘误请求
这一条:
reAuthenticate() success path:
this._reauthBackoffUntil = 0
我认为不是 bug。
因为函数入口 manager.js:290-294 已经有:
if (_reauthBackoffUntil > Date.now()) {
return false;
}
既然能进入 success path,就说明 backoff 已经过期了。
此时 _reauthBackoffUntil 已经只是一个过去时间戳,对后续:
Date.now() > _reauthBackoffUntil
这种判断不会产生任何行为差异。
所以把它 reset 成 0 只是装饰性质,不修任何真实逻辑,建议从 must-fix 里拿掉,避免误导 reviewer。
前三条修复方向:
try提前tick加try/catch新增
pokeHeartbeat
都是正确方向,#548 目前也是沿着这个思路在推进。
我这边后续
#548 现在还是 draft。
等它 ready-for-review 后,我会继续 review:
heartbeatSupervisor.js的 drift threshold60s 是否足够避免 macOS timer coalesce 误判
pokeHeartbeat的 60s throttlehealthy node 判定逻辑
另外,#548 自己 “Out of scope” 里提到的:
node_disabled / node_revoked
未识别为 terminal error → 无限 retry
我会另外补一个 follow-up issue 跟踪,避免它和主线 fix 缠在一起拖延期。
谢谢这个硬核 repro。
不需要 hub、不需要 credential,直接:
node repro-heartbeat.js
就能把两个 bug 同时打出来。
这种最小化复现质量,是 issue 不会被埋掉的最大原因。
Fixed in evolver-private-dev#147 (commit 0f55571), shipped on next release. Both Bug 1 (pre-fetch helpers escaping the try block) and Bug 2 (30min backoff cap with no wake path) addressed. New pokeHeartbeatLoop() method available for callers wanting wake-on-event semantics; backoff cap lowered to 15min and made strictly above the default interval so exponential branch doesn't invert.