From 2e102d6e37fdfe4079467b55cf9a21aded150239 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Thu, 15 Oct 2026 22:56:50 +0800 Subject: [PATCH 1/5] =?UTF-8?q?fix:=20=E5=8E=8B=E7=BC=A9=E6=80=9D=E8=80=83?= =?UTF-8?q?=E5=9B=9E=E6=94=B6(#651)=E8=A7=A6=E5=8F=91=E7=9A=84=E9=87=8D?= =?UTF-8?q?=E8=AE=A1=E8=B4=B9=E8=A2=AB=E8=AF=AF=E6=8A=A5=E4=B8=BA=E6=9C=AA?= =?UTF-8?q?=E7=9F=A5=E7=BC=93=E5=AD=98=E6=8E=A5=E7=BC=9D,=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E5=8D=95=E7=8B=AC=E5=BD=92=E5=9B=A0=20(#3198)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 每个压缩回合关闭时,reasoning-drop 会把该回合的思考内容从出站 视图移除——这是一次已知的中段历史改写,每次回合恰好重计费一次。 此前账本把这笔 miss 记成「⚠ CACHE SEAM(疑似中段前缀断裂)」, #3198 排查正是被这个无归因桶吓出来的。 现在 prepare-* 在 planReasoningDrop 之后上报计划 (noteReasoningDropPlan):计划增长=有回合新关闭,下一个大残差 miss 归因为 prov="reasoning" 的新桶,并在 /acp-cache 输出 「℞ COMPRESS-REASONING ROUND-CLOSE」一节(含 compress.reasoning. drop=false 的关闭方法),网页轨迹图同步新增该颜色桶。进程内首次 观测只做基线(重启后视图已稳定,不误借归因);打点消费一次即失效, 120 秒窗口兜底。 --- src/cache-ledger.ts | 66 +++++++++++++-- src/server/prepare-anthropic.ts | 2 + src/server/prepare-openai.ts | 2 + src/server/prepare-responses.ts | 2 + src/web/client.ts | 5 +- src/web/i18n.ts | 2 + tests/cache-seam-reasoning-drop.test.ts | 102 ++++++++++++++++++++++++ 7 files changed, 172 insertions(+), 9 deletions(-) create mode 100644 tests/cache-seam-reasoning-drop.test.ts diff --git a/src/cache-ledger.ts b/src/cache-ledger.ts index 20dbe753fb..0ae4dec63f 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 (known once-per-round re-bill, not a seam; 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 ROUND-CLOSE (#651) — known 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/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index 73d82c583c..e079e02fa0 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -6,6 +6,7 @@ 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 { 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"; @@ -223,6 +224,7 @@ 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))); + noteReasoningDropPlan(session, reasoningPlan); const turn = core.processTurn({ messages: msgs, state: session.state, config: loopConfig, tokenCount, renderTags: renderStrategy, contentStore: contentStoreOf(session) }); session.state = turn.state; adoptContentStore(session, turn.contentStore); diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index e047fb8099..750d263d67 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -7,6 +7,7 @@ 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 { 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"; @@ -168,6 +169,7 @@ 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))); + noteReasoningDropPlan(session, reasoningPlan); const turn = core.processTurn({ messages: msgs, state: session.state, config: loopConfig, tokenCount, renderTags: renderStrategy, contentStore: contentStoreOf(session) }); session.state = turn.state; adoptContentStore(session, turn.contentStore); diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index 76e0411eb7..0ae7b4728c 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -7,6 +7,7 @@ import { resolveAbsorbSettings } from "../compress-settings.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 { 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"; @@ -276,6 +277,7 @@ 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))); + noteReasoningDropPlan(session, reasoningPlan); const turn = core.processTurn({ messages: msgs, state: session.state, config: loopConfig, tokenCount, renderTags, contentStore: contentStoreOf(session) }); session.state = turn.state; adoptContentStore(session, turn.contentStore); diff --git a/src/web/client.ts b/src/web/client.ts index bfc20abbb2..a1773eb8de 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -923,8 +923,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"; @@ -952,6 +952,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"; diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 6ada878235..068ed76545 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": "折叠", "ov.gross_note": "按每次折叠的节省量 × 其后每个请求累计(理论上界)", @@ -725,6 +726,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", "ov.gross_note": "sums each fold's savings across every later request (theoretical upper bound)", diff --git a/tests/cache-seam-reasoning-drop.test.ts b/tests/cache-seam-reasoning-drop.test.ts new file mode 100644 index 0000000000..c0fc237570 --- /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 ROUND-CLOSE/); + 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); +}); From 491d52a6da3cec7c1ac23ef9c05652b8b12d2fbb Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 16 Oct 2026 00:38:27 +0800 Subject: [PATCH 2/5] fix: render the missing $(reasoning) legend swatch so det.leg_reasoning is a live i18n key The #3300 change added CAUSE_COLOR.rd / CAUSE_KEY.rd and the prov==='reasoning' cause mapping but never pushed a legendItem() for the new bucket, so the purple segment rendered unlabeled AND the i18n dead-key guard (#1024) failed because t("det.leg_reasoning") was never referenced. Add the swatch mirroring its siblings (color matches CAUSE_COLOR.rd = #8250df). --- src/web/client.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/web/client.ts b/src/web/client.ts index a1773eb8de..a03ffeb1d3 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -1349,6 +1349,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")) From 7e5708ebfce5e4104da739ed56213d7f94cbdd7b Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 16 Oct 2026 00:38:27 +0800 Subject: [PATCH 3/5] test: regenerate storage-render goldens for the two new ledger counters #3300 adds reasoningDropMisses/reasoningDropMissed to the cache-ledger agg, which persists inside session.metadata, so the digest-based storage-render snapshots drift (only the metadata section hash changes; state/blockContents/ stats unchanged). Regenerate via scripts/update-storage-render-goldens.ts. Additive, zero-default, backward-compatible fields (backfilled on load); no persistence version bump. --- tests/golden/storage-render/anthropic.json | 4 ++-- tests/golden/storage-render/chat.json | 4 ++-- tests/golden/storage-render/google.json | 4 ++-- tests/golden/storage-render/responses.json | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/golden/storage-render/anthropic.json b/tests/golden/storage-render/anthropic.json index 266b8df34e..4900728130 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": "96fe7ed64ee5067a41c42c88989f56ce4e77542423f5700b5c1bbf46450009f0", + "stateDigest": "68363b214d7a6da793a5928b2f3ed4ec001698a6fbbe5a825de54cf010b47da4", "sectionDigests": { "state": "5db7a736df3a3e5b", "blockContents": "dc7d13d250c94bb4", "stats": "d296e6929cff0970", - "metadata": "47410ac26797409c" + "metadata": "50b212234639b493" }, "stateKeyDigests": { "blocks": "1cbe172309e4490d", diff --git a/tests/golden/storage-render/chat.json b/tests/golden/storage-render/chat.json index e94243e68c..6efe109c4b 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": "169b3f2c63f523bf93b5409941adaa7e8eee43745ff855e560ce32395f417f75", + "stateDigest": "6ae9d3ba645075a011dade58db3ec9e8f0f7307f95fed8edf4c1617f2b74267e", "sectionDigests": { "state": "bba2f434570acbd2", "blockContents": "94a58f96d7c5cfc3", "stats": "0387e0a7f852af4e", - "metadata": "e668bd93e7435b67" + "metadata": "f89493a516a8613b" }, "stateKeyDigests": { "blocks": "9aa73e5fb9f93d6c", diff --git a/tests/golden/storage-render/google.json b/tests/golden/storage-render/google.json index 0637a6cb99..815e9fd554 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": "84d8e87180c4cf4dd9cc2e26234b62cb6a504b1c4dd4f3c73797c7286a4476ab", + "stateDigest": "617cb93e913125f29603586fa097ab731497570fc007eac36086569469b9d259", "sectionDigests": { "state": "6d2f312d7bc924d7", "blockContents": "473264d9df8ba338", "stats": "5702a6493cdfe768", - "metadata": "44253c0faed160f9" + "metadata": "f8123bcb3be47bbc" }, "stateKeyDigests": { "blocks": "8e14f0879bf7ebd7", diff --git a/tests/golden/storage-render/responses.json b/tests/golden/storage-render/responses.json index a4d9833212..12e6075d69 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": "13dfa2fc327ec2c292b20f373c10da4abc2712509103640f2227427d5f54db42", + "stateDigest": "64df387ffbe4b8dfed35a25a6307445798c0144d1a8e0401deadda92dbe823b8", "sectionDigests": { "state": "07823f2d3271c52a", "blockContents": "8460729b2654a816", "stats": "c21b1ef672b5274c", - "metadata": "9cd94af0e95aaafe" + "metadata": "165a77e25af8e60e" }, "stateKeyDigests": { "blocks": "7fff1dfb54a617cf", From 97ce469ef763594d10f71f11c4d13dcd1af7c365 Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 16 Oct 2026 03:49:07 +0800 Subject: [PATCH 4/5] fix(web): normalize seam.reasoningDrop defensively like its sibling buckets (#3198) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit detailSeam() tolerates servers predating each attribution bucket by defaulting absent fields to zero — the legend row added in 491d52a6d reads seam.reasoningDrop.count without that tolerance, so any payload whose seam lacks the field (test fixtures, older server builds) throws during loadDetail and the trajectory never binds (#2489 brush tests time out in waitFor). Add the missing normalization line; behavior for current server payloads is unchanged. --- src/web/client.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/web/client.ts b/src/web/client.ts index c80328fbaa..df6c992a9e 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -1081,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, }; } From 5fb81f6edf58ceb5f3e1a2c2a59e92450196d8d7 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Fri, 16 Oct 2026 09:55:50 +0800 Subject: [PATCH 5/5] test: regen storage-render goldens on merged tree --- tests/golden/storage-render/anthropic.json | 4 ++-- tests/golden/storage-render/chat.json | 4 ++-- tests/golden/storage-render/google.json | 4 ++-- tests/golden/storage-render/responses.json | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) 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",