From 3333582ba860d6076ec2d1d422890c58ed922352 Mon Sep 17 00:00:00 2001 From: ci-check Date: Wed, 4 Nov 2026 18:26:10 +0800 Subject: [PATCH 1/2] fix(#5666): unref the cache-keepalive timer so short-lived processes can exit The armed cadence timer was a plain setTimeout without unref(), holding the Node event loop open. In an inline-lane short-lived process (pi -p, sub-agents) that timer is the only live handle left once the turn finishes, so the process lingered until maxDurationMs (default 24h) instead of exiting. Route both the default scheduler and its test-reset through a single realSchedule() helper that unrefs every handle. Interactive hosts stay alive for their own reasons and the pings still fire on schedule; print-mode hosts now exit cleanly when their work is done. Regression: tests/cache-keepalive.test.ts spawns a child that arms a keepalive through the real scheduler and asserts the process exits on its own (hangs / times out without the fix). --- src/cache-keepalive.ts | 15 +++++++++-- tests/cache-keepalive.test.ts | 51 +++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/src/cache-keepalive.ts b/src/cache-keepalive.ts index 333332c53c..69d8da0034 100644 --- a/src/cache-keepalive.ts +++ b/src/cache-keepalive.ts @@ -172,8 +172,19 @@ interface KeepaliveEntry { const registry = new Map(); +/** Real-timer scheduler: every handle is unref'd (#5666) so an armed cadence + * timer never holds the event loop open. Interactive hosts stay alive for + * their own reasons and the pings still fire on schedule; a short-lived + * process (pi -p, a sub-agent) whose only remaining handle is the armed + * keepalive now exits cleanly instead of limping along until maxDurationMs. */ +function realSchedule(fn: () => void, ms: number): ReturnType { + const t = setTimeout(fn, ms); + t.unref?.(); + return t; +} + let clock: () => number = () => Date.now(); -let scheduleFn: (fn: () => void, ms: number) => ReturnType = (fn, ms) => setTimeout(fn, ms); +let scheduleFn: (fn: () => void, ms: number) => ReturnType = realSchedule; let cancelFn: (id: ReturnType) => void = (id) => clearTimeout(id); export interface KeepaliveArmInput { @@ -454,7 +465,7 @@ export function _setKeepaliveSchedulerForTest(sched: FakeScheduler | undefined): scheduleFn = (fn, ms) => sched.schedule(fn, ms) as ReturnType; cancelFn = (id) => sched.cancel(id as unknown); } else { - scheduleFn = (fn, ms) => setTimeout(fn, ms); + scheduleFn = realSchedule; cancelFn = (id) => clearTimeout(id); } } diff --git a/tests/cache-keepalive.test.ts b/tests/cache-keepalive.test.ts index a1146d0e8e..dff015b3ec 100644 --- a/tests/cache-keepalive.test.ts +++ b/tests/cache-keepalive.test.ts @@ -6,6 +6,11 @@ import { test, before, after, beforeEach } from "node:test"; import assert from "node:assert"; import http from "node:http"; +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { buildPingBody, @@ -507,3 +512,49 @@ test("keepaliveStatusFor: mirrors armed state, ping history and disarm", async ( await settle(() => _keepaliveArmedForTest().length === 0); assert.equal(keepaliveStatusFor(sid), undefined, "disarmed sessions report no state"); }); + +// ---- process-liveness (real timers) --------------------------------------- + +test("arm: the real scheduler unrefs its timer, so short-lived processes exit (#5666)", async () => { + // A child arms a keepalive through the DEFAULT (non-injected) scheduler and + // then does nothing else. The armed cadence timer is that process's only + // remaining handle — exactly the inline-lane pi -p / sub-agent shape. With + // the fix the timer is unref'd, so the event loop drains and the process + // exits on its own; without it the ref'd timer holds the loop open and the + // child hangs until the (270 s) timer fires. Hermetic: no network (the ping + // URL is never reached before the process is gone). + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bili-ka-exit-")); + for (const d of ["cfg", "state", "data"]) fs.mkdirSync(path.join(tmp, d), { recursive: true }); + const env = { + ...process.env, + XDG_CONFIG_HOME: path.join(tmp, "cfg"), + XDG_STATE_HOME: path.join(tmp, "state"), + XDG_DATA_HOME: path.join(tmp, "data"), + ACP_LOG_FILE: "off", + }; + const kaUrl = pathToFileURL(fileURLToPath(new URL("../src/cache-keepalive.ts", import.meta.url))).href; + const code = ` +process.env.BILI_CACHE_KEEPALIVE = "1"; +process.env.BILI_CACHE_KEEPALIVE_ASSUME_TTL = "5m"; +const { noteSuccessfulForward } = await import(${JSON.stringify(kaUrl)}); +noteSuccessfulForward({ + sessionId: "ka-exit", protocol: "anthropic", reqMethod: "POST", sidePassthrough: false, resignLane: false, + wireBody: JSON.stringify({ model: "claude-opus-test", max_tokens: 4096, stream: true, system: [{ type: "text", text: "s", cache_control: { type: "ephemeral", ttl: "5m" } }], messages: [{ role: "user", content: "hi" }] }), + upstreamUrl: "http://127.0.0.1:9/v1/messages", headers: { "content-type": "application/json" }, dispatcher: undefined, routes: undefined, +}); +`; + const child = spawn(process.execPath, ["--import", "tsx", "--input-type=module", "--eval", code], { + cwd: fileURLToPath(new URL("../", import.meta.url)), + env, + stdio: ["ignore", "pipe", "pipe"], + }); + let out = ""; + child.stdout?.on("data", (c) => (out += String(c))); + child.stderr?.on("data", (c) => (out += String(c))); + const exited = new Promise((resolve) => child.on("close", (c) => resolve(c))); + const timedOut = new Promise((resolve) => setTimeout(() => resolve(null), 10_000).unref()); + const exitCode = await Promise.race([exited, timedOut]); + child.kill(); + 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}`); +}); From 2e99a66e9827e452a331525b96aa692dab126821 Mon Sep 17 00:00:00 2001 From: ci-check Date: Wed, 4 Nov 2026 18:58:54 +0800 Subject: [PATCH 2/2] test(#5666): register the cache-keepalive liveness suite in LIVE_FILES MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tests/cache-keepalive.test.ts now spawns a child (node --import tsx) for the #5666 process-liveness regression, which trips the SPAWN_RE guard in scripts/run-ci-tests.mjs: every process-spawning suite must be listed in LIVE_FILES or the runner bails with exit 1 before any test runs (all 11 CI shards failed on this pre-flight tripwire). Append it at the end of the table (slot = index drives each file's zone port band, so mid-list inserts are forbidden); the child runs under a per-run mkdtemp XDG sandbox with no ports bound, so no zone band is needed — the entry is for the tripwire alone, like #3890/#5114. --- scripts/live-files.mjs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/scripts/live-files.mjs b/scripts/live-files.mjs index 5f97c04528..d5fe6a7773 100644 --- a/scripts/live-files.mjs +++ b/scripts/live-files.mjs @@ -107,6 +107,12 @@ export const LIVE_FILES = [ // #4612: spawns an idle node child as the "other live process" fixture; // binds no ports, mkdtemp-isolated per test "tests/issue4612-gc-online-guard.test.ts", + // #5666: process-liveness regression — spawns ONE bare node child (--import + // tsx) that arms a keepalive through the real scheduler and asserts it exits + // on its own; the child runs under a per-run mkdtemp XDG sandbox, does no + // network I/O and binds no port, so no zone band is needed — the entry is for + // the tripwire alone, like #3890/#5114 + "tests/cache-keepalive.test.ts", ]; /** Band width per live file: the zone ladder drifts +1 per EADDRINUSE retry;