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 b862723ab5..c4b88a73a1 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"; @@ -213,6 +214,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 94fadf9083..ecda609205 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"; @@ -166,6 +167,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 0cb8b37fa5..34ac75152c 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -6,6 +6,7 @@ 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 { 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,6 +273,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 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..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); +}); 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",