Skip to content
4 changes: 2 additions & 2 deletions kernel/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions src/concurrent-forwards.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// #3102: per-session in-flight model-forward counter — lets the degenerate-turn
// diagnostic line report whether another same-session forward (dsh title-gen
// sidecar, #2503) was in flight when the turn ended. Correlation only: bili's
// transport is structurally isolated (one socket per concurrent request).
// In-memory only — never persisted.

const counts = new Map<string, number>();

export function beginForward(sessionId: string): void {
counts.set(sessionId, (counts.get(sessionId) ?? 0) + 1);
}

export function endForward(sessionId: string): void {
const n = (counts.get(sessionId) ?? 0) - 1;
if (n <= 0) counts.delete(sessionId);
else counts.set(sessionId, n);
}

/** Other forwards currently in flight under the same session id (the caller's own forward excluded). */
export function otherForwardsInFlight(sessionId: string): number {
return Math.max(0, (counts.get(sessionId) ?? 0) - 1);
}

export function _resetConcurrentForwardsForTest(): void {
counts.clear();
}
19 changes: 17 additions & 2 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { getStore, storageStatusLabel } from "./persist.js";
import { cloneStoreForRefs } from "./store.js";
import { acquireInFlight, createSession, getSession, publishForkSession, diagnoseSuccessWithoutUsage, effectiveConfig, findSessionByCanonicalId, listSessions, markCompactionBoundary, markDirty, peekSession, releaseInFlight, statusInputBaseline, withSessionLock, type Session } from "./session.js";
import { clientConversationHeader } from "./session-id.js";
import { otherForwardsInFlight } from "./concurrent-forwards.js";
import { buildContextView } from "./context-view.js";
import { ABSORB_TOOL_NAME, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_OPENAI_NO_RANGE, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, PROXY_TOOL_NAMES, READ_ORIGINAL_IMAGE_TOOL, READ_ORIGINAL_IMAGE_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL_OPENAI, READ_ORIGINAL_IMAGE_TOOL_RESPONSES, RETRIEVE_TOOL_NAME, RULE_TOOL, RULE_TOOL_NAME, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, SEARCH_CONTEXT_TOOL_NAME, absorbToolsFor, retrieveToolsFor, withAcpNotes, withAcpNotesOpenAI } from "./compress-tool.js";
import { externalSummaryEnabled, externalSummaryMaxToolDurationMs, withExternalSummaryTools } from "./external-summary-surface.js";
Expand Down Expand Up @@ -2170,7 +2171,7 @@ export async function handlePluginTool(
// part of the context size, but NOT a cache hit (#790).
// declaredInclusive = #4128 upstream self-declaration (billing_usage.semantic)
// that input_tokens already INCLUDES cache_read — set only on the anthropic lane.
export type UsageSample = { inputTokens?: number; cachedTokens?: number; outputTokens?: number; creationTokens?: number; declaredInclusive?: boolean };
export type UsageSample = { inputTokens?: number; cachedTokens?: number; outputTokens?: number; creationTokens?: number; declaredInclusive?: boolean; reasoningTokens?: number };

function num(v: unknown): number | undefined {
return typeof v === "number" && Number.isFinite(v) ? v : undefined;
Expand Down Expand Up @@ -2233,6 +2234,10 @@ export function usageFromSseEvent(obj: Record<string, unknown>): UsageSample | u
if (creation !== undefined && creation > 0) sample.creationTokens = creation;
const output = num(usage["output_tokens"]);
if (output !== undefined) sample.outputTokens = output;
// Relays that split the Anthropic thinking share out of output_tokens
// expose it as thinking_tokens (#3102 diagnostic).
const thinking = num(usage["thinking_tokens"]);
if (thinking !== undefined) sample.reasoningTokens = thinking;
// #4128: honour a billing_usage stamp carried on the delta frame too.
const declared = declaredInclusiveFromUsage(usage);
if (declared !== undefined) sample.declaredInclusive = declared;
Expand All @@ -2257,6 +2262,11 @@ export function usageFromSseEvent(obj: Record<string, unknown>): UsageSample | u
// DeepSeek-style upstreams report KV-cache hits as top-level
// prompt_cache_hit_tokens instead of the standard details field (#779).
cachedTokens: num((usage["prompt_tokens_details"] as Record<string, unknown> | undefined)?.["cached_tokens"]) ?? num(usage["prompt_cache_hit_tokens"]),
// Reasoning gateways bill the thinking share inside completion_tokens
// and expose it under completion_tokens_details (top-level spelling on
// some relays) — the only self-classifying signal for a length-finish
// turn that spent its whole budget before any prose (#3102).
reasoningTokens: num((usage["completion_tokens_details"] as Record<string, unknown> | undefined)?.["reasoning_tokens"]) ?? num(usage["reasoning_tokens"]),
};
}
return undefined;
Expand Down Expand Up @@ -2317,6 +2327,7 @@ export function mergeUsageSample(acc: UsageSample, sample: UsageSample): void {
if (sample.cachedTokens !== undefined) acc.cachedTokens = sample.cachedTokens;
if (sample.creationTokens !== undefined) acc.creationTokens = sample.creationTokens;
if (sample.outputTokens !== undefined) acc.outputTokens = sample.outputTokens;
if (sample.reasoningTokens !== undefined) acc.reasoningTokens = sample.reasoningTokens;
if (sample.declaredInclusive !== undefined) acc.declaredInclusive = sample.declaredInclusive;
}

Expand Down Expand Up @@ -2392,6 +2403,10 @@ export async function pipePluginChatWithStrip(
let decoder = new TextDecoder("utf-8");
let buf = "";
const acc: UsageSample = {};
// #3102: wall-clock start for the degenerate-terminal diagnostic line — the
// elapsed time distinguishes a fast "produced nothing" turn from one that
// ran its whole budget before ending length.
const pipeStartedAt = Date.now();
let replyPart = 0;
let lastReplyEntry = "";
let replyTool = 0;
Expand Down Expand Up @@ -2580,7 +2595,7 @@ export async function pipePluginChatWithStrip(
const answerChars = answerProse.trim().length;
if (!draftTail && (answerChars > 0 || sawToolUse)) return false;
if (reason === undefined || !CLEAN_TURN_REASONS.has(reason)) {
if (!sawToolUse && !draftTail && answerChars === 0) log?.(`[plugin] degenerate terminal turn not retried (finish ${reason ?? "none"} is not a clean stop): visibleTextChars=${visibleTextChars}, releasedMarkupChars=${releasedMarkupChars} (#2756)`);
if (!sawToolUse && !draftTail && answerChars === 0) log?.(`[plugin] degenerate terminal turn not retried (finish ${reason ?? "none"} is not a clean stop): visibleTextChars=${visibleTextChars}, releasedMarkupChars=${releasedMarkupChars}, outputTokens=${acc.outputTokens ?? "?"}, reasoningTokens=${acc.reasoningTokens ?? "?"}, sawThinking=${sawThinking}, elapsedMs=${Date.now() - pipeStartedAt}, sessConcurrentForwards=${session ? otherForwardsInFlight(session.id) : "?"} (#2756/#3102)`);
return false;
}
if (res.destroyed || res.writableEnded) return false;
Expand Down
32 changes: 29 additions & 3 deletions src/server/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { resolveCompress } from "../compress-settings.js";
import { buildAbsorbSystemPrompt, buildCompressHybridSystemPrompt, buildCompressSystemPrompt, withMarkerIntegrityNote, withMcpDialectNote, withProjectAttribution, withSummaryBudgetNote } from "../compress-tool.js";
import { detectGenerationBoundary, GENERATION_BOUNDARY_NOTE } from "../generation-boundary.js";
import { findRoute, resolveDeclaredProtocol, type ProxyOptions } from "../config.js";
import { beginForward, endForward } from "../concurrent-forwards.js";
import { makeContinuationRefetch } from "../degenerate-retry.js";
import { dumpRejectedBody } from "../error-dump.js";
import { extractWsOversizeError, formatMiB, shedEgressIfOverBudget, shedWireImages, shedWireImagesToCount, type ShedStats } from "../egress-shed.js";
Expand Down Expand Up @@ -248,11 +249,36 @@ export function armFirstByteWatchdog(o: {
return timer;
}

export function forward(...args: Parameters<typeof forwardCaptured>): Promise<void> {
return withCacheCapture(args[4]?.session, () => forwardCaptured(...args));
// #3102: counts in-flight model forwards per session so the degenerate-terminal
// diagnostic line can report whether another same-session forward (the dsh
// title-gen sidecar, #2503) was in flight when the turn ended. The counter
// wraps the cache-captured forward; forwardInner keeps its original body.
export async function forward(
req: http.IncomingMessage,
res: http.ServerResponse,
opts: ProxyOptions,
body: Buffer | string,
prepared: Prepared | null,
core: CompressionCore,
config: Config,
log: (level: string, msg: string) => void,
route: ReturnType<typeof resolveUpstream>,
instanceId: string,
affinity?: string,
overflowRefold?: (realWindow: number | undefined) => Promise<{ body: string | Buffer; prepared: Prepared | null } | null>,
v1Meta?: Record<string, unknown>,
): Promise<void> {
const sid = prepared?.session.id;
const counted = sid !== undefined && req.method !== "GET" && req.method !== "HEAD";
if (counted) beginForward(sid);
try {
await withCacheCapture(prepared?.session, () => forwardInner(req, res, opts, body, prepared, core, config, log, route, instanceId, affinity, overflowRefold, v1Meta));
} finally {
if (counted) endForward(sid);
}
}

async function forwardCaptured(
async function forwardInner(
req: http.IncomingMessage,
res: http.ServerResponse,
opts: ProxyOptions,
Expand Down
156 changes: 156 additions & 0 deletions tests/issue3102-degenerate-diag.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { pipePluginChatWithStrip } from "../src/plugin.ts";
import type { Session } from "../src/session.ts";
import { _resetConcurrentForwardsForTest, beginForward, endForward, otherForwardsInFlight } from "../src/concurrent-forwards.ts";

// #3102: two normal-budget first turns returned finish=length with zero visible
// chars, both concurrent with the dsh title-gen sidecar (#2503). The audit ruled
// out stream interleaving structurally (one socket per concurrent request), so
// the remaining suspects — budget burned in reasoning before any prose vs an
// upstream co-occurrence effect — were NOT observable from logs: the #2756
// refusal line reported only char counters. These tests pin the extended
// diagnostics: the line now carries the sniffed output/reasoning token split,
// the thinking flag, elapsed time, and the same-session in-flight forward count.

function makeSession(id = "testsess"): Session {
return {
id,
protocol: "openai",
upstreamOrigin: "http://127.0.0.1:9/v1",
label: "test",
createdAt: 0,
lastUsedAt: 0,
requests: 0,
lastInputTokens: 0,
stats: {},
dirty: false,
} as unknown as Session;
}

function makeRes(chunks: string[]) {
return {
write(b: Buffer | string) {
chunks.push(typeof b === "string" ? b : b.toString("utf8"));
return true;
},
end(b?: Buffer | string) {
if (b !== undefined) chunks.push(typeof b === "string" ? b : b.toString("utf8"));
},
once() {},
destroyed: false,
writableEnded: false,
} as unknown as import("node:http").ServerResponse;
}

function streamOf(events: string[]): ReadableStream<Uint8Array> {
const enc = new TextEncoder();
let i = 0;
return new ReadableStream<Uint8Array>({
pull(controller) {
if (i < events.length) {
controller.enqueue(enc.encode(events[i]));
i += 1;
} else {
controller.close();
}
},
});
}

function chatChunk(delta: Record<string, unknown>, extra: Record<string, unknown> = {}): string {
return `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "qwen", choices: [{ index: 0, delta, finish_reason: null }], ...extra })}\n\n`;
}

function chatFinish(reason = "stop"): string {
return `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "qwen", choices: [{ index: 0, delta: {}, finish_reason: reason }] })}\n\n`;
}

const DONE = "data: [DONE]\n\n";

test("#3102 counter: per-session in-flight accounting excludes the caller's own forward", () => {
_resetConcurrentForwardsForTest();
assert.equal(otherForwardsInFlight("s1"), 0);
beginForward("s1");
assert.equal(otherForwardsInFlight("s1"), 0, "a single in-flight forward sees zero others");
beginForward("s1");
assert.equal(otherForwardsInFlight("s1"), 1, "a second same-session forward is visible");
assert.equal(otherForwardsInFlight("s2"), 0, "other sessions are unaffected");
endForward("s1");
assert.equal(otherForwardsInFlight("s1"), 0);
endForward("s1");
assert.equal(otherForwardsInFlight("s1"), 0, "underflow clamps at zero instead of going negative");
});

test("#3102: a length-finish zero-visible turn reports token split, thinking flag, elapsed time, and sidecar concurrency", async () => {
_resetConcurrentForwardsForTest();
const out: string[] = [];
const logs: string[] = [];
let refetches = 0;
const refetch = (): Promise<ReadableStream<Uint8Array> | null> => {
refetches += 1;
return Promise.resolve(streamOf([chatChunk({ content: "dup" }), chatFinish("stop"), DONE]));
};
// Production shape: the relay wrapper counts the MAIN forward, the title-gen
// sidecar adds a second entry while it is in flight.
beginForward("testsess");
beginForward("testsess");
try {
await pipePluginChatWithStrip(streamOf([
chatChunk({ role: "assistant", reasoning_content: "planning the whole answer before writing any prose..." }),
chatChunk({}, { usage: { prompt_tokens: 100, completion_tokens: 32768, completion_tokens_details: { reasoning_tokens: 32768 } } }),
chatFinish("length"),
DONE,
]), makeRes(out), "openai", makeSession(), (m) => logs.push(m), refetch, "http://up");
} finally {
endForward("testsess");
endForward("testsess");
}
assert.equal(refetches, 0, "finish=length is not a clean stop — never re-send those");
const diag = logs.find((l) => l.includes("not retried") && l.includes("not a clean stop"));
assert.ok(diag, "the refusal line exists");
assert.ok(diag!.includes("outputTokens=32768"), `sniffed output tokens reported: ${diag}`);
assert.ok(diag!.includes("reasoningTokens=32768"), `reasoning split reported (budget burned in thinking): ${diag}`);
assert.ok(diag!.includes("sawThinking=true"), `thinking flag reported: ${diag}`);
assert.ok(/elapsedMs=\d+/.test(diag!), `elapsed time reported: ${diag}`);
assert.ok(diag!.includes("sessConcurrentForwards=1"), `concurrent same-session forward reported: ${diag}`);
});

test("#3102: with no other forward in flight the concurrency field reads zero", async () => {
_resetConcurrentForwardsForTest();
const out: string[] = [];
const logs: string[] = [];
const refetch = (): Promise<ReadableStream<Uint8Array> | null> => Promise.resolve(null);
// The main forward counts itself; with no sidecar nothing else is in flight.
beginForward("testsess");
try {
await pipePluginChatWithStrip(streamOf([
chatChunk({ role: "assistant", content: "" }),
chatFinish("length"),
DONE,
]), makeRes(out), "openai", makeSession(), (m) => logs.push(m), refetch, "http://up");
} finally {
endForward("testsess");
}
const diag = logs.find((l) => l.includes("not retried") && l.includes("not a clean stop"));
assert.ok(diag, "the refusal line exists");
assert.ok(diag!.includes("sessConcurrentForwards=0"), `no concurrency: ${diag}`);
assert.ok(diag!.includes("reasoningTokens=?"), `absent usage field reports '?': ${diag}`);
});

test("#3102: anthropic message_delta thinking_tokens is captured as the reasoning split", async () => {
_resetConcurrentForwardsForTest();
const out: string[] = [];
const logs: string[] = [];
const refetch = (): Promise<ReadableStream<Uint8Array> | null> => Promise.resolve(null);
const sse = (type: string, payload: Record<string, unknown>) => `event: ${type}\ndata: ${JSON.stringify({ type, ...payload })}\n\n`;
await pipePluginChatWithStrip(streamOf([
sse("message_start", { message: { id: "msg_1", role: "assistant", usage: { input_tokens: 100 } } }),
sse("message_delta", { delta: { stop_reason: "max_tokens" }, usage: { output_tokens: 32768, thinking_tokens: 32768 } }),
sse("message_stop", {}),
]), makeRes(out), "anthropic", makeSession(), (m) => logs.push(m), refetch, "http://up");
const diag = logs.find((l) => l.includes("not retried") && l.includes("not a clean stop"));
assert.ok(diag, "max_tokens is not a clean stop — the refusal line fires on the anthropic lane too");
assert.ok(diag!.includes("outputTokens=32768"), `anthropic output tokens reported: ${diag}`);
assert.ok(diag!.includes("reasoningTokens=32768"), `thinking split reported: ${diag}`);
});
Loading