Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
32 changes: 22 additions & 10 deletions src/cache-ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -841,13 +841,16 @@ export function recordCacheSample(
// #2350: `prompt` sits between key and wire — a host system-prompt rewrite
// is more specific than a wire/upstream re-route and drops every downstream
// prefix cache entry just like a key rotation does.
const cause: "restart" | "model" | "key" | "prompt" | "wire" | "upstream" | null =
const freshCause: "restart" | "model" | "key" | "prompt" | "wire" | "upstream" | null =
restarted ? "restart"
: modelSwitched ? "model"
: keySwitched ? "key"
: promptSwitched ? "prompt"
: wireSwitched ? "wire"
: upstreamSwitched ? "upstream"
: null;
const cause: "restart" | "model" | "key" | "prompt" | "wire" | "upstream" | null =
freshCause !== null ? freshCause
: contWithin(led.invModel) ? "model"
: contWithin(led.invKey) ? "key"
: contWithin(led.invSp) ? "prompt"
Expand Down Expand Up @@ -896,15 +899,19 @@ export function recordCacheSample(
agg.nc += dec.newContent;
agg.cr += dec.compRepay;
agg.tr += dec.ttlRepay;
// Event counters fire whenever a dimension actually changed (or a restart boundary did) — independent
// of attribution, preserving the full from→to log. Token buckets charge EXACTLY the primary cause so
// the per-cause breakdown partitions the residual instead of overlapping it across dimensions.
if (modelSwitched) agg.switches += 1;
if (keySwitched) agg.keySwitches += 1;
if (promptSwitched) agg.promptSwitches += 1;
if (wireSwitched) agg.wireSwitches += 1;
if (upstreamSwitched) agg.upstreamSwitches += 1;
if (restarted) agg.restartDrops += 1;
// #2784: event counters follow the SAME rule as the token partition — one line, exactly ONE narrative
// cause. One user action often flips several identity dimensions at once (dsh's model switch re-renders
// the model name into its system prompt, so the prompt fingerprint flips on the SAME line as the model
// change); counting the shadowed dimensions narrates one action twice and the web panel renders them as
// independent zero-token causes ("prompt rewrite 0 x1"). The raw observation stays on the line itself
// (per-dimension flags + values + the winning cause), so forensics lose nothing. Token buckets charge
// EXACTLY the primary cause so the per-cause breakdown partitions the residual instead of overlapping it.
if (freshCause === "restart") agg.restartDrops += 1;
else if (freshCause === "model") agg.switches += 1;
else if (freshCause === "key") agg.keySwitches += 1;
else if (freshCause === "prompt") agg.promptSwitches += 1;
else if (freshCause === "wire") agg.wireSwitches += 1;
else if (freshCause === "upstream") agg.upstreamSwitches += 1;
if (cause === "model") agg.switchMissed += dec.ttlRepay;
else if (cause === "key") agg.keySwitchMissed += dec.ttlRepay;
else if (cause === "prompt") agg.promptSwitchMissed += dec.ttlRepay;
Expand Down Expand Up @@ -1268,6 +1275,11 @@ export function buildSessionCacheReport(session: Session): BiliCacheReport {
for (let i = 0; i < led.lines.length; i++) {
const l = led.lines[i];
if (!l || l.unk === 1 || !flag(l)) continue;
// #2784: only lines where THIS dimension won the partition are narrated as events — a flip
// shadowed by a higher-priority cause on the same line stays on the line itself (flag + value),
// not in the narrative list. Lines persisted pre-#1847 have no `cause` field: keep their
// historical display so old ledgers render as before.
if (l.cause !== undefined && l.cause !== dim) continue;
// #1847: from = the last KNOWN line strictly before this one (its value is the pre-switch
// identity) — scanning past intervening unmeasured lines keeps the pair intact when a
// switch straddles an unknown-cache boundary.
Expand Down
11 changes: 7 additions & 4 deletions tests/cache-ledger-key-switch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ test("a byte-identical re-note without headers inherits the prior fingerprint (#
assert.equal(l1.keyFp, keyA);
});

test("a model change outranks a co-occurring key change; the counters stay independent (#2131)", () => {
test("a model change outranks a co-occurring key change; the shadowed counter stays silent (#2131 #2784)", () => {
const session = makeSession();
session.metadata.lastModel = "glm-5.3";
const keyA = fp("sk-account-one");
Expand All @@ -143,10 +143,13 @@ test("a model change outranks a co-occurring key change; the counters stay indep
session.metadata.lastModel = "deepseek-v4.1";
turn(session, "b3", keyB, T0 + 3000, 11_000, 0);
const r = buildSessionCacheReport(session);
// Both dimensions OBSERVED the change (independent event counters)…
// ONE narrative cause per line (#2784): the model switch narrates it; the rotation that rode
// along on the same request no longer books its own zero-token event. The raw observation
// stays on the line itself (kw flag + fingerprint pair).
assert.equal(r.modelSwitches.count, 1);
assert.equal(r.keySwitches.count, 1);
// …but the partition charges the residual to the model only.
assert.equal(r.keySwitches.count, 0);
assert.deepEqual(r.keySwitches.events, []);
// The partition charges the residual to the model only.
assert.equal(r.modelSwitches.missedTokens, 10_500);
assert.equal(r.keySwitches.missedTokens, 0);
assert.equal(r.invalidation.model, 10_500);
Expand Down
47 changes: 41 additions & 6 deletions tests/cache-ledger-prompt-switch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
buildSessionCacheReport,
handleAcpCache,
noteForwardedBody,
readPromptSwitchStats,
settleUsageReport,
} from "../src/cache-ledger.ts";
import type { Session } from "../src/session.ts";
Expand All @@ -17,6 +18,7 @@ import type { Session } from "../src/session.ts";
const T0 = Date.parse("2026-10-07T02:40:00Z");
const FP_A = "aaaaaa1111bbbbbb";
const FP_B = "cccccc2222dddddd";
const FP_C = "eeeeee3333ffffff";

let seq = 0;
function makeSession(): Session {
Expand Down Expand Up @@ -127,41 +129,74 @@ test("lanes without a noted system never fabricate rewrite events (#2350 sparsen
assert.deepEqual(r.promptSwitches.events, []);
});

test("a model change outranks a co-occurring prompt rewrite; counters stay independent (#2350 priority)", () => {
test("a model change outranks a co-occurring prompt rewrite; the shadowed counter stays silent (#2350 #2784)", () => {
const session = makeSession();
session.metadata.lastModel = "gpt-6.1-sol";
turn(session, "b1", FP_A, T0 + 1000, 10_000, 9_000);
turn(session, "b2", FP_A, T0 + 2000, 10_500, 10_000);
session.metadata.lastModel = "glm-5.3";
turn(session, "b3", FP_B, T0 + 3000, 11_000, 0);
const r = buildSessionCacheReport(session);
// Both dimensions OBSERVED the change (independent event counters)…
// ONE narrative cause per line: the model switch narrates it; the fingerprint flip that rode
// along on the same request no longer books its own zero-token event (#2784).
assert.equal(r.modelSwitches.count, 1);
assert.equal(r.promptSwitches.count, 1);
// …but the partition charges the residual to the model only.
assert.equal(r.promptSwitches.count, 0);
assert.deepEqual(r.promptSwitches.events, []);
// The partition still charges the residual to the model only.
assert.equal(r.modelSwitches.missedTokens, 10_500);
assert.equal(r.promptSwitches.missedTokens, 0);
assert.equal(r.invalidation.model, 10_500);
assert.equal(r.invalidation.prompt, 0);
assert.equal(r.totals.residual, 0);
});

test("a prompt rewrite outranks a co-occurring wire switch (#2350 priority)", () => {
test("a prompt rewrite outranks a co-occurring wire switch; the shadowed counter stays silent (#2350 #2784)", () => {
const session = makeSession();
session.metadata.lastModel = "gpt-6.1-sol";
turn(session, "b1", FP_A, T0 + 1000, 10_000, 9_000, "openai");
turn(session, "b2", FP_A, T0 + 2000, 10_500, 10_000, "openai");
turn(session, "b3", FP_B, T0 + 3000, 11_000, 0, "anthropic");
const r = buildSessionCacheReport(session);
assert.equal(causeOf(session, 3), "prompt");
assert.equal(r.promptSwitches.count, 1);
assert.equal(r.wireSwitches.count, 1);
assert.equal(r.wireSwitches.count, 0);
assert.equal(r.promptSwitches.missedTokens, 10_500);
assert.equal(r.wireSwitches.missedTokens, 0);
assert.equal(r.invalidation.prompt, 10_500);
assert.equal(r.invalidation.wire, 0);
assert.equal(r.totals.residual, 0);
});

test("a dsh-style model switch narrates ONE cause; a later genuine rewrite still fires (#2784)", () => {
const session = makeSession();
session.metadata.lastModel = "deepseek-v4";
turn(session, "b1", FP_A, T0 + 1000, 10_000, 9_000);
turn(session, "b2", FP_A, T0 + 2000, 10_500, 10_000);
// dsh re-renders the active model into its system prompt on every switch: the
// fingerprint flips on the SAME request as the model change.
session.metadata.lastModel = "deepseek-v4-pro";
turn(session, "b3", FP_B, T0 + 3000, 11_000, 0);
const r = buildSessionCacheReport(session);
assert.equal(causeOf(session, 3), "model");
assert.equal(r.modelSwitches.count, 1);
assert.equal(r.modelSwitches.missedTokens, 10_500);
// No shadowed zero-token event → the web chip gate (count>0 || tokens>0) renders nothing.
assert.equal(readPromptSwitchStats(session)?.count, 0);
assert.equal(readPromptSwitchStats(session)?.missedTokens, 0);
// The raw observation survives on the line itself…
const led = (session.metadata as Record<string, { lines: Array<{ sf?: number }> }> & object)["cacheLedger"]!;
assert.equal(led.lines[2]!.sf, 1);
// …and the baseline advanced with it: a LATER genuine host rewrite still fires.
turn(session, "b4", FP_C, T0 + 4000, 11_500, 0);
const r2 = buildSessionCacheReport(session);
assert.equal(causeOf(session, 4), "prompt");
assert.equal(r2.promptSwitches.count, 1);
assert.equal(r2.modelSwitches.count, 1);
const ev = r2.promptSwitches.events[0]!;
assert.equal(ev.from, FP_B);
assert.equal(ev.to, FP_C);
});

test("handleAcpCache surfaces a PROMPT SWITCHES section with fingerprints only (#2350)", () => {
const session = makeSession();
session.metadata.lastModel = "gpt-6.1-sol";
Expand Down
7 changes: 4 additions & 3 deletions tests/cache-ledger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -688,10 +688,11 @@ test("per-cause buckets partition a multi-flag sample's residual (#1847)", () =>
const named = r.invalidation.model + r.invalidation.wire + r.invalidation.upstream + r.invalidation.restart;
assert.equal(named, r.totals.ttlRepay, "buckets are a partition: named + remaining closes exactly");
assert.equal(r.invalidation.remaining, 0);
// event counts still reflect every observed change (only the CHARGING is deduped)
// #2784: the counters follow the partition too — only the winning dimension (model)
// narrates the line; the wire/upstream flips stay visible on the line itself (flags + values).
assert.equal(r.modelSwitches.count, 1);
assert.equal(r.wireSwitches.count, 1);
assert.equal(r.upstreamSwitches.count, 1);
assert.equal(r.wireSwitches.count, 0);
assert.equal(r.upstreamSwitches.count, 0);
assert.equal(r.totals.balanced, true);
});

Expand Down
Loading