diff --git a/CHANGELOG.md b/CHANGELOG.md index bcbd058ec7..0bb8d27e9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag independent #1729 wire-level dsh-compaction refusal, the #2709 framing-absent rewrite attribution, and the #2695 majority-absent zombie reap (its `orphan-reap` ledger record); none of those paths are touched here. Goldens: metadata-only drift, exactly the new latch. +- **Self-restart: replacement no longer hops to the next port when the target port is occupied (#3044)** — with `autoRestartOnUpdate`, a replacement spawned while the old instance still held its port (or a racing process took it during the drain window) inherited the launcher's EADDRINUSE ladder and silently drifted to P+1, P+2, …: idle orphans serving no client while the prior instance never exited (reported shape: 14 orphans over 9 h, ~8 GB private memory combined). Now the replacement is marked at spawn (`BILI_UPGRADE_REPLACEMENT=1`, internal spawn channel) and must bind EXACTLY the freed port — after the bounded same-lane predecessor wait of #1723 — or fail fast with exit code 1 and a clear log line ("upgrade pending; the host decides retry"). The parent verifies the handover against the replacement's own registry record (pid + port it ACTUALLY bound) instead of a raw TCP answer: bound the wrong port → terminated, kill verified, service resumes; another live bili instance already owns the port → the upgrade counts as landed there and the parent exits cleanly instead of resuming an old-code copy that would ladder-drift into its own zombie; a kill that does not take effect escalates loudly with a manual-cleanup hint. A foreign non-bili squatter keeps today's resume behavior. A lane'd spawn that races a LIVE same-build instance on the same port (the host-respawn trigger path of the 2026-10-13 recurrence) now exits loudly instead of hopping: the duplicate loses, the serving instance keeps serving, and the next launch attaches to it. Tests: tests/listen-policy.test.ts (policy matrix), auto-restart.test.ts (marker env, misplaced termination, supersede-exit, unkillable escalation), port-zone-live.test.ts (live fail-fast end-to-end, CI lane). - **Storage: drop the `better-sqlite3` optional dependency (#2823)** — the native SQLite engine lived in `optionalDependencies`, but pnpm ≥10's strict build-script gate (`strictDepBuilds`) blocks any unlisted install script and treats it as a hard error, so dsh plugin-market installs/updates on fresh profiles failed with `[ERR_PNPM_IGNORED_BUILDS] better-sqlite3`. Unified storage is OFF by default (legacy file persistence), so dropping the optional native engine is low-impact: the driver already prefers built-in `node:sqlite` when the native module is absent, and when no engine is available at all `UnifiedShadow.maybeOpen` degrades to legacy-only (one warn, never bricks). New tests pin the no-engine contract (`tests/storage-engine-proofs.test.ts`: `maybeOpen` → null; `SessionStore` runs legacy-only, writes survive, no `index.db`). The opportunistic `require("better-sqlite3")` probe is kept, so hosts that still have the native module keep using it. The dsh-side fix (downgrading build-blocking of *optional* deps to non-fatal) is tracked separately. - **Inbound markers: one declarative engine for all four wires (#2789, #2798, #2811 plan B)** — the per-protocol inbound stripping calls (panel → status markers → chain carriers, each wired diff --git a/CONFIGURATION.md b/CONFIGURATION.md index b3db2cb508..cf2f3435df 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -333,6 +333,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `BILI_MCP_PROXY` | string | unset | — | Spawn channel: MCP proxy target for plugin-hosted tools. | | `BILI_PARENT_PID` | number | unset | — | Spawn channel: parent process id for lifecycle supervision. | | `BILI_STRICT_PORT` | number | unset | — | Spawn channel: exact-port requirement (squatters refused loudly instead of hopping). | +| `BILI_UPGRADE_REPLACEMENT` | boolean-ish | unset | — | Spawn channel: marks a self-restart replacement — it must own exactly the freed port or exit without hopping (#3044). | | `BILI_OPENCODE_ACP_SPEC` | string | unset | — | Spawn channel: ACP spec marker for opencode-native lanes. | | `BILI_LAUNCHER_MODEL_WINDOWS` | string | unset | — | Launcher channel: model-window overrides passed into spawned clients. | | `BILI_LAUNCHER_LANE` | string | unset | — | Launcher channel: lane identity of the spawning bili process. | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 8093474b5b..e7dbcf71ce 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -333,6 +333,7 @@ | `BILI_MCP_PROXY` | string | unset | — | 派生通道:插件宿主工具的 MCP 代理目标。 | | `BILI_PARENT_PID` | number | unset | — | 派生通道:父进程 id,用于生命周期监管。 | | `BILI_STRICT_PORT` | number | unset | — | 派生通道:精确端口要求(被占用时响亮拒绝而非跳端口)。 | +| `BILI_UPGRADE_REPLACEMENT` | boolean-ish | unset | — | 派生通道:标记自重启替换进程——必须独占被释放的精确端口,否则直接退出而非跳端口(#3044)。 | | `BILI_OPENCODE_ACP_SPEC` | string | unset | — | 派生通道:opencode 原生车道的 ACP 规格标记。 | | `BILI_LAUNCHER_MODEL_WINDOWS` | string | unset | — | 启动器通道:传入被派生客户端的模型窗口覆盖。 | | `BILI_LAUNCHER_LANE` | string | unset | — | 启动器通道:派生方 bili 进程的车道身份。 | diff --git a/src/instance.ts b/src/instance.ts index 00cf3233da..d1485f2c24 100644 --- a/src/instance.ts +++ b/src/instance.ts @@ -165,6 +165,28 @@ export function findSameLanePredecessor( return undefined; } +/** #3044 follow-up: a live holder on the same lane running OUR build — a + * twin, not a predecessor. Nothing is draining (it is healthy and serving), + * so waiting cannot help; laddering +1 strands the newcomer as an orphan + * nobody routes to while the twin keeps serving (the second trigger path of + * #3044: a host respawn racing a live instance). The newcomer must exit + * loudly instead — the duplicate loses, the serving instance wins. Missing + * fingerprints never match: an unknown build is not our twin. */ +export function findSameLaneTwin( + entries: RegistryEntry[], + port: number, + lane: string | undefined, + ownFingerprint: string | undefined, +): RegistryEntry | undefined { + if (!lane || !ownFingerprint) return undefined; + for (const e of entries) { + if (e.port !== port || e.lane !== lane) continue; + if (!isPidAlive(e.pid)) continue; + if (e.codeFingerprint === ownFingerprint) return e; + } + return undefined; +} + /** #1225: content identity of a bili entry script (sha256 of its bytes). * The spawned child records this for ITS script; an attaching launcher * compares it against the hash of the script it would spawn — so "same diff --git a/src/listen-policy.ts b/src/listen-policy.ts new file mode 100644 index 0000000000..4b0e7a2bee --- /dev/null +++ b/src/listen-policy.ts @@ -0,0 +1,73 @@ +/** + * EADDRINUSE retry policy for the proxy's own listen socket (#407/#964/#1723/#3044). + * Pure decision table extracted from the server's 'error' handler so every + * branch can be pinned without booting a server. + * + * #3044: a self-restart replacement must own EXACTLY the port its predecessor + * freed. Hopping +1 strands it serving no client while the prior instance + * keeps holding the real port — the orphan-leak shape reported in #3044. It + * gets the bounded same-port predecessor wait (#1723 overlap: slow release), + * then fails fast instead of laddering. + * + * #3044 follow-up: a live holder running OUR build on the same lane is a + * twin, not a predecessor — nothing is draining, so the newcomer exits loudly + * instead of hopping (the duplicate loses; the serving instance keeps serving + * and the next launch attaches to it). Applies to marked AND unmarked spawns. + */ +/** Internal spawn-channel env set by performSelfRestart onto its replacement + * (#3044): the marked process must bind-or-die on exactly the freed port. */ +export const UPGRADE_REPLACEMENT_ENV = "BILI_UPGRADE_REPLACEMENT"; + +type EaddrinuseAction = + | { kind: "wait-predecessor"; port: number } + /** nextPort 0 = ask the OS for an ephemeral port (ladder exhausted). */ + | { kind: "ladder"; nextPort: number } + | { kind: "fail-fast"; reason: "upgrade-replacement" | "strict-port" | "port-busy" | "twin-collision" }; + +export interface EaddrinuseContext { + /** #3044: this process is a self-restart replacement (BILI_UPGRADE_REPLACEMENT). */ + upgradeReplacement: boolean; + /** #3044 follow-up: a live same-lane instance running our build holds the port. */ + twinHolds: boolean; + launchToken: boolean; + strictPort: boolean; + attempts: number; + maxAttempts: number; + predecessorTicksLeft: number; + predecessorHolds: boolean; + lastTriedPort: number; +} + +export function decideEaddrinuse(ctx: EaddrinuseContext): EaddrinuseAction { + // The twin rule outranks everything else: a healthy same-build peer is + // serving real traffic on that port, so no wait/ladder variant may touch + // it — the newcomer dies loudly regardless of its own spawn rights. + if (ctx.twinHolds) return { kind: "fail-fast", reason: "twin-collision" }; + if (ctx.upgradeReplacement) { + if (ctx.predecessorTicksLeft > 0 && ctx.predecessorHolds) { + return { kind: "wait-predecessor", port: ctx.lastTriedPort }; + } + return { kind: "fail-fast", reason: "upgrade-replacement" }; + } + if (!ctx.launchToken || ctx.strictPort || ctx.attempts >= ctx.maxAttempts) { + return { kind: "fail-fast", reason: ctx.strictPort ? "strict-port" : "port-busy" }; + } + if (ctx.predecessorTicksLeft > 0 && ctx.predecessorHolds) { + return { kind: "wait-predecessor", port: ctx.lastTriedPort }; + } + const nextAttempts = ctx.attempts + 1; + return { kind: "ladder", nextPort: nextAttempts === ctx.maxAttempts ? 0 : ctx.lastTriedPort + 1 }; +} + +/** #3044/#2941: ladder rights for the POST-BIND claim check (port-owner's + * resolvePortClaim). A launcher-spawned child that finds a foreign live + * listener on its just-bound port may move +1 off the contested port (#2941); + * strict-port and manual launches never did. A marked upgrade replacement must + * not either, even though it inherits its parent's launch token: hopping is + * exactly the orphan shape #3044 kills, and this is the second path where a + * replacement could hop — on socket semantics that tolerate a concurrent bind + * onto an actively-listening port, a successful bind does not exclude the + * still-draining predecessor or a racing host respawn (#707/libuv#1360). */ +export function postBindCanLadder(hasLaunchToken: boolean, strictPort: boolean, upgradeReplacement: boolean): boolean { + return hasLaunchToken && !strictPort && !upgradeReplacement; +} diff --git a/src/restart.ts b/src/restart.ts index 806a833d12..9e05d8318a 100644 --- a/src/restart.ts +++ b/src/restart.ts @@ -37,6 +37,17 @@ * (#414) and logs wherever the parent does. The #414 group-kill rationale is * moot on win32 — stopProxy() relies on the BILI_PARENT_PID watchdog there, * never a group kill — so detaching costs nothing there. + * + * #3044 handover contract: the replacement is marked BILI_UPGRADE_REPLACEMENT + * so it binds-or-dies on exactly the port freed here (no +1 ladder — hopping + * stranded replacements serving no client while the prior instance kept the + * real port). The parent verifies the child through its OWN registry record + * (pid + actual bound port) rather than trusting a raw TCP answer on the port + * (a racing host respawn could masquerade as the child), terminates any + * misplaced or still-starting child and VERIFIES the kill, and exits instead + * of resuming when another live bili instance has taken over the port + * (resuming would ladder-drift this old-code copy onto a fresh port — the + * zombie half of the leak). */ import { spawn, type ChildProcess, type SpawnOptions } from "node:child_process"; import net from "node:net"; @@ -49,6 +60,8 @@ import { flushAllSessions, totalInFlight } from "./session.js"; import { flushConversations } from "./plugin.js"; import { flushPrefixAffinity } from "./affinity-persist.js"; import { findInstallDir, isVersionNewer, verifyInstallLoadable } from "./update.js"; +import { isPidAlive, listInstances } from "./instance.js"; +import { UPGRADE_REPLACEMENT_ENV } from "./listen-policy.js"; const MARKER_FILE = path.join(cacheDir(), ".auto-restart"); @@ -66,6 +79,10 @@ const READY_TIMEOUT_MS = 20_000; const POLL_MS = 200; /** Grace for the close callback after force-closing idle sockets down. */ const FORCE_CLOSE_GRACE_MS = 1_000; +/** #3044: how long to wait for a killed replacement to actually die before + * escalating to a loud manual-cleanup error — an unverified kill is how the + * orphan processes of that report survived their parent's timeout. */ +const KILL_VERIFY_MS = 2_000; type AutoRestartInput = { enabled: boolean; @@ -197,6 +214,9 @@ type SelfRestartDeps = { * startServer() (restartForceCloseOf); returns how many were destroyed. * Absent for plain servers (tests) — force-close stays as before. */ destroyLingeringSockets?: () => number; + /** Kill-verification window in ms after terminating a failed replacement + * (#3044). Injectable for tests; defaults to KILL_VERIFY_MS. */ + killVerifyMs?: number; }; type SelfRestartResult = { ok: boolean; error?: string; childPid?: number }; @@ -292,10 +312,16 @@ export async function performSelfRestart(deps: SelfRestartDeps): Promise { exitReason = String(err); }); + // Readiness signal ladder (#3044). The authoritative proof that the + // handover landed is the replacement's OWN registry record (its pid plus + // the port it ACTUALLY bound, written on announceListening). A raw TCP + // answer on our port can come from a racing peer (a host respawn during + // our drain window) — trusting it made us exit believing the upgrade had + // landed while the real replacement idled on a drifted port serving no + // client. The TCP probe remains as fallback only (pre-registry children, + // and children that have not announced yet). + type HandoverOutcome = + | { kind: "ready" } + | { kind: "misplaced"; boundPort: number } + | { kind: "superseded"; peerPid: number } + | { kind: "not-ready"; exitReason?: string }; + const childPid = child.pid; const readyDeadline = Date.now() + readyTimeoutMs; - let ready = false; + let outcome: HandoverOutcome = { kind: "not-ready", exitReason }; while (Date.now() < readyDeadline) { - if (exitReason !== undefined) break; - if (await probeReady(probeHostFor(host), port)) { ready = true; break; } + if (exitReason !== undefined) { outcome = { kind: "not-ready", exitReason }; break; } + const ownRecord = childPid !== undefined ? listInstances().find((e) => e.pid === childPid) : undefined; + if (ownRecord !== undefined) { + outcome = ownRecord.port === port + ? { kind: "ready" } + : { kind: "misplaced", boundPort: ownRecord.port }; + break; + } + if (await probeReady(probeHostFor(host), port)) { + // Our OWN registry record (written at our announceListening) still + // claims this port while we drain — without excluding process.pid a + // healthy not-yet-announced replacement reads as "superseded by us" + // and gets killed (pinned by the #2895 tunnel handover test). + const foreignPeer = listInstances().find((e) => e.port === port && e.pid !== childPid && e.pid !== process.pid && isPidAlive(e.pid)); + if (foreignPeer !== undefined) { + outcome = { kind: "superseded", peerPid: foreignPeer.pid }; + } else { + outcome = { kind: "ready" }; + } + break; + } await sleep(POLL_MS); } - if (!ready) { - try { child.kill(); } catch { /* already gone */ } - log("warn", `[restart] aborted: replacement did not become ready within ${readyTimeoutMs / 1000}s${exitReason ? ` (${exitReason})` : ""} — resuming service`); - resumeListening(server, host, port, log); - return { ok: false, error: exitReason ?? "replacement-not-ready" }; + if (outcome.kind === "ready") { + log("info", `[restart] replacement is up (pid ${childPid ?? "?"}) — handing over v${deps.runningVersion} -> v${deps.diskVersion}, exiting`); + (deps.finish ?? defaultFinish)(); + return { ok: true, childPid }; + } + if (outcome.kind === "misplaced") { + log("error", `[restart] replacement bound port ${outcome.boundPort} instead of ${port} — terminating it; a drifted replacement serves no client while the prior instance keeps the real port (#3044)`); + } else if (outcome.kind === "superseded") { + log("warn", `[restart] port ${port} is already served by another bili instance (pid ${outcome.peerPid}) — treating the upgrade as landed there; terminating our still-starting replacement`); + } else { + log("warn", `[restart] aborted: replacement did not become ready within ${readyTimeoutMs / 1000}s${outcome.exitReason ? ` (${outcome.exitReason})` : ""}`); } + await killAndVerify(child, childPid, deps.killVerifyMs ?? KILL_VERIFY_MS, log); + // Terminal decision (#3044): if another LIVE bili instance now owns our + // port, resuming THIS old-code copy would ladder-drift it onto a fresh + // port nobody routes to — the zombie half of the reported leak. The + // upgrade effectively landed elsewhere; exit cleanly instead. A foreign + // non-bili squatter keeps today's resume behavior. + const biliPeer = listInstances().find((e) => e.port === port && e.pid !== process.pid && isPidAlive(e.pid)); + if (biliPeer !== undefined) { + log("warn", `[restart] port ${port} is served by bili instance pid ${biliPeer.pid} — exiting instead of resuming (a resumed old-code copy would drift to a new port and leak, #3044)`); + (deps.finish ?? defaultFinish)(); + return { ok: true, childPid }; + } + log("warn", "[restart] resuming service"); + resumeListening(server, host, port, log); + return { + ok: false, + error: outcome.kind === "misplaced" + ? `replacement-misplaced:${outcome.boundPort}` + : outcome.kind === "superseded" + ? "superseded-by-peer" + : (outcome.exitReason ?? "replacement-not-ready"), + }; +} - log("info", `[restart] replacement is up (pid ${child.pid ?? "?"}) — handing over v${deps.runningVersion} -> v${deps.diskVersion}, exiting`); - (deps.finish ?? defaultFinish)(); - return { ok: true, childPid: child.pid }; +/** Terminate a failed replacement and verify it actually died (#3044): a + * kill that silently no-ops leaves exactly the orphan processes that report + * describes — idle, holding a port nobody routes to, accumulating memory. */ +async function killAndVerify(child: ChildProcess, pid: number | undefined, verifyMs: number, log: Logger): Promise { + try { child.kill(); } catch { /* already gone */ } + if (pid === undefined) return; + const deadline = Date.now() + verifyMs; + while (Date.now() < deadline) { + if (!isPidAlive(pid)) return; + await sleep(POLL_MS); + } + log("error", `[restart] replacement pid ${pid} is still alive after SIGTERM — manual cleanup required (kill ${pid}); until it dies it keeps leaking CPU/memory on a port nobody routes to (#3044)`); } function resumeListening(server: http.Server, host: string, port: number, log: Logger): void { diff --git a/src/server.ts b/src/server.ts index 2d1726751e..09aee84b5a 100644 --- a/src/server.ts +++ b/src/server.ts @@ -58,6 +58,7 @@ import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcil import { biliToolsDeclaredOnWire, countBiliToolUses, evaluateSelfHealRound, nudgeSuppressed, pluginLaneDegraded, pluginLaneRestore } from "./session-self-heal.js"; import { getSession, hasProcessedState, listSessions, peekSession, type PendingRetrieval, type Session, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, totalInFlight, snapshotMessages, ensureCanonicalId, storeEffectiveConfig, foldCoverage, postRebuildAnchorTokens, setPostRebuildAnchor, tickPostRebuildAnchor, splitSessionWarnings, RESPONSES_TURN_SEPARATOR_ID_PREFIX } from "./session.js"; import { detectStaleInstall } from "./update.js"; +import { decideEaddrinuse, postBindCanLadder, UPGRADE_REPLACEMENT_ENV } from "./listen-policy.js"; import { getAdvisoryState, cannotResolveTarget } from "./advisory.js"; import { PACKAGE_NAME, VERSION } from "./version.js"; import { @@ -97,7 +98,7 @@ import { getStore } from "./persist.js"; import { log as loggerLog, configureLogger, getLogPath, closeLogger, isFileLoggingActive, isStreamWriteError, isBenignSocketRaceError, enterSessionContext, muteStderrLeg } from "./logger.js"; import { queryLogLines } from "./web/logs-query.js"; import { configFile, defaultLogFile, stateDir } from "./paths.js"; -import { atomicWriteInstanceFile, clearProxyInstanceFile, entryScriptFingerprint, findSameLanePredecessor, isPidAlive, listInstances, readProxyInstanceFile, registerInstanceAndWarn, unregisterInstance, warnOnNewPeers, type ProxyInstanceFile } from "./instance.js"; +import { atomicWriteInstanceFile, clearProxyInstanceFile, entryScriptFingerprint, findSameLanePredecessor, findSameLaneTwin, isPidAlive, listInstances, readProxyInstanceFile, registerInstanceAndWarn, unregisterInstance, warnOnNewPeers, type ProxyInstanceFile, type RegistryEntry } from "./instance.js"; import { mayClobberPointer, probeOwnerInfo, resolvePortClaim } from "./port-owner.js"; import { hoistTrappedToolItems } from "./tool-pair-order.js"; import { computeAnthropicMessageMarks, stampAnthropicSystemCacheControl, anthropicToolsCarryCacheControl } from "./loop/cache-control.js"; @@ -911,6 +912,11 @@ export async function startServer(opts: ProxyOptions): Promise { // "success" would strand every model request on the dead original port. const launchToken = process.env.BILI_LAUNCH_TOKEN?.trim(); const strictPort = process.env.BILI_STRICT_PORT === "1"; + // #3044: a self-restart replacement must own exactly the port its + // predecessor freed — it fails fast instead of inheriting the +1 ladder + // (hopping strands it serving no client while the old instance keeps the + // real port: the orphan leak #3044 reports). + const upgradeReplacement = process.env[UPGRADE_REPLACEMENT_ENV] === "1"; // #1225: lane identity + code fingerprint recorded into the instance file // so later launches can decide reuse by WHO started us and WHICH code we // run — not just config shape (same-version stale dist kept serving after @@ -1121,7 +1127,7 @@ export async function startServer(opts: ProxyOptions): Promise { const outcome = await resolvePortClaim({ origin: boundOrigin(addr.port), ownPid: process.pid, - canLadder: Boolean(launchToken) && !strictPort, + canLadder: postBindCanLadder(Boolean(launchToken), strictPort, upgradeReplacement), listenAttempts, maxListenAttempts: MAX_LISTEN_ATTEMPTS, }); @@ -1166,23 +1172,43 @@ export async function startServer(opts: ProxyOptions): Promise { // graceful-shutdown flush can run. Catch, log a human-readable message, // flush sessions, and exit cleanly (exit code 1 so callers/scripts notice). server.on("error", (err: NodeJS.ErrnoException) => { - if (err.code === "EADDRINUSE" && launchToken && !strictPort && listenAttempts < MAX_LISTEN_ATTEMPTS) { - if (predecessorTicksLeft > 0 && sameLanePredecessorHolds(lastTriedPort)) { + let busyReason: "upgrade-replacement" | "strict-port" | "port-busy" | "twin-collision" | undefined; + let twin: RegistryEntry | undefined; + if (err.code === "EADDRINUSE") { + twin = findSameLaneTwin(listInstances(), lastTriedPort, launcherLane, ownFingerprint); + const action = decideEaddrinuse({ + upgradeReplacement, + twinHolds: twin !== undefined, + launchToken: launchToken !== undefined, + strictPort, + attempts: listenAttempts, + maxAttempts: MAX_LISTEN_ATTEMPTS, + predecessorTicksLeft, + predecessorHolds: sameLanePredecessorHolds(lastTriedPort), + lastTriedPort, + }); + if (action.kind === "wait-predecessor") { predecessorTicksLeft -= 1; - setTimeout(() => attemptListen(lastTriedPort), PREDECESSOR_WAIT_MS); + setTimeout(() => attemptListen(action.port), PREDECESSOR_WAIT_MS); return; } - listenAttempts += 1; - const next = listenAttempts === MAX_LISTEN_ATTEMPTS ? 0 : lastTriedPort + 1; - log("warn", `port ${lastTriedPort} busy — ${next === 0 ? "retrying on an ephemeral port" : `retrying on port ${next}`}`); - attemptListen(next); - return; + if (action.kind === "ladder") { + listenAttempts += 1; + log("warn", `port ${lastTriedPort} busy — ${action.nextPort === 0 ? "retrying on an ephemeral port" : `retrying on port ${action.nextPort}`}`); + attemptListen(action.nextPort); + return; + } + busyReason = action.reason; } const hint = err.code === "EADDRINUSE" - ? strictPort - ? ` — port ${lastTriedPort} is pinned (strict-port mode) but already in use. Free it or point the client at another port (e.g. BILI_CLAUDE_NATIVE_PORT for the claude native posture).` - : ` — port ${lastTriedPort} is already in use. Stop the other process or use --port .` + ? busyReason === "twin-collision" + ? ` — port ${lastTriedPort} is already served by a same-build bili instance (pid ${twin?.pid}, lane ${launcherLane}) — exiting instead of hopping: the duplicate loses and the serving instance keeps serving; the next launch will attach to it (#3044).` + : busyReason === "upgrade-replacement" + ? ` — this process is an upgrade-restart replacement (#3044): it must own port ${lastTriedPort} exactly, but the prior instance still holds it. Exiting instead of hopping to ${lastTriedPort + 1} — a drifted replacement serves no client and leaks while the prior instance keeps serving; the upgrade retries on the next cooldown cycle.` + : busyReason === "strict-port" + ? ` — port ${lastTriedPort} is pinned (strict-port mode) but already in use. Free it or point the client at another port (e.g. BILI_CLAUDE_NATIVE_PORT for the claude native posture).` + : ` — port ${lastTriedPort} is already in use. Stop the other process or use --port .` : err.code === "EACCES" ? ` — port ${lastTriedPort} requires privileges. Use a port >= 1024.` : ""; diff --git a/tests/auto-restart.test.ts b/tests/auto-restart.test.ts index 8758ff8746..6bbf7987f7 100644 --- a/tests/auto-restart.test.ts +++ b/tests/auto-restart.test.ts @@ -15,6 +15,8 @@ import { startServer as startBiliServer, restartForceCloseOf } from "../src/serv import type { ProxyOptions } from "../src/config.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { isPidAlive } from "../src/instance.ts"; +import { UPGRADE_REPLACEMENT_ENV } from "../src/listen-policy.ts"; const root = mkdtempSync(path.join(tmpdir(), "bc-auto-restart-")); process.env.XDG_CACHE_HOME = path.join(root, "cache"); @@ -464,10 +466,16 @@ test("performSelfRestart: hands the platform-specific spawn options through to s finish: () => {}, }); assert.equal(result.ok, true, JSON.stringify(result)); + const baseOpts = selfRestartSpawnOptions(platform); assert.deepEqual( record.options, - selfRestartSpawnOptions(platform), - `${platform}: spawn must be called with the platform-specific options`, + { + ...baseOpts, + // #3044: the replacement is marked so it cannot inherit the + // launcher's +1 ladder rights (bind-or-die on the freed port). + env: { ...(baseOpts.env as NodeJS.ProcessEnv), [UPGRADE_REPLACEMENT_ENV]: "1" }, + }, + `${platform}: spawn must be called with the platform-specific options plus the #3044 replacement marker`, ); } finally { record.child?.kill(); @@ -520,3 +528,168 @@ test("readLastRestart: tolerant of missing/corrupt markers", async () => { await writeFile(path.join(markerDir, ".auto-restart"), JSON.stringify({ ts: 12345, from: "1.0.0", to: "1.0.1" })); assert.equal(await readLastRestart(), 12345); }); + +// --------------------------------------------------------------------------- +// #3044: occupied target port must never strand an orphan replacement. The +// old shape: a replacement that hit EADDRINUSE on the freed port silently +// hopped +1 and idled serving no client while the prior instance kept the +// real port — accumulating one zombie per upgrade cycle. Pinned here at the +// parent side (readiness verification + terminal decision); the child side +// (bind-or-die) is pinned in listen-policy.test.ts and port-zone-live.test.ts. +// --------------------------------------------------------------------------- + +function instancesDir(): string { + return path.join(process.env.XDG_STATE_HOME ?? "", "billion-context", "instances"); +} + +function writeRegistryEntry(entry: Record): void { + mkdirSync(instancesDir(), { recursive: true }); + const id = typeof entry.instanceId === "string" ? entry.instanceId : "anon"; + writeFileSync(path.join(instancesDir(), `${id}.json`), JSON.stringify(entry)); +} + +// resumeListening is fire-and-forget (as in production): give the rebind a +// bounded chance to complete before asserting on the listener state. +async function waitForListening(server: { listening: boolean }, ms = 3000): Promise { + const deadline = Date.now() + ms; + while (!server.listening && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 25)); + } + return server.listening; +} + +test("performSelfRestart: replacement spawn env carries the bind-or-die marker without mutating the parent env (#3044)", { timeout: 30_000 }, async () => { + const { server, port } = await startServer(); + const { log } = makeLog(); + const record: SpawnRecord = {}; + process.env.BILI_TEST_SENTINEL = "sentinel-value"; + try { + const result = await performSelfRestart({ + server, host: "127.0.0.1", port, + installDir: makeInstall("1.0.1"), + runningVersion: "1.0.0", diskVersion: "1.0.1", + log, inFlightProvider: () => 0, + platform: "linux", + spawnImpl: makeSpawn(makeReadyStub("stub-marker.mjs"), port, record), + settleMs: 500, readyTimeoutMs: 5000, + finish: () => {}, + }); + assert.equal(result.ok, true, JSON.stringify(result)); + const env = record.options?.env as NodeJS.ProcessEnv | undefined; + assert.ok(env, "spawn options carry an env"); + assert.equal(env[UPGRADE_REPLACEMENT_ENV], "1", "replacement marked so it binds-or-dies on the freed port (#3044)"); + assert.equal(env.BILI_TEST_SENTINEL, "sentinel-value", "inherited env survives the merge"); + assert.equal(process.env[UPGRADE_REPLACEMENT_ENV], undefined, "the parent's own env must not be mutated"); + } finally { + delete process.env.BILI_TEST_SENTINEL; + record.child?.kill(); + server.closeAllConnections?.(); + await new Promise((r) => server.close(() => r())); + } +}); + +test("performSelfRestart: replacement that binds the WRONG port is terminated and service resumes (#3044)", { timeout: 30_000 }, async () => { + const { server, port } = await startServer(); + const { log, entries } = makeLog(); + const record: SpawnRecord = {}; + try { + const pending = performSelfRestart({ + server, host: "127.0.0.1", port, + installDir: makeInstall("1.0.1"), + runningVersion: "1.0.0", diskVersion: "1.0.1", + log, inFlightProvider: () => 0, + // The stub listens on port+9 instead of the freed port: it models a + // replacement that drifted via the old ladder after EADDRINUSE. + spawnImpl: makeSpawn(makeReadyStub("stub-misplaced.mjs"), port + 9, record), + settleMs: 500, readyTimeoutMs: 5000, + finish: () => assert.fail("must not finish when the replacement drifted"), + }); + for (let i = 0; i < 500 && record.child?.pid === undefined; i++) { + await new Promise((r) => setTimeout(r, 10)); + } + assert.ok(record.child?.pid, "replacement spawned"); + // The drifted replacement announces itself on the wrong port — exactly + // what the parent's readiness loop must catch instead of trusting TCP. + writeRegistryEntry({ instanceId: "stub-misplaced", pid: record.child.pid, port: port + 9, origin: `http://127.0.0.1:${port + 9}`, startedAt: Date.now(), lane: "dsh" }); + const result = await pending; + assert.equal(result.ok, false, JSON.stringify(result)); + assert.equal(result.error, `replacement-misplaced:${port + 9}`); + assert.match(entries.join("\n"), /bound port \d+ instead of \d+ — terminating/s); + assert.equal(await waitForListening(server), true, "original listener must be resumed"); + assert.equal(await requestOk(port), true, "resumed listener must serve"); + if (record.child?.pid !== undefined) { + for (let i = 0; i < 100 && isPidAlive(record.child.pid); i++) await new Promise((r) => setTimeout(r, 20)); + assert.equal(isPidAlive(record.child.pid), false, "misplaced replacement must be gone — no orphan left behind"); + } + } finally { + record.child?.kill("SIGKILL"); + server.closeAllConnections?.(); + await new Promise((r) => server.close(() => r())); + } +}); + +test("performSelfRestart: port taken over by another bili instance → parent exits instead of resuming (#3044)", { timeout: 30_000 }, async () => { + const { server, port } = await startServer(); + const { log, entries } = makeLog(); + const record: SpawnRecord = {}; + let finished = 0; + // A live non-listening process standing in for a peer bili instance. + const sleeper = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000);"], { stdio: "ignore" }); + try { + assert.ok(sleeper.pid, "sleeper pid for the fake peer"); + // A live bili peer now owns our port (e.g. a host respawn that beat the + // replacement): resuming THIS old-code copy would ladder-drift it onto + // a fresh port nobody routes to — the zombie half of the leak. + writeRegistryEntry({ instanceId: "superseding-peer", pid: sleeper.pid, port, origin: `http://127.0.0.1:${port}`, startedAt: Date.now(), lane: "dsh" }); + const result = await performSelfRestart({ + server, host: "127.0.0.1", port, + installDir: makeInstall("1.0.1"), + runningVersion: "1.0.0", diskVersion: "1.0.1", + log, inFlightProvider: () => 0, + spawnImpl: makeSpawn(makeCrashStub("stub-superseded.mjs"), port, record), + settleMs: 500, readyTimeoutMs: 3000, + finish: () => { finished++; }, + }); + assert.equal(result.ok, true, "the upgrade landed elsewhere — handover achieved, parent exits cleanly"); + assert.equal(finished, 1, "finish seam called exactly once"); + assert.equal(server.listening, false, "no resume: the old-code copy must not drift onto a new port"); + assert.match(entries.join("\n"), /served by bili instance pid \d+ — exiting instead of resuming/s); + } finally { + record.child?.kill(); + try { sleeper.kill("SIGKILL"); } catch {} + server.closeAllConnections?.(); + await new Promise((r) => server.close(() => r())); + } +}); + +test("performSelfRestart: a replacement that survives SIGTERM is escalated loudly (#3044)", { timeout: 30_000 }, async () => { + const { server, port } = await startServer(); + const { log, entries } = makeLog(); + const record: SpawnRecord = {}; + const stubborn = path.join(root, "stub-stubborn.mjs"); + writeFileSync(stubborn, [ + "process.on('SIGTERM', () => {});", + "setInterval(() => {}, 1000);", + ].join("\n")); + try { + const result = await performSelfRestart({ + server, host: "127.0.0.1", port, + installDir: makeInstall("1.0.1"), + runningVersion: "1.0.0", diskVersion: "1.0.1", + log, inFlightProvider: () => 0, + spawnImpl: makeSpawn(stubborn, port, record), + settleMs: 500, readyTimeoutMs: 800, killVerifyMs: 400, + finish: () => assert.fail("must not finish while the replacement is stuck"), + }); + assert.equal(result.ok, false, JSON.stringify(result)); + assert.equal(result.error, "replacement-not-ready"); + // An unverified kill was how the orphans of #3044 survived their + // parent's timeout — the loud escalation is the point of this test. + assert.match(entries.join("\n"), /still alive after SIGTERM — manual cleanup required \(kill \d+\)/s); + assert.equal(await waitForListening(server), true, "service resumes regardless"); + } finally { + record.child?.kill("SIGKILL"); + server.closeAllConnections?.(); + await new Promise((r) => server.close(() => r())); + } +}); diff --git a/tests/listen-policy.test.ts b/tests/listen-policy.test.ts new file mode 100644 index 0000000000..79aa11ff23 --- /dev/null +++ b/tests/listen-policy.test.ts @@ -0,0 +1,90 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { decideEaddrinuse, postBindCanLadder, UPGRADE_REPLACEMENT_ENV, type EaddrinuseContext } from "../src/listen-policy.ts"; + +const base: EaddrinuseContext = { + upgradeReplacement: false, + twinHolds: false, + launchToken: true, + strictPort: false, + attempts: 0, + maxAttempts: 17, + predecessorTicksLeft: 10, + predecessorHolds: false, + lastTriedPort: 18787, +}; + +test("decideEaddrinuse: upgrade replacement never ladders (#3044)", () => { + // No predecessor recognized (foreign squatter, same-code peer, or no lane): + // fail fast on the first hit — the +1 ladder is exactly what stranded the + // orphan processes of #3044. + assert.deepEqual( + decideEaddrinuse({ ...base, upgradeReplacement: true }), + { kind: "fail-fast", reason: "upgrade-replacement" }, + ); + // A same-lane DIFFERENT-code holder gets the bounded same-port wait + // (#1723 overlap: the prior instance may still be releasing)... + assert.deepEqual( + decideEaddrinuse({ ...base, upgradeReplacement: true, predecessorHolds: true }), + { kind: "wait-predecessor", port: 18787 }, + ); + // ...but once the budget is spent it still fails fast instead of laddering. + assert.deepEqual( + decideEaddrinuse({ ...base, upgradeReplacement: true, predecessorHolds: true, predecessorTicksLeft: 0 }), + { kind: "fail-fast", reason: "upgrade-replacement" }, + ); + // The replacement contract does not depend on launch token or attempt count. + assert.deepEqual( + decideEaddrinuse({ ...base, upgradeReplacement: true, launchToken: false, attempts: 5 }), + { kind: "fail-fast", reason: "upgrade-replacement" }, + ); +}); + +test("decideEaddrinuse: legacy launcher-child behavior is unchanged", () => { + // Predecessor overlap still waits out the draining old build on the SAME port. + assert.deepEqual( + decideEaddrinuse({ ...base, predecessorHolds: true }), + { kind: "wait-predecessor", port: 18787 }, + ); + // Plain contention ladders +1... + assert.deepEqual(decideEaddrinuse(base), { kind: "ladder", nextPort: 18788 }); + // ...and the final attempt asks for an ephemeral port. + assert.deepEqual( + decideEaddrinuse({ ...base, attempts: 16 }), + { kind: "ladder", nextPort: 0 }, + ); + // Exhausted attempts fall through to fail-fast. + assert.deepEqual( + decideEaddrinuse({ ...base, attempts: 17 }), + { kind: "fail-fast", reason: "port-busy" }, + ); +}); + +test("decideEaddrinuse: strict-port and manual launches keep their fail-fast reasons", () => { + assert.deepEqual( + decideEaddrinuse({ ...base, strictPort: true }), + { kind: "fail-fast", reason: "strict-port" }, + ); + // A manual launch (no launch token) was always fail-fast; unchanged. + assert.deepEqual( + decideEaddrinuse({ ...base, launchToken: false }), + { kind: "fail-fast", reason: "port-busy" }, + ); +}); + +test("decideEaddrinuse: env marker name is stable (#3044)", () => { + assert.equal(UPGRADE_REPLACEMENT_ENV, "BILI_UPGRADE_REPLACEMENT"); +}); + +test("postBindCanLadder: a marked upgrade replacement never gains post-bind ladder rights (#3044/#2941)", () => { + // Launcher child on a contested just-bound port keeps today's move-off + // right (#2941). + assert.equal(postBindCanLadder(true, false, false), true); + // Strict-port and manual launches never laddered; unchanged. + assert.equal(postBindCanLadder(true, true, false), false); + assert.equal(postBindCanLadder(false, false, false), false); + // #3044: the replacement inherits its parent's launch token but must die + // on a contested port instead of hopping — the orphan shape, via the + // second hop path. + assert.equal(postBindCanLadder(true, false, true), false); +}); diff --git a/tests/port-zone-live.test.ts b/tests/port-zone-live.test.ts index bdc7e5b8c9..475579a71a 100644 --- a/tests/port-zone-live.test.ts +++ b/tests/port-zone-live.test.ts @@ -1,13 +1,14 @@ import test, { after } from "node:test"; import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; +import { execFileSync, spawn } from "node:child_process"; import fs from "node:fs"; import net from "node:net"; import os from "node:os"; import path from "node:path"; import { ensureProxyRunning } from "../src/launcher.ts"; -import { portZoneFilePath, readZonePort } from "../src/instance.ts"; +import { isPidAlive, portZoneFilePath, readZonePort } from "../src/instance.ts"; import { ZONE_PORT_BASE } from "../src/config.ts"; +import { UPGRADE_REPLACEMENT_ENV } from "../src/listen-policy.ts"; // #1660 live regression: the sticky-zone lifecycle against REAL proxy // processes — real spawn handshake, real EADDRINUSE ladder, real attach @@ -63,6 +64,17 @@ function killNow(pid: number | undefined): void { } } +function portOpen(port: number): Promise { + return new Promise((resolve) => { + const s = net.connect({ host: "127.0.0.1", port }); + s.once("connect", () => { + s.destroy(); + resolve(true); + }); + s.once("error", () => resolve(false)); + }); +} + function freePort(): Promise { return new Promise((resolve, reject) => { const srv = net.createServer(); @@ -331,3 +343,96 @@ test( }); }, ); + +// --------------------------------------------------------------------------- +// #3044: the orphan shape end-to-end. A self-restart replacement that cannot +// grab the freed port must DIE LOUDLY instead of hopping +1 and idling as an +// orphan nobody routes to. Spawned directly (not through ensureProxyRunning) +// so the exact replacement env is under test control: launch token + lane +// (which would earn it the #407 ladder pre-#3044) plus the bind-or-die marker. +// --------------------------------------------------------------------------- + +test( + "zone live: marked upgrade-replacement fails fast on an occupied port instead of hopping (#3044)", + { timeout: 240_000, skip: LIVE ? process.platform !== "linux" : liveSkip }, + async () => { + await withSandbox(async () => { + ensureDistBuilt(); + // A non-bili squatter holds the zone base: no same-lane predecessor + // is recognized, so the marked child gets no wait budget at all — + // first EADDRINUSE must be its last breath. Under the pre-#3044 + // ladder this exact spawn drifted to base+1 and idled there. + const squatter = await squatted(ZONE_PORT_BASE); + const child = spawn( + process.execPath, + [distCli, "start", "--host", "127.0.0.1", "--port", String(ZONE_PORT_BASE)], + { + env: { + ...process.env, + BILI_LAUNCH_TOKEN: "3044-live-test", + BILI_LAUNCHER_LANE: "zcode", + [UPGRADE_REPLACEMENT_ENV]: "1", + }, + stdio: "ignore", + detached: true, + }, + ); + trackKill(child.pid); + try { + const exitCode = await new Promise((resolve) => { + child.once("exit", (code) => resolve(code)); + setTimeout(() => resolve(undefined), 120_000).unref(); + }); + assert.equal(exitCode, 1, "the marked replacement must fail fast with exit code 1 (upgrade pending, host decides retry)"); + assert.equal(await portOpen(ZONE_PORT_BASE + 1), false, "nothing may have hopped onto the next port — that idle hopper IS the #3044 orphan shape"); + assert.equal(await portOpen(ZONE_PORT_BASE), true, "the squatter still owns the base port"); + squatter.close(); + } finally { + killNow(child.pid); + } + }); + }, +); + +test( + "zone live: unmarked lane'd spawn against a LIVE same-build twin exits instead of hopping (#3044)", + { timeout: 240_000, skip: LIVE ? process.platform !== "linux" : liveSkip }, + async () => { + await withSandbox(async () => { + ensureDistBuilt(); + // The 2026-10-13 recurrence shape: a host respawn raced an attach + // scan and spawned while an identical instance already served the + // lane's port. Before this fix that child laddered to base+1 and + // idled as an orphan; now the duplicate must lose loudly. Spawned + // directly (unmarked, exactly what the launcher produces) because + // ensureProxyRunning would attach to the twin and never spawn. + const h1 = await launch({ lane: "zcode" }); + const daemon1 = h1.child?.pid; + trackKill(daemon1); + assert.equal(h1.port, ZONE_PORT_BASE, "precondition: the twin serves the zone base"); + const child = spawn( + process.execPath, + [distCli, "start", "--host", "127.0.0.1", "--port", String(ZONE_PORT_BASE)], + { + env: { ...process.env, BILI_LAUNCH_TOKEN: "3044-twin-test", BILI_LAUNCHER_LANE: "zcode" }, + stdio: "ignore", + detached: true, + }, + ); + trackKill(child.pid); + try { + const exitCode = await new Promise((resolve) => { + child.once("exit", (code) => resolve(code)); + setTimeout(() => resolve(undefined), 120_000).unref(); + }); + assert.equal(exitCode, 1, "the duplicate must fail fast with exit code 1"); + assert.equal(await portOpen(ZONE_PORT_BASE + 1), false, "nothing may have hopped onto the next port — the hopper IS the orphan shape"); + assert.equal(await portOpen(ZONE_PORT_BASE), true, "the serving twin keeps its port"); + assert.ok(daemon1 !== undefined && isPidAlive(daemon1), "the serving twin must still be alive"); + } finally { + killNow(child.pid); + killNow(daemon1); + } + }); + }, +); diff --git a/website/config-reference/env-only.yaml b/website/config-reference/env-only.yaml index 213d4021f5..7b4d0c7b4e 100644 --- a/website/config-reference/env-only.yaml +++ b/website/config-reference/env-only.yaml @@ -154,6 +154,14 @@ entries: group: envonly desc_en: "Spawn channel: exact-port requirement (squatters refused loudly instead of hopping)." desc_zh: "派生通道:精确端口要求(被占用时响亮拒绝而非跳端口)。" + - key: BILI_UPGRADE_REPLACEMENT + type: boolean-ish + default: "unset" + kind: env-only + audience: internal + group: envonly + desc_en: "Spawn channel: marks a self-restart replacement — it must own exactly the freed port or exit without hopping (#3044)." + desc_zh: "派生通道:标记自重启替换进程——必须独占被释放的精确端口,否则直接退出而非跳端口(#3044)。" - key: BILI_OPENCODE_ACP_SPEC type: string default: "unset"