Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/inline-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down
31 changes: 31 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
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<symbol, unknown>)[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
Expand Down
8 changes: 4 additions & 4 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 */ }
Expand Down Expand Up @@ -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.
Expand Down
9 changes: 7 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -853,7 +857,7 @@ export async function startServer(opts: ProxyOptions): Promise<http.Server> {
// 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).
Expand Down Expand Up @@ -4523,6 +4527,7 @@ export async function preflightCompressIfNeeded(
registerRequestAbort(res, clientAbort);
res.on("close", () => {
if (!res.writableEnded) {
setAbortOrigin(res, "client-disconnect");
clientAbort.abort();
noteClientAbort(session);
}
Expand Down
5 changes: 4 additions & 1 deletion src/server/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand Down
65 changes: 65 additions & 0 deletions tests/issue7661-abort-origin.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const port = (server.address() as { port: number }).port;
try {
await new Promise<void>((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<void>((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"));
});
Loading