From c5fed0ef142899bc78a080d79dcb3a7edbabd4b1 Mon Sep 17 00:00:00 2001 From: dog Date: Mon, 9 Nov 2026 08:35:46 +0800 Subject: [PATCH 1/6] loop: retry degenerate turns that end with whitespace-only text (#732 follow-up) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A thinking model can end a turn with reasoning + whitespace-only text (e.g. "\n\n") and finish_reason=stop. No tool call, no visible answer, client stalls. The #732 one-shot retry gate read this as 'visible output already reached' (length-2 text) and skipped the retry, passing the empty turn through silently. - track non-whitespace visible text (forwardedVisibleText) separately; the #732 gate now uses trimmed text + that flag, so whitespace-only terminals take the retry path exactly like pure-reasoning terminals - the #1988 truncation gates keep the original forwardedVisible semantics (forwarded, not parsed) — untouched - observability: warn when the one-shot budget was consumed and the retry output was empty again (double-degenerate), so the fleet can count the residual case the host nudge still covers - compress receipt hardening: the FAILED receipt now ends with an explicit return-to-task instruction, reducing the observed pattern of a model derailing into the compression bookkeeping after a refused call and then going quiet --- src/loop/core.ts | 40 +++++++++++++++++++++++++++-- src/stream.ts | 2 +- tests/loop-degenerate-retry.test.ts | 38 +++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 3 deletions(-) diff --git a/src/loop/core.ts b/src/loop/core.ts index 079b5b3a4f..0bbc7f96d2 100644 --- a/src/loop/core.ts +++ b/src/loop/core.ts @@ -798,6 +798,17 @@ export async function* runCompressLoop( // round-2 truncation out of this retry path. let forwardedFraming = false; let forwardedVisible = false; + // #732 follow-up: whitespace-only text ("\n\n") is not visible + // output in any host-turn sense — a thinking model ends the turn with + // reasoning + 2 newlines and the client still stalls, but the length-2 + // text made the #732 gate read "visible output reached" and skip the + // retry. Track NON-whitespace visible text separately for that gate. + // NOTE (post-review): set at PARSE time, not forward time — Responses + // textProtocol rounds parse text that is never forwarded, and this flag + // is still set. It is only ever safe in the degenerate gate, where it is + // equivalent to `assistantText.trim().length > 0`; NEVER reuse it in the + // truncation gates, which need forwarded (not parsed) semantics. + let forwardedVisibleText = false; // #2501: a thinking block reached the client without its signature — // unrecoverable by re-fetch on a signing upstream (see the gates). // Set when the held start is released (adapter's thinkingStart meta), @@ -846,6 +857,7 @@ export async function* runCompressLoop( sawThinking = false; forwardedFraming = false; forwardedVisible = false; + forwardedVisibleText = false; unsignedThinkingOnWire = false; sawSignedThinkingThisAttempt = false; fwdBytes = 0; @@ -854,6 +866,7 @@ export async function* runCompressLoop( if (signal?.aborted) break; if (ev.kind === "text") { assistantText += ev.delta; + if (ev.delta.trim().length > 0) forwardedVisibleText = true; let tp = roundParts[roundParts.length - 1]; if (!tp || tp.kind !== "text") { tp = { kind: "text", text: "" }; @@ -1126,9 +1139,12 @@ export async function* runCompressLoop( finishReason !== "failed" && finishReason !== "incomplete" && finishReason !== "error" && - assistantText.length === 0 && + assistantText.trim().length === 0 && calls.length === 0 && - !forwardedVisible && + // #732 follow-up: whitespace-only text ("\n\n") must not bar the retry — + // it reached the client (forwardedVisible) but is invisible to + // host turn semantics, same class as the reasoning prefix. + !forwardedVisibleText && !signal?.aborted ) { degenerateRetried = true; @@ -1227,6 +1243,26 @@ export async function* runCompressLoop( break; } + // #732 follow-up (observability only): the one-shot budget was consumed this + // round AND the FINAL attempt (i.e. the retry's own output) still ended with zero + // visible output — a double-degenerate turn passing through. The host nudge is the + // only remaining safety net, so make the fleet able to count it. + if ( + degenerateRetried && + sawDone && + !truncatedDone && + !suppressCompletion && + typeof finishReason === "string" && + finishReason !== "failed" && + finishReason !== "incomplete" && + finishReason !== "error" && + assistantText.trim().length === 0 && + calls.length === 0 && + !signal?.aborted + ) { + loggerLog("warn", `[acp-loop] degenerate-turn DOUBLE-degenerate: the retry output was empty again, round ${round} (session ${ctx.session.id}) — passing through; host nudge is the remaining safety net (#732 follow-up)`); + } + if ( usage.inputTokens !== undefined || usage.outputTokens !== undefined || diff --git a/src/stream.ts b/src/stream.ts index 27123b2c8f..ecd66b125e 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -1119,7 +1119,7 @@ export function applyRanges(parsed: ReturnType, ctx: const notArrayHint = diagnostics.kind === "content-not-array" ? " If your 'content' string encoded a single JSON object, wrap it in square brackets so it encodes an ARRAY of entries (\"[...]\"), or use the line-form headers below." : ""; - return compressResult(`[Compression FAILED: no valid ranges parsed (kind=${diagnostics.kind}, dropped=${diagnostics.invalidItems}).${why}${notArrayHint} compress takes ONE 'content' STRING holding every range: each block starts with its header line 'mNNNNN–mNNNNN optional topic' followed by that block's summary markdown; a JSON-encoded array of {startId, endId, summary} objects is also accepted INSIDE that same string. startId/endId are mNNNNN message refs from the conversation (call acp_status to see current refs).${recovery.hint}${retry}${guard}${loopGuard}]`, "refused", 0, `parse:${diagnostics.kind}`); + return compressResult(`[Compression FAILED: no valid ranges parsed (kind=${diagnostics.kind}, dropped=${diagnostics.invalidItems}).${why}${notArrayHint} compress takes ONE 'content' STRING holding every range: each block starts with its header line 'mNNNNN–mNNNNN optional topic' followed by that block's summary markdown; a JSON-encoded array of {startId, endId, summary} objects is also accepted INSIDE that same string. startId/endId are mNNNNN message refs from the conversation (call acp_status to see current refs).${recovery.hint}${retry}${guard}${loopGuard} This failure only concerns the compress call. Return to the original task now and continue it (visible output or a tool call).]`, "refused", 0, `parse:${diagnostics.kind}`); } // #847: detect reversed refs as SUBMITTED, before #1001 normalization // rewrites them (order matters — normalizeRangeOrder mutates in place). diff --git a/tests/loop-degenerate-retry.test.ts b/tests/loop-degenerate-retry.test.ts index 5608035973..264a321ca5 100644 --- a/tests/loop-degenerate-retry.test.ts +++ b/tests/loop-degenerate-retry.test.ts @@ -191,6 +191,44 @@ test("#821 O2: genuinely empty (no-reasoning) terminal turn is NOT retried", asy assert.equal(fetchCalls, 0, "sawThinking=false → the empty turn passes through untouched"); }); +// #732 follow-up: a thinking model ends the turn with reasoning + +// whitespace-only text ("\n\n") and no tool call. The 2-char text made the +// #732 gate read "visible output reached" (assistantText.length>0 && +// forwardedVisible) and the retry never fired — the host session stalled +// until its daemon nudge, which the model also answered with a bare "\n\n". + +const OPENAI_THINKING_WSPRIBE = openaiSse([ + { id: "chatcmpl_w1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, + { id: "chatcmpl_w1", choices: [{ index: 0, delta: { reasoning_content: "let me check the logs first to understand what happened" }, finish_reason: null }] }, + { id: "chatcmpl_w1", choices: [{ index: 0, delta: { content: "\n\n" }, finish_reason: null }] }, + { id: "chatcmpl_w1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }, +]); + +const OPENAI_THINKING_REALTEXT = openaiSse([ + { id: "chatcmpl_w2", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" }, finish_reason: null }] }, + { id: "chatcmpl_w2", choices: [{ index: 0, delta: { reasoning_content: "the user asked a question" }, finish_reason: null }] }, + { id: "chatcmpl_w2", choices: [{ index: 0, delta: { content: "Here is the answer you asked for." }, finish_reason: null }] }, + { id: "chatcmpl_w2", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }, +]); + +test("#732-follow-up W1: reasoning + whitespace-only text + stop → the #732 retry now fires (was bypassed via length 2)", async () => { + const { out, fetchCalls, bodies } = await drainOpenai(OPENAI_THINKING_WSPRIBE, [OPENAI_GOOD], "deg-w1"); + assert.equal(fetchCalls, 1, "exactly one degenerate auto-retry fired despite the forwarded \"\\n\\n\""); + assert.ok( + bodies[0].includes("ended without a tool call"), + "the retry body carries the ephemeral continuation nudge", + ); + assert.ok(out.includes("let me check the logs"), "the thinking prefix was streamed to the client"); + assert.ok(out.includes("\n\n"), "the whitespace-only text reached the client"); + assert.ok(out.includes("continued after nudge"), "the retried turn's content was delivered on the same stream"); +}); + +test("#732-follow-up W2: reasoning + real visible text + stop is NOT retried (a delivered answer is not degenerate)", async () => { + const { out, fetchCalls } = await drainOpenai(OPENAI_THINKING_REALTEXT, [OPENAI_GOOD], "deg-w2"); + assert.equal(fetchCalls, 0, "non-whitespace visible text bars the retry — no false positive on a normal answer"); + assert.ok(out.includes("Here is the answer"), "the normal answer passes through untouched"); +}); + // #1862: the degenerate-retry boundary on the Responses wire misfired in two ways. // A: a completed reasoning+custom_tool_call turn carries executable output, but the // adapter counted zero tool calls, so the gate treated it as degenerate and re-issued From 65dd4b39ef46d82ab44183134d60c61a545eca9e Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 9 Nov 2026 09:01:13 +0800 Subject: [PATCH 2/6] refactor(loop): drop redundant forwardedVisibleText from the degenerate-retry gate (#5986 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review finding 1 of PR #5986: the flag was provably equivalent to the gate's assistantText.trim().length === 0 check — both reset per attempt at the top of the retry loop, and assistantText is mutated only by delta accumulation, so the flag could never disagree with the trim check. Removing it keeps one source of truth; behavior is unchanged. The truncation gates keep forwardedVisible, which needs forwarded-not-parsed semantics; that boundary is now documented on the trim condition itself. --- src/loop/core.ts | 21 ++++----------------- 1 file changed, 4 insertions(+), 17 deletions(-) diff --git a/src/loop/core.ts b/src/loop/core.ts index 0bbc7f96d2..a9e09cc9d8 100644 --- a/src/loop/core.ts +++ b/src/loop/core.ts @@ -798,17 +798,6 @@ export async function* runCompressLoop( // round-2 truncation out of this retry path. let forwardedFraming = false; let forwardedVisible = false; - // #732 follow-up: whitespace-only text ("\n\n") is not visible - // output in any host-turn sense — a thinking model ends the turn with - // reasoning + 2 newlines and the client still stalls, but the length-2 - // text made the #732 gate read "visible output reached" and skip the - // retry. Track NON-whitespace visible text separately for that gate. - // NOTE (post-review): set at PARSE time, not forward time — Responses - // textProtocol rounds parse text that is never forwarded, and this flag - // is still set. It is only ever safe in the degenerate gate, where it is - // equivalent to `assistantText.trim().length > 0`; NEVER reuse it in the - // truncation gates, which need forwarded (not parsed) semantics. - let forwardedVisibleText = false; // #2501: a thinking block reached the client without its signature — // unrecoverable by re-fetch on a signing upstream (see the gates). // Set when the held start is released (adapter's thinkingStart meta), @@ -857,7 +846,6 @@ export async function* runCompressLoop( sawThinking = false; forwardedFraming = false; forwardedVisible = false; - forwardedVisibleText = false; unsignedThinkingOnWire = false; sawSignedThinkingThisAttempt = false; fwdBytes = 0; @@ -866,7 +854,6 @@ export async function* runCompressLoop( if (signal?.aborted) break; if (ev.kind === "text") { assistantText += ev.delta; - if (ev.delta.trim().length > 0) forwardedVisibleText = true; let tp = roundParts[roundParts.length - 1]; if (!tp || tp.kind !== "text") { tp = { kind: "text", text: "" }; @@ -1139,12 +1126,12 @@ export async function* runCompressLoop( finishReason !== "failed" && finishReason !== "incomplete" && finishReason !== "error" && + // #732 follow-up: trim, so whitespace-only text ("\n\n") must not bar + // the retry — it is invisible to host turn semantics, same class as + // the reasoning prefix. (The truncation gates keep the raw + // forwardedVisible: they need forwarded-not-parsed semantics.) assistantText.trim().length === 0 && calls.length === 0 && - // #732 follow-up: whitespace-only text ("\n\n") must not bar the retry — - // it reached the client (forwardedVisible) but is invisible to - // host turn semantics, same class as the reasoning prefix. - !forwardedVisibleText && !signal?.aborted ) { degenerateRetried = true; From 518255971d5e4eceb11161aee0f6814ac221a9cb Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 9 Nov 2026 09:01:17 +0800 Subject: [PATCH 3/6] fix(loop): correct double-degenerate warn attribution to the request-scoped budget (#5986 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review finding 2 of PR #5986: degenerateRetried is declared once per request (core.ts top of runCompressLoop) and shared with the #2303 draft-tail retry path — it is never reset per round. The warn's comment and log line both claimed 'consumed this round' / 'the retry output was empty again', which misattributes the pass-through in the chain where an earlier round (or a draft-tail retry) spent the budget and a LATER round degenerates fresh. Reword comment and log message to the accurate request-scoped attribution; keep the stable 'DOUBLE-degenerate' token for fleet grep continuity. No logic change. --- src/loop/core.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/loop/core.ts b/src/loop/core.ts index a9e09cc9d8..09866d16d9 100644 --- a/src/loop/core.ts +++ b/src/loop/core.ts @@ -1230,10 +1230,12 @@ export async function* runCompressLoop( break; } - // #732 follow-up (observability only): the one-shot budget was consumed this - // round AND the FINAL attempt (i.e. the retry's own output) still ended with zero - // visible output — a double-degenerate turn passing through. The host nudge is the - // only remaining safety net, so make the fleet able to count it. + // #732 follow-up (observability only): the one-shot PER-REQUEST retry budget + // (degenerateRetried — shared with the #2303 draft-tail path, never reset per + // round) was already spent earlier in this request, and THIS round still ended + // degenerate — zero visible output, no tool call — so nothing will retry it. + // The host nudge is the only remaining safety net; make the fleet able to + // count these pass-throughs. if ( degenerateRetried && sawDone && @@ -1247,7 +1249,7 @@ export async function* runCompressLoop( calls.length === 0 && !signal?.aborted ) { - loggerLog("warn", `[acp-loop] degenerate-turn DOUBLE-degenerate: the retry output was empty again, round ${round} (session ${ctx.session.id}) — passing through; host nudge is the remaining safety net (#732 follow-up)`); + loggerLog("warn", `[acp-loop] degenerate-turn DOUBLE-degenerate: degenerate terminal turn after the per-request retry budget was already spent, round ${round} (session ${ctx.session.id}) — passing through; host nudge is the remaining safety net (#732 follow-up)`); } if ( From 7a513466aec75c801bf871088d33551afbcaca7c Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 9 Nov 2026 09:01:21 +0800 Subject: [PATCH 4/6] test(loop): pin the double-degenerate warn both directions (#5986 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review finding 3 of PR #5986: the double-degenerate pass-through (per-request retry budget already spent, round still ended degenerate) was observable only in fleet logs — no test captured loggerLog. Add R1/R2 via the setLogCapture seam: R1 drives the degenerate-re-request + degenerate-retry chain and asserts exactly one DOUBLE-degenerate warn with the request-scoped attribution; R2 drives a successful retry and asserts NO double-degenerate warn while proving the capture is live via the auto-retry warn. Gate discipline holds both ways. --- tests/loop-degenerate-retry.test.ts | 45 +++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/tests/loop-degenerate-retry.test.ts b/tests/loop-degenerate-retry.test.ts index 264a321ca5..5f340a634d 100644 --- a/tests/loop-degenerate-retry.test.ts +++ b/tests/loop-degenerate-retry.test.ts @@ -6,6 +6,7 @@ import type { Session } from "../src/session.ts"; import { runCompressLoop, createResponsesAdapter, createOpenaiAdapter } from "../src/loop/index.ts"; import { buildCompressSystemPrompt } from "../src/compress-tool.ts"; import { getCacheLedger } from "../src/cache-ledger.ts"; +import { setLogCapture } from "../src/logger.ts"; // #732: invisible single-retry for a degenerate terminal turn (reasoning-only // completion, zero visible text, zero tool calls) that reached the client with @@ -229,6 +230,50 @@ test("#732-follow-up W2: reasoning + real visible text + stop is NOT retried (a assert.ok(out.includes("Here is the answer"), "the normal answer passes through untouched"); }); +// #732 follow-up review: the double-degenerate pass-through (per-request budget +// already spent, round still ended degenerate) is observable only through its +// warn line — pin both directions so a regression that drops or spams it fails +// here instead of silently vanishing from fleet logs. + +test("#732-follow-up R1: double-degenerate pass-through emits exactly one DOUBLE-degenerate warn", async () => { + const lines: Array<{ level: string; msg: string }> = []; + setLogCapture((level, msg) => { lines.push({ level, msg }); }); + try { + // Re-request degenerate → retry fires (spends the per-request budget); + // the retry comes back degenerate too → passes through with the warn. + const { fetchCalls } = await drain([ROUND_DEGENERATE, ROUND_DEGENERATE], "deg-r1"); + assert.equal(fetchCalls, 2, "re-request + one retry"); + } finally { + setLogCapture(null); + } + const warns = lines.filter((l) => l.level === "warn" && l.msg.includes("DOUBLE-degenerate")); + assert.equal(warns.length, 1, "exactly one double-degenerate warn"); + assert.ok( + warns[0].msg.includes("retry budget was already spent"), + "the warn attributes the pass-through to the spent per-request budget", + ); +}); + +test("#732-follow-up R2: a SUCCESSFUL retry emits no DOUBLE-degenerate warn", async () => { + const lines: Array<{ level: string; msg: string }> = []; + setLogCapture((level, msg) => { lines.push({ level, msg }); }); + try { + const { fetchCalls } = await drain([ROUND_DEGENERATE, ROUND_GOOD], "deg-r2"); + assert.equal(fetchCalls, 2, "re-request + one successful retry"); + } finally { + setLogCapture(null); + } + assert.deepEqual( + lines.filter((l) => l.msg.includes("DOUBLE-degenerate")), + [], + "no double-degenerate warn when the retry recovered", + ); + assert.ok( + lines.some((l) => l.level === "warn" && l.msg.includes("degenerate-turn auto-retry")), + "the auto-retry warn fired — the capture is live, so the negative above is meaningful", + ); +}); + // #1862: the degenerate-retry boundary on the Responses wire misfired in two ways. // A: a completed reasoning+custom_tool_call turn carries executable output, but the // adapter counted zero tool calls, so the gate treated it as degenerate and re-issued From 4c159034417452a2cdbd149f269eeb32f0c25f39 Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 9 Nov 2026 09:01:26 +0800 Subject: [PATCH 5/6] fix(stream): extend the return-to-task instruction to all parse-failure receipts (#5986 review) Review finding 4 of PR #5986: the 'return to the original task' sentence was appended only to the 'no valid ranges parsed' receipt, though the observed failure mode (model entangled in compression bookkeeping after a rejection, then stopping out) applies to every parse-failure receipt. Extract it into a named constant RETURN_TO_TASK_SUFFIX and append it to the empty-call and argument-corruption receipts as well; the armed-breaker one-liner already carries its own 'Continue your task without compressing.' and is left untouched. The policy-refusal receipts (superseded-ref, out-of-recommendation) are deliberately unchanged: their repair instructions ('re-issue with updated labels', 'stay within the recommendation set') take precedence over 'move on'. --- src/stream.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/stream.ts b/src/stream.ts index ecd66b125e..a4c8c32840 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -280,6 +280,13 @@ function armedRefusalReceipt(n: number, decayMinutes: number): string { return `[Compression refused: this call carried no usable ranges and the compress circuit breaker is still armed (${n} consecutive failures) — while it stays armed, repeat parse-failure lectures are withheld. Format reminder: 'content' must be a non-empty array whose elements are {startId, endId, summary} objects with mNNNNN refs from your visible history. The breaker disarms on one successful fold or ${decayMinutes} minutes without a failing call. Continue your task without compressing.]`; } +// #5986 review fix: the observed failure mode after a compress rejection is the +// model getting entangled in compression bookkeeping and then stopping out — +// every parse-failure receipt ends with this explicit return-to-task instruction +// (the armed-breaker one-liner above already carries its own "Continue your task +// without compressing.", so it is left untouched). +const RETURN_TO_TASK_SUFFIX = " This failure only concerns the compress call. Return to the original task now and continue it (visible output or a tool call)."; + /** #2146: record one total compress failure (any spec) and return "" while * healthy, or the pause paragraph to embed in the receipt once the * consecutive-failure threshold is reached. Only failed-call receipts carry @@ -1103,11 +1110,11 @@ export function applyRanges(parsed: ReturnType, ctx: return compressResult(armedRefusalReceipt(armedDetail.n, armedDetail.decayMinutes), "refused", 0, `parse:${diagnostics.kind}`); } if (isEmptyCall) { - return compressResult(`[Compression FAILED: the call carried no content at all (kind=${diagnostics.kind}) — an empty compress() compresses nothing and can never succeed. Do NOT re-issue an empty call; if you meant to compress, put content as ONE non-empty string in that SAME single call — each block headed by a 'mNNNNN–mNNNNN optional topic' line followed by its summary markdown (a JSON-encoded array of {startId, endId, summary} objects is also accepted INSIDE that same string).${guard}${loopGuard}]`, "refused", 0, `parse:${diagnostics.kind}`); + return compressResult(`[Compression FAILED: the call carried no content at all (kind=${diagnostics.kind}) — an empty compress() compresses nothing and can never succeed. Do NOT re-issue an empty call; if you meant to compress, put content as ONE non-empty string in that SAME single call — each block headed by a 'mNNNNN–mNNNNN optional topic' line followed by its summary markdown (a JSON-encoded array of {startId, endId, summary} objects is also accepted INSIDE that same string).${guard}${loopGuard}${RETURN_TO_TASK_SUFFIX}]`, "refused", 0, `parse:${diagnostics.kind}`); } if (argCorruption) { const truncNote = diagnostics.kind === "truncated" ? " (looks truncated)" : ""; - return compressResult(`[Compression FAILED: the call's arguments (${argLen} chars) were not parseable JSON${truncNote} — the intended content was lost and nothing was compressed. Re-issue ONE compress call whose arguments parse as a single object with a STRING 'content' field: {"content": ""}. Never send 'content' as an actual JSON array or nested object — it is one plain string.${guard}${loopGuard}]`, "refused", 0, `parse:${diagnostics.kind}`); + return compressResult(`[Compression FAILED: the call's arguments (${argLen} chars) were not parseable JSON${truncNote} — the intended content was lost and nothing was compressed. Re-issue ONE compress call whose arguments parse as a single object with a STRING 'content' field: {"content": ""}. Never send 'content' as an actual JSON array or nested object — it is one plain string.${guard}${loopGuard}${RETURN_TO_TASK_SUFFIX}]`, "refused", 0, `parse:${diagnostics.kind}`); } const recovery = loopGuard === "" ? compressionRecovery(ctx) : { hint: "", canRetry: false }; const retry = recovery.canRetry ? " Re-issue the compress call using those eligible refs." : ""; @@ -1119,7 +1126,7 @@ export function applyRanges(parsed: ReturnType, ctx: const notArrayHint = diagnostics.kind === "content-not-array" ? " If your 'content' string encoded a single JSON object, wrap it in square brackets so it encodes an ARRAY of entries (\"[...]\"), or use the line-form headers below." : ""; - return compressResult(`[Compression FAILED: no valid ranges parsed (kind=${diagnostics.kind}, dropped=${diagnostics.invalidItems}).${why}${notArrayHint} compress takes ONE 'content' STRING holding every range: each block starts with its header line 'mNNNNN–mNNNNN optional topic' followed by that block's summary markdown; a JSON-encoded array of {startId, endId, summary} objects is also accepted INSIDE that same string. startId/endId are mNNNNN message refs from the conversation (call acp_status to see current refs).${recovery.hint}${retry}${guard}${loopGuard} This failure only concerns the compress call. Return to the original task now and continue it (visible output or a tool call).]`, "refused", 0, `parse:${diagnostics.kind}`); + return compressResult(`[Compression FAILED: no valid ranges parsed (kind=${diagnostics.kind}, dropped=${diagnostics.invalidItems}).${why}${notArrayHint} compress takes ONE 'content' STRING holding every range: each block starts with its header line 'mNNNNN–mNNNNN optional topic' followed by that block's summary markdown; a JSON-encoded array of {startId, endId, summary} objects is also accepted INSIDE that same string. startId/endId are mNNNNN message refs from the conversation (call acp_status to see current refs).${recovery.hint}${retry}${guard}${loopGuard}${RETURN_TO_TASK_SUFFIX}]`, "refused", 0, `parse:${diagnostics.kind}`); } // #847: detect reversed refs as SUBMITTED, before #1001 normalization // rewrites them (order matters — normalizeRangeOrder mutates in place). From 8c3a3f149b97f400df55c25d1fc372f0f523ce16 Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 9 Nov 2026 09:31:45 +0800 Subject: [PATCH 6/6] test(ci): align issue411 waitFor with the #4161 timing-window idiom (PR #5986 red CI) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit windows-latest/22 shard failed '#411 plugin stream' on a 3s budget for the async abort info-log; this file was the only suite outside the repo-wide 'timeout waiting for …' idiom, so the #4161 classifier saw a concrete failure instead of a recoverable timing-window flake. Label every waitFor call site, throw the idiom, and widen the log-delivery budget to 8s (belt and suspenders per #4161). --- tests/issue411-abort-usage.test.ts | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/tests/issue411-abort-usage.test.ts b/tests/issue411-abort-usage.test.ts index f2b50fd24b..ef95cc79b8 100644 --- a/tests/issue411-abort-usage.test.ts +++ b/tests/issue411-abort-usage.test.ts @@ -133,10 +133,15 @@ function modelBody(stream: boolean): string { return JSON.stringify({ model: "i411-model", max_tokens: 8192, stream, messages: [{ role: "user", content: "hello" }] }); } -async function waitFor(cond: () => boolean, ms = 3000): Promise { +// #4161: the deadline message follows the repo-wide 'timeout waiting for …' +// idiom so a load-starved windows-latest shard classifies as a recoverable +// timing-window failure (one bounded retry) instead of a hard concrete fail — +// this file's old "condition not met within timeout" literal was the only one +// in the suite outside that classification. +async function waitFor(cond: () => boolean, what: string, ms = 3000): Promise { const t0 = Date.now(); while (!cond()) { - if (Date.now() - t0 > ms) throw new Error("condition not met within timeout"); + if (Date.now() - t0 > ms) throw new Error(`timeout waiting for ${what}`); await new Promise((r) => setTimeout(r, 25)); } } @@ -154,12 +159,16 @@ test("#411 plugin stream: client abort keeps sniffed usage, logs info (not error await reader.read(); await reader.read(); ac.abort(); - await waitFor(() => listSessions().some((s) => s.stats.lastInputTokens === 1234)); - await waitFor(() => _liveUpstreamTimersForTest() === 0); + await waitFor(() => listSessions().some((s) => s.stats.lastInputTokens === 1234), "sniffed usage (lastInputTokens=1234) to land"); + await waitFor(() => _liveUpstreamTimersForTest() === 0, "upstream timer to clear"); // #2305 review: the info abort log is a SEPARATE async side effect // that can land after the timer clears — waiting avoids the // synchronous-assert flake seen on a loaded windows-latest runner. - await waitFor(() => captured.some((l) => l.level === "info" && l.msg.includes("client aborted mid-stream"))); + // #4161 follow-up: that async delivery still exceeded 3s on a loaded + // windows-latest/22 shard (PR #5986 run, 2026-11-09) — widen THIS + // budget to 8s; the message idiom above earns the bounded retry as + // belt and suspenders. + await waitFor(() => captured.some((l) => l.level === "info" && l.msg.includes("client aborted mid-stream")), "client aborted mid-stream info log", 8000); assert.ok(captured.some((l) => l.level === "info" && l.msg.includes("client aborted mid-stream")), `expected info abort log, got: ${JSON.stringify(captured)}`); assert.ok(!captured.some((l) => l.level === "error" && l.msg.includes("AbortError")), `no bare AbortError error log, got: ${JSON.stringify(captured.filter((l) => l.level === "error"))}`); } finally { @@ -179,7 +188,7 @@ test("#411 abort storm: repeated client cancels do not accumulate upstream timer await reader.read(); await reader.read(); ac.abort(); - await waitFor(() => _liveUpstreamTimersForTest() === 0); + await waitFor(() => _liveUpstreamTimersForTest() === 0, "upstream timers to clear after cancel round"); } assert.equal(_liveUpstreamTimersForTest(), 0); } finally { @@ -204,8 +213,8 @@ test("#411 upstream cut with client alive: usage still lands, failure is a real } catch { // upstream socket destroyed mid-stream — the client sees a cut } - await waitFor(() => listSessions().some((s) => s.stats.lastInputTokens === 1234)); - await waitFor(() => _liveUpstreamTimersForTest() === 0); + await waitFor(() => listSessions().some((s) => s.stats.lastInputTokens === 1234), "sniffed usage (lastInputTokens=1234) to land"); + await waitFor(() => _liveUpstreamTimersForTest() === 0, "upstream timer to clear"); assert.ok(!captured.some((l) => l.msg.includes("client aborted mid-stream")), "client-alive cut must not be classified as a client abort"); } finally { setLogCapture(null); @@ -229,7 +238,7 @@ test("#411 plugin non-stream: client abort mid-body does not crash and clears th // aborted mid-body — expected } }); - await waitFor(() => _liveUpstreamTimersForTest() === 0); + await waitFor(() => _liveUpstreamTimersForTest() === 0, "upstream timer to clear"); } finally { await rig.closeAll(); } @@ -246,7 +255,7 @@ test("#411 anonymous passthrough: client abort clears the timer and logs info", const reader = res.body!.getReader(); await reader.read(); ac.abort(); - await waitFor(() => _liveUpstreamTimersForTest() === 0); + await waitFor(() => _liveUpstreamTimersForTest() === 0, "upstream timer to clear"); assert.ok(!captured.some((l) => l.level === "error" && l.msg.includes("AbortError")), `no bare AbortError error log, got: ${JSON.stringify(captured.filter((l) => l.level === "error"))}`); } finally { setLogCapture(null);