Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
2e102d6
fix: 压缩思考回收(#651)触发的重计费被误报为未知缓存接缝,改为单独归因 (#3198)
Oct 15, 2026
0dc09ee
merge #3300 attribution branch (stack: #3196 -> #3300 -> fold-flush)
Oct 15, 2026
cabb2ad
fix: 压缩思考回收(#651)默认改为随折叠统一下线,消除每轮关闭的缓存接缝 (#3198)
Oct 15, 2026
491d52a
fix: render the missing $(reasoning) legend swatch so det.leg_reasoni…
Oct 15, 2026
7e5708e
test: regenerate storage-render goldens for the two new ledger counters
Oct 15, 2026
4dee7e9
Merge branch 'master' into 2026-10-15_reasoning-drop-attribution
Oct 15, 2026
95196d6
Merge remote-tracking branch 'origin/master' into HEAD
Oct 15, 2026
67351e1
docs: add missing compress.reasoning.flush seed entry so docs-sync re…
Oct 15, 2026
b71283e
fix(web): give #3300's reasoning-drop bucket a seam sub-legend row — …
Oct 15, 2026
32c0bbb
fix(web): normalize seam.reasoningDrop defensively like its sibling b…
Oct 15, 2026
3b51931
test(golden): restore the storage-render goldens #3300 regenerated — …
Oct 15, 2026
97ce469
fix(web): normalize seam.reasoningDrop defensively like its sibling b…
Oct 15, 2026
eba8b94
merge master into reasoning-flush-fold; storage-render goldens resolv…
Oct 16, 2026
b0a9431
Merge remote-tracking branch 'origin/master' into conflict-3300-r2
Oct 16, 2026
faa38f7
Merge remote-tracking branch 'origin/master' into conflict-3300-r2
Oct 16, 2026
714db14
merge master (#3312) into reasoning-flush-fold — clean, no conflict
Oct 16, 2026
2652c4f
Merge remote-tracking branch 'origin/2026-10-15_reasoning-drop-attrib…
Oct 16, 2026
a13515f
Merge remote-tracking branch 'origin/2026-10-16_reasoning-flush-fold'…
Oct 16, 2026
74d53cd
merge: master into reasoning-flush-fold (remove-absorb follows master…
Oct 16, 2026
0858d4e
test: regen storage-render goldens on merged tree
Oct 16, 2026
0ec0bf1
Merge commit 'd8c0e50e7' into 2026-10-16_reasoning-flush-fold
Oct 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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**
Expand Down
3 changes: 2 additions & 1 deletion CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 候选按当前计划状态重排;关闭时结果逐字节不变。 |
Expand Down Expand Up @@ -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 的弃用别名(接受,映射到后者)。 _(已弃用)_ |

**路由表字段**
Expand Down
66 changes: 59 additions & 7 deletions src/cache-ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -475,6 +485,9 @@ function firstDivergentInboundMsg(prev: InboundSlot, cur: InboundSlot): number |
}
const lastClientAbort = new WeakMap<Session, number>();

const lastReasoningDrop = new WeakMap<Session, number>();
const lastReasoningDropKey = new WeakMap<Session, string>();

interface ContextObservation {
sessionId: string;
tokens: number;
Expand Down Expand Up @@ -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<string>): 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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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<CacheReportLine & { bodyDigest?: string; bodyEqual?: 0 | 1; bodyLcp?: number; bodyClass?: "head" | "append" | "mid" | "tail" | "unknown"; keyFp?: string; sysFp?: string; seam?: 1; prov?: "ttl" | "side" | "rewind" | "client" }>;
lines: Array<CacheReportLine & { bodyDigest?: string; bodyEqual?: 0 | 1; bodyLcp?: number; bodyClass?: "head" | "append" | "mid" | "tail" | "unknown"; keyFp?: string; sysFp?: string; seam?: 1; prov?: "ttl" | "side" | "rewind" | "client" | "reasoning" }>;
modelSwitches: ModelSwitchStats;
/** #2131: relay account rotations (credential fingerprint changes) —
* the identity a URL-granular upstream switch cannot see. */
Expand All @@ -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 {
Expand Down Expand Up @@ -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 } },
};
}

Expand Down Expand Up @@ -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')`);
Expand Down
22 changes: 20 additions & 2 deletions src/reasoning-drop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<CompressReasoningConfig> = { drop: true, threshold: 2048 };
export const DEFAULT_COMPRESS_REASONING: Required<CompressReasoningConfig> = { 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<CompressReasoningConfig> {
let threshold = DEFAULT_COMPRESS_REASONING.threshold;
Expand All @@ -38,7 +55,8 @@ export function resolveReasoningDrop(cfg?: CompressReasoningConfig): Required<Co
threshold = Math.floor(t);
}
}
return { drop: cfg?.drop !== false, threshold };
const flush = cfg?.flush === "close" ? "close" : "fold";
return { drop: cfg?.drop !== false, threshold, flush };
}

/** Request-time pass: remove reasoning messages attached to a `compress`
Expand Down
Loading
Loading