From 34b6c7e7c682abee95b0f3e05dac99ee3ebfb069 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 13 Oct 2026 21:23:50 +0800 Subject: [PATCH 1/5] =?UTF-8?q?fix(#3013,#3022):=20refusal=20is=20terminal?= =?UTF-8?q?=20=E2=80=94=20bili=5Ffinal=20marker=20+=20storm-visible=20logg?= =?UTF-8?q?ing=20(A1+A3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Field report #3013: one session burned 5069 refused dsh compaction calls (5038 retries, median 328ms, 0 outbound) while the user watched a stuck '生成中'. Two halves: A1 — the refusal body now carries bili_final:true (top level on both protocol shapes; inside error on the openai envelope where retryable lives). retryable:false did not stop the loop: dsh's retry pressure comes from its own raw ledger (#2490), which nothing on bili's side can shrink, so the same call fails identically forever. bili_final is the stable machine-readable contract for dsh upstream to latch (consumption is a cross-project follow-up). REFUSAL_MESSAGE now states the terminal semantics and the levers (bili compress / #2474 recipe / #2028 opt-in; dropped the stale web-UI mention deleted by #3042). A3 — logging. Pipeline lane: after the once-warn, every 100th refusal logs an info with the running count, the #2490 mechanism, and the levers (previously: 5051 silent refusals, zero log lines, user blind). Passthrough lane: was warn-per-refusal (the spam direction) — now warns on the process's first refusal, then the same 1-per-100 cadence. Tests: tests/issue3013-refusal-terminal.test.ts (A1 body shapes on both protocols incl. error.bili_final; A3 storm cadence on both lanes via setLogCapture with log:true rigs — request-scoped log is gated on opts.log, log:false rigs made guard lines no-ops). Red-green proven. Family regressions green (dsh guard/2028/2709/2658/2432/2451, claude guard #2612, codex 2451, archives): 97 tests. --- src/server/dsh-compaction-guard.ts | 28 +++- src/server/handle.ts | 20 ++- tests/issue3013-refusal-terminal.test.ts | 186 +++++++++++++++++++++++ 3 files changed, 230 insertions(+), 4 deletions(-) create mode 100644 tests/issue3013-refusal-terminal.test.ts diff --git a/src/server/dsh-compaction-guard.ts b/src/server/dsh-compaction-guard.ts index 50f6bb53d3..52d9f0507f 100644 --- a/src/server/dsh-compaction-guard.ts +++ b/src/server/dsh-compaction-guard.ts @@ -265,7 +265,20 @@ export type Refusal = { status: number; body: unknown }; const REFUSAL_MESSAGE = `dsh native compaction call refused by billion-context: bili owns compression on this lane (#1729, cf. #1772/#1206). ` + `A landed dsh compaction checkpoint durably shadows the raw conversation history, which destroys the proxy's compression substrate. ` + - `To run dsh native compaction on this lane anyway, opt in explicitly: "allowDshCompaction": true in the bili config (web UI) or env BILI_ALLOW_DSH_COMPACTION=1 (#2028).`; + `This refusal is terminal for the session (bili_final) — the same call will be refused every time, so stop retrying (#3013: one session burned 5069 refused retries). ` + + `To manage context use bili's compress; to stop dsh's retry pressure disable its auto-compaction (profile recipe #2474); ` + + `to run dsh native compaction anyway opt in explicitly: "allowDshCompaction": true in the bili config file or env BILI_ALLOW_DSH_COMPACTION=1 (#2028).`; + +/** #3013/#3022 (A1): the refusal is a DECISION, not a transient error — dsh's + * retry loop is driven by its own raw pressure ledger which nothing on bili's + * side can shrink (#2490), so every retry of the same call fails identically. + * `bili_final: true` gives clients an unambiguous machine-readable terminal + * marker to latch and stop retrying (consumption needs dsh-upstream + * coordination; `retryable:false` alone did not stop the field-reported + * 5038-retry storm). Present at the top level of both protocol shapes and, + * for the openai error envelope (where `retryable` lives), inside `error` + * too. */ +const BILI_FINAL_FIELD = "bili_final" as const; /** Protocol-shaped refusal body (mirrors the #554 side-request guard shape so * clients render it natively). 422: a policy refusal of this one request — not @@ -276,18 +289,29 @@ export function dshCompactionRefusal(protocol: string): Refusal { if (protocol === "anthropic") { return { status: 422, - body: { type: "error", error: { type: "invalid_request_error", message: REFUSAL_MESSAGE } }, + body: { type: "error", [BILI_FINAL_FIELD]: true, error: { type: "invalid_request_error", message: REFUSAL_MESSAGE } }, }; } return { status: 422, body: { + [BILI_FINAL_FIELD]: true, error: { type: "server_error", code: "dsh_compaction_refused", message: REFUSAL_MESSAGE, retryable: false, + [BILI_FINAL_FIELD]: true, }, }, }; } + +/** #3013/#3022 (A3): cadence for the pipeline-lane storm log. The first + * refusal warns once (once-warn dedup on session.metadata), then refusals are + * silent unless this many more arrive — the field-reported storm re-fired + * every ~328ms for hours with ZERO log lines after the first, leaving the + * user staring at a stuck "生成中" with no clue (#3013). Same cadence caps the + * passthrough lane's per-refusal warn so an agentless storm cannot spam the + * log either. Constant, not config (#2155 precedent). */ +export const DSH_REFUSAL_STORM_LOG_EVERY = 100; diff --git a/src/server/handle.ts b/src/server/handle.ts index 2a0fd8b08d..2ec08cb3b7 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -49,7 +49,7 @@ import { noInjectTool as knobNoInjectTool, rawDumpDir as knobRawDumpDir } from " import { anthropicBetaContextWindow, BILI_HOP_HEADER, capRegistryWindowByStandard, expandedContextSuffixWindow, launcherContextWindow, launcherMaxOutput, windowSourceLogged } from "./context-window.js"; import { NO_IDENTITY_MESSAGE, safeSessionId } from "./headers.js"; import { demoteGate, hasLeakedBiliToolsOnly, isDshTitleRequest, isServerToolUtilityCall, isSideRequest, resolveSideLane, restoreOutputBudget, sideRequestGuard, stripLeakedBiliTools } from "./side-request.js"; -import { DSH_COMPACTION_SHAPE_MSGS, detectPassthroughDshCompactionCall, dshCompactionRefusal, dshPassthroughGuardStats, isDshCompactionCall } from "./dsh-compaction-guard.js"; +import { DSH_COMPACTION_SHAPE_MSGS, DSH_REFUSAL_STORM_LOG_EVERY, detectPassthroughDshCompactionCall, dshCompactionRefusal, dshPassthroughGuardStats, isDshCompactionCall } from "./dsh-compaction-guard.js"; import { artifactSeedHit, detectAcpArtifacts } from "./chain-artifacts.js"; import { piSubagentChannelFallback } from "./pi-subagent-channel.js"; import { FORCE_TEXT_PROTOCOL } from "./inject.js"; @@ -256,7 +256,15 @@ async function handleRequest( if (protocol !== null && req.method === "POST" && bodyBuffer.length > 0 && opts.allowDshCompaction !== true && await detectPassthroughDshCompactionCall(protocol, bodyBuffer, headerValue(req, "content-encoding"), async (enc, buf) => (await decodeRequestBody(enc, buf, MAX_DECODED_REQUEST_BYTES, { signal: decodingSignal, onBytes: (bytes) => admission.observe(bytes) })).body)) { dshPassthroughGuardStats.refusals += 1; - log("warn", `[passthrough] dsh native compaction call identified on the unattributed passthrough lane (#1117/#2709) — REFUSED, not forwarded: bili owns compression on this lane; a landed dsh checkpoint would durably shadow the raw history (#1729, cf. #1772/#1206). No session exists on this lane, so this log line (not the #2490 ledger) is the record; passthrough refusals so far: ${dshPassthroughGuardStats.refusals}`); + // #3013/#3022 (A3): first refusal warns; then every + // DSH_REFUSAL_STORM_LOG_EVERY-th refusal logs an info so an + // agentless retry storm stays visible without spamming (the + // field-reported storm re-fired every ~328ms — per-refusal warn + // would have written thousands of lines). This log line, not the + // #2490 ledger, is the only record on this lane. + if (dshPassthroughGuardStats.refusals === 1 || dshPassthroughGuardStats.refusals % DSH_REFUSAL_STORM_LOG_EVERY === 0) { + log(dshPassthroughGuardStats.refusals === 1 ? "warn" : "info", `[passthrough] dsh native compaction call identified on the unattributed passthrough lane (#1117/#2709) — REFUSED, not forwarded: bili owns compression on this lane; a landed dsh checkpoint would durably shadow the raw history (#1729, cf. #1772/#1206). No session exists on this lane, so this log line (not the #2490 ledger) is the record; passthrough refusals so far: ${dshPassthroughGuardStats.refusals}` + (dshPassthroughGuardStats.refusals === 1 ? "" : ` — retrying will keep failing (terminal; #3013): disable dsh auto-compaction (#2474) or opt in via allowDshCompaction (#2028)`)); + } const refusal = dshCompactionRefusal(protocol); if (!res.headersSent && !res.writableEnded && !res.destroyed) { res.writeHead(refusal.status, { "content-type": "application/json" }); @@ -1608,6 +1616,14 @@ async function handleRequest( const prevBytes = typeof session.metadata["dshCompactionRefusedBytes"] === "number" ? session.metadata["dshCompactionRefusedBytes"] as number : 0; session.metadata["dshCompactionRefusedBytes"] = Math.max(prevBytes, inboundBytes); session.metadata["dshCompactionRefusals"] = (typeof session.metadata["dshCompactionRefusals"] === "number" ? session.metadata["dshCompactionRefusals"] as number : 0) + 1; + // #3013/#3022 (A3): after the once-warn above, refusals were fully + // silent — the field storm burned 5051 refusals with zero further + // log lines while the user saw a stuck "生成中". Every + // DSH_REFUSAL_STORM_LOG_EVERY-th refusal re-surfaces with the + // running count and the actual levers. + if ((session.metadata["dshCompactionRefusals"] as number) % DSH_REFUSAL_STORM_LOG_EVERY === 0) { + log("info", `[${session.id}] dsh native compaction refusal #${session.metadata["dshCompactionRefusals"]} on this session (raw-ledger high-water ${(session.metadata["dshCompactionRefusedBytes"] as number)} bytes) — dsh keeps retrying because its own raw pressure ledger never shrinks (#2490), and every retry of this call will be refused (terminal, #3013). Disable dsh auto-compaction (profile recipe #2474), manage context via bili's compress, or lift the refusal with allowDshCompaction (#2028). If bili's own compression looks idle while this repeats, the nudge channel may be dead — report it (#3004/#3013).`); + } markDirty(session); const refusal = dshCompactionRefusal(protocol); if (!res.headersSent && !res.writableEnded && !res.destroyed) { diff --git a/tests/issue3013-refusal-terminal.test.ts b/tests/issue3013-refusal-terminal.test.ts new file mode 100644 index 0000000000..0d60e52f5b --- /dev/null +++ b/tests/issue3013-refusal-terminal.test.ts @@ -0,0 +1,186 @@ +/** + * #3013 / #3022 (A1 + A3): the dsh compaction refusal storm. + * + * Field report: one long session burned 5069 refused compaction calls + * (5038 retries after the first, median interval 328ms, 0 outbound) because + * (a) the refusal body carried no machine-readable terminal marker a client + * could latch (`retryable:false` did not stop dsh's own pressure-ledger + * driven retry loop), and (b) after the once-warn, every further refusal was + * silent — the user stared at a stuck "生成中" for hours with zero log lines. + * + * This pins the two halves of the fix: + * - A1: every refusal body carries `bili_final: true` (top level on both + * protocol shapes; inside `error` on the openai envelope where + * `retryable` lives). Consumption by dsh upstream is a cross-project + * follow-up — bili's side of the contract is stable here. + * - A3: the pipeline lane logs an info every DSH_REFUSAL_STORM_LOG_EVERY-th + * refusal with the running count and the levers; the passthrough lane + * (previously warn-per-refusal — the spam direction) warns on the first + * refusal in the process and then follows the same cadence. + */ +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import type { AddressInfo } from "node:net"; + +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { DSH_COMPACTION_INSTRUCTION_PREFIX, DSH_REFUSAL_STORM_LOG_EVERY, dshCompactionRefusal, dshPassthroughGuardStats } from "../src/server/dsh-compaction-guard.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { setLogCapture } from "../src/logger.ts"; + +const INSTRUCTION = `${DSH_COMPACTION_INSTRUCTION_PREFIX} Summarize the conversation above.`; + +function startUpstream(captured: string[]): Promise { + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c) => chunks.push(c)); + req.on("end", () => { + captured.push(Buffer.concat(chunks).toString("utf8")); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ choices: [{ message: { role: "assistant", content: "ok" } }] })); + }); + }); + upstream.listen(0, "127.0.0.1"); + return once(upstream, "listening").then(() => upstream); +} + +async function startBili(upstreamPort: number): Promise<{ port: number; close: () => Promise }> { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "gpt-test": { context: 400_000 } } } }, + modelContextLimit: 400_000, + kernelConfig: defaultConfig(400_000), + promptCache: { routing: "auto" }, + compress: { injectTool: false, injectNudge: false }, + sessionHeader: "x-acp-session", + log: true, + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + return { + port: (proxy.address() as AddressInfo).port, + close: async () => { + proxy.close(); + await once(proxy, "close"); + }, + }; +} + +test("A1: refusal bodies carry the bili_final terminal marker on both protocol shapes", () => { + const anthropic = dshCompactionRefusal("anthropic"); + const body = anthropic.body as Record; + assert.equal(body.bili_final, true, "anthropic shape: top-level bili_final"); + assert.equal((body.error as Record).type, "invalid_request_error"); + + const openai = dshCompactionRefusal("openai"); + const ob = openai.body as Record; + assert.equal(ob.bili_final, true, "openai shape: top-level bili_final"); + const err = ob.error as Record; + assert.equal(err.retryable, false); + assert.equal(err.bili_final, true, "openai shape: error.bili_final (where retryable lives)"); + assert.equal(err.code, "dsh_compaction_refused"); + + // the message must state the terminal semantics + the levers (#3013) + assert.match(String(err.message), /terminal for the session/); + assert.match(String(err.message), /stop retrying/); + assert.match(String(err.message), /#2474/); + assert.match(String(err.message), /allowDshCompaction/); +}); + +test("A3: pipeline storm — first refusal warns once, then every DSH_REFUSAL_STORM_LOG_EVERY-th logs an info with the levers", async () => { + const captured: string[] = []; + const upstream = await startUpstream(captured); + const upstreamPort = (upstream.address() as AddressInfo).port; + const bili = await startBili(upstreamPort); + + const lines: { level: string; msg: string }[] = []; + setLogCapture((level, msg) => lines.push({ level, msg })); + try { + let sawTerminal = false; + for (let i = 0; i < DSH_REFUSAL_STORM_LOG_EVERY; i++) { + const resp = await fetch(`http://127.0.0.1:${bili.port}/v1/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": "s-3013" }, + body: JSON.stringify({ model: "gpt-test", messages: [{ role: "user", content: INSTRUCTION }] }), + }); + assert.equal(resp.status, 422, `refusal ${i + 1} must stay 422`); + const parsed = JSON.parse(await resp.text()) as Record; + assert.equal(parsed.bili_final, true, `refusal ${i + 1} carries bili_final on the wire`); + sawTerminal = true; + } + assert.ok(sawTerminal); + + assert.equal(captured.length, 0, "no refusal may ever reach the upstream"); + + const warns = lines.filter((l) => l.level === "warn" && l.msg.includes("dsh native compaction call identified")); + assert.equal(warns.length, 1, "exactly one identification warn (the once-warn)"); + + const storm = lines.filter((l) => l.level === "info" && l.msg.includes("dsh native compaction refusal #")); + assert.equal(storm.length, 1, `exactly one storm info in ${DSH_REFUSAL_STORM_LOG_EVERY} refusals`); + assert.match(storm[0].msg, new RegExp(`refusal #${DSH_REFUSAL_STORM_LOG_EVERY}\\b`)); + assert.match(storm[0].msg, /never shrinks \(#2490\)/); + assert.match(storm[0].msg, /#2474/); + assert.match(storm[0].msg, /allowDshCompaction/); + assert.match(storm[0].msg, /#3013/); + } finally { + setLogCapture(null); + await bili.close(); + upstream.close(); + await once(upstream, "close"); + } +}); + +test("A3: passthrough storm — first-in-process warns, then the same cadence (no per-refusal spam)", async () => { + const captured: string[] = []; + const upstream = await startUpstream(captured); + const upstreamPort = (upstream.address() as AddressInfo).port; + const bili = await startBili(upstreamPort); + + const lines: { level: string; msg: string }[] = []; + setLogCapture((level, msg) => lines.push({ level, msg })); + const before = dshPassthroughGuardStats.refusals; + // any 100 consecutive refusals cross exactly one multiple of + // DSH_REFUSAL_STORM_LOG_EVERY; the warn fires only when this process's + // first passthrough refusal happens to land inside the loop. + const firstInLoop = before === 0; + try { + for (let i = 0; i < DSH_REFUSAL_STORM_LOG_EVERY; i++) { + const resp = await fetch(`http://127.0.0.1:${bili.port}/bili/http://127.0.0.1:${upstreamPort}/v1/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-passthrough": "1" }, + body: JSON.stringify({ model: "gpt-test", messages: [{ role: "user", content: INSTRUCTION }] }), + }); + assert.equal(resp.status, 422); + assert.equal((JSON.parse(await resp.text()) as Record).bili_final, true, "passthrough refusal also carries bili_final"); + } + assert.equal(captured.length, 0, "nothing forwarded"); + + const lane = lines.filter((l) => l.msg.includes("[passthrough] dsh native compaction call identified")); + const warns = lane.filter((l) => l.level === "warn"); + const infos = lane.filter((l) => l.level === "info"); + if (firstInLoop) { + assert.equal(warns.length, 1, "process-first refusal warns"); + assert.equal(infos.length, 1, "and the 100th logs one cadence info"); + assert.match(infos[0].msg, /terminal; #3013/); + } else { + assert.equal(infos.length, 1, "exactly one cadence info per 100 consecutive refusals"); + } + assert.ok(lane.length <= 2, `no per-refusal spam: ${lane.length} lines for ${DSH_REFUSAL_STORM_LOG_EVERY} refusals`); + } finally { + setLogCapture(null); + await bili.close(); + upstream.close(); + await once(upstream, "close"); + } +}); From 19f6ed574b65c96594b8c586afed1139a0ee1044 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 13 Oct 2026 22:44:25 +0800 Subject: [PATCH 2/5] fix(#2731): google persona site rides the post-refactor personaConversationOrder adapter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fa7dc4e1 merge kept #2731's direct personaNamespace(...) call for the google lane but dropped its import — master had already swapped the direct calls for the session-resolve.ts personaConversationOrder wiring adapter (content-blind, keyed by order+id, (systemText, log) params gone). Translate the call faithfully and add the empty-system non-anchoring guard the other lanes already have, so typecheck (tsconfig.json, not CI-run) is green again. Verified: typecheck 0; dsh-persona-fingerprint + side-request-isolation + issue2709 + dsh-compaction-guard 58/58. --- src/server/handle.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/server/handle.ts b/src/server/handle.ts index f98004a702..1d357f4ee5 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -815,12 +815,13 @@ async function handleRequest( // parity with the other three lanes includes the #2601 model // argument: a chain-broken model switch still migrates instead of // forking when the plugin header corroborates it. - ? (dshPersona && !sideRequestLike - ? personaNamespace( + ? (dshPersona && !sideRequestLike && personaSystemText !== "" + // Empty system is non-anchoring (kernel anchor semantics, + // same guard as the openai lane): ride the verbatim id. + ? personaConversationOrder( googleIdentity?.value ?? googleSignal, - personaSystemText, (parsed as GoogleRequestBody).contents, - log, + personaSystemText, pluginReportedModel(req.headers), ) : (googleIdentity?.value ?? googleSignal)) From 464f0db24d9ebdb52f960217c3bf8d7949a0e32c Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 13 Oct 2026 22:57:17 +0800 Subject: [PATCH 3/5] test(#2731): pin the google-lane empty-system non-anchoring guard in the side-lane suite The persona-gate conjunct sits on the sideRequestLike line in handle.ts, so lane-guard (#2170) demands the suite edit. Pins: a dsh MAIN google request with NO systemInstruction rides the verbatim key and never enters personaConversationOrder (whose cold-shallow branch would fork |sub:aux). 25/25 in side-request-isolation. --- tests/side-request-isolation.test.ts | 70 ++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/tests/side-request-isolation.test.ts b/tests/side-request-isolation.test.ts index 9f262d1402..6a10ffdd86 100644 --- a/tests/side-request-isolation.test.ts +++ b/tests/side-request-isolation.test.ts @@ -991,3 +991,73 @@ test("e2e: google-lane dsh side request resolves verbatim — no kernel state, n await once(upstream, "close"); } }); + +// #2731 follow-up: the google-lane persona gate carries the SAME empty-system +// non-anchoring guard as the openai lane — a dsh main request with NO +// systemInstruction rides the verbatim conversation key and never enters the +// persona order resolver (a cold shallow history there would fork onto +// |sub:aux). Pinned here because the gate conjunct sits on the sideRequestLike +// line in handle.ts (lane-guard #2170). +test("e2e: google-lane dsh persona with empty system rides verbatim — resolver never consulted (#2731)", async () => { + const upstream = http.createServer((req, res) => { + req.resume(); + req.on("end", () => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ candidates: [{ content: { role: "model", parts: [{ text: "ok" }] }, finishReason: "STOP" }], modelVersion: "gemini-test", usageMetadata: { promptTokenCount: 10, candidatesTokenCount: 3, totalTokenCount: 13 } })); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: {} }, + modelContextLimit: 200_000, + kernelConfig: defaultConfig(200_000), + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + autoRestartOnUpdate: false, + advisoryCheck: false, + releaseNotesCheck: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + updateTag: "latest", + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as { port: number }).port; + const CONV = "dsh-google-empty-system"; + const url = `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1beta/models/gemini-test:generateContent`; + const headers: Record = { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": CONV }; + try { + // A dsh MAIN turn (full output budget → not a side request) with NO + // systemInstruction: the persona gate's personaSystemText !== "" conjunct + // must keep it on the verbatim key — empty system is non-anchoring. + const contents = Array.from({ length: 4 }, (_, i): { role: string; parts: { text: string }[] } => ({ role: i % 2 === 0 ? "user" : "model", parts: [{ text: `main-${i + 1}-` + "z".repeat(2000) }] })); + const r1 = await fetch(url, { method: "POST", headers, body: JSON.stringify({ contents, generationConfig: { maxOutputTokens: 64_000 } }) }); + assert.equal(r1.status, 200); + await r1.text(); + const s = peekSession(CONV); + assert.ok(s, "the empty-system main turn resolved onto the RAW conversation key"); + assert.ok(Object.keys(s.state.messageRefs.byRaw).length >= 4, "refs assigned under the bare id"); + // The exact regression shape: without the call-site guard a cold + // shallow history through personaConversationOrder lands on |sub:aux. + assert.equal(peekSession(`${CONV}|sub:aux`), undefined, "empty system must not fork onto |sub:aux"); + } finally { + proxy.close(); + await once(proxy, "close"); + upstream.close(); + await once(upstream, "close"); + } +}); From 984515957f758c80e3f0920481e5e0ea014eabca Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 13 Oct 2026 23:21:41 +0800 Subject: [PATCH 4/5] test: align the #2219 codex remediation pin with #3008's honest scope copy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Master-red picked up in this branch: 98e4cf4e (#3008) rewrote the codex remediation line (BILI_CODEX_COMPACT only governs explicit compaction requests) without touching the pin — fails on pure origin/master too. Verified locally before/after: 10 pass 1 fail -> 11 pass. --- tests/conflict-remediation.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/conflict-remediation.test.ts b/tests/conflict-remediation.test.ts index 74b7d7d1ce..4c4d85c381 100644 --- a/tests/conflict-remediation.test.ts +++ b/tests/conflict-remediation.test.ts @@ -66,7 +66,10 @@ test("conflictRemediation: one line per known client, generic fallback for the r assert.ok(cl.includes("CLAUDE_CODE_AUTO_COMPACT_WINDOW"), cl); assert.ok(cl.includes("bili claude"), cl); const cx = conflictRemediation("codex"); - assert.ok(cx.includes("BILI_CODEX_COMPACT=intercept"), cx); + // #3008: honest compaction scope — the knob only governs codex's explicit + // compaction requests (auto-compaction never transits the proxy, #2372). + assert.ok(cx.includes("BILI_CODEX_COMPACT only governs codex's explicit compaction requests"), cx); + assert.ok(cx.includes("never transits the proxy"), cx); assert.equal(conflictRemediation("pi"), conflictRemediation("omp"), "pi and omp share the carriage-evidence hint"); assert.ok(conflictRemediation("pi").includes("report client + bili version")); const gen = conflictRemediation(undefined); From 9d9d23cb304f61f6b859cd35af9b7118cfb824f3 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Wed, 14 Oct 2026 00:33:38 +0800 Subject: [PATCH 5/5] =?UTF-8?q?test:=20absorb=20#3058's=20preserveRecentMe?= =?UTF-8?q?ssages=205=E2=86=923=20default=20into=20the=20tail=20+=20golden?= =?UTF-8?q?=20pins?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Master-red picked up in this branch (fails on pure origin/master too): - ca93ef49 (#3058) moved the kernel default without touching the two #1387 tail tests (which ride the default and rely on m00003–m00007 being inside the protected zone) or the storage-render goldens (persisted metadata section digest is the only drift; state/blockContents/stats unchanged). - #1387 tests now pin preserveRecentMessages: 5 explicitly — they exercise the stop-signal contract, not the preserveRecent default. - goldens regenerated via scripts/update-storage-render-goldens.ts. Verified: compress-success-tail 8/8, golden-storage-render 5/5 (was 2/6). --- tests/compress-success-tail.test.ts | 13 ++++++++----- tests/golden/storage-render/anthropic.json | 4 ++-- tests/golden/storage-render/chat.json | 4 ++-- tests/golden/storage-render/google.json | 4 ++-- tests/golden/storage-render/responses.json | 4 ++-- 5 files changed, 16 insertions(+), 13 deletions(-) diff --git a/tests/compress-success-tail.test.ts b/tests/compress-success-tail.test.ts index 14bbd01e15..1b2ff90635 100644 --- a/tests/compress-success-tail.test.ts +++ b/tests/compress-success-tail.test.ts @@ -135,8 +135,10 @@ test("#2404: a rejected range keeps advertising the still-offered remainder (rec }); test("#1387: clean success that drains every compressible range emits the stop signal (pi #521)", () => { - // Default preserveRecentMessages: 5 → after folding m00001–m00002 the rest + // Pinned preserveRecentMessages: 5 — after folding m00001–m00002 the rest // (m00003–m00007) sits in the protected recent zone: nothing actionable left. + // (The kernel default dropped 5 → 3 in #3058; these tests exercise the + // #1387 tail contract, not the preserveRecent default.) const msgs = [ textMsg("raw_1", "user", "x".repeat(20000)), textMsg("raw_2", "assistant", "x".repeat(20000)), @@ -146,7 +148,7 @@ test("#1387: clean success that drains every compressible range emits the stop s textMsg("raw_6", "assistant", "x".repeat(5000)), textMsg("raw_7", "user", "x".repeat(5000)), ]; - const ctx = withRefs(makeCtx(msgs)); + const ctx = withRefs(makeCtx(msgs, { preserveRecentMessages: 5 })); ctx.session.stats.lastInputTokens = 80000; const out = runApply(ctx, { content: [{ startId: "m00001", endId: "m00002", summary: "TAIL-TEST-SUMMARY-PAYLOAD-LONG-ENOUGH-FOR-THE-KERNEL-MIN-LENGTH-CHECK" }] }); assert.ok(out.startsWith("[Compressed"), `expected success, got: ${out.slice(0, 120)}`); @@ -213,8 +215,9 @@ test("#2029: estimate-grade baseline must not suppress the stop signal via phant }); test("#1387: partial failure (some ranges rejected) keeps the old silent tail", () => { - // m00003–m00007 sit entirely in the protected recent zone under the default - // config; pairing that range with a valid one exercises the partial-failure + // m00003–m00007 sit entirely in the protected recent zone (pinned + // preserveRecentMessages: 5, as above — #3058 moved the default to 3); + // pairing that range with a valid one exercises the partial-failure // gate: no stop verdict while errors are still owed an answer (pi #521). const msgs = [ textMsg("raw_1", "user", "x".repeat(20000)), @@ -225,7 +228,7 @@ test("#1387: partial failure (some ranges rejected) keeps the old silent tail", textMsg("raw_6", "assistant", "x".repeat(5000)), textMsg("raw_7", "user", "x".repeat(5000)), ]; - const ctx = withRefs(makeCtx(msgs)); + const ctx = withRefs(makeCtx(msgs, { preserveRecentMessages: 5 })); ctx.session.stats.lastInputTokens = 80000; const out = runApply(ctx, { content: [ { startId: "m00001", endId: "m00002", summary: "TAIL-TEST-SUMMARY-PAYLOAD-LONG-ENOUGH-FOR-THE-KERNEL-MIN-LENGTH-CHECK" }, diff --git a/tests/golden/storage-render/anthropic.json b/tests/golden/storage-render/anthropic.json index 2ce8b40947..8d156c35d8 100644 --- a/tests/golden/storage-render/anthropic.json +++ b/tests/golden/storage-render/anthropic.json @@ -80,12 +80,12 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "e47a82482ed9d3fc1201562c2c539f5432873acb264862e055c5569396040aac", + "stateDigest": "858ed1c3988c25280181c34a9b30ddf78c86b4237eb5076ab311456a3001c322", "sectionDigests": { "state": "285aa622a037321b", "blockContents": "b3a9c59b22ec1a3a", "stats": "4271a6483e02458a", - "metadata": "f582165dae264d64" + "metadata": "32e9f789c44286ca" }, "stateKeyDigests": { "blocks": "8a3021f39f1f2eb8", diff --git a/tests/golden/storage-render/chat.json b/tests/golden/storage-render/chat.json index 759da3f0ca..b106fc7f96 100644 --- a/tests/golden/storage-render/chat.json +++ b/tests/golden/storage-render/chat.json @@ -80,12 +80,12 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "3a6d4239e182ebb6fe02a99faf40324a963d5f74f9bb0be0b1752f47bee65497", + "stateDigest": "7488de3b6fbb1f061c1fdc7e83b2b99009a936aef04dc36624e21fc161159903", "sectionDigests": { "state": "6e905e4ae1e678b8", "blockContents": "dd2de296a5bc6160", "stats": "ed7d3e3f253e0942", - "metadata": "1f78ed1b58e4a77e" + "metadata": "59f40d0ef9c2755e" }, "stateKeyDigests": { "blocks": "bdde93b0e100e13e", diff --git a/tests/golden/storage-render/google.json b/tests/golden/storage-render/google.json index 86f9ef858d..6696bdfa2d 100644 --- a/tests/golden/storage-render/google.json +++ b/tests/golden/storage-render/google.json @@ -80,12 +80,12 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "91d1cdd51aed493c3f1c1e4857e4a768cd43be23cc69647ca3f2376f4270e74a", + "stateDigest": "65929f00d8a26805ef859fd9ab9197d605e0531bccb17813c3457019c617ad54", "sectionDigests": { "state": "0725cfe81690b748", "blockContents": "4cc83a808a659f28", "stats": "096da9a1f61d84d0", - "metadata": "a615198f56928645" + "metadata": "0fb314268fb92034" }, "stateKeyDigests": { "blocks": "9adb53303cd4b786", diff --git a/tests/golden/storage-render/responses.json b/tests/golden/storage-render/responses.json index 3a81a2ecbe..8b72013415 100644 --- a/tests/golden/storage-render/responses.json +++ b/tests/golden/storage-render/responses.json @@ -80,12 +80,12 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "bbb968638e19d82d097871d73240d0dbabdbd3978fb7b6e140960c232e1de1bb", + "stateDigest": "c326a242c21c86ec70b0c148fc8c4951cb31f449e125f97a970a7130444a1ec4", "sectionDigests": { "state": "7194736468931151", "blockContents": "1727e2e1faf79b55", "stats": "062b6eaaeb325945", - "metadata": "cd0990da20e0f33c" + "metadata": "3b76417727dbe3d0" }, "stateKeyDigests": { "blocks": "0458e9c8a7bb1a99",