From ed367d41d62905cc8ccd332bf3636e48f020a765 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 24 Nov 2026 10:06:40 +0800 Subject: [PATCH] fix: count real prose around a pure refs-only echo as the answer (#6034) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The plugin-mode degenerate-turn latch armed on ANY stripped render tag (one-shot per stream) and never checked what the drop LEFT BEHIND. The latch design premise — "a stripped tag leaves its interior pending" — only holds for the prose-wrapping close, which releases its body into the SAME call. A pure refs-only echo (the kernel emit shape: open + ref + close, no prose body) is dropped as a whole unit and leaves nothing behind, yet the latch armed anyway: the model real answer arriving in the same or a later delta then counted as markup, answerChars went to zero, the turn regenerated once (paid full re-read), the retry re-matched, and the session died with the #870 in-band error. The tag-echo filter gains a per-drop verdict callback (onDropVerdict: (leavesInterior: boolean) => void) — delivered on EVERY drop, unlike the one-shot onDrop log: - TRUE (pending interior, frame suspect) only when the dropped unit can still release real prose: the session-start open, the truncated open-body span, the prose-wrapping close — and a single-ref body terminated by a MANGLED close name (degenCloseAfterRef matches ANY short close, #2190, so that path carries both the clean echo and the unclosed-echo shape; verdict by close name: = clean echo = false, anything else = the model opened a render tag and botched the close = true, the shape plugin-empty-turn-retry pins). - FALSE for whole-unit atomic drops that release nothing: paired / self-close / lone-close units, the mangled attrs unit, the bare-open split, the refs-only close (#6034 shape), the oversized pending-ref span and the attested-content overflow drops. The degenerate gate droppedTagInFrame becomes last-write-wins over the verdicts delivered as the frame is RELEASED (push() returns, then the accounting loop reads the flag), which fixes the old one-shot ordering (a pending arm that outlived its interior, and multi-artifact frames where only the FIRST drop had a voice) while keeping every shape the retry tests pin. Model-visible text changes: none. No wire-byte change (internal accounting only). No config surface. Tests (tests/issue6034-pure-echo-latch.test.ts, both directions per #3617): - repro, red on master: single-frame real prose + complete refs-only echo in one delta → no retry, prose delivered (was: retry + #870). - repro, red on master: refs-only echo split across frames, answer in the close frame → no retry, prose delivered (was: retry + #870). - filter-level verdict sequences: clean refs-only echo [true, false] vs prose-wrapping echo [true, true] vs single-frame complete unit [false] vs mangled-close unit [true, true]. - controls, green on both sides: pure-echo turn still retries once + recovers; prose-wrapped echo still retries (#2756); the three unclosed-echo tests in plugin-empty-turn-retry stay green. - all 24 tag-echo / degenerate-turn suites (367 tests) green. --- src/loop/tag-echo-filter.ts | 43 +++-- src/plugin.ts | 24 ++- tests/issue6034-pure-echo-latch.test.ts | 218 ++++++++++++++++++++++++ 3 files changed, 271 insertions(+), 14 deletions(-) create mode 100644 tests/issue6034-pure-echo-latch.test.ts diff --git a/src/loop/tag-echo-filter.ts b/src/loop/tag-echo-filter.ts index ffeccfc48d..f2f27e8b91 100644 --- a/src/loop/tag-echo-filter.ts +++ b/src/loop/tag-echo-filter.ts @@ -1054,7 +1054,7 @@ export function createBiliArtifactFilter(onDrop?: (snippet: string) => void): Ta }; } -export function createTagEchoFilter(onDrop?: (snippet: string, duringDrain?: boolean) => void, onResidueWarn?: (snippet: string) => void, absorbInstructed?: boolean, requestText?: string): TagEchoFilter { +export function createTagEchoFilter(onDrop?: (snippet: string, duringDrain?: boolean) => void, onResidueWarn?: (snippet: string) => void, absorbInstructed?: boolean, requestText?: string, onDropVerdict?: (leavesInterior: boolean) => void): TagEchoFilter { let held = ""; /** Settled prose deferred alongside a NON-definite tag-head tail: it * carries a dead ref-close unit whose verdict is content-determined @@ -1107,7 +1107,16 @@ export function createTagEchoFilter(onDrop?: (snippet: string, duringDrain?: boo // below (spent by the response's FIRST drop) left it with no line at all. // It gets its own one-shot budget so a held head at EOF is always audible. let drainNoticed = false; - const recordDrop = (snippet: string, duringDrain = false) => { + /** #6034 (option E): delivered on EVERY drop (the one-shot notices above + * only reach the first) — does this dropped artifact leave interior + * bytes behind that a consumer's answer ledger must count as markup + * (true: a session-start open whose body verdict is still open, and a + * close that releases its prose body), or does the artifact die whole / + * release content (false: complete refs-only units, dead orphans, a + * refs-only close, discarded payloads)? Default false; only the sites + * below that provably leave or release interior pass true. */ + const recordDrop = (snippet: string, duringDrain = false, leavesInterior = false) => { + onDropVerdict?.(leavesInterior); droppedAny = true; if (duringDrain) { if (onDrop && !drainNoticed) { @@ -1122,17 +1131,17 @@ export function createTagEchoFilter(onDrop?: (snippet: string, duringDrain?: boo } }; /** One self-contained artifact resolved by a single drop call. */ - const drop = (snippet: string, duringDrain = false) => { + const drop = (snippet: string, duringDrain = false, leavesInterior = false) => { dropCount += 1; - recordDrop(snippet, duringDrain); + recordDrop(snippet, duringDrain, leavesInterior); }; /** Any drop inside a live swallow session — the session counts once. */ - const dropSwallowSpan = (snippet: string, duringDrain = false) => { + const dropSwallowSpan = (snippet: string, duringDrain = false, leavesInterior = false) => { if (!swallowSessionCounted) { dropCount += 1; swallowSessionCounted = true; } - recordDrop(snippet, duringDrain); + recordDrop(snippet, duringDrain, leavesInterior); }; /** #2862: strip dead ref-close units (ref + unterminated close head) from * a span about to be RELEASED as prose; each unit is one self-contained @@ -1190,7 +1199,17 @@ export function createTagEchoFilter(onDrop?: (snippet: string, duringDrain?: boo if (swallowReleases) { const dspan = degenCloseAfterRef(combined); if (dspan !== null) { - dropSwallowSpan(combined.slice(0, dspan.end)); + // #6034: a single-ref body terminates on ANY short close (#2190), + // so this path also carries the CLEAN echo (proper close name). + // Verdict by name: the proper close is a well-formed kernel tag + // quote — nothing left behind, the frame stays an answer; a + // mangled close name is the unclosed-echo shape (the model opened + // a render tag and botched the close), so whatever the frame still + // releases after the dead unit is suspect markup — exactly as the + // one-shot era armed it (the unclosed-echo retry tests in + // plugin-empty-turn-retry pin that direction). + const mangledClose = !combined.startsWith("\x3c/acp\x3e", dspan.start); + dropSwallowSpan(combined.slice(0, dspan.end), false, mangledClose); swallowed = ""; swallowUntilClose = false; buf = combined.slice(dspan.end); @@ -1254,10 +1273,10 @@ export function createTagEchoFilter(onDrop?: (snippet: string, duringDrain?: boo const t = TRUNC_OPEN.exec(inner); if (t !== null) { out += stripDeadRefCloses(inner.slice(0, t.index)); - dropSwallowSpan(combined.slice(t.index, span.end)); + dropSwallowSpan(combined.slice(t.index, span.end), false, true); buf = combined.slice(span.end); } else { - dropSwallowSpan(combined.slice(span.start, span.end)); + dropSwallowSpan(combined.slice(span.start, span.end), false, true); buf = inner + combined.slice(span.end); } } @@ -1296,6 +1315,10 @@ export function createTagEchoFilter(onDrop?: (snippet: string, duringDrain?: boo swallowed = ""; swallowUntilClose = false; buf = combined; + // #644: the over-budget tail is content, not the tag's + // interior — un-arm any pending verdict so the released + // payload counts as the answer (#6034 class). + onDropVerdict?.(false); if (onResidueWarn && containsEchoResidue(combined)) onResidueWarn(combined); continue; } @@ -1480,7 +1503,7 @@ export function createTagEchoFilter(onDrop?: (snippet: string, duringDrain?: boo continue; } swallowSessionCounted = false; - recordDrop(m[0]); + recordDrop(m[0], false, true); // An odd number of quotes means the opening's attribute list // never closed: the model wrapped its turn inside the value (the // sibling shape opens with such a value and then runs into a `<`, diff --git a/src/plugin.ts b/src/plugin.ts index 8252b2284b..4bde66cd3c 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -2921,11 +2921,23 @@ export async function pipePluginChatWithStrip( // every count taken from bili.log. const who = session ? `[${session.id}] ` : ""; const onTagDrop = (snippet: string, duringDrain?: boolean) => { - droppedTagInFrame = true; sawStrippedEcho = true; const what = duringDrain === true ? "held head dropped during drain" : "stripped model-emitted render tag (plugin passthrough)"; loggerLog("warn", `${who}[tag-echo] ${what}: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); }; + // #6034 (option E): the answer ledger's markup flag is VERDICT-driven, + // not "any drop arms it". A complete refs-only echo unit dies whole — it + // leaves no interior behind, so the answer text around it must count as + // the answer; arming on every drop miscounted a 108-char real answer as + // markup after such an echo and killed a healthy turn twice (the sample + // in #6034). Only a session-start open (verdict pending until the span + // resolves) and a close that releases its prose body leave interior. + // Last-write-wins is safe: the filter delivers verdicts in release order + // within a frame (a unit's drop precedes its interior's resolution), and + // the frame's released text is counted only after push() returns. + const onTagDropVerdict = (leavesInterior: boolean) => { + droppedTagInFrame = leavesInterior; + }; // #2190: the filter released bytes that still carry echo-residue shape — // the leak is now observable instead of silent. Log-only; the bytes were // already decided by the state machine. @@ -2961,7 +2973,7 @@ export async function pipePluginChatWithStrip( // openai reasoning fields — the thinking channel is NEVER // rewritten, only the visible text channel is. const signedThinking = field === "thinking" || (protocol === "openai" && (field === "reasoning_content" || field === "reasoning")); - s = { filter: signedThinking ? createIdentityStreamFilter() : composeStreamFilters(composeStreamFilters(createTagEchoFilter(onTagDrop, onResidueWarn, absorbInstructed, requestText), createMarkerLineFilter(onMarkerDrop)), createBiliArtifactFilter(onBiliDrop)), field, index }; + s = { filter: signedThinking ? createIdentityStreamFilter() : composeStreamFilters(composeStreamFilters(createTagEchoFilter(onTagDrop, onResidueWarn, absorbInstructed, requestText, onTagDropVerdict), createMarkerLineFilter(onMarkerDrop)), createBiliArtifactFilter(onBiliDrop)), field, index }; streams.set(key, s); } return s; @@ -3009,8 +3021,12 @@ export async function pipePluginChatWithStrip( * unclosed-tag case): markup the filter declined to swallow. A turn whose * only visible output is this is as dead to the host as an empty one. */ let releasedMarkupChars = 0; - /** Set while a frame is being rewritten because a render tag was dropped: - * the text that survives such a frame is the tag's own interior. */ + /** VERDICT-driven (onTagDropVerdict, #6034 option E): true while the + * filter has just dropped an artifact whose interior the stream still + * releases — the text surviving such a frame is the tag's own interior + * (markup), so the answer ledger must not count it as the answer. A + * whole-dead unit (complete refs-only echo) or a content release keeps + * it false and the released text stays answer. */ let droppedTagInFrame = false; let finalFinishReason: string | undefined; // #2328 Q2/Q4: termination diagnostics — every truncation emit below diff --git a/tests/issue6034-pure-echo-latch.test.ts b/tests/issue6034-pure-echo-latch.test.ts new file mode 100644 index 0000000000..21845050f0 --- /dev/null +++ b/tests/issue6034-pure-echo-latch.test.ts @@ -0,0 +1,218 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createTagEchoFilter } from "../src/loop/tag-echo-filter.ts"; +import { pipePluginChatWithStrip } from "../src/plugin.ts"; +import type { Session } from "../src/session.ts"; + +// #6034 (option E): the plugin's answer ledger armed its markup flag on ANY +// dropped tag (onTagDrop was one-shot, so the first drop owned the flag). A +// complete refs-only echo unit — the model citing its own render tag, +// `m00258` — dies WHOLE: it +// leaves no interior behind. Arming on it miscounted the turn's 108-char real +// answer as markup, the answer gate read the turn as degenerate, retried, +// hit the same echo again, and emitted the in-band #870 error — killing a +// healthy turn twice on 300K+ tokens of full-price refetch. The verdict now +// rides a separate always-delivered callback (the one-shot notice only +// reaches the first drop, which is precisely the case that must be +// overruled): only a session-start open and a close releasing its prose body +// leave interior; whole-dead units and content releases do not. +// Directions: T1/T2 (pure echo + real prose => no retry) are the fix; +// T3/T4 (no answer at all => still retry) are the kept controls (#3617). + +const ECHO = `\x3cacp tokens="102" type="text" time="2026-11-23 09:44:20"\x3em00258\x3c/acp\x3e`; +const ECHO_OPEN = `\x3cacp tokens="102" type="text" time="2026-11-23 09:44:20"\x3e`; +const PROSE = "The migration finished without errors — all 1,204 rows copied, checksums verified, and the old bucket archived as requested."; + +function makeSession(): Session { + return { + id: "testsess", + 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): string { + return `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "qwen", choices: [{ index: 0, delta, finish_reason: null }] })}\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("filter: a cross-chunk refs-only echo arms on session start, then disarms on its whole-dead close (#6034)", () => { + const verdicts: boolean[] = []; + const f = createTagEchoFilter(undefined, undefined, false, undefined, (v) => verdicts.push(v)); + const a = f.push(ECHO_OPEN); + const b = f.push(`m00258\x3c/acp\x3e`); + const c = f.push(PROSE); + assert.equal(a, "", "the open holds"); + assert.equal(b, "", "the refs-only unit dies whole — nothing released"); + assert.equal(c, PROSE, "the prose after the echo flows to the client"); + assert.deepEqual(verdicts, [true, false], "session start leaves a pending interior; the refs-only close leaves none"); +}); + +test("filter: a mangled close after a ref (unclosed echo) keeps the frame armed — the span died uncleanly (#6034 vs the unclosed-echo retry tests)", () => { + const verdicts: boolean[] = []; + const f = createTagEchoFilter(undefined, undefined, false, undefined, (v) => verdicts.push(v)); + // The production shape from plugin-empty-turn-retry: the model opens a + // render tag, writes a ref inside, then fails to close it (`` is the + // mangled close). The unit dies atomically, but the mangled close is the + // resolution event — whatever the frame still releases after it is suspect. + f.push("\x3cacp tokens=\"247\" type=\"text\"\x3e"); + const released = f.push(` m00693${" ".repeat(80)}`); + assert.ok(released.length > 0, "the residue after the mangled close flows to the client"); + assert.deepEqual(verdicts, [true, true], "session start AND the mangled-close resolution both leave the frame armed"); +}); + +test("filter: a closed span with a prose body leaves interior (markup), both in-frame and across chunks (#6034 control)", () => { + const verdicts: boolean[] = []; + const f = createTagEchoFilter(undefined, undefined, false, undefined, (v) => verdicts.push(v)); + f.push(``.replace(//g, "\x3e")); + const released = f.push(`wrapped body\x3c/acp\x3e`); + assert.equal(released, "wrapped body", "the body is released (only the close goes)"); + assert.deepEqual(verdicts, [true, true], "session start AND the body-releasing close both leave interior"); +}); + +test("filter: a complete refs-only echo in one buffer is a whole-dead unit — no interior verdict (#6034)", () => { + const verdicts: boolean[] = []; + const f = createTagEchoFilter(undefined, undefined, false, undefined, (v) => verdicts.push(v)); + const released = f.push(`prefix prose ${ECHO}`); + assert.equal(released, "prefix prose ", "only the echo unit dies"); + assert.deepEqual(verdicts, [false], "a complete unit never leaves interior"); +}); + +test("chat pipe: real answer + pure refs-only echo in ONE frame is NOT degenerate — no retry (#6034 sample 2 shape)", async () => { + 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])); + }; + // The exact #6034 sample-2 wire: 108 chars of real content, then the + // model's own render tag echoed back as a complete refs-only unit — in + // ONE buffer, so the whole-dead drop and the answer release land in the + // same frame (the frame the ledger counts). + await pipePluginChatWithStrip(streamOf([ + chatChunk({ role: "assistant", content: PROSE + ECHO }), + chatFinish("stop"), + DONE, + ]), makeRes(out), "openai", makeSession(), (m) => logs.push(m), refetch, "http://up"); + const body = out.join(""); + assert.equal(refetches, 0, "a turn that delivered a real answer must not be regenerated"); + assert.ok(body.includes(PROSE), "the delivered answer reaches the client"); + assert.ok(!logs.some((l) => l.includes("degenerate terminal turn")), "no degenerate verdict for a healthy turn"); +}); + +test("chat pipe: refs-only echo split across chunks, close and answer in the last frame — no retry (#6034 chunking variant)", async () => { + 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])); + }; + // The open is still held when the close lands with the answer in the + // SAME frame: the session was armed on the open, so only the close's + // whole-dead verdict (not the one-shot notice) can keep the answer. + await pipePluginChatWithStrip(streamOf([ + chatChunk({ role: "assistant", content: ECHO_OPEN }), + chatChunk({ content: `m00258\x3c/acp\x3e ${PROSE}` }), + chatFinish("stop"), + DONE, + ]), makeRes(out), "openai", makeSession(), (m) => logs.push(m), refetch, "http://up"); + const body = out.join(""); + assert.equal(refetches, 0, "the close's whole-dead verdict must keep the same-frame answer"); + assert.ok(body.includes(PROSE), "the delivered answer reaches the client"); + assert.ok(!logs.some((l) => l.includes("degenerate terminal turn")), "no degenerate verdict for a healthy turn"); +}); + +test("chat pipe: a pure refs-only echo turn still retries — the control direction (#6034 vs #732)", async () => { + const out: string[] = []; + const logs: string[] = []; + let refetches = 0; + const refetch = (): Promise | null> => { + refetches += 1; + return Promise.resolve(streamOf([ + chatChunk({ content: "recovered answer" }), + chatFinish("stop"), + DONE, + ])); + }; + // Whole turn = the echoed tag, nothing else: still no answer, still retry. + await pipePluginChatWithStrip(streamOf([ + chatChunk({ role: "assistant", content: ECHO_OPEN }), + chatChunk({ content: `m00258\x3c/acp\x3e` }), + chatFinish("stop"), + DONE, + ]), makeRes(out), "openai", makeSession(), (m) => logs.push(m), refetch, "http://up"); + const body = out.join(""); + assert.equal(refetches, 1, "an answerless echo turn must retry exactly once"); + assert.ok(body.includes("recovered answer"), "the retry's answer reaches the client"); + assert.ok(logs.some((l) => l.includes("#732/#821") || l.includes("degenerate")), "the retry is logged"); +}); + +test("chat pipe: a closed span with a prose body still reads as markup — retry kept (#2756 control)", async () => { + const out: string[] = []; + const logs: string[] = []; + let refetches = 0; + const refetch = (): Promise | null> => { + refetches += 1; + return Promise.resolve(streamOf([ + chatChunk({ content: "recovered answer" }), + chatFinish("stop"), + DONE, + ])); + }; + // Wrapped-turn imitation: the released body IS the tag's interior — + // the host stalls on it, so the turn stays degenerate and retries. + await pipePluginChatWithStrip(streamOf([ + chatChunk({ role: "assistant", content: ``.replace(//g, "\x3e") }), + chatChunk({ content: `wrapped body that is not an answer\x3c/acp\x3e` }), + chatFinish("stop"), + DONE, + ]), makeRes(out), "openai", makeSession(), (m) => logs.push(m), refetch, "http://up"); + const body = out.join(""); + assert.equal(refetches, 1, "tag interior is markup, not an answer — the retry must fire"); + assert.ok(body.includes("recovered answer"), "the retry's answer reaches the client"); + assert.ok(logs.some((l) => l.includes("#732/#821") || l.includes("degenerate")), "the retry is logged"); +});