From 09ef5bbb69e8b33eaeeb301e6f2447d599603337 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Wed, 14 Oct 2026 10:41:30 +0800 Subject: [PATCH 1/2] feat: self-classifying diagnostics for degenerate terminal turns (#3102) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #2756 refusal line reported only char counters, so the two normal-budget length-finish empty turns of #3102 could not be self-classified from logs (budget burned in reasoning vs produced nothing; sidecar co-occurrence needed manual archaeology). - src/concurrent-forwards.ts: per-session in-flight forward counter (in-memory only) — correlation signal for same-session sidecars - relay.ts: thin forward() wrapper counts model forwards per session - plugin.ts: UsageSample.reasoningTokens sniffed from completion_tokens_details.reasoning_tokens / top-level spelling / anthropic thinking_tokens; degenerate-terminal line now carries outputTokens, reasoningTokens, sawThinking, elapsedMs, sessConcurrentForwards --- src/concurrent-forwards.ts | 26 ++++ src/plugin.ts | 19 ++- src/server/relay.ts | 30 +++++ tests/issue3102-degenerate-diag.test.ts | 156 ++++++++++++++++++++++++ 4 files changed, 229 insertions(+), 2 deletions(-) create mode 100644 src/concurrent-forwards.ts create mode 100644 tests/issue3102-degenerate-diag.test.ts diff --git a/src/concurrent-forwards.ts b/src/concurrent-forwards.ts new file mode 100644 index 0000000000..d43e9f851d --- /dev/null +++ b/src/concurrent-forwards.ts @@ -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(); + +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(); +} diff --git a/src/plugin.ts b/src/plugin.ts index ffaaebbcb1..430b812baa 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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 { 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, RETRIEVE_TOOL_NAME, RULE_TOOL, RULE_TOOL_NAME, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, SEARCH_CONTEXT_TOOL_NAME, retrieveToolsFor, withAcpNotes, withAcpNotesOpenAI } from "./compress-tool.js"; import { externalSummaryEnabled, externalSummaryMaxToolDurationMs, withExternalSummaryTools } from "./external-summary-surface.js"; import { salvageCompressArgs } from "./plugin-compress-salvage.js"; @@ -1848,7 +1849,7 @@ export async function handlePluginTool( // creationTokens = Anthropic cache-write segment (cache_creation_input_tokens): // part of the context size, but NOT a cache hit (#790). -type UsageSample = { inputTokens?: number; cachedTokens?: number; outputTokens?: number; creationTokens?: number }; +type UsageSample = { inputTokens?: number; cachedTokens?: number; outputTokens?: number; creationTokens?: number; reasoningTokens?: number }; function num(v: unknown): number | undefined { return typeof v === "number" && Number.isFinite(v) ? v : undefined; @@ -1907,6 +1908,10 @@ function usageFromSseEvent(obj: Record): UsageSample | undefine 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; return Object.keys(sample).length > 0 ? sample : undefined; } if (type === "response.completed") { @@ -1928,6 +1933,11 @@ function usageFromSseEvent(obj: Record): UsageSample | undefine // 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 | 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 | undefined)?.["reasoning_tokens"]) ?? num(usage["reasoning_tokens"]), }; } return undefined; @@ -1977,6 +1987,7 @@ 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; } /** Terminal reasons after which the model genuinely finished its turn. A @@ -2050,6 +2061,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 sawStrippedEcho = false; // #2405(c): one warn line per event, session-prefixed — the former second // write through the request logger landed in the SAME tee file, doubling @@ -2223,7 +2238,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; diff --git a/src/server/relay.ts b/src/server/relay.ts index 43ffb3eb5d..7b3cf20512 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -16,6 +16,7 @@ import { compressLoopResponsesJson } from "../compress-loop-responses.js"; import { resolveCompress } from "../compress-settings.js"; import { buildCompressHybridSystemPrompt, buildCompressSystemPrompt, withMarkerIntegrityNote, withProjectAttribution, withSummaryBudgetNote } from "../compress-tool.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 { externalSummaryEnabled } from "../external-summary-surface.js"; @@ -166,6 +167,10 @@ function armFailureShrink(prepared: Prepared, log: (level: string, msg: string) } } +// #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. Thin wrapper — +// forwardInner keeps its original body and indentation (pure rename). export async function forward( req: http.IncomingMessage, res: http.ServerResponse, @@ -180,6 +185,31 @@ export async function forward( affinity?: string, overflowRefold?: (realWindow: number | undefined) => Promise<{ body: string | Buffer; prepared: Prepared | null } | null>, v1Meta?: Record, +): Promise { + const sid = prepared?.session.id; + const counted = sid !== undefined && req.method !== "GET" && req.method !== "HEAD"; + if (counted) beginForward(sid); + try { + await forwardInner(req, res, opts, body, prepared, core, config, log, route, instanceId, affinity, overflowRefold, v1Meta); + } finally { + if (counted) endForward(sid); + } +} + +async function forwardInner( + 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, + instanceId: string, + affinity?: string, + overflowRefold?: (realWindow: number | undefined) => Promise<{ body: string | Buffer; prepared: Prepared | null } | null>, + v1Meta?: Record, ): Promise { const forwardStartedAt = Date.now(); // E2: a codex native-compaction request intercepted in prepare() carries a diff --git a/tests/issue3102-degenerate-diag.test.ts b/tests/issue3102-degenerate-diag.test.ts new file mode 100644 index 0000000000..b0b8691ea5 --- /dev/null +++ b/tests/issue3102-degenerate-diag.test.ts @@ -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 { + const enc = new TextEncoder(); + let i = 0; + return new ReadableStream({ + pull(controller) { + if (i < events.length) { + controller.enqueue(enc.encode(events[i])); + i += 1; + } else { + controller.close(); + } + }, + }); +} + +function chatChunk(delta: Record, extra: Record = {}): 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 | 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 | 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 | null> => Promise.resolve(null); + const sse = (type: string, payload: Record) => `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}`); +}); From dfadc21b339bfa45c6ec03b2f13e723ce6bf0507 Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 26 Oct 2026 15:22:50 +0800 Subject: [PATCH 2/2] fix(ci): sync lockfile recorded versions with acp-kernel 0.0.165 (#4599) master window commits 293ae6542/de5e03659 bumped kernel/package.json to 0.0.165 without regenerating the lockfiles; lock-sync re-resolution then rewrites the stale recorded versions (root 0.0.163, kernel 0.0.164) and fails. Pure recorded-version sync via npm install --package-lock-only; no dependency or semantic change. --- kernel/package-lock.json | 4 ++-- package-lock.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/kernel/package-lock.json b/kernel/package-lock.json index da011d94e1..4c5e2d79e9 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.164", + "version": "0.0.165", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.164", + "version": "0.0.165", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", diff --git a/package-lock.json b/package-lock.json index 380212c96e..15a6e3f4e9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.163", + "version": "0.0.165", "dev": true, "license": "MIT", "devDependencies": {