From f07d5c2404019754213da9c450185801481e72c0 Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 24 Nov 2026 22:36:04 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix:=20log=20mid-stream=20abort=20origin=20?= =?UTF-8?q?=E2=80=94=20distinguish=20client=20hangup=20from=20bili-initiat?= =?UTF-8?q?ed=20abort=20(#7661)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "client aborted mid-stream" fired for BOTH a client that hung up and a bili-initiated abort (runaway guard / upstream watchdog): both surface as a generic AbortError on a destroyed/ended response, so the log could not say who initiated it. #7661's ~20% DSH mid-stream aborts were stuck on exactly this observability gap. Tag each response with its abort origin (a global Symbol.for property, set at the initiation sites — the client close handler and the runaway guard) and render the line by origin in the catch sites. A bili-initiated abort now logs "bili-initiated abort mid-stream ... [origin: X]"; client-initiated and unknown-origin cases keep the exact old string (grep-stable). Behavior change (intended): bili-initiated mid-stream aborts log a distinct "bili-initiated abort mid-stream" line (was mislabeled "client"); client aborts are byte-identical to before. --- src/inline-engine.ts | 8 ++-- src/logger.ts | 31 +++++++++++++ src/plugin.ts | 8 ++-- src/server.ts | 5 ++- src/server/relay.ts | 5 ++- tests/issue7661-abort-origin.test.ts | 65 ++++++++++++++++++++++++++++ 6 files changed, 111 insertions(+), 11 deletions(-) create mode 100644 tests/issue7661-abort-origin.test.ts diff --git a/src/inline-engine.ts b/src/inline-engine.ts index eaee425ef2..b9732b8227 100644 --- a/src/inline-engine.ts +++ b/src/inline-engine.ts @@ -19,7 +19,7 @@ import { createEngineContext, type EngineContext } from "./server.js"; import { handle } from "./server/handle.js"; import { withFetchTransport } from "./fetch-transport.js"; import type { FetchOptions } from "./fetch-util.js"; -import { log as loggerLog, muteStderrLeg } from "./logger.js"; +import { log as loggerLog, muteStderrLeg, getAbortOrigin, abortMidStreamLine } from "./logger.js"; import { buildProxyFailureResponse, isExpectedFailFast } from "./upstream-fail.js"; /** Pseudo-origin of the inline lane. Never DNS-resolved: any request reaching @@ -305,7 +305,7 @@ function makeDispatcher(ctx: EngineContext): InlineEngine["dispatch"] { const msg = String(err); const e = err as { name?: string; message?: string }; const clientAbort = (e?.name === "AbortError" || /abort/i.test(String(e?.message ?? ""))) && (res.destroyed || res.writableEnded); - if (clientAbort && !abortSurfaced) ctx.log("info", `client aborted mid-stream: ${msg}`); + if (clientAbort && !abortSurfaced) ctx.log("info", abortMidStreamLine(msg, getAbortOrigin(res))); // #2465/#5663: classified transport deaths are already fully described on // one line (kind/code/errno/syscall/address/hint) — stack frames add no signal. else if (err instanceof Error && (err as Error & { biliTransportFailure?: boolean }).biliTransportFailure === true) ctx.log("error", msg); @@ -339,7 +339,7 @@ function makeDispatcher(ctx: EngineContext): InlineEngine["dispatch"] { const e = err as { name?: string; message?: string }; if ((e?.name === "AbortError" || /abort/i.test(String(e?.message ?? ""))) && res.destroyed) { abortSurfaced = true; - ctx.log("info", `client aborted mid-stream: ${String(err)}`); + ctx.log("info", abortMidStreamLine(String(err), getAbortOrigin(res))); } throw err; } finally { @@ -372,7 +372,7 @@ function makeHttpDispatch(ctx: EngineContext): InlineEngine["dispatchHttp"] { const msg = String(err); const e = err as { name?: string; message?: string }; const clientAbort = (e?.name === "AbortError" || /abort/i.test(String(e?.message ?? ""))) && (res.destroyed || res.writableEnded); - if (clientAbort) ctx.log("info", `client aborted mid-stream: ${msg}`); + if (clientAbort) ctx.log("info", abortMidStreamLine(msg, getAbortOrigin(res))); else if (err instanceof Error && err.stack) ctx.log("error", `${msg}\n${err.stack.split("\n").slice(1, 8).join("\n")}`); else ctx.log("error", msg); if (res.destroyed) return; diff --git a/src/logger.ts b/src/logger.ts index b54c5ba9be..582e15f98c 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -63,6 +63,37 @@ const MAX_BYTES = (): number => logRetention().segmentBytes; export type Logger = (level: string, msg: string) => void; +// ── Mid-stream abort origin (#7661) ───────────────────────────────────────── +// The "client aborted mid-stream" log line (server.ts dispatch catch, +// inline-engine, plugin pipe) fires for BOTH a client that hung up AND a +// bili-initiated abort (runaway guard, upstream watchdog), because both +// surface as a generic AbortError on a destroyed/ended response. This +// per-response tag lets the catch sites say WHO initiated the abort — the +// observability gap #7661's 20% DSH mid-stream aborts were stuck on. The +// symbol rides the global Symbol.for registry so the tag is readable across +// module boundaries without an import cycle (logger is the one leaf every +// abort site already imports). +export const ABORT_ORIGIN = Symbol.for("bili.abortOrigin"); +export type AbortOrigin = "client-disconnect" | "runaway-guard" | "upstream-watchdog" | "bili-internal"; + +export function setAbortOrigin(res: object, origin: AbortOrigin): void { + Object.defineProperty(res, ABORT_ORIGIN, { value: origin, enumerable: false, writable: true }); +} + +export function getAbortOrigin(res: object): AbortOrigin | undefined { + return (res as unknown as Record)[ABORT_ORIGIN] as AbortOrigin | undefined; +} + +/** The mid-stream abort log line, attributed by origin. A bili-initiated abort + * (runaway guard / watchdog) is no longer mislabeled "client"; the origin tag + * rides the tail so the base phrase stays grep-stable. `msg` is optional — the + * plugin pipe sites log the bare phrase, the dispatch catches append the error. */ +export function abortMidStreamLine(msg: string | undefined, origin: AbortOrigin | undefined): string { + const tail = msg !== undefined ? `: ${msg}` : ""; + if (origin && origin !== "client-disconnect") return `bili-initiated abort mid-stream${tail} [origin: ${origin}]`; + return `client aborted mid-stream${tail}`; +} + // ── Request-scoped session attribution ───────────────────────────────────── // enterSessionContext() is called once per inbound model request, at the point // where identity resolves (server.ts main pipeline funnel). Because it rides diff --git a/src/plugin.ts b/src/plugin.ts index 1aa848c154..06efde6941 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -23,7 +23,7 @@ import { executeProxyToolAsync } from "./loop/core.js"; import type { ProxyToolResult } from "./proxy-tool-result.js"; import { normalizeSseLineEndings, finalizeSseLineEndings } from "./sse-util.js"; import { composeStreamFilters, containsBiliInternalText, containsEchoResidue, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, containsToolCallXmlFragment, createBiliArtifactFilter, createIdentityStreamFilter, createMarkerLineFilter, createTagEchoFilter, isOrphanMarkupText, mayStartBiliInternal, mayStartDegenerateRenderTag, mayStartMarkerLine, mayStartRenderTag, mayStartToolCallEmission, stripAcpTags, stripAnthropicText, stripOpenaiChatText, stripResponsesText, type TagEchoFilter } from "./loop/tag-echo-filter.js"; -import { log as loggerLog } from "./logger.js"; +import { log as loggerLog, getAbortOrigin, abortMidStreamLine } from "./logger.js"; import { scanModelOutputForPhantomAttachments } from "./phantom-attachment.js"; import { ccrEnabled, ccrLoopConfig, contentStoreOf, retrieveToolName } from "./store.js"; import { formatProtectedMass, uncoveredAudit, type ProtectedMassLedger } from "./uncovered.js"; @@ -4277,7 +4277,7 @@ export async function pipePluginChatWithStrip( maybeSummarizeStrips(); settleWitnesses(); if (res.destroyed || res.writableEnded) { - log?.("client aborted mid-stream"); + log?.(abortMidStreamLine(undefined, getAbortOrigin(res))); // #5293: the partial output of an aborted turn never reports usage — record the pre-abort anchor so the first nudge decision after resume can absorb that debt. if (session) noteAbortedTurn(session); // A terminal already arrived before the client left: the reply is @@ -4447,7 +4447,7 @@ export async function pipePluginJsonlWithStrip( } catch (e) { settleUsage(); if (res.destroyed || res.writableEnded) { - log?.("client aborted mid-stream"); + log?.(abortMidStreamLine(undefined, getAbortOrigin(res))); return; } try { await flushFieldTails(); } catch { /* client half-gone; the signal below is best-effort too */ } @@ -5376,7 +5376,7 @@ export async function pipePluginResponsesWithStrip( maybeSummarizeStrips(); settleWitnesses(); if (res.destroyed || res.writableEnded) { - log?.("client aborted mid-stream"); + log?.(abortMidStreamLine(undefined, getAbortOrigin(res))); // #5293: same as the chat lane — record the pre-abort anchor for the post-resume re-anchor. if (session) noteAbortedTurn(session); // Completed turn, dead socket: keep the reply for the handoff render. diff --git a/src/server.ts b/src/server.ts index 61525fdf2f..f883824bfd 100644 --- a/src/server.ts +++ b/src/server.ts @@ -98,7 +98,7 @@ import { reapOrphanBlocks } from "./orphan-gc.js"; import { conflictScanEnabled, isDesignBenign, scanClientPlugins, sniffScanClient } from "./thirdparty-scan.js"; import { clearConflictEvents, recordConflict, summarizeConflicts } from "./conflict-watch.js"; import { getStore, setGlobalSessionCommitListener } from "./persist.js"; -import { log as loggerLog, configureLogger, getLogPath, closeLogger, isStreamWriteError, isBenignSocketRaceError, enterSessionContext, muteStderrLeg, onFileLegLive, shouldMuteStderrLegAfterFileLive, logTimestamp } from "./logger.js"; +import { log as loggerLog, configureLogger, getLogPath, closeLogger, isStreamWriteError, isBenignSocketRaceError, enterSessionContext, muteStderrLeg, onFileLegLive, shouldMuteStderrLegAfterFileLive, logTimestamp, setAbortOrigin, getAbortOrigin, abortMidStreamLine } from "./logger.js"; import { kernelWarnSink } from "./kernel-warn-channel.js"; import { configureLogRetention } from "./log-retention.js"; import { configFile, defaultLogFile, sessionsDir, stateDir } from "./paths.js"; @@ -853,7 +853,7 @@ export async function startServer(opts: ProxyOptions): Promise { // With the client already gone it is logged as info instead of // feeding the context-free [error] AbortError storm. const clientAbort = (e?.name === "AbortError" || /abort/i.test(String(e?.message ?? ""))) && (res.destroyed || res.writableEnded); - if (clientAbort) log("info", `client aborted mid-stream: ${msg}`); + if (clientAbort) log("info", abortMidStreamLine(msg, getAbortOrigin(res))); // #2465/#5663: classified transport deaths are already fully described on // one line (kind/code/errno/syscall/address/hint) — stack frames were pure // noise in field EHOSTUNREACH storms (305 failures × 7). @@ -4523,6 +4523,7 @@ export async function preflightCompressIfNeeded( registerRequestAbort(res, clientAbort); res.on("close", () => { if (!res.writableEnded) { + setAbortOrigin(res, "client-disconnect"); clientAbort.abort(); noteClientAbort(session); } diff --git a/src/server/relay.ts b/src/server/relay.ts index b94170967a..c15645965a 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -36,7 +36,7 @@ import { fetchWithTimeout, fetchWithTransportRetry } from "../fetch-util.js"; import { applyEgressTransforms, type EgressTransformBase } from "../egress-transforms.js"; import { currentFetchTransport } from "../fetch-transport.js"; import { countImagesInParsedBody, countImagesInRawBody, upstreamHost } from "../image-tokens.js"; -import { log as loggerLog } from "../logger.js"; +import { log as loggerLog, setAbortOrigin } from "../logger.js"; import { dumpReqAllowed as knobDumpReqAllowed, limitsMaxMessages, rawDumpDir as knobRawDumpDir } from "../knobs.js"; import { gcDumpDirIfConfigured } from "../state-gc.js"; import { applyLaneCredential, laneCredential } from "../lane-credentials.js"; @@ -1154,6 +1154,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare const ageMs = Date.now() - forwardStartedAt; const clientBytes = res.socket?.bytesWritten ?? 0; log("info", `[${prepared?.session.id ?? "passthrough"}] client disconnected mid-stream after ${ageMs}ms (${clientBytes} bytes written to client)`); + setAbortOrigin(res, "client-disconnect"); clientAbort.abort(); if (prepared?.session) noteClientAbort(prepared.session); } @@ -2278,6 +2279,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare // observe the raw upstream bytes even when the guard aborts them. pluginBody = wrapStreamWithRunawayGuard(pluginBody, (v) => { log("error", `[${prepared.session.id}] output-side runaway guard tripped (${v.reason}; ${JSON.stringify(v.detail)}) — aborting upstream stream`); + setAbortOrigin(res, "runaway-guard"); clientAbort.abort(); }); if (prepared.commandcode) { @@ -2630,6 +2632,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare // observes raw upstream bytes even when the guard aborts them. responseBody = wrapStreamWithRunawayGuard(responseBody, (v) => { log("error", `[${prepared.session.id}] output-side runaway guard tripped (${v.reason}; ${JSON.stringify(v.detail)}) — aborting upstream stream`); + setAbortOrigin(res, "runaway-guard"); clientAbort.abort(); }); // P1.1: wrap the rewriter loops in try/catch. If a rewriter throws diff --git a/tests/issue7661-abort-origin.test.ts b/tests/issue7661-abort-origin.test.ts new file mode 100644 index 0000000000..7818533bfb --- /dev/null +++ b/tests/issue7661-abort-origin.test.ts @@ -0,0 +1,65 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { ABORT_ORIGIN, abortMidStreamLine, getAbortOrigin, setAbortOrigin } from "../src/logger.ts"; + +// #7661: DSH on 0.1.216 aborted ~20% of streaming requests mid-stream, but the +// "client aborted mid-stream" log line fired for BOTH a client that hung up +// AND a bili-initiated abort (runaway guard / upstream watchdog), because both +// surface as a generic AbortError on a destroyed/ended response. Triage could +// not tell who initiated the abort. This test pins the observability fix: the +// per-response abort-origin tag plus the log line that attributes it. + +test("abortMidStreamLine attributes the line by origin (client vs bili)", () => { + // No origin set (unknown) → the legacy client phrase, grep-stable. + assert.equal(abortMidStreamLine("boom", undefined), "client aborted mid-stream: boom"); + // A client that hung up → the legacy client phrase, byte-identical to before. + assert.equal(abortMidStreamLine("boom", "client-disconnect"), "client aborted mid-stream: boom"); + // A bili-initiated abort is no longer mislabeled "client"; the origin tag + // rides the tail so the base phrase stays grep-stable. + assert.equal(abortMidStreamLine("boom", "runaway-guard"), "bili-initiated abort mid-stream: boom [origin: runaway-guard]"); + assert.equal(abortMidStreamLine("boom", "upstream-watchdog"), "bili-initiated abort mid-stream: boom [origin: upstream-watchdog]"); + assert.equal(abortMidStreamLine("boom", "bili-internal"), "bili-initiated abort mid-stream: boom [origin: bili-internal]"); + // The plugin pipe sites log the bare phrase (no error message attached). + assert.equal(abortMidStreamLine(undefined, undefined), "client aborted mid-stream"); + assert.equal(abortMidStreamLine(undefined, "client-disconnect"), "client aborted mid-stream"); + assert.equal(abortMidStreamLine(undefined, "runaway-guard"), "bili-initiated abort mid-stream [origin: runaway-guard]"); +}); + +test("setAbortOrigin / getAbortOrigin round-trip on a real ServerResponse", async () => { + let fresh: unknown; + let tagged: unknown; + let retagged: unknown; + const server = http.createServer((req, res) => { + fresh = getAbortOrigin(res); + setAbortOrigin(res, "runaway-guard"); + tagged = getAbortOrigin(res); + setAbortOrigin(res, "client-disconnect"); + retagged = getAbortOrigin(res); + res.writeHead(200, { "content-type": "text/plain", connection: "close" }); + res.end("ok"); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as { port: number }).port; + try { + await new Promise((resolve, reject) => { + http.get({ host: "127.0.0.1", port, path: "/", agent: false }, (res) => { + res.resume(); + res.on("end", () => resolve()); + }).on("error", reject); + }); + } finally { + server.closeAllConnections?.(); + await new Promise((resolve) => server.close(() => resolve())); + } + assert.equal(fresh, undefined, "a fresh response carries no abort origin"); + assert.equal(tagged, "runaway-guard", "a tagged response reads back its origin"); + assert.equal(retagged, "client-disconnect", "the origin is re-writable"); +}); + +test("ABORT_ORIGIN is the global symbol readable across module boundaries", () => { + // Symbol.for lives in the global registry — a second reference to the same + // key resolves to the very same symbol. That is what lets the tag be read + // by a catch site in a different module without an import cycle. + assert.equal(ABORT_ORIGIN, Symbol.for("bili.abortOrigin")); +}); From 5428f46fb5f30246fb118e23375e2cbe736cd690 Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 24 Nov 2026 23:12:36 +0800 Subject: [PATCH 2/3] fix: tag the request-idle watchdog abort as bili-initiated (#7661) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The request watchdog (armRequestWatchdog) aborts the CLIENT's controller (requestAborts.get(res)), so its dispatch catch was mislabeled 'client aborted mid-stream' — the same observability gap #7661 closes for the runaway guard. Tag it 'bili-internal' (the previously-unused origin value) so the catch site renders 'bili-initiated abort mid-stream [origin: bili-internal]' instead. Pure log attribution; when/whether the watchdog fires is untouched. --- src/server.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/server.ts b/src/server.ts index f883824bfd..00eb87c18f 100644 --- a/src/server.ts +++ b/src/server.ts @@ -390,6 +390,10 @@ function armRequestWatchdog(req: http.IncomingMessage, res: http.ServerResponse, if (res.writableEnded || res.destroyed || !res.socket || res.socket.destroyed) return; const secs = Math.round((Date.now() - startedAt) / 1000); log("error", `[watchdog] ${req.method ?? "?"} ${maskUrlForLog(req.url ?? "")} produced no output for ${secs}s (idle budget ${Math.round(budgetMs / 1000)}s) — closing the request so the client can fail fast instead of hanging forever`); + // #7661: this aborts the CLIENT's controller (requestAborts), so the + // dispatch catch mislabels it "client aborted mid-stream" without the tag. + // Bili-initiated (idle watchdog), not a client hangup. + setAbortOrigin(res, "bili-internal"); requestAborts.get(res)?.abort(); try { if (!res.headersSent) { From 5395894a6c74c2bc1250f61017b84e52105e90e5 Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 24 Nov 2026 23:32:13 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix:=20make=20AbortOrigin=20internal=20?= =?UTF-8?q?=E2=80=94=20only=20referenced=20inside=20src/logger.ts=20(#7661?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The unused-exports gate flagged AbortOrigin as INTERNAL_ONLY: the union type is referenced only within src/logger.ts (the three exported function signatures) and imported by no other module. Drop the leading export so the gate passes; the type still names the union at its definition site and no consumer imports it (the test uses string literals directly). --- src/logger.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/logger.ts b/src/logger.ts index 582e15f98c..11c417abb4 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -74,7 +74,7 @@ export type Logger = (level: string, msg: string) => void; // module boundaries without an import cycle (logger is the one leaf every // abort site already imports). export const ABORT_ORIGIN = Symbol.for("bili.abortOrigin"); -export type AbortOrigin = "client-disconnect" | "runaway-guard" | "upstream-watchdog" | "bili-internal"; +type AbortOrigin = "client-disconnect" | "runaway-guard" | "upstream-watchdog" | "bili-internal"; export function setAbortOrigin(res: object, origin: AbortOrigin): void { Object.defineProperty(res, ABORT_ORIGIN, { value: origin, enumerable: false, writable: true });