Merge pull request #1966 from ranxianglei/2026-10-03_restart-negative-health-cache

fix(#1957): invalidate stale health verdicts across the respawn boundary
This commit is contained in:
ranxianglei
2026-10-03 15:21:20 +08:00
committed by GitHub
2 changed files with 190 additions and 8 deletions
+28 -7
View File
@@ -467,17 +467,36 @@ export interface LiveOriginResolverDeps {
* fallback for attach mode — #1130/#1135); this resolver only decides WHEN
* to fire it and whether the result is actually alive. */
export function createLiveOriginResolver(state: NativeInterceptState, deps: LiveOriginResolverDeps = {}): () => Promise<string | undefined> {
const probe = withProbeTtl(deps.probe ?? probeHealth, deps.probeTtlMs ?? HEALTH_PROBE_TTL_MS);
// #1957: a health verdict describes a PROCESS GENERATION, not a URL. A
// respawn puts a new process behind the same origin (lane port memory,
// #1723), so every verdict obtained before that boundary is void — a
// stale negative hit would send the first post-recovery request(s)
// direct (uncompressed) until the TTL lapses. At each respawn the TTL
// cache is rebuilt (kills cached verdicts) and `generation` advances
// (kills in-flight verdicts, which must not clear a healthy
// replacement that already landed).
const healthProbe = deps.probe ?? probeHealth;
const probeTtlMs = deps.probeTtlMs ?? HEALTH_PROBE_TTL_MS;
let probe = withProbeTtl(healthProbe, probeTtlMs);
let generation = 0;
const respawnCooldownMs = deps.respawnCooldownMs ?? RESPAWN_COOLDOWN_MS;
let lastRespawn = 0;
return async (): Promise<string | undefined> => {
let ownedThenLost = false;
if (state.origin !== undefined) {
if (await probe(state.origin)) return state.origin;
// Proxy died mid-session. Clearing origin first makes concurrent
// callers share the same state.ready (dedup).
ownedThenLost = true;
state.origin = undefined;
const held = state.origin;
const gen = generation;
if (held !== undefined) {
const ok = await probe(held);
// Act on the verdict only if the world didn't move while it was
// in flight: a concurrent caller's respawn (generation bump) or
// any origin change underneath us voids it — re-resolve instead.
if (gen === generation && state.origin === held) {
if (ok) return held;
// Proxy died mid-session. Clearing origin first makes concurrent
// callers share the same state.ready (dedup).
ownedThenLost = true;
state.origin = undefined;
}
}
// Retry bootstrap whenever no live origin is held — either just lost
// it or the load-time bootstrap failed (the hook cannot observe send
@@ -485,6 +504,8 @@ export function createLiveOriginResolver(state: NativeInterceptState, deps: Live
// one per interval instead of one per request.
if (state.respawn !== undefined && (ownedThenLost || Date.now() - lastRespawn >= respawnCooldownMs)) {
lastRespawn = Date.now();
generation += 1;
probe = withProbeTtl(healthProbe, probeTtlMs);
state.ready = state.respawn();
}
const o = await readyOrigin(state);
+162 -1
View File
@@ -1,6 +1,6 @@
import test from "node:test";
import assert from "node:assert/strict";
import { installNativeFetchIntercept, isModelApiUrl, noteRoutedOrigin, observeRoutedOrigin, _resetForTest, type NativeInterceptState } from "../src/agent/native-intercept.ts";
import { createLiveOriginResolver, installNativeFetchIntercept, isModelApiUrl, noteRoutedOrigin, observeRoutedOrigin, _resetForTest, type NativeInterceptState } from "../src/agent/native-intercept.ts";
test("isModelApiUrl: matches model-API endpoint shapes", () => {
assert.equal(isModelApiUrl("http://127.0.0.1:8199/v1/messages"), true);
@@ -848,3 +848,164 @@ test("#1365 observeRoutedOrigin: pre-set evidence skips the window; expiry clean
else process.env.BILI_ATTACH_EVIDENCE_GRACE_MS = saved;
}
});
// — #1957: a health verdict describes a PROCESS GENERATION, not a URL —
// A respawn puts a new process behind the same origin (lane port memory,
// #1723). Verdicts obtained before that boundary — cached or still in flight
// — must not steer routing for the replacement.
test("#1957 same-origin respawn: replacement is probed for real (stale negative verdict discarded)", async (t) => {
let now = 100_000;
t.mock.method(Date, "now", () => now);
const origin = "http://127.0.0.1:18787";
let online = true;
let probes = 0;
let respawnCalls = 0;
const state: NativeInterceptState = {
origin,
ready: Promise.resolve(origin),
respawn: async () => {
respawnCalls += 1;
online = true;
state.origin = origin;
return origin;
},
};
const resolve = createLiveOriginResolver(state, {
probe: async () => { probes += 1; return online; },
probeTtlMs: 2_000,
});
assert.equal(await resolve(), origin, "healthy hold fast-paths through the cached verdict");
now += 2_001;
online = false;
const recovered = await resolve();
assert.equal(respawnCalls, 1, "one respawn on death");
assert.equal(recovered, origin, "post-recovery request must route to the respawned proxy");
assert.equal(probes, 3, "replacement must be probed for real, not served from the stale negative cache");
assert.equal(state.origin, origin);
});
test("#1957 new-origin respawn lands on the replacement's own origin", async (t) => {
t.mock.method(Date, "now", () => 100_000);
const dead = "http://127.0.0.1:1";
const fresh = "http://127.0.0.1:2";
const state: NativeInterceptState = {
origin: dead,
ready: Promise.resolve(dead),
respawn: async () => { state.origin = fresh; return fresh; },
};
const resolve = createLiveOriginResolver(state, {
probe: async (o: string) => o === fresh,
probeTtlMs: 2_000,
});
assert.equal(await resolve(), fresh, "respawn lands on a different origin and passes its real probe");
assert.equal(state.origin, fresh);
assert.equal(await resolve(), fresh, "subsequent requests reuse the landed origin");
});
test("#1957 a replacement that fails its real probe degrades — the respawn URL is never trusted blindly", async (t) => {
t.mock.method(Date, "now", () => 100_000);
const origin = "http://127.0.0.1:18787";
let giveUps = 0;
let respawnCalls = 0;
const state: NativeInterceptState = {
origin,
ready: Promise.resolve(origin),
onGiveUp: () => { giveUps += 1; },
respawn: async () => { respawnCalls += 1; state.origin = origin; return origin; },
};
const resolve = createLiveOriginResolver(state, {
probe: async () => false,
probeTtlMs: 2_000,
});
assert.equal(await resolve(), undefined, "an unhealthy replacement must not be routed to");
assert.equal(respawnCalls, 1);
assert.equal(giveUps, 1, "onGiveUp fires so the host can surface the loss");
});
test("#1957 failed respawn: cooldown suppresses re-fire within the window", async (t) => {
let now = 100_000;
t.mock.method(Date, "now", () => now);
const origin = "http://127.0.0.1:18787";
let giveUps = 0;
let respawnCalls = 0;
const state: NativeInterceptState = {
origin,
ready: Promise.resolve(origin),
onGiveUp: () => { giveUps += 1; },
respawn: async () => { respawnCalls += 1; return undefined; },
};
const resolve = createLiveOriginResolver(state, {
probe: async () => false,
probeTtlMs: 2_000,
});
assert.equal(await resolve(), undefined);
assert.equal(respawnCalls, 1);
now += 5_000;
assert.equal(await resolve(), undefined, "still degraded inside the cooldown");
assert.equal(respawnCalls, 1, "cooldown bounds attempts to one per interval");
assert.equal(giveUps, 1, "loss is reported once per observed loss, not per degraded request");
now += 15_001;
assert.equal(await resolve(), undefined, "replacement still absent after the cooldown");
assert.equal(respawnCalls, 2, "cooldown elapsed → retry bootstrap");
});
test("#1957 steady-state verdict reuse survives the fix (#928)", async (t) => {
let now = 100_000;
t.mock.method(Date, "now", () => now);
const origin = "http://127.0.0.1:18787";
let probes = 0;
const state: NativeInterceptState = { origin, ready: Promise.resolve(origin) };
const resolve = createLiveOriginResolver(state, {
probe: async () => { probes += 1; return true; },
probeTtlMs: 2_000,
});
for (let i = 0; i < 3; i++) assert.equal(await resolve(), origin);
assert.equal(probes, 1, "steady-state requests ride the cached positive verdict");
now += 2_001;
assert.equal(await resolve(), origin, "after the TTL lapses a fresh probe confirms and routes");
assert.equal(probes, 2);
});
test("#1957 a stale in-flight verdict cannot clobber a healthy same-origin replacement", async (t) => {
t.mock.method(Date, "now", () => 100_000);
const origin = "http://127.0.0.1:18787";
let respawnCalls = 0;
const gates: Array<(ok: boolean) => void> = [];
const state: NativeInterceptState = {
origin,
ready: Promise.resolve(origin),
respawn: async () => {
respawnCalls += 1;
state.origin = origin; // replacement binds the SAME origin
return origin;
},
};
const resolve = createLiveOriginResolver(state, {
probe: async () => new Promise<boolean>((res) => { gates.push(res); }),
probeTtlMs: 2_000,
});
const tick = (): Promise<void> => new Promise((r) => { setTimeout(r, 0); });
const first = resolve();
const second = resolve(); // both hold the pre-respawn origin while probing
assert.equal(gates.length, 2, "two concurrent in-flight probes");
gates[0](false); // caller 1 sees the OLD process dead
await tick(); // → respawn fires, replacement lands on the same origin,
// caller 1 starts its post-ready verification probe
assert.equal(respawnCalls, 1);
assert.equal(gates.length, 3, "caller 1 verifies the replacement for real");
gates[1](false); // caller 2's verdict arrives AFTER the boundary — stale
await tick(); // it must be discarded, not acted on
assert.equal(state.origin, origin, "stale verdict must not wipe the healthy replacement");
assert.equal(respawnCalls, 1, "stale verdict must not trigger a redundant respawn");
assert.ok(gates.length >= 4, "caller 2 must verify the current origin for real");
gates[2](true); // caller 1's verification: replacement is alive
await tick();
gates[3](true); // caller 2's own verification of the current origin
assert.equal(await first, origin);
assert.equal(await second, origin, "caller 2 recovers through the shared ready");
});