diff --git a/CONFIGURATION.md b/CONFIGURATION.md index e6a77f5502..7ecd053d07 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -246,7 +246,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compress.rules` | boolean | false | — | Persistent model reminders delivered through an injected acp_rule tool, hard-protected from folds; pi/omp expose an /acp-rule command. | | `compress.injectTool` | boolean | true | ACP_COMPRESS_TOOL | Register the acp_compress tool for clients (global level only). | | `compress.injectNudge` | boolean | true | ACP_COMPRESS_NUDGE | Send growth nudges as the window fills (global level only). | -| `compress.reasoning` | { drop?, threshold? } | drop true · threshold 2048 | — | Drop finished-round reasoning runs longer than 2048 chars (drop: true by default); strict-reasoning upstreams need drop:false. | +| `compress.reasoning` | { drop?, threshold?, flush? } | drop true · threshold 2048 · flush "fold" | — | Drop finished-round reasoning runs longer than 2048 chars (drop: true by default); strict-reasoning upstreams need drop:false. "flush" decides WHEN dropped reasoning leaves the wire (see compress.reasoning.flush). | | `compress.ccr` | object | enabled in proxy mode since v2 | — | Content cache & retrieve: large outputs stored losslessly beside the session, replaced by head excerpt + pointer fetched back via acp_retrieve; no cap or eviction. | | `compress.search` | object | off | — | Search-behavior settings for search_context; currently holds planAware re-ranking. | | `compress.search.planAware` | boolean | false | — | When on, search_context candidates are re-ranked against current plan state; off keeps byte-identical lexical results. | @@ -279,6 +279,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compress.priceProfile.q` | number | unset (registry) | — | Output price ratio relative to the input price. | | `compress.reasoning.drop` | boolean | true | — | Drop finished-round reasoning runs longer than the threshold. | | `compress.reasoning.threshold` | number | 2048 | — | Character threshold above which finished reasoning runs are dropped. | +| `compress.reasoning.flush` | "fold" \| "close" | "fold" | — | When closed-round reasoning leaves the forwarded view (#3198). "fold" (default): the drop set is frozen between folds and flushes in the same request as a fold — the wire stays byte-stable across round closes, so the reclaim rides the fold's own re-billed prefix-cache region instead of opening a fresh seam per round. A 64 KB pending-mass cap flushes early for sessions that never fold (one attributed re-bill per crossing, shown in the cache ledger under the compress-reasoning bucket). "close" (legacy timing, opt-in): flush on the first request after each round closes — reclaims the floor one fold earlier, but every round close rewrites mid-history bytes and pays a NEW cache miss; enabling it means accepting those seams, reasonable only where misses are cheap (e.g. local endpoints). | | `compress.minCompressRange` | number | same as minCompressRangeChars | — | Deprecated alias of minCompressRangeChars (accepted, mapped onto it). _(deprecated)_ | **Provider route fields** diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 46e0b056e1..40348d0c23 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -246,7 +246,7 @@ | `compress.rules` | boolean | false | — | 通过注入的 acp_rule 工具提供持久模型提醒——对折叠硬保护;pi/omp 提供 /acp-rule 命令。 | | `compress.injectTool` | boolean | true | ACP_COMPRESS_TOOL | 向客户端注册 acp_compress 工具(仅全局层级生效)。 | | `compress.injectNudge` | boolean | true | ACP_COMPRESS_NUDGE | 窗口填满过程中发送增长提醒(仅全局层级生效)。 | -| `compress.reasoning` | { drop?, threshold? } | drop true · threshold 2048 | — | 丢弃超过 2048 字符的已结束轮次推理块(drop 默认 true);严格推理上游需设 drop:false。 | +| `compress.reasoning` | { drop?, threshold?, flush? } | drop true · threshold 2048 · flush "fold" | — | 丢弃超过 2048 字符的已结束轮次推理块(drop 默认 true);严格推理上游需设 drop:false。"flush" 决定被丢弃的推理何时离开转发视图(见 compress.reasoning.flush)。 | | `compress.ccr` | object | enabled in proxy mode since v2 | — | 内容缓存与回取:大输出无损存到会话旁、替换为首段摘录+指针,模型用 acp_retrieve 取回原文;无上限、永不清除。 | | `compress.search` | object | off | — | search_context 的检索行为设置;当前含 planAware 重排。 | | `compress.search.planAware` | boolean | false | — | 开启后 search_context 候选按当前计划状态重排;关闭时结果逐字节不变。 | @@ -279,6 +279,7 @@ | `compress.priceProfile.q` | number | unset (registry) | — | 输出价相对输入价的比率。 | | `compress.reasoning.drop` | boolean | true | — | 丢弃超过阈值的已结束轮次推理块。 | | `compress.reasoning.threshold` | number | 2048 | — | 已结束推理块被丢弃的字符阈值。 | +| `compress.reasoning.flush` | "fold" \| "close" | "fold" | — | 已结束轮次的推理何时从转发视图移除(#3198)。"fold"(默认):丢弃集合在两次折叠之间冻结,随折叠所在的那次请求一起冲刷 —— 回合结束时线上字节保持不变,回收搭折叠自身已重计费的前缀缓存区域,不再每回合开一条新接缝。对从不折叠的会话有 64 KB 积压上限(超限即冲刷,每次越界一笔已归因重计费,记在缓存账本的压缩思考桶)。"close"(旧时序,主动开启):每回合结束后的第一条请求即冲刷 —— 地板早一个折叠周期回收,但每次回合结束都会改写中段历史字节、付出一次全新的缓存 miss;开启即表示接受这些接缝,只适合 miss 代价低的场景(如本地端点)。 | | `compress.minCompressRange` | number | same as minCompressRangeChars | — | minCompressRangeChars 的弃用别名(接受,映射到后者)。 _(已弃用)_ | **路由表字段** diff --git a/src/cache-ledger.ts b/src/cache-ledger.ts index 20dbe753fb..94b7e6e16b 100644 --- a/src/cache-ledger.ts +++ b/src/cache-ledger.ts @@ -113,13 +113,16 @@ interface LedgerLine { /** #2929: which attribution arm detectSeam booked this sample's residual * into — "ttl" (long-idle byte-stable miss, normal ageing), "side" * (short-idle byte-stable miss, abnormal provider failure), "rewind" - * (client revert/trim re-bill) or "client" (#3023: the client's own + * (client revert/trim re-bill), "client" (#3023: the client's own * resent history broke mid-list — host-side insert/rewrite, e.g. another * plugin or paste hoisting; the outbound seam is bili's faithful rebuild - * of host churn). Sparse: omitted unless booked. The seam arm sets `seam` + * of host churn) or "reasoning" (#651/#3198: a compress-reasoning round + * newly closed — the drop pass removed that round's reasoning from the + * outbound view, a known once-per-round mid-history rewrite). Sparse: + * omitted unless booked. The seam arm sets `seam` * above instead. Lets the web trajectory chart paint the same bucket * membership the economics card aggregates. */ - prov?: "ttl" | "side" | "rewind" | "client"; + prov?: "ttl" | "side" | "rewind" | "client" | "reasoning"; /** #1535: 1 iff `model` differs from the previous sample's KNOWN model * (unknown sides never flag); marks the re-billed stable prefix on the * first request after a model switch. Sparse: omitted unless set. */ @@ -275,6 +278,13 @@ interface CacheLedger { * abort/retry churn correlates with prefix misses (the retried * request carries a rewritten tail). Correlation, not causation. */ abortCorrelated: number; + /** #651/#3198: re-bills on the request where a compress-reasoning + * round newly closed — the drop pass removed that round's reasoning + * from the outbound view, a known once-per-round mid-history + * rewrite. Expected cost of `compress.reasoning.drop` (default on), + * never an unexplained seam. */ + reasoningDropMisses: number; + reasoningDropMissed: number; }; /** #1592-family: bounded forensic log of suspected mid-history cache-seam * breaks (consecutive outbound bodies diverged with no structural @@ -475,6 +485,9 @@ function firstDivergentInboundMsg(prev: InboundSlot, cur: InboundSlot): number | } const lastClientAbort = new WeakMap(); +const lastReasoningDrop = new WeakMap(); +const lastReasoningDropKey = new WeakMap(); + interface ContextObservation { sessionId: string; tokens: number; @@ -510,6 +523,21 @@ export function noteClientAbort(session: Session): void { lastClientAbort.set(session, Date.now()); } +/** #651/#3198: track the compress-reasoning drop plan between requests. + * Called by prepare-* right after planReasoningDrop. When the plan GROWS + * (a compress round newly closed since the previous request) the outbound + * view drops that round's reasoning mid-history exactly once — the miss it + * bills is a known cause, booked by detectSeam into the reasoningDrop + * bucket. The first observation in a process only primes the key: after a + * restart the dropped view is already steady, so no rewrite happens and a + * later unrelated miss must not borrow the attribution. */ +export function noteReasoningDropPlan(session: Session, plan: Set): void { + const key = plan.size === 0 ? "" : `${plan.size}:${[...plan].sort().join("\x00")}`; + const prev = lastReasoningDropKey.get(session); + lastReasoningDropKey.set(session, key); + if (prev !== undefined && prev !== key && plan.size > 0) lastReasoningDrop.set(session, Date.now()); +} + /** #2131: stable fingerprint of the outbound credential — the ONLY form the * key is ever persisted in (raw secrets never reach the ledger, logs or the * web UI). Checks the standard bearer/api-key headers, case-insensitively; @@ -758,6 +786,25 @@ function detectSeam(session: Session, led: CacheLedger): void { // Substantive unexplained residual only: a big ttlRepay slice of a big bill. if (!(line.tr > 8192 && line.tr > 0.3 * line.input)) return; const agg = led.agg; + // #651/#3198: a compress-reasoning round closed on THIS request — the + // drop pass removed the closed round's reasoning from the outbound view, + // a known once-per-round mid-history rewrite. Consume the stamp so a + // later unrelated miss can never borrow it, and book the re-bill as a + // known cause instead of an unexplained seam. Full-hit rounds leave the + // stamp in place; the 120s window bounds any stale read. + const rdAt = lastReasoningDrop.get(session); + if (rdAt !== undefined) { + lastReasoningDrop.delete(session); + if (Math.abs(line.at - rdAt) < 120_000) { + line.prov = "reasoning"; + agg.reasoningDropMisses += 1; + agg.reasoningDropMissed += line.tr; + if (agg.reasoningDropMisses === 1) { + loggerLog("info", `[${session.id}] [cache-seam] compress-reasoning round-close rewrite (#651): hit ${line.hitPct}% (input=${line.input}, re-paid=${Math.round(line.tr)} tok) — the closed round's reasoning left the outbound view (not a seam; default flush:'fold' rides the next fold's re-billed region, flush:'close'/cap = this once-per-round/out-of-fold re-bill; compress.reasoning.drop:false disables the drop)`); + } + return; + } + } const cur = session.transient?.sentBody; const prev = session.transient?.settledBody; // #2929: split the provider-side arms by idle gap — a byte-stable miss @@ -906,6 +953,7 @@ export function getCacheLedger(session: Session): CacheLedger { "restartDropMissed", "attributedMissed", "unknownSamples", "unknownInput", "nbSamples", "nbInput", "seamSuspects", "seamMissed", + "reasoningDropMisses", "reasoningDropMissed", "providerSideMisses", "providerSideMissed", "providerTtlMisses", "providerTtlMissed", "rewinds", "rewindMissed", "abortCorrelated", "clientInserts", "clientInsertMissed", ] as const) { if (typeof g[key] !== "number") g[key] = 0; @@ -923,7 +971,7 @@ export function getCacheLedger(session: Session): CacheLedger { foldSeqCounter: 0, folds: [], lines: [], - agg: { requests: 0, input: 0, cached: 0, output: 0, nc: 0, cr: 0, tr: 0, switches: 0, switchMissed: 0, keySwitches: 0, keySwitchMissed: 0, promptSwitches: 0, promptSwitchMissed: 0, projSwitches: 0, projSwitchMissed: 0, wireSwitches: 0, wireSwitchMissed: 0, upstreamSwitches: 0, upstreamSwitchMissed: 0, restartDrops: 0, restartDropMissed: 0, attributedMissed: 0, unknownSamples: 0, unknownInput: 0, nbSamples: 0, nbInput: 0, seamSuspects: 0, seamMissed: 0, providerSideMisses: 0, providerSideMissed: 0, providerTtlMisses: 0, providerTtlMissed: 0, rewinds: 0, rewindMissed: 0, abortCorrelated: 0, clientInserts: 0, clientInsertMissed: 0 }, + agg: { requests: 0, input: 0, cached: 0, output: 0, nc: 0, cr: 0, tr: 0, switches: 0, switchMissed: 0, keySwitches: 0, keySwitchMissed: 0, promptSwitches: 0, promptSwitchMissed: 0, projSwitches: 0, projSwitchMissed: 0, wireSwitches: 0, wireSwitchMissed: 0, upstreamSwitches: 0, upstreamSwitchMissed: 0, restartDrops: 0, restartDropMissed: 0, attributedMissed: 0, unknownSamples: 0, unknownInput: 0, nbSamples: 0, nbInput: 0, seamSuspects: 0, seamMissed: 0, providerSideMisses: 0, providerSideMissed: 0, providerTtlMisses: 0, providerTtlMissed: 0, rewinds: 0, rewindMissed: 0, abortCorrelated: 0, clientInserts: 0, clientInsertMissed: 0, reasoningDropMisses: 0, reasoningDropMissed: 0 }, }; meta[LEDGER_KEY] = led; return led; @@ -1619,7 +1667,7 @@ interface BodyStability { interface BiliCacheReport extends CacheReport { stability: BodyStability; /** #2131: line set widened with the per-call body-stability fields. */ - lines: Array; + lines: Array; modelSwitches: ModelSwitchStats; /** #2131: relay account rotations (credential fingerprint changes) — * the identity a URL-granular upstream switch cannot see. */ @@ -1641,7 +1689,7 @@ interface BiliCacheReport extends CacheReport { * is booked as new content, never as a prefix re-pay. */ initialBills: { samples: number; inputTokens: number }; invalidation: InvalidationTokenBreakdown; - seam: { suspects: number; missed: number; events: SeamEvent[]; providerSide: { count: number; missed: number }; providerTtl: { count: number; missed: number }; rewinds: { count: number; missed: number }; abortCorrelated: number; client: { count: number; missed: number } }; + seam: { suspects: number; missed: number; events: SeamEvent[]; providerSide: { count: number; missed: number }; providerTtl: { count: number; missed: number }; rewinds: { count: number; missed: number }; abortCorrelated: number; client: { count: number; missed: number }; reasoningDrop: { count: number; missed: number } }; } export function buildSessionCacheReport(session: Session): BiliCacheReport { @@ -1825,7 +1873,7 @@ export function buildSessionCacheReport(session: Session): BiliCacheReport { initialBills: { samples: a.nbSamples, inputTokens: a.nbInput }, invalidation, stability, - seam: { suspects: a.seamSuspects, missed: a.seamMissed, events: led.seamEvents ?? [], providerSide: { count: a.providerSideMisses, missed: a.providerSideMissed }, providerTtl: { count: a.providerTtlMisses, missed: a.providerTtlMissed }, rewinds: { count: a.rewinds, missed: a.rewindMissed }, abortCorrelated: a.abortCorrelated, client: { count: a.clientInserts, missed: a.clientInsertMissed } }, + seam: { suspects: a.seamSuspects, missed: a.seamMissed, events: led.seamEvents ?? [], providerSide: { count: a.providerSideMisses, missed: a.providerSideMissed }, providerTtl: { count: a.providerTtlMisses, missed: a.providerTtlMissed }, rewinds: { count: a.rewinds, missed: a.rewindMissed }, abortCorrelated: a.abortCorrelated, client: { count: a.clientInserts, missed: a.clientInsertMissed }, reasoningDrop: { count: a.reasoningDropMisses, missed: a.reasoningDropMissed } }, }; } @@ -1996,6 +2044,10 @@ function formatSeam(r: BiliCacheReport): string { if (e.client) out.push(` #${e.seq} ${fmtTime(e.at)} hit ${e.hitPct.toFixed(1)}% · input ${fmtTok(e.input)} · inbound message[${e.client.idx}] ${e.client.role}/${e.client.cls} ${e.client.len}B JSON · outbound ${fmtTok(e.lcpBytes)}B @ message[${e.msgIndex ?? "?"}] of ${e.prevMsgs}→${e.curMsgs}`); } } + if (r.seam.reasoningDrop.count > 0) { + out.push("℞ COMPRESS-REASONING DROP (#651/#3198) — reasoning reclaimed off the wire (default rides the next fold's re-billed region; flush:'close' = once-per-round re-bill)"); + out.push(` ${r.seam.reasoningDrop.count} sample(s) · ${fmtTok(r.seam.reasoningDrop.missed)} tok re-billed where a closed compress round's reasoning left the outbound view — expected cost of compress.reasoning.drop (default on): the drop rewrites that stretch of history exactly once per round. Not a seam; set compress.reasoning.drop=false to keep reasoning (larger prompts, no re-bill).`); + } if (r.seam.abortCorrelated > 0) { out.push("⏻ ABORT-CORRELATED"); out.push(` ${r.seam.abortCorrelated} missed sample(s) within 30s of a client mid-stream abort — abort/retry churn rewrites the resent tail; correlation, not causation (see bili.log 'client aborted mid-stream')`); diff --git a/src/reasoning-drop.ts b/src/reasoning-drop.ts index 3fa6f7d374..7c976a2b07 100644 --- a/src/reasoning-drop.ts +++ b/src/reasoning-drop.ts @@ -26,9 +26,26 @@ export interface CompressReasoningConfig { * `compress` call must total STRICTLY more than this to be dropped. * Default: 2048. `0` drops any non-empty run. */ threshold?: number; + /** When closed rounds' reasoning leaves the OUTBOUND view (#3198-C): + * - "fold" (default): the applied drop set is frozen between folds and + * flushes only when a fold lands in the same request (or the pending + * mass cap trips) — the wire stays byte-stable across round closes, so + * each flush rides the fold's own re-billed region instead of opening + * a NEW prefix-cache seam; + * - "close": legacy timing — flush on the first request after each round + * close. Reclaims the floor one fold earlier, but every round close + * rewrites mid-history bytes and pays a fresh cache miss (fine where + * misses are cheap, e.g. local endpoints). */ + flush?: "fold" | "close"; } -export const DEFAULT_COMPRESS_REASONING: Required = { drop: true, threshold: 2048 }; +export const DEFAULT_COMPRESS_REASONING: Required = { drop: true, threshold: 2048, flush: "fold" }; + +/** Pending-mass backstop for flush:"fold": chars of closed-but-unflushed + * reasoning beyond which the flush fires even without a fold, so sessions + * that never fold do not grow the floor unboundedly. One attributed seam + * per crossing (the ledger's compress-reasoning bucket, #3198). */ +export const REASONING_FLUSH_CAP = 64 * 1024; export function resolveReasoningDrop(cfg?: CompressReasoningConfig): Required { let threshold = DEFAULT_COMPRESS_REASONING.threshold; @@ -38,7 +55,8 @@ export function resolveReasoningDrop(cfg?: CompressReasoningConfig): Required, + msgs: BiliMessage[], + reasoning: CompressReasoningConfig | undefined, + blockIdsBefore: Set, + blocksAfter: readonly { blockId: string }[], + log: (level: string, msg: string) => void, + sessionId: string, +): Set { + const t = (session.transient ??= {}); + if (candidate.size === 0) { + // Gate closed / disabled / no match: nothing applies, and any earlier + // applied ids stop applying (presence-based gates, per-request). + t.reasoningDropped = new Set(); + return t.reasoningDropped; + } + const prev = t.reasoningDropped ?? new Set(); + const flush = resolveReasoningDrop(reasoning).flush; + if (flush === "close") { + t.reasoningDropped = candidate; + return candidate; + } + const folded = blocksAfter.some((b) => !blockIdsBefore.has(b.blockId)); + if (folded) { + t.reasoningDropped = candidate; + return candidate; + } + let pendingMass = 0; + for (const m of msgs) { + if (candidate.has(m.id) && !prev.has(m.id)) pendingMass += (m.text ?? "").length; + } + if (pendingMass > REASONING_FLUSH_CAP) { + log("info", `[${sessionId}] compress-reasoning: pending ${pendingMass} chars > ${REASONING_FLUSH_CAP} cap — flushing outside a fold (one attributed re-bill; compress.reasoning.flush:"close" opts into the legacy per-round timing) (#3198)`); + t.reasoningDropped = candidate; + return candidate; + } + return prev; +} + /** [#651] Strip oversized reasoning from closed compress turns (see * src/reasoning-drop.ts) with an ops log line when anything was dropped. * Standalone form for callers holding an anchor-intact array (tests, ad-hoc diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index b862723ab5..ea732d4f8b 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -5,7 +5,8 @@ import { anthropicToCore, buildSystem, coreToAnthropic, extractSystem, type Anth import { rewriteInboundThreadContinue } from "./thread-tracking.js"; import type { CompressReasoningConfig } from "../reasoning-drop.js"; import type { ProxyOptions } from "../config.js"; -import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, reapOrphansLogged, runNudgeDecision, stripKernelSummaries, warnAnthropicThinkingPairs, type Prepared } from "../server.js"; +import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, reapOrphansLogged, settleReasoningDropPlan, runNudgeDecision, stripKernelSummaries, warnAnthropicThinkingPairs, type Prepared } from "../server.js"; +import { noteReasoningDropPlan } from "../cache-ledger.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; @@ -213,8 +214,15 @@ export async function prepareAnthropic( // inactive call+result pairs inside, which would strip the anchors // this pass needs (the leak applies to the bare name too). reasoningPlan = planReasoningDrop(msgs, reasoning, isStrictReasoningEcho(session, upstreamOrigin, modelIdOf(parsed))); + const reasoningBlockIdsBefore = new Set(session.state.blocks.map((b) => b.blockId)); const turn = core.processTurn({ messages: msgs, state: session.state, config: loopConfig, tokenCount, renderTags: renderStrategy, contentStore: contentStoreOf(session) }); session.state = turn.state; + // #3198-C: settle the applied drop set AFTER processTurn — a fold that + // landed in this request flushes the pending closed-round reasoning in + // the SAME request, riding the fold's re-billed region instead of + // opening a new prefix-cache seam at every round close. + reasoningPlan = settleReasoningDropPlan(session, reasoningPlan, msgs, reasoning, reasoningBlockIdsBefore, session.state.blocks, log, sessionId); + noteReasoningDropPlan(session, reasoningPlan); adoptContentStore(session, turn.contentStore); // The fold from last turn's compress has now materialized in state — // future usage reports are post-fold reality, drop the credit. diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index 94fadf9083..2ade08de16 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -6,7 +6,8 @@ import type { CompressReasoningConfig } from "../reasoning-drop.js"; import type { ProxyOptions } from "../config.js"; import { currentCalibrationFactor, hardenOpenaiAssistantContent, systemToUser } from "../util.js"; import { conversationHeaderSource, shouldStampRelayAffinityPck } from "../session-id.js"; -import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, reapOrphansLogged, runNudgeDecision, stripKernelSummaries, warnDroppedOpenaiParts, warnReasoningPairs, type Prepared } from "../server.js"; +import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, reapOrphansLogged, settleReasoningDropPlan, runNudgeDecision, stripKernelSummaries, warnDroppedOpenaiParts, warnReasoningPairs, type Prepared } from "../server.js"; +import { noteReasoningDropPlan } from "../cache-ledger.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; @@ -166,8 +167,15 @@ export async function prepareOpenai( // inactive call+result pairs inside, which would strip the anchors // this pass needs (the leak applies to the bare name too). reasoningPlan = planReasoningDrop(msgs, reasoning, isStrictReasoningEcho(session, upstreamOrigin, modelIdOf(parsed))); + const reasoningBlockIdsBefore = new Set(session.state.blocks.map((b) => b.blockId)); const turn = core.processTurn({ messages: msgs, state: session.state, config: loopConfig, tokenCount, renderTags: renderStrategy, contentStore: contentStoreOf(session) }); session.state = turn.state; + // #3198-C: settle the applied drop set AFTER processTurn — a fold that + // landed in this request flushes the pending closed-round reasoning in + // the SAME request, riding the fold's re-billed region instead of + // opening a new prefix-cache seam at every round close. + reasoningPlan = settleReasoningDropPlan(session, reasoningPlan, msgs, reasoning, reasoningBlockIdsBefore, session.state.blocks, log, sessionId); + noteReasoningDropPlan(session, reasoningPlan); adoptContentStore(session, turn.contentStore); // The fold from last turn's compress has now materialized in state — // future usage reports are post-fold reality, drop the credit. diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index 0cb8b37fa5..02665ba99a 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -5,7 +5,8 @@ import { injectResponsesDeveloperMessage, type BiliMessage, type ResponseInputIt import type { CompressReasoningConfig } from "../reasoning-drop.js"; import { resolveCompressProtocol, type CompressSettings, type ProxyOptions } from "../config.js"; import { currentCalibrationFactor, strippedResponseIdWarning } from "../util.js"; -import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, repairResponsesAssistantOrdering, reapOrphansLogged, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, warnResponsesReasoningPairs, type Prepared } from "../server.js"; +import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, repairResponsesAssistantOrdering, reapOrphansLogged, settleReasoningDropPlan, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, warnResponsesReasoningPairs, type Prepared } from "../server.js"; +import { noteReasoningDropPlan } from "../cache-ledger.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { mergeAdjacentConfigurationUpdates, patchResponsesInputWithToolImages as patchResponsesInput, responsesToCoreWithToolImages as responsesToCore } from "../responses-tool-output.js"; @@ -272,8 +273,15 @@ export async function prepareResponses( // inactive call+result pairs inside, which would strip the anchors // this pass needs (the leak applies to the bare name too). reasoningPlan = planReasoningDrop(msgs, reasoning, isStrictReasoningEcho(session, upstreamOrigin, modelIdOf(parsed))); + const reasoningBlockIdsBefore = new Set(session.state.blocks.map((b) => b.blockId)); const turn = core.processTurn({ messages: msgs, state: session.state, config: loopConfig, tokenCount, renderTags, contentStore: contentStoreOf(session) }); session.state = turn.state; + // #3198-C: settle the applied drop set AFTER processTurn — a fold that + // landed in this request flushes the pending closed-round reasoning in + // the SAME request, riding the fold's re-billed region instead of + // opening a new prefix-cache seam at every round close. + reasoningPlan = settleReasoningDropPlan(session, reasoningPlan, msgs, reasoning, reasoningBlockIdsBefore, session.state.blocks, log, sessionId); + noteReasoningDropPlan(session, reasoningPlan); adoptContentStore(session, turn.contentStore); // The fold from last turn's compress has now materialized in state — // future usage reports are post-fold reality, drop the credit. diff --git a/src/session.ts b/src/session.ts index 86396bd820..20008190c3 100644 --- a/src/session.ts +++ b/src/session.ts @@ -245,6 +245,13 @@ export type Session = { * bili's rebuild. */ inBody?: InboundSlot; settledInBody?: InboundSlot; + /** [#3198-C] The #651 reasoning-drop ids ACTUALLY applied to the + * outbound view (frozen between folds under flush:"fold"; see + * settleReasoningDropPlan in src/server.ts). Memory-only by design: + * a restart resets it, reasoning reappears on the wire, and the + * restart re-bill is already attributed — same event class as the + * drop:false kill-switch flip. */ + reasoningDropped?: Set; }; id: string; /** Identity / descriptive metadata. Populated on first request. */ diff --git a/src/web/client.ts b/src/web/client.ts index b53b91b19a..df6c992a9e 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -928,8 +928,8 @@ export const WEB_CLIENT = `(function () { // the same bucket membership the economics card aggregates. The gap // heuristic remains only as the legacy fallback for old ledgers whose // lines carry no attribution fields. - const CAUSE_COLOR = { cold: "#6e7681", comp: "#bf8700", seam: "#cf222e", pt: "#1a7f37", ps: "#f0883e", rw: "#57606a", ci: "#0969da", rest: "#9aa1a8" }; - const CAUSE_KEY = { cold: "det.cause_cold", comp: "det.cause_comp", seam: "det.legend_seam", pt: "det.leg_pttl", ps: "det.leg_pside", rw: "det.leg_rewind", ci: "det.leg_client", rest: "det.cause_ttl" }; + const CAUSE_COLOR = { cold: "#6e7681", comp: "#bf8700", seam: "#cf222e", pt: "#1a7f37", ps: "#f0883e", rw: "#57606a", ci: "#0969da", rd: "#8250df", rest: "#9aa1a8" }; + const CAUSE_KEY = { cold: "det.cause_cold", comp: "det.cause_comp", seam: "det.legend_seam", pt: "det.leg_pttl", ps: "det.leg_pside", rw: "det.leg_rewind", ci: "det.leg_client", rd: "det.leg_reasoning", rest: "det.cause_ttl" }; let foldTailClaims = 0; const causes = lines.map((l, i) => { if (i === 0) return !(l.cached || 0) ? "cold" : "new"; @@ -957,6 +957,7 @@ export const WEB_CLIENT = `(function () { if (l.prov === "side") return "ps"; if (l.prov === "rewind") return "rw"; if (l.prov === "client") return "ci"; + if (l.prov === "reasoning") return "rd"; // Legacy fallback only: no attribution fields on this line. if (l.foldSeq == null && l.seam === undefined && l.prov === undefined && (l.at || 0) - (p.at || 0) > GAP_MS && missed > growth + 2048) return "rest"; return "new"; @@ -1080,6 +1081,7 @@ export const WEB_CLIENT = `(function () { providerTtl: { count: (raw.providerTtl && Number(raw.providerTtl.count)) || 0, missed: (raw.providerTtl && Number(raw.providerTtl.missed)) || 0 }, rewinds: { count: (raw.rewinds && Number(raw.rewinds.count)) || 0, missed: (raw.rewinds && Number(raw.rewinds.missed)) || 0 }, client: { count: (raw.client && Number(raw.client.count)) || 0, missed: (raw.client && Number(raw.client.missed)) || 0 }, + reasoningDrop: { count: (raw.reasoningDrop && Number(raw.reasoningDrop.count)) || 0, missed: (raw.reasoningDrop && Number(raw.reasoningDrop.missed)) || 0 }, abortCorrelated: Number(raw.abortCorrelated) || 0, }; } @@ -1501,6 +1503,7 @@ export const WEB_CLIENT = `(function () { if (seam.providerSide.count > 0) sub.push(legendItem("background:#f0883e", t("det.leg_pside"))); if (seam.rewinds.count > 0) sub.push(legendItem("background:#57606a", t("det.leg_rewind"))); if (seam.client.count > 0) sub.push(legendItem("background:#0969da", t("det.leg_client"))); + if (seam.reasoningDrop.count > 0) sub.push(legendItem("background:#8250df", t("det.leg_reasoning"))); sub.push(legendItem("background:#9aa1a8", t("det.leg_rest"))); parts.push('' + legendItem("background:#8250df", t("det.cause_unattrib")) diff --git a/src/web/i18n.ts b/src/web/i18n.ts index b49c5d8ee7..4c54b7f312 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -252,6 +252,7 @@ export const MESSAGES: Record> = { "det.leg_pside": "▲ 上游侧失效", "det.leg_rewind": "↩ 历史回退", "det.leg_client": "✎ 客户端中段改写", + "det.leg_reasoning": "℞ 压缩思考回收", "det.leg_rest": "其余", "det.fold_short": "折叠", "det.traj_zoom_hint": "拖拽图表可放大选中的序号区间;双击图表或按 Esc 复位", @@ -728,6 +729,7 @@ export const MESSAGES: Record> = { "det.leg_pside": "▲ provider-side miss", "det.leg_rewind": "↩ rewind", "det.leg_client": "✎ client rewrite", + "det.leg_reasoning": "℞ compress-reasoning round-close", "det.leg_rest": "rest", "det.fold_short": "fold", "det.traj_zoom_hint": "Drag across the chart to zoom into a sample range; double-click or press Esc to reset", diff --git a/tests/cache-seam-reasoning-drop.test.ts b/tests/cache-seam-reasoning-drop.test.ts new file mode 100644 index 0000000000..41934bd266 --- /dev/null +++ b/tests/cache-seam-reasoning-drop.test.ts @@ -0,0 +1,102 @@ +// #651/#3198: the compress-reasoning round-close rewrite is a KNOWN +// once-per-round mid-history change (compress.reasoning.drop, default on). +// The ledger must attribute the miss it bills to the new reasoningDrop bucket +// (prov="reasoning", ℞ report section) instead of an unexplained ⚠ CACHE SEAM — +// the seam panic that opened #3198. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { noteForwardedBody, noteReasoningDropPlan, settleUsageReport, getCacheLedger, buildSessionCacheReport, handleAcpCache } from "../src/cache-ledger.ts"; +import type { Session } from "../src/session.ts"; + +let seq = 0; +function makeSession(): Session { + seq += 1; + return { + id: `rdrop-${seq}`, + metadata: {}, + stats: {}, + state: { blocks: [], messageRefs: { byRaw: {}, byRef: {} }, tokenSnapshot: {} }, + } as unknown as Session; +} + +const body = (msgs: string[]): string => JSON.stringify({ model: "m", messages: msgs.map((c) => ({ role: "user", content: c })) }); + +function settle(session: Session, input: number, cached: number): void { + settleUsageReport(session, { total: input, reportedCached: cached, output: 0, protocol: "openai", upstream: "http://u" }); +} + +function lastLine(session: Session) { + const led = getCacheLedger(session); + return { led, line: led.lines[led.lines.length - 1]! }; +} + +test("reasoning drop: round-close growth books prov=reasoning, not a seam", () => { + const s = makeSession(); + // Baseline: round in flight (empty drop plan) — primes the key. + noteReasoningDropPlan(s, new Set()); + noteForwardedBody(s, body(["a", "b", "c"])); + settle(s, 100_000, 99_000); + // Round closes: plan grows, outbound view drops that round's reasoning → + // mid-history rewrite + big residual on the next settle. + noteReasoningDropPlan(s, new Set(["r1", "r2"])); + noteForwardedBody(s, body(["a", "B2", "c"])); + settle(s, 100_000, 20_000); + const { led, line } = lastLine(s); + assert.equal(line.prov, "reasoning", "attributed to the reasoning-drop bucket"); + assert.equal(line.seam, undefined, "must NOT flag an unexplained seam"); + assert.equal(led.agg.seamSuspects, 0); + assert.equal(led.agg.reasoningDropMisses, 1); + assert.ok(led.agg.reasoningDropMissed > 0); + const report = buildSessionCacheReport(s); + assert.equal(report.seam.reasoningDrop.count, 1); + const text = handleAcpCache(s).text; + assert.match(text, /COMPRESS-REASONING DROP/); + assert.doesNotMatch(text, /⚠ CACHE SEAM/); +}); + +test("reasoning drop: first observation in a process only primes (no stamp)", () => { + const s = makeSession(); + noteForwardedBody(s, body(["a", "b"])); + settle(s, 100_000, 99_000); + // No prior plan observation (restart case): the already-dropped view is + // steady; a miss here must NOT borrow the attribution. + noteReasoningDropPlan(s, new Set(["r1"])); + noteForwardedBody(s, body(["a", "B"])); + settle(s, 100_000, 20_000); + const { led, line } = lastLine(s); + assert.equal(line.prov, undefined); + assert.equal(line.seam, 1, "falls through to the unexplained seam arm"); + assert.equal(led.agg.reasoningDropMisses, 0); +}); + +test("reasoning drop: stamp is consumed once — a later identical miss is a seam again", () => { + const s = makeSession(); + noteReasoningDropPlan(s, new Set()); + noteForwardedBody(s, body(["a", "b", "c"])); + settle(s, 100_000, 99_000); + noteReasoningDropPlan(s, new Set(["r1"])); + noteForwardedBody(s, body(["a", "B2", "c"])); + settle(s, 100_000, 20_000); + // Same round-close window is over; a second unexplained break without new + // growth books as a seam. + noteForwardedBody(s, body(["a", "XX", "c"])); + settle(s, 100_000, 20_000); + const { led, line } = lastLine(s); + assert.equal(line.seam, 1); + assert.equal(led.agg.reasoningDropMisses, 1, "first miss consumed the stamp"); + assert.equal(led.agg.seamSuspects, 1); +}); + +test("reasoning drop: no plan growth (same plan) never books", () => { + const s = makeSession(); + noteReasoningDropPlan(s, new Set(["r1"])); + noteForwardedBody(s, body(["a", "b"])); + settle(s, 100_000, 99_000); + noteReasoningDropPlan(s, new Set(["r1"])); + noteForwardedBody(s, body(["a", "B"])); + settle(s, 100_000, 20_000); + const { led, line } = lastLine(s); + assert.equal(line.prov, undefined); + assert.equal(led.agg.reasoningDropMisses, 0); + assert.equal(led.agg.seamSuspects, 1); +}); diff --git a/tests/golden/storage-render/anthropic.json b/tests/golden/storage-render/anthropic.json index 124e2b3598..b67f0a40dd 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": "7e70d816c2a47282523e89d4d8fa6322e0b6b78d38466de2402b48217919b5db", + "stateDigest": "8bf118a8d19fc432be9a311b42b7fe95e58fd89ab5b27cc19fea7dc8661b7793", "sectionDigests": { "state": "fae14b25a41f5844", "blockContents": "dc7d13d250c94bb4", "stats": "cff3c2546898aeb3", - "metadata": "6b1b4b87cb2dfcf1" + "metadata": "e2c360eba91dd6ed" }, "stateKeyDigests": { "blocks": "1cbe172309e4490d", diff --git a/tests/golden/storage-render/chat.json b/tests/golden/storage-render/chat.json index 719951bb6a..03f19c4a99 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": "7762ebbdd202e17ff0e3e446797725e8294be6da46b14bef50ed46ae7b25c68a", + "stateDigest": "3c25b900738dbaca2b352f79ac9e11ecd5197b91424d84160e4e78c0983160fc", "sectionDigests": { "state": "d5bc5306f840723d", "blockContents": "94a58f96d7c5cfc3", "stats": "59842ce5415d3a4d", - "metadata": "88b0e384ede8cd5b" + "metadata": "59b7ae3aa1c4742d" }, "stateKeyDigests": { "blocks": "9aa73e5fb9f93d6c", diff --git a/tests/golden/storage-render/google.json b/tests/golden/storage-render/google.json index c9071c5cac..2d9681553f 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": "3144c27caf4bafa2dcebb7509175f1998a17db4334951572f4dc59d398be39ec", + "stateDigest": "0c78588e92021809dd6db64bbfc65d38b99b8f8f312eddba6c3e285dc95b88db", "sectionDigests": { "state": "2a2af1c92fcb4f88", "blockContents": "473264d9df8ba338", "stats": "660f1797bf2044c4", - "metadata": "208a3c79d1adeebb" + "metadata": "54711a8363b86429" }, "stateKeyDigests": { "blocks": "8e14f0879bf7ebd7", diff --git a/tests/golden/storage-render/responses.json b/tests/golden/storage-render/responses.json index 843ff92f02..73e95c447a 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": "f6db1c6abecd1c32f75fff4fa5b9ecda9e1e5b4e9df88ad34b0ef12f0f5a2371", + "stateDigest": "6645a3f839cf70e6d588c93a9ee74d236f92a0063995e50b26053d990e33315e", "sectionDigests": { "state": "6546d2e5f2826284", "blockContents": "8460729b2654a816", "stats": "e3a3aeb598c183ff", - "metadata": "4d5cfeb5b55a9b1d" + "metadata": "d2f774b5848c0dda" }, "stateKeyDigests": { "blocks": "7fff1dfb54a617cf", diff --git a/tests/reasoning-drop.test.ts b/tests/reasoning-drop.test.ts index 6b74618996..acc3163bc3 100644 --- a/tests/reasoning-drop.test.ts +++ b/tests/reasoning-drop.test.ts @@ -97,11 +97,14 @@ test("idempotence: a second pass changes nothing", () => { }); test("resolveReasoningDrop: defaults, validation, and passthrough", () => { - assert.deepEqual(resolveReasoningDrop(undefined), { drop: true, threshold: 2048 }); - assert.deepEqual(resolveReasoningDrop({}), { drop: true, threshold: 2048 }); - assert.deepEqual(resolveReasoningDrop({ drop: false, threshold: 0 }), { drop: false, threshold: 0 }); - assert.deepEqual(resolveReasoningDrop({ threshold: -3 }), { drop: true, threshold: 2048 }); - assert.deepEqual(resolveReasoningDrop({ threshold: 512.9 }), { drop: true, threshold: 512 }); + assert.deepEqual(resolveReasoningDrop(undefined), { drop: true, threshold: 2048, flush: "fold" }); + assert.deepEqual(resolveReasoningDrop({}), { drop: true, threshold: 2048, flush: "fold" }); + assert.deepEqual(resolveReasoningDrop({ drop: false, threshold: 0 }), { drop: false, threshold: 0, flush: "fold" }); + assert.deepEqual(resolveReasoningDrop({ threshold: -3 }), { drop: true, threshold: 2048, flush: "fold" }); + assert.deepEqual(resolveReasoningDrop({ threshold: 512.9 }), { drop: true, threshold: 512, flush: "fold" }); + // #3198-C: flush timing — "close" is the legacy opt-in, anything else folds. + assert.deepEqual(resolveReasoningDrop({ flush: "close" }), { drop: true, threshold: 2048, flush: "close" }); + assert.deepEqual(resolveReasoningDrop({ flush: "nonsense" as unknown as "fold" }), { drop: true, threshold: 2048, flush: "fold" }); }); test("multiple closed compress rounds all get stripped (distinct toolCallIds)", () => { diff --git a/tests/reasoning-flush-fold.test.ts b/tests/reasoning-flush-fold.test.ts new file mode 100644 index 0000000000..9a92a1b232 --- /dev/null +++ b/tests/reasoning-flush-fold.test.ts @@ -0,0 +1,119 @@ +// #3198-C: compress.reasoning.flush — the #651 reasoning drop's +// LEAVE-THE-WIRE timing. Default "fold" freezes the applied drop set between +// folds: the wire stays byte-stable across round closes (no fresh prefix-cache +// seam per round), and the reclaim rides the fold's own re-billed region. +// "close" keeps the legacy per-round-close timing (opt-in: every round close +// rewrites mid-history bytes and pays a cache miss — fine where misses are +// cheap, e.g. local endpoints). The pending-mass cap (REASONING_FLUSH_CAP) +// bounds sessions that never fold: one attributed flush per crossing. The +// applied set is memory-only; a restart brings reasoning back with the +// already-attributed restart re-bill. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { applyReasoningDrop, settleReasoningDropPlan } from "../src/server.ts"; +import { dropCompressReasoningIds, REASONING_FLUSH_CAP } from "../src/reasoning-drop.ts"; +import type { Session } from "../src/session.ts"; +import type { BiliMessage } from "acp-kernel/wire"; + +let seq = 0; +function makeSession(): Session { + seq += 1; + return { id: `flush-${seq}`, metadata: {}, stats: {}, state: { blocks: [], messageRefs: { byRaw: {}, byRef: {} }, tokenSnapshot: {} } } as unknown as Session; +} + +const logs: string[] = []; +const capLog = (level: string, msg: string): void => { if (level === "info") logs.push(msg); }; + +const reason = (id: string, n = 3000): BiliMessage => ({ id, role: "assistant", contentType: "reasoning", text: "x".repeat(n) }) as BiliMessage; +const call = (id: string, cid: string): BiliMessage => ({ id, role: "assistant", contentType: "tool-call", toolName: "compress", toolCallId: cid }) as BiliMessage; +const result = (id: string, cid: string): BiliMessage => ({ id, role: "user", contentType: "tool-result", toolCallId: cid, text: "ok" }) as BiliMessage; +const user = (id: string): BiliMessage => ({ id, role: "user", contentType: "text", text: "next" }) as BiliMessage; + +/** A closed compress round: reasoning run → compress call → result → a later + * message (round demonstrably moved on, #348 twin). */ +function closedRound(round: string): BiliMessage[] { + return [reason(`${round}-r1`, 6000), reason(`${round}-r2`, 6000), call(`${round}-c`, `tc-${round}`), result(`${round}-res`, `tc-${round}`), user(`${round}-u`)]; +} + +const blockIds = (n: number): Set => new Set(Array.from({ length: n }, (_, i) => `b${i}`)); +const blocksOf = (ids: string[]): { blockId: string }[] => ids.map((blockId) => ({ blockId })); + +function settle(s: Session, candidate: Set, msgs: BiliMessage[], reasoning: { flush?: "fold" | "close" } | undefined, before: Set, after: string[]): Set { + return settleReasoningDropPlan(s, candidate, msgs, reasoning, before, blocksOf(after), capLog, s.id); +} + +test("flush=fold (default): round close does NOT change the wire; the fold flushes", () => { + const s = makeSession(); + const msgs = closedRound("a"); + const candidate = dropCompressReasoningIds(msgs, undefined); + assert.equal(candidate.size, 2, "both reasoning messages of the closed round are candidates"); + // Request after the round closes, no fold in it: applied stays empty. + let plan = settle(s, candidate, msgs, undefined, blockIds(0), []); + assert.equal(plan.size, 0, "frozen: reasoning stays on the wire"); + assert.equal(applyReasoningDrop(msgs, plan, capLog, s.id), msgs, "wire byte-stable — no mid-history rewrite"); + // A second round closes, still no fold: still frozen. + const msgs2 = [...msgs, ...closedRound("b")]; + const candidate2 = dropCompressReasoningIds(msgs2, undefined); + assert.equal(candidate2.size, 4); + plan = settle(s, candidate2, msgs2, undefined, blockIds(0), []); + assert.equal(plan.size, 0); + // The fold lands (new block): everything flushes in the SAME request. + plan = settle(s, candidate2, msgs2, undefined, blockIds(0), ["b0"]); + assert.equal(plan.size, 4, "fold flushes all pending closed rounds"); + assert.equal(applyReasoningDrop(msgs2, plan, capLog, s.id).length, msgs2.length - 4); +}); + +test("flush=close (legacy opt-in): applied follows every candidate", () => { + const s = makeSession(); + const msgs = closedRound("a"); + const candidate = dropCompressReasoningIds(msgs, { flush: "close" }); + const plan = settle(s, candidate, msgs, { flush: "close" }, blockIds(0), []); + assert.equal(plan.size, 2, "legacy timing drops at the first request after round close"); + assert.equal(applyReasoningDrop(msgs, plan, capLog, s.id).length, msgs.length - 2); +}); + +test("pending-mass cap: a never-folding session flushes once past REASONING_FLUSH_CAP", () => { + const s = makeSession(); + const msgs = [...closedRound("a"), ...closedRound("b"), ...closedRound("c"), ...closedRound("d"), ...closedRound("e"), ...closedRound("f")]; + const candidate = dropCompressReasoningIds(msgs, undefined); + const mass = msgs.filter((m) => candidate.has(m.id)).reduce((n, m) => n + (m.text ?? "").length, 0); + assert.ok(mass > REASONING_FLUSH_CAP, `fixture must exceed the cap (mass=${mass}, cap=${REASONING_FLUSH_CAP})`); + const plan = settle(s, candidate, msgs, undefined, blockIds(0), []); + assert.equal(plan.size, candidate.size, "cap flush applies the full candidate set"); + assert.ok(logs.some((l) => l.includes("flushing outside a fold")), "one info line explains the out-of-fold flush"); +}); + +test("gate opens (candidate empty): applied resets, reasoning returns to the wire", () => { + const s = makeSession(); + const msgs = closedRound("a"); + // A fold earlier flushed round a. + settle(s, dropCompressReasoningIds(msgs, undefined), msgs, undefined, blockIds(0), ["b0"]); + assert.ok((s.transient?.reasoningDropped?.size ?? 0) > 0); + // The strict-echo / signed-thinking gate arms: candidate empty this request. + const plan = settle(s, new Set(), msgs, undefined, blockIds(1), []); + assert.equal(plan.size, 0, "presence-based gate per request: nothing applies"); + assert.equal(s.transient?.reasoningDropped?.size, 0, "applied set resets with the gate"); +}); + +test("restart semantics: a fresh process starts with an empty applied set", () => { + const s1 = makeSession(); + const msgs = closedRound("a"); + const candidate = dropCompressReasoningIds(msgs, undefined); + settle(s1, candidate, msgs, undefined, blockIds(0), ["b0"]); + // Restart = transient gone; the same inbound view keeps candidate frozen + // only after the next fold — reasoning reappears until then (the restart + // re-bill is already attributed by the ledger's restart arm). + const s2 = makeSession(); + const plan = settle(s2, candidate, msgs, undefined, blockIds(1), []); + assert.equal(plan.size, 0); + const plan2 = settle(s2, candidate, msgs, undefined, blockIds(1), ["b1"]); + assert.equal(plan2.size, candidate.size); +}); + +test("invalid flush values fall back to fold", () => { + const s = makeSession(); + const msgs = closedRound("a"); + const candidate = dropCompressReasoningIds(msgs, { flush: "nonsense" as unknown as "fold" }); + const plan = settle(s, candidate, msgs, { flush: "nonsense" as unknown as "fold" }, blockIds(0), []); + assert.equal(plan.size, 0, "unknown value behaves as the default fold policy"); +}); diff --git a/website/config-reference/compress.yaml b/website/config-reference/compress.yaml index 894aaafb52..9cf6ceafcc 100644 --- a/website/config-reference/compress.yaml +++ b/website/config-reference/compress.yaml @@ -246,15 +246,15 @@ entries: site_en: "Send growth nudges as the window fills (on by default; global level only)." site_zh: "窗口填满过程中发送增长提醒(默认开;仅全局层级生效)。" - key: compress.reasoning - type: "{ drop?, threshold? }" - default: "drop true · threshold 2048" + type: "{ drop?, threshold?, flush? }" + default: "drop true · threshold 2048 · flush \"fold\"" group: compress id: ct.rz render: compress-row - desc_en: "Drop finished-round reasoning runs longer than 2048 chars (drop: true by default); strict-reasoning upstreams need drop:false." - desc_zh: "丢弃超过 2048 字符的已结束轮次推理块(drop 默认 true);严格推理上游需设 drop:false。" - site_en: "{ drop?, threshold? } — drop finished-round reasoning runs longer than 2048 chars (drop: true by default); strict-reasoning upstreams need drop:false." - site_zh: "{ drop?, threshold? }——丢弃超过 2048 字符的已结束轮次推理块(drop 默认 true);严格推理上游需设 drop:false。" + desc_en: "Drop finished-round reasoning runs longer than 2048 chars (drop: true by default); strict-reasoning upstreams need drop:false. \"flush\" decides WHEN dropped reasoning leaves the wire (see compress.reasoning.flush)." + desc_zh: "丢弃超过 2048 字符的已结束轮次推理块(drop 默认 true);严格推理上游需设 drop:false。\"flush\" 决定被丢弃的推理何时离开转发视图(见 compress.reasoning.flush)。" + site_en: "{ drop?, threshold?, flush? } — drop finished-round reasoning runs longer than 2048 chars (drop: true by default); strict-reasoning upstreams need drop:false." + site_zh: "{ drop?, threshold?, flush? }——丢弃超过 2048 字符的已结束轮次推理块(drop 默认 true);严格推理上游需设 drop:false。" - key: compress.ccr type: object default: "enabled in proxy mode since v2" @@ -479,6 +479,12 @@ entries: group: compress desc_en: "Character threshold above which finished reasoning runs are dropped." desc_zh: "已结束推理块被丢弃的字符阈值。" + - key: compress.reasoning.flush + type: "\"fold\" | \"close\"" + default: "\"fold\"" + group: compress + desc_en: "When closed-round reasoning leaves the forwarded view (#3198). \"fold\" (default): the drop set is frozen between folds and flushes in the same request as a fold — the wire stays byte-stable across round closes, so the reclaim rides the fold's own re-billed prefix-cache region instead of opening a fresh seam per round. A 64 KB pending-mass cap flushes early for sessions that never fold (one attributed re-bill per crossing, shown in the cache ledger under the compress-reasoning bucket). \"close\" (legacy timing, opt-in): flush on the first request after each round closes — reclaims the floor one fold earlier, but every round close rewrites mid-history bytes and pays a NEW cache miss; enabling it means accepting those seams, reasonable only where misses are cheap (e.g. local endpoints)." + desc_zh: "已结束轮次的推理何时从转发视图移除(#3198)。\"fold\"(默认):丢弃集合在两次折叠之间冻结,随折叠所在的那次请求一起冲刷 —— 回合结束时线上字节保持不变,回收搭折叠自身已重计费的前缀缓存区域,不再每回合开一条新接缝。对从不折叠的会话有 64 KB 积压上限(超限即冲刷,每次越界一笔已归因重计费,记在缓存账本的压缩思考桶)。\"close\"(旧时序,主动开启):每回合结束后的第一条请求即冲刷 —— 地板早一个折叠周期回收,但每次回合结束都会改写中段历史字节、付出一次全新的缓存 miss;开启即表示接受这些接缝,只适合 miss 代价低的场景(如本地端点)。" - key: compress.minCompressRange type: number default: "same as minCompressRangeChars" diff --git a/website/docs/index.html b/website/docs/index.html index de87dfdf14..19435c7c72 100644 --- a/website/docs/index.html +++ b/website/docs/index.html @@ -202,7 +202,7 @@

compress — every knob

rulesbooleanOff by default: persistent model reminders delivered through an injected acp_rule tool, hard-protected from folds. pi/omp expose an /acp-rule command. injectToolbooleanRegister the acp_compress tool for clients (on by default; global level only). injectNudgebooleanSend growth nudges as the window fills (on by default; global level only). - reasoning{ drop?, threshold? }{ drop?, threshold? } — drop finished-round reasoning runs longer than 2048 chars (drop: true by default); strict-reasoning upstreams need drop:false. + reasoning{ drop?, threshold?, flush? }{ drop?, threshold?, flush? } — drop finished-round reasoning runs longer than 2048 chars (drop: true by default); strict-reasoning upstreams need drop:false. diff --git a/website/main.js b/website/main.js index b1dbba4dcb..ee59d6d890 100644 --- a/website/main.js +++ b/website/main.js @@ -85,7 +85,7 @@ "ct.rules": "Off by default: persistent model reminders delivered through an injected acp_rule tool, hard-protected from folds. pi/omp expose an /acp-rule command.", "ct.it": "Register the acp_compress tool for clients (on by default; global level only).", "ct.in": "Send growth nudges as the window fills (on by default; global level only).", - "ct.rz": "{ drop?, threshold? } — drop finished-round reasoning runs longer than 2048 chars (drop: true by default); strict-reasoning upstreams need drop:false.", + "ct.rz": "{ drop?, threshold?, flush? } — drop finished-round reasoning runs longer than 2048 chars (drop: true by default); strict-reasoning upstreams need drop:false.", "co.ccr": "ccr — content cache & retrieve: large outputs are stored losslessly beside the session and replaced by a head excerpt plus pointer; the model fetches originals back via acp_retrieve. No cap or eviction; on by default in proxy mode since v2 (enabled, minToolTokens (~4000), excludeTools, toolName \"acp_retrieve\", maxHeadChars).", "co.searchRoot": "search — search-behavior settings for search_context; currently holds planAware.", "co.search": "search.planAware — off by default: when on, search_context candidates are re-ranked against current plan state (latest-wins todos + last user turn); off keeps byte-identical lexical results.", @@ -323,7 +323,7 @@ "ct.rules": "默认关:通过注入的 acp_rule 工具提供持久模型提醒——对折叠硬保护。pi/omp 提供 /acp-rule 命令。", "ct.it": "向客户端注册 acp_compress 工具(默认开;仅全局层级生效)。", "ct.in": "窗口填满过程中发送增长提醒(默认开;仅全局层级生效)。", - "ct.rz": "{ drop?, threshold? }——丢弃超过 2048 字符的已结束轮次推理块(drop 默认 true);严格推理上游需设 drop:false。", + "ct.rz": "{ drop?, threshold?, flush? }——丢弃超过 2048 字符的已结束轮次推理块(drop 默认 true);严格推理上游需设 drop:false。", "co.ccr": "ccr —— 内容缓存与回取:大输出无损存到会话旁、替换为首段摘录+指针,模型用 acp_retrieve 取回原文;无上限、永不清除;自 v2 起代理模式默认开(enabled, minToolTokens(~4000), excludeTools, toolName \"acp_retrieve\", maxHeadChars)。", "co.searchRoot": "search —— search_context 的检索行为设置;当前含 planAware。", "co.search": "search.planAware —— 默认关:开启后 search_context 候选按当前计划状态重排(todo 最新优先 + 上一轮用户消息);关闭时结果逐字节不变。",