From 6c4aeeafcbb2d1705f4e0b073992ef11591d6e4f Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 19 Nov 2026 01:47:15 +0800 Subject: [PATCH 1/2] fix: scope-gate (requireRecommendation) refusals no longer arm the compress breaker (#7197) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ⚠️ MODEL-FACING TEXT CHANGE: scope-gate refusal receipts no longer carry the 'COMPRESS CIRCUIT BREAKER: ARMED — STOP calling compress now: do not try other ranges, do not re-issue any previous range, and do not poll acp_status.' paragraph. The core refusal wording is unchanged. The model now sees the refusal + advice ('Call acp_status ... stay within them') and follows it with an in-recommendation retry — the recovery the removed paragraph forbade. No number/ref/position the model propagates moves. The out-of-recommendation scope gate is a range-correctness gate ('your span was wrong'), not a fold-feasibility signal. Its recovery (acp_status -> an in-recommendation retry) is always available and succeeds if followed, so arming the session-level breaker (which orders 'do not try other ranges ... do not poll acp_status') forbade the only recovery the code still allowed: an obedient model lost compression for the whole session while a disobedient one recovered on the next call. Remove noteCompressLoopFailure from the scope-gate branch; keep recordCompressFailure so the #6728 repeat-collapse still fires on identical re-submission. The nudge gate keeps the breaker charge (its recovery is 'wait for a nudge' - no self-recovery). Update tests/issue6728-policy-gate-ledger.test.ts: the requireRecommendation test now asserts the breaker stays disarmed and the repeat-collapse still fires. (cherry picked from commit 97c4a1e37d8a5bd0cb759a7c1ec46455a7eff366) --- src/stream.ts | 20 +++++++++++++------- tests/issue6728-policy-gate-ledger.test.ts | 16 ++++++++-------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/src/stream.ts b/src/stream.ts index bd38ae7d71..a427178ea5 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -1310,20 +1310,26 @@ export function applyRanges(parsed: ReturnType, ctx: if (offending.length > 0) { const listed = offending.slice(0, 3).join(", ") + (offending.length > 3 ? ` (+${offending.length - 3} more)` : ""); ctx.log(`[acp-proxy: refused out-of-recommendation compress — span(s) ${listed} outside the current recommendation set (compress.requireRecommendation)]`); - // #6728: charge the ledger (see the nudge gate above). The - // spec-repeat guard text recordCompressFailure returns is dropped - // on purpose (one counter, stated once — the collapse below says - // it); only the ledger charge matters here. + // #6728: charge the SPEC-REPEAT ledger (recordCompressFailure) so + // the repeat-collapse below fires on identical re-submission. + // #7197: do NOT charge the session-level breaker + // (noteCompressLoopFailure) — the scope gate is a range-correctness + // gate ("your span was wrong"), not a fold-feasibility signal; its + // recovery (acp_status → an in-recommendation retry) is always + // available and succeeds if followed, so arming the breaker (which + // orders "do not try other ranges … do not poll acp_status") would + // forbid the only recovery the code still allows. The nudge gate + // above keeps the breaker charge (its recovery is "wait for a + // nudge" — the model cannot self-recover). const specKey = normalizedSpecKey(ranges); recordCompressFailure(ctx.session, specKey); - const loopGuard = trackLoop ? noteCompressLoopFailure(ctx, specKey) : ""; const occurrences = compressFailOccurrencesOf(ctx.session, specKey); if (trackLoop && occurrences >= 2) { ctx.log( `[acp-proxy: out-of-recommendation receipt collapsed to one-liner (attempt ${occurrences})]`, ); return compressResult( - `[Compression REFUSED again — span(s) ${listed} have now been refused ${occurrences} time(s) the same way (compress.requireRecommendation); nothing was compressed. The full refusal and the current compressible ranges are in the FIRST refused receipt above — do not re-send this call verbatim.${loopGuard}]`, + `[Compression REFUSED again — span(s) ${listed} have now been refused ${occurrences} time(s) the same way (compress.requireRecommendation); nothing was compressed. The full refusal and the current compressible ranges are in the FIRST refused receipt above — do not re-send this call verbatim.`, "refused", 0, "out-of-recommendation", @@ -1339,7 +1345,7 @@ export function applyRanges(parsed: ReturnType, ctx: const advice = recommendedEmpty ? " No compressible ranges remain — the context is already at its minimum; continue the task without compressing. Compression happens again only when there is genuinely new content to fold." : " Call acp_status for the current compressible ranges and stay within them: subdividing a listed span into smaller chunks is fine, and re-folding an already-compressed block to update its summary is fine."; - return compressResult(`[Compression REFUSED: out-of-bounds compression is disabled on this route (compress.requireRecommendation) — span(s) ${listed} contain content bili does not currently recommend folding.${advice}${loopGuard}]`, "refused", 0, "out-of-recommendation"); + return compressResult(`[Compression REFUSED: out-of-bounds compression is disabled on this route (compress.requireRecommendation) — span(s) ${listed} contain content bili does not currently recommend folding.${advice}]`, "refused", 0, "out-of-recommendation"); } } if (ctx.messages.length > 0) { diff --git a/tests/issue6728-policy-gate-ledger.test.ts b/tests/issue6728-policy-gate-ledger.test.ts index 6a1b48be0c..a2306fe7fa 100644 --- a/tests/issue6728-policy-gate-ledger.test.ts +++ b/tests/issue6728-policy-gate-ledger.test.ts @@ -198,26 +198,26 @@ test("#6728: requireNudge refusals charge the ledger — breaker arms by the 3rd ); }); -test("#6728: requireRecommendation refusals charge the ledger — breaker arms by the 3rd identical refusal", () => { +test("#7197: requireRecommendation refusals do NOT arm the breaker (range-correctness gate, not fold-feasibility)", () => { const ctx = scopeGateCtx(); const first = runApply(ctx, SCOPE_CALL); assert.ok( first.startsWith("[Compression REFUSED"), `expected refusal, got: ${first.slice(0, 120)}`, ); + runApply(ctx, SCOPE_CALL); + const third = runApply(ctx, SCOPE_CALL); assert.ok( !compressBreakerArmed(ctx.session), - "breaker must not arm on the first refusal", + "#7197: scope-gate refusals must NOT arm the breaker — the recovery (acp_status + in-recommendation retry) is always available, so the stop wording would forbid the only recovery the code allows", ); - runApply(ctx, SCOPE_CALL); - const third = runApply(ctx, SCOPE_CALL); assert.ok( - compressBreakerArmed(ctx.session), - "breaker must be armed after 3 consecutive gate refusals", + !third.includes("COMPRESS CIRCUIT BREAKER"), + "scope-gate refusal must not carry the breaker paragraph:\n" + third, ); assert.ok( - third.includes("COMPRESS CIRCUIT BREAKER"), - "3rd receipt must carry the breaker paragraph:\n" + third, + third.includes("again"), + "the spec-repeat collapse must still fire on the 3rd identical call (#6728 protection preserved):\n" + third, ); }); From da7bda3197f8fb23a9bd3c9138c56dd99e515d59 Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 19 Nov 2026 23:31:51 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E2=9A=A0=EF=B8=8F=20MODEL-FACING=20TEXT=20?= =?UTF-8?q?CHANGE:=20breaker=20disarm=20wording=20now=20says=20"one=20subs?= =?UTF-8?q?tantial=20fold/success=20(a=20trivial=20one=20that=20saves=20al?= =?UTF-8?q?most=20nothing=20does=20not=20count)"=20instead=20of=20"one=20s?= =?UTF-8?q?uccessful=20fold/success"=20=E2=80=94=20the=20armed=20receipt,?= =?UTF-8?q?=20the=20substrate-destruction=20paragraph,=20and=20the=20acp?= =?UTF-8?q?=5Fstatus=20armed=20note=20all=20moved=20from=20"any=20success?= =?UTF-8?q?=20disarms"=20to=20"a=20success=20that=20saves=20=E2=89=A5500?= =?UTF-8?q?=20tokens=20disarms".?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix: only a substantial fold discharges the compress-loop breaker (#7300) The breaker streak (compressFailStreak) reset on ANY successful compress, so the incident's "fail×N → trivial-success×1 → fail×N" loop (bili 0.1.216: 398 compress calls, 289 "too small" fails, 92 trivial successes netting only 86–290 tokens) never armed the 3-strike breaker and the model burned tokens probing forever. r.tokensCompressed is the TOTAL folded mass (the kernel sums the folded message tokens and never subtracts the new summary), so a barely-over-minimum range reads ~1250 even when the NET saving is 86–290 tokens. Discharge the streak only when the NET saving (folded mass minus the new summary mass of the block(s) this fold created/updated) is ≥ COMPRESS_LOOP_DISCHARGE_MIN_TOKENS (500): a trivial fold is the model still probing, not "compression is working". Tests: tests/issue7300-compress-loop-trivial.test.ts pins both directions (trivial success does NOT discharge; substantial success DOES). Updated the three existing assertions that quoted the old disarm wording. --- src/acp-status.ts | 4 +- src/stream.ts | 51 +++++-- tests/issue2432-breaker-awareness.test.ts | 8 +- ...ue4812-armed-breaker-short-receipt.test.ts | 2 +- tests/issue7300-compress-loop-trivial.test.ts | 140 ++++++++++++++++++ 5 files changed, 188 insertions(+), 17 deletions(-) create mode 100644 tests/issue7300-compress-loop-trivial.test.ts diff --git a/src/acp-status.ts b/src/acp-status.ts index dd474184c7..7e68c0bc77 100644 --- a/src/acp-status.ts +++ b/src/acp-status.ts @@ -373,9 +373,9 @@ export function handleAcpStatus(args: Record, ctx: AcpStatusCtx } if (breaker) { extra.push(""); - extra.push(`COMPRESS CIRCUIT BREAKER: ARMED — consecutiveFailures: ${breaker.n} / ${breaker.threshold}. Disarms on one successful compress or ${breaker.decayMinutes} min without further failures.`); + extra.push(`COMPRESS CIRCUIT BREAKER: ARMED — consecutiveFailures: ${breaker.n} / ${breaker.threshold}. Disarms on one substantial compress (a trivial one that saves almost nothing does not count) or ${breaker.decayMinutes} min without further failures.`); if (substrateDestroyed) { - extra.push("Last failures were attributed to substrate-destruction (an out-of-band history rewrite). The Compressible-ranges list above was re-derived from the CURRENT resent view: per the receipt, compress ONLY a range listed there — one success clears this breaker. If no ranges are listed, continue the task without compressing."); + extra.push("Last failures were attributed to substrate-destruction (an out-of-band history rewrite). The Compressible-ranges list above was re-derived from the CURRENT resent view: per the receipt, compress ONLY a range listed there — one substantial success clears this breaker. If no ranges are listed, continue the task without compressing."); } else { extra.push("The Compressible-ranges list above was re-derived from the current view — the table is live; it is the earlier attempts that failed, not these ranges. Per the failure receipt: do not attempt to compress now; continue the task."); } diff --git a/src/stream.ts b/src/stream.ts index a427178ea5..0de0f77bf7 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -231,6 +231,14 @@ function compressFailOccurrencesOf(session: Session, key: string): number { const COMPRESS_LOOP_KEY = "compressFailStreak"; const COMPRESS_LOOP_THRESHOLD = 3; const COMPRESS_LOOP_DECAY_MS = 10 * 60 * 1000; +// #7300: a success only discharges the breaker when it is a SUBSTANTIAL fold. +// The incident loop was "fail×N → trivial-success×1 → fail×N": each trivial +// fold (86–290 tokens saved — a barely-over-minimum range) reset the streak, +// so the 3-strike breaker never armed and the model burned tokens probing +// forever. A fold below this threshold is still the model probing, not +// "compression is working" — it must not reset the strikes. Hardcoded by +// design (config-surface discipline, same as COMPRESS_LOOP_THRESHOLD above). +const COMPRESS_LOOP_DISCHARGE_MIN_TOKENS = 500; type CompressLoopStreak = { n: number; lastAt: number; cause?: string }; @@ -263,12 +271,13 @@ function loopNoisePauseParagraph(n: number): string { // #2432: substrate-destruction is NOT loop noise. When the fold substrate was // destroyed by an out-of-band history rewrite, blind stopping leaves the model // in a room with no exit — the ONLY recovery is one acp_status plus a -// live-range re-anchor, and one success clears the breaker. The blanket "do +// live-range re-anchor, and one substantial success clears the breaker +// (#7300: a trivial fold does not discharge the streak). The blanket "do // not poll acp_status" order above is right for noise and wrong for this // cause, so the armed receipt branches on compressFailureCause (#2360 §2.4 // already computes it at the same sites). function substrateDestructionPauseParagraph(n: number): string { - return ` [COMPRESS CIRCUIT BREAKER: ${n} consecutive compress failures in this session — every attempt has failed because the fold substrate was destroyed by an out-of-band history rewrite. STOP calling compress now: do not try other ranges and do not re-issue any previous ones. There is exactly ONE recovery step: run acp_status once, then compress ONLY a range it currently reports as compressible — one success clears this breaker. If acp_status reports no compressible ranges, continue your task without compressing.]`; + return ` [COMPRESS CIRCUIT BREAKER: ${n} consecutive compress failures in this session — every attempt has failed because the fold substrate was destroyed by an out-of-band history rewrite. STOP calling compress now: do not try other ranges and do not re-issue any previous ones. There is exactly ONE recovery step: run acp_status once, then compress ONLY a range it currently reports as compressible — one substantial success clears this breaker (a trivial fold that saves almost nothing does not count). If acp_status reports no compressible ranges, continue your task without compressing.]`; } // #4812: short refusal for parse-failure receipts once the breaker has climbed @@ -287,7 +296,7 @@ function substrateDestructionPauseParagraph(n: number): string { // recovery step — acp_status once, then ONE live range — still goes through // and can clear the breaker. 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' is ONE string holding every range — each block starts with its 'mNNNNN–mNNNNN optional topic' header line followed by its summary markdown (a JSON-encoded array of {startId, endId, summary} objects as that string also works), using refs from your visible history. The breaker disarms on one successful fold or ${decayMinutes} minutes without a failing call. Continue your task without compressing.]`; + 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' is ONE string holding every range — each block starts with its 'mNNNNN–mNNNNN optional topic' header line followed by its summary markdown (a JSON-encoded array of {startId, endId, summary} objects as that string also works), using refs from your visible history. The breaker disarms on one substantial fold (a trivial one that saves almost nothing does not count) 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 @@ -300,10 +309,13 @@ const RETURN_TO_TASK_SUFFIX = " This failure only concerns the compress call. Re /** #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 - * it: successful calls always go through, and one success clears the streak - * (clearCompressLoopStreak). The pause paragraph branches on the failure - * cause (#2432): substrate-destruction gets the single-recovery-step - * wording, everything else keeps the verbatim loop-noise paragraph. */ + * it: successful calls always go through, and one SUBSTANTIAL success clears + * the streak (clearCompressLoopStreak — #7300: a trivial fold below + * COMPRESS_LOOP_DISCHARGE_MIN_TOKENS does not, so the "fail×N → trivial + * success×1 → fail×N" loop can still arm the breaker). The pause paragraph + * branches on the failure cause (#2432): substrate-destruction gets the + * single-recovery-step wording, everything else keeps the verbatim loop-noise + * paragraph. */ function noteCompressLoopFailure(ctx: RewriteCtx, specLabel: string, errs?: string, forcedCause?: string): string { const now = Date.now(); let streak = readCompressLoopStreak(ctx.session); @@ -322,7 +334,7 @@ function noteCompressLoopFailure(ctx: RewriteCtx, specLabel: string, errs?: stri if (n < COMPRESS_LOOP_THRESHOLD) return ""; const label = specLabel || "unparseable call"; if (n === COMPRESS_LOOP_THRESHOLD) { - ctx.log(`[warn: compress-loop] circuit breaker armed after ${n} consecutive compress failures (last spec: ${label}) — receipts now demand a full stop; disarms on success or ${COMPRESS_LOOP_DECAY_MS / 60000} min quiet`); + ctx.log(`[warn: compress-loop] circuit breaker armed after ${n} consecutive compress failures (last spec: ${label}) — receipts now demand a full stop; disarms on a substantial fold (≥${COMPRESS_LOOP_DISCHARGE_MIN_TOKENS} tok) or ${COMPRESS_LOOP_DECAY_MS / 60000} min quiet`); } else { ctx.log(`[warn: compress-loop] failure ${n} in armed streak (last spec: ${label})`); } @@ -332,7 +344,15 @@ function noteCompressLoopFailure(ctx: RewriteCtx, specLabel: string, errs?: stri return loopNoisePauseParagraph(n); } -function clearCompressLoopStreak(session: Session): void { +/** #7300: discharge the breaker streak on a SUBSTANTIAL fold only. A trivial + * success (tokensCompressed < COMPRESS_LOOP_DISCHARGE_MIN_TOKENS) is the + * model still probing (a barely-over-minimum range), not "compression is + * working" — it must not reset the strikes, or the "fail×N → trivial + * success×1 → fail×N" loop never arms the breaker. A substantial fold means + * the model found a range that genuinely shrank the context, so the loop is + * over and the strikes reset. */ +function clearCompressLoopStreak(session: Session, tokensCompressed: number): void { + if (tokensCompressed < COMPRESS_LOOP_DISCHARGE_MIN_TOKENS) return; if (readCompressLoopStreak(session)) writeCompressLoopStreak(session, undefined); } @@ -1642,7 +1662,18 @@ export function applyRanges(parsed: ReturnType, ctx: // its time-attribute mark raise) on a call that folded nothing. ctx.session.pendingLedgerAlign = true; clearCompressFailures(ctx.session); - clearCompressLoopStreak(ctx.session); + // #7300: only a SUBSTANTIAL fold discharges the breaker. r.tokensCompressed + // is the TOTAL folded mass (kernel sums the folded message tokens and + // never subtracts the new summary), so a barely-over-minimum range reads + // ~1250 even when the NET saving is 86–290 tokens — the incident's + // trivial folds. Use the NET saving (folded mass minus the new summary + // mass of the block(s) this fold created/updated): a trivial fold is the + // model still probing and must not reset the strikes. + const newSummaryTokens = res.state.blocks + .filter((b) => !beforeIds.has(b.blockId) || beforeSummaries.get(b.blockId) !== b.summary) + .reduce((n, b) => n + defaultCountTokens(b.summary), 0); + const netSaved = Math.max(0, r.tokensCompressed - newSummaryTokens); + clearCompressLoopStreak(ctx.session, netSaved); // #189 observability: record the rewrite magnitude + fold point so a // downstream transient rejection (GLM 3007) can be correlated with it. diff --git a/tests/issue2432-breaker-awareness.test.ts b/tests/issue2432-breaker-awareness.test.ts index 6d1205bbdc..3cc42cdb0c 100644 --- a/tests/issue2432-breaker-awareness.test.ts +++ b/tests/issue2432-breaker-awareness.test.ts @@ -130,7 +130,7 @@ test("#2432/#2451: acp_status shows the armed counter and keeps reporting the li session.metadata["compressFailStreak"] = { n: 4, lastAt: Date.now() }; const armed = handleAcpStatus({}, ctx); assert.match(armed.text, /COMPRESS CIRCUIT BREAKER: ARMED — consecutiveFailures: 4 \/ 3\./, "armed section with the visible counter"); - assert.match(armed.text, /Disarms on one successful compress or 10 min/, "disarm condition stated"); + assert.match(armed.text, /Disarms on one substantial compress \(a trivial one that saves almost nothing does not count\) or 10 min/, "disarm condition stated (#7300: a trivial fold does not count)"); assert.ok(armed.text.includes("Compressible ranges ("), "armed surface still reports the live table — it is re-derived from the current view, and hiding it contradicts the recovery receipts that point here"); assert.match(armed.text, /do not attempt to compress now; continue the task/, "unknown-cause armed note mirrors the receipt's STOP order instead of inventing a second command"); assert.doesNotMatch(armed.text, /SUPPRESSED/, "no false claim that the list is hidden"); @@ -185,8 +185,8 @@ test("#2432/#2451: substrate/stale-ref verdicts annotate honestly BEFORE arming; test("#2451 review: armed + substrate-destruction reports live ranges — the receipt's recovery path is reachable", () => { // The armed receipt (#2432) orders: "run acp_status once, then compress - // ONLY a range it currently reports as compressible — one success clears - // this breaker." Before this fix acp_status suppressed the list whenever + // ONLY a range it currently reports as compressible — one substantial + // success clears this breaker." Before this fix acp_status suppressed the list whenever // armed, so the promised recovery was unreachable and the output carried // two contradictory orders ("do not attempt to compress now" / // "start a fresh conversation") — the #2360 two-orders shape. @@ -200,7 +200,7 @@ test("#2451 review: armed + substrate-destruction reports live ranges — the re assert.ok(armed.includes("Compressible ranges ("), "armed substrate-destruction still reports live ranges (the receipt's single recovery step)"); assert.match(armed, /COMPRESS CIRCUIT BREAKER: ARMED — consecutiveFailures: 4 \/ 3\./, "armed section with the visible counter"); assert.match(armed, /re-derived from the CURRENT resent view/, "tailored recovery line replaces the blanket suppression order"); - assert.match(armed, /one success clears this breaker/, "disarm-by-success is restated on the status surface"); + assert.match(armed, /one substantial success clears this breaker/, "disarm-by-success is restated on the status surface (#7300: a trivial fold does not count)"); assert.doesNotMatch(armed, /SUPPRESSED while the breaker is armed/, "no blanket suppression on the receipt's own recovery path"); assert.doesNotMatch(armed, /Do not attempt to compress now/, "no contradictory compress ban"); assert.doesNotMatch(armed, /start a fresh conversation/, "no second, contradictory recovery order (#2360 shape)"); diff --git a/tests/issue4812-armed-breaker-short-receipt.test.ts b/tests/issue4812-armed-breaker-short-receipt.test.ts index 3f826e011d..785945cca1 100644 --- a/tests/issue4812-armed-breaker-short-receipt.test.ts +++ b/tests/issue4812-armed-breaker-short-receipt.test.ts @@ -93,7 +93,7 @@ test("#4812: parse-failure receipts collapse per-repeat once the breaker climbs assert.doesNotMatch(f4, /acp_status/, "no contradictory order beside the loop-noise stop (#2360)"); assert.match(f4, /\{startId, endId, summary\}/, "keeps a one-line format reminder"); assert.doesNotMatch(f4, /must be a non-empty array/, "reminder no longer teaches the retired raw-array shape"); - assert.match(f4, /disarms on one successful fold or 10 minutes/, "states the disarm conditions"); + assert.match(f4, /disarms on one substantial fold \(a trivial one that saves almost nothing does not count\) or 10 minutes/, "states the disarm conditions (#7300: a trivial fold does not count)"); assert.ok(f4.length < 700, `short refusal stays small (got ${f4.length} chars)`); const f5 = applyRanges(parseCompressInput(malformedArgs()), ctx).text; diff --git a/tests/issue7300-compress-loop-trivial.test.ts b/tests/issue7300-compress-loop-trivial.test.ts new file mode 100644 index 0000000000..cd06a49d2c --- /dev/null +++ b/tests/issue7300-compress-loop-trivial.test.ts @@ -0,0 +1,140 @@ +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { test } from "node:test"; +import type { Config, CoreMessage } from "acp-kernel"; +import { createCore, createInitialState, assignRefs, emptyRefMap, defaultConfig } from "acp-kernel"; +import type { Session } from "../src/session.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { applyRanges, type RewriteCtx } from "../src/stream.ts"; +import { parseCompressInput } from "../src/compress-tool.ts"; + +_setStoreForTest(new SessionStore({ enabled: false })); + +// #7300: the breaker streak used to reset on ANY successful compress, so the +// incident's "fail×N → trivial-success×1 → fail×N" loop (398 calls, 289 +// "too small" fails, 92 trivial successes netting only 86–290 tokens) never +// armed the 3-strike breaker. A trivial success — one whose NET saving (folded +// mass minus the new summary mass) is below COMPRESS_LOOP_DISCHARGE_MIN_TOKENS +// (500) — is the model still probing a barely-over-minimum range, not +// "compression is working", and must not discharge the streak. + +const SUMMARY = "summary ".repeat(20); // 160 chars → ~40 tokens (substantial folds) +const TRIVIAL_SUMMARY = "s".repeat(3500); // 3500 chars → ~875 tokens + +function textMsg(id: string, role: "user" | "assistant", text: string): CoreMessage { + return { id, role, contentType: "text", text }; +} + +function makeSession(): Session { + return { + id: `issue7300-${randomUUID()}`, + meta: {}, + stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 15000, compressCreditTokens: 0, contextTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 }, + metadata: {}, + state: createInitialState(), + createdAt: Date.now(), + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + persisted: false, + pendingRetrievals: [], + }; +} + +function makeCtx(messages: CoreMessage[], config?: Config, logs?: string[]): RewriteCtx & { session: Session; config: Config } { + const session = makeSession(); + const res = assignRefs(messages, { existing: emptyRefMap(), nextIndex: 0 }); + session.state.messageRefs = res.map; + return { core: createCore(), config: config ?? defaultConfig(200000), messages, session, log: logs ? (m) => logs.push(m) : () => {} }; +} + +function compressArgs(startId: string, endId: string, summary: string = SUMMARY) { + return JSON.parse(JSON.stringify({ content: [{ startId, endId, summary }] })); +} + +// Two sub-gate messages (800 chars each → "too small" failures), one +// barely-over-minimum message (5000 chars → a trivial fold when its summary is +// long enough that the net saving stays under 500 tokens), and four 5000-char +// padding messages after it. The padding must accumulate ≥ preserveRecentTokens +// (5000 tok) so the tail-token protection rule stops BEFORE reaching m00003 — +// otherwise the whole small session sits inside the protected zone and the +// trivial fold is a no-op. +function trivialFixture(): CoreMessage[] { + return [ + textMsg("raw_1", "assistant", "a".repeat(800)), + textMsg("raw_2", "assistant", "b".repeat(800)), + textMsg("raw_3", "assistant", "x".repeat(5000)), + textMsg("raw_4", "assistant", "c".repeat(5000)), + textMsg("raw_5", "assistant", "d".repeat(5000)), + textMsg("raw_6", "assistant", "e".repeat(5000)), + textMsg("raw_7", "assistant", "f".repeat(5000)), + ]; +} + +// The same two sub-gate messages plus six 5000-char messages (30000 chars → a +// guaranteed substantial fold when summarized with the short 160-char summary). +function substantialFixture(): CoreMessage[] { + const msgs: CoreMessage[] = [ + textMsg("raw_1", "assistant", "a".repeat(800)), + textMsg("raw_2", "assistant", "b".repeat(800)), + ]; + for (let i = 3; i <= 8; i++) msgs.push(textMsg(`raw_${i}`, "assistant", "x".repeat(5000))); + return msgs; +} + +test("#7300: a trivial success (net saving < 500 tok) does NOT discharge the breaker", () => { + const logs: string[] = []; + const ctx = makeCtx(trivialFixture(), undefined, logs); + + const f1 = applyRanges(parseCompressInput(compressArgs("m00001", "m00001")), ctx).text; + assert.ok(f1.startsWith("[Compression FAILED:"), `failure 1 at the too-small gate (got: ${f1.slice(0, 120)})`); + assert.ok(!f1.includes("CIRCUIT BREAKER"), "failure 1 carries no breaker"); + + const f2 = applyRanges(parseCompressInput(compressArgs("m00002", "m00002")), ctx).text; + assert.ok(f2.startsWith("[Compression FAILED:"), "failure 2"); + assert.ok(!f2.includes("CIRCUIT BREAKER"), "failure 2 still carries no breaker"); + + // m00003 is 5000 chars (just over the 5000-char minimum) summarized to + // 3500 chars: folded mass ≈ 1250 tok, new summary ≈ 875 tok, net saving + // ≈ 375 tok < 500 → a TRIVIAL success. It must NOT reset the streak. + const trivial = applyRanges(parseCompressInput(compressArgs("m00003", "m00003", TRIVIAL_SUMMARY)), ctx).text; + assert.ok(trivial.startsWith("[Compressed "), `trivial fold succeeds (got: ${trivial.slice(0, 120)})`); + const afterTrivial = ctx.session.metadata["compressFailStreak"] as { n?: number } | undefined; + assert.equal(afterTrivial?.n, 2, "trivial success must NOT reset the streak (still n=2)"); + + // One more failure → n=3 → the breaker must arm, proving the trivial + // success did not discharge it (the pre-fix behavior reset here, so the + // loop never armed). + const f3 = applyRanges(parseCompressInput(compressArgs("m00001", "m00002")), ctx).text; + assert.ok(f3.startsWith("[Compression FAILED:"), "failure 3"); + assert.match(f3, /COMPRESS CIRCUIT BREAKER: 3 consecutive/, "breaker must arm — the trivial success must not have reset the strikes"); + assert.ok(logs.some((l) => l.includes("[warn: compress-loop] circuit breaker armed after 3 consecutive")), "arm event logged for operator diagnosis"); +}); + +test("#7300: a substantial success (net saving ≥ 500 tok) DOES discharge the breaker (negative direction)", () => { + const ctx = makeCtx(substantialFixture()); + + const f1 = applyRanges(parseCompressInput(compressArgs("m00001", "m00001")), ctx).text; + assert.ok(f1.startsWith("[Compression FAILED:"), "failure 1"); + const f2 = applyRanges(parseCompressInput(compressArgs("m00002", "m00002")), ctx).text; + assert.ok(f2.startsWith("[Compression FAILED:"), "failure 2"); + + // m00003–m00008 is 30000 chars summarized to 160 chars: folded mass + // ≈ 7500 tok, new summary ≈ 40 tok, net saving ≈ 7460 tok ≥ 500 → a + // SUBSTANTIAL success. It MUST reset the streak. + const substantial = applyRanges(parseCompressInput(compressArgs("m00003", "m00008")), ctx).text; + assert.ok(substantial.startsWith("[Compressed "), `substantial fold succeeds (got: ${substantial.slice(0, 120)})`); + assert.equal(ctx.session.metadata["compressFailStreak"], undefined, "substantial success clears the streak"); + + // A later failure restarts the streak at 1 — no breaker. + const after = applyRanges(parseCompressInput(compressArgs("m00001", "m00002")), ctx).text; + assert.ok(after.startsWith("[Compression FAILED:"), "small range still fails after the successful compress"); + assert.ok(!after.includes("CIRCUIT BREAKER"), "post-substantial-success failure restarts the streak at 1"); +}); + +test("#7300: a trivial success alone (no prior failures) is a no-op on the streak", () => { + const ctx = makeCtx(trivialFixture()); + const trivial = applyRanges(parseCompressInput(compressArgs("m00003", "m00003", TRIVIAL_SUMMARY)), ctx).text; + assert.ok(trivial.startsWith("[Compressed "), "trivial fold succeeds"); + assert.equal(ctx.session.metadata["compressFailStreak"], undefined, "no streak exists to clear — trivial success is a no-op"); +});