From 0d2ee1d61af9f353f13abad08abedf6fea9d6995 Mon Sep 17 00:00:00 2001 From: Afloat Date: Tue, 10 Nov 2026 11:21:36 +0800 Subject: [PATCH] fix: ignore stale keepalive response bodies after rearming --- src/cache-keepalive.ts | 1 + tests/cache-keepalive.test.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/cache-keepalive.ts b/src/cache-keepalive.ts index d14606747a..4cb13d0619 100644 --- a/src/cache-keepalive.ts +++ b/src/cache-keepalive.ts @@ -379,6 +379,7 @@ async function firePing(entry: KeepaliveEntry): Promise { entry.pingInFlight = false; if (registry.get(entry.sessionId) !== entry) return; const text = await resp.text().catch(() => ""); + if (registry.get(entry.sessionId) !== entry) return; if (!resp.ok) { if (resp.status === 429) { disarm(entry.sessionId, "rate-limited(429)"); diff --git a/tests/cache-keepalive.test.ts b/tests/cache-keepalive.test.ts index 6c2988ad15..66b060a2f5 100644 --- a/tests/cache-keepalive.test.ts +++ b/tests/cache-keepalive.test.ts @@ -590,3 +590,34 @@ noteSuccessfulForward({ fs.rmSync(tmp, { recursive: true, force: true }); assert.equal(exitCode, 0, `an armed keepalive must not hold the event loop open (got ${exitCode === null ? "TIMEOUT — the cadence timer kept the process alive" : `exit code ${exitCode}`})\n--- child output ---\n${out}`); }); + +for (const reply of [ + { label: "rate limit", status: 429, body: { error: "slow down" } }, + { label: "cache miss", status: 200, body: MISS_BODY }, + { label: "cache hit", status: 200, body: HIT_BODY }, +]) { + test(`ping: a stale ${reply.label} body cannot change a replacement snapshot`, async (t) => { + let finishBody!: (text: string) => void; + let startedBody!: () => void; + const body = new Promise((resolve) => { finishBody = resolve; }); + const started = new Promise((resolve) => { startedBody = resolve; }); + const response = new Response(null, { status: reply.status }); + t.mock.method(response, "text", () => { + startedBody(); + return body; + }); + t.mock.method(globalThis, "fetch", async () => response); + + noteSuccessfulForward(armInput()); + timers.advance(270_000); + await started; + noteSuccessfulForward(armInput({ wireBody: BODY_1H })); + const replacement = _keepaliveEntryForTest(sid); + assert.equal(replacement?.tierLabel, "1h"); + + finishBody(JSON.stringify(reply.body)); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(_keepaliveEntryForTest(sid), replacement); + assert.equal(timers.pendingCount(), 1, "only the replacement snapshot stays scheduled"); + }); +}