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
23 changes: 20 additions & 3 deletions src/cache-ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,21 @@ export const CALIBRATION_CLAMP_MAX = 4;
export const CALIBRATION_SAMPLE_WINDOW = 3;
const CALIBRATION_CONSISTENCY_RATIO = 2;

/** #2867/#2973: the canonical incoming system fp is a responses-LANE-ONLY
* classification input — its sole writer is prepare-responses'
* noteCanonicalSystemFingerprint. Session metadata persists across turns AND
* lanes, so a session that switched responses→anthropic/openai/google still
* carries the last responses request's fp in the slot. Gating on the CURRENT
* request's wire keeps every non-responses sample free of that stale value
* (feeding it would mis-bucket the #2867 host-rewrite-vs-proxy-projection
* attribution). Split out as a pure helper so the lane gate is unit-testable
* off-Windows. */
export function canonicalSysFpForSettle(session: Session, protocol?: string): string | undefined {
if (protocol !== "responses") return undefined;
const noted = session.metadata?.[METADATA_CANONICAL_SYS_FP] as { fp?: unknown } | undefined;
return typeof noted?.fp === "string" && noted.fp !== "" ? noted.fp : undefined;
}

export function settleUsageReport(
session: Session,
s: { total: number; reportedCached: number | null; output?: number; protocol?: string; upstream?: string },
Expand Down Expand Up @@ -1229,9 +1244,11 @@ export function settleUsageReport(
// #2867: the canonical incoming fingerprint + compression mode ride along so
// recordCacheSample can tell a host-side prompt rewrite from bili's own
// projection/mode switch (responses lane only; other lanes omit both).
const notedCanon = session.metadata?.[METADATA_CANONICAL_SYS_FP] as { fp?: unknown } | undefined;
const curCanonFp = typeof notedCanon?.fp === "string" && notedCanon.fp !== "" ? notedCanon.fp : undefined;
const lastMode = session.metadata?.[METADATA_LAST_RESPONSES_MODE] as unknown;
const curCanonFp = canonicalSysFpForSettle(session, s.protocol);
// Same lane-gate as the canon slot above: the mode stamp is written only by
// prepare-responses, so on a non-responses settle it would leak the last
// responses request's label into an inert-but-misleading line field.
const lastMode = s.protocol === "responses" ? (session.metadata?.[METADATA_LAST_RESPONSES_MODE] as unknown) : undefined;
const led = getCacheLedger(session);
recordCacheSample(session, { at: Date.now(), input: s.total, cached: s.reportedCached, output: s.output, protocol: s.protocol, upstream: s.upstream, keyFp: curKeyFp, sysFp: curSysFp, canonFp: curCanonFp, mode: lastMode === "plugin" || lastMode === "proxy" ? lastMode : undefined });
// #2131: per-call body-stability proof on the just-recorded line — the same
Expand Down
9 changes: 8 additions & 1 deletion src/dsh-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,16 @@ export function syncDshProfileManifestSpec(profileDir: string, installedVersion:
if (!m) return `non-version spec ${spec} respected`;
if (m[1] === installedVersion) return undefined; // already in step — no rewrite
deps[DSH_PACKAGE] = spec.startsWith("^") ? `^${installedVersion}` : installedVersion;
// #2972-M1: write atomically (tmp sibling + rename, same discipline as
// persist.ts #2674) — a crash/power-loss mid-write must leave the host-owned
// dsh manifest byte-identical, never a torn package.json that breaks dsh's
// plugin reconcile. The tmp sits beside the target (same volume ⇒ rename atomic).
const tmp = `${file}.${process.pid}.tmp`;
try {
fs.writeFileSync(file, JSON.stringify(doc, null, 2) + "\n");
fs.writeFileSync(tmp, JSON.stringify(doc, null, 2) + "\n");
fs.renameSync(tmp, file);
} catch (e) {
try { fs.rmSync(tmp, { force: true }); } catch { /* best-effort cleanup */ }
return `manifest write failed: ${e instanceof Error ? e.message : String(e)}`;
}
return undefined;
Expand Down
18 changes: 15 additions & 3 deletions src/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -694,14 +694,26 @@ interface HostManagedInstall {
// allowed to overwrite in place. Residual second-writer risk with the app's
// own manager is explicitly accepted by the owner; reverting means dropping
// this check.
function isDshDesktopBiliCopy(installDir: string, real: string, env: NodeJS.ProcessEnv): boolean {
const anchor = path.join(resolveDshHome(env), "profiles", DSH_DESKTOP_PROFILE).split(path.sep).join("/");
// #2972-L3: pure path-membership predicate split out so the case-sensitivity
// policy is unit-testable off-Windows. ci=true lowercases both sides (Windows
// paths are case-insensitive — a DSH_HOME spelled with different casing than the
// resolved install dir must still match, or the #2894 manifest sync is silently
// skipped and the copy is misread as pnpm-owned); ci=false stays byte-exact (POSIX).
export function dshDesktopCopyPathMatches(installDir: string, real: string, anchor: string, suffix: string, ci: boolean): boolean {
const a = ci ? anchor.toLowerCase() : anchor;
const suf = ci ? suffix.toLowerCase() : suffix;
return [installDir, real].some((dir) => {
const norm = dir.split(path.sep).join("/");
return norm.startsWith(anchor + "/") && norm.endsWith(`/node_modules/${DSH_PACKAGE}`);
const n = ci ? norm.toLowerCase() : norm;
return n.startsWith(a + "/") && n.endsWith(suf);
});
}

function isDshDesktopBiliCopy(installDir: string, real: string, env: NodeJS.ProcessEnv): boolean {
const anchor = path.join(resolveDshHome(env), "profiles", DSH_DESKTOP_PROFILE).split(path.sep).join("/");
return dshDesktopCopyPathMatches(installDir, real, anchor, `/node_modules/${DSH_PACKAGE}`, process.platform === "win32");
}

/** #1234/#2199: true when `installDir` is the OpenCode v2 plugin-manager CACHE
* copy of billion-context — under $XDG_CACHE_HOME/opencode (default
* ~/.cache/opencode) at .../node_modules/billion-context. A bare
Expand Down
59 changes: 49 additions & 10 deletions tests/cache-ledger-projection-switch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ function turn(
at: number,
total: number,
cached: number | null,
proto = "openai",
proto = "responses",
): void {
// Default wire is "responses": #2973 gates settle's canon/mode slot reads
// to that lane, so scenarios modeling the self-heal degrade must settle on
// it too. Non-responses lanes are passed explicitly where a test needs one.
// Production writes these in the wire prepare phase (prepare-responses:
// noteSystemPromptFingerprint + noteCanonicalSystemFingerprint + the
// lastResponsesMode stamp); settle reads them back under the lock.
Expand All @@ -58,7 +61,7 @@ function turn(
led.lines[led.lines.length - 1]!.at = at;
}

type Line = { seq: number; cause?: string; sf?: number; pf?: number; cf?: number; pm?: string };
type Line = { seq: number; cause?: string; sf?: number; pf?: number; cf?: number; pw?: number; pm?: string };
function lineOf(session: Session, n: number): Line {
const led = (session.metadata as Record<string, { lines: Line[] }> & object)["cacheLedger"]!;
return led.lines.find((l) => l.seq === n)!;
Expand Down Expand Up @@ -170,9 +173,9 @@ test("lanes without a canonical fingerprint keep the legacy host-side reading (#
session.metadata.lastModel = "gpt-6.1-sol";
// Non-responses lanes never write canonicalSysFp: an sp flip there is
// exactly what #2350 measured — attributed to the host as before.
turn(session, "b1", FP_A, undefined, undefined, T0 + 1000, 10_000, 9000);
turn(session, "b2", FP_A, undefined, undefined, T0 + 2000, 10_500, 10_000);
turn(session, "b3", FP_B, undefined, undefined, T0 + 3000, 11_000, 0);
turn(session, "b1", FP_A, undefined, undefined, T0 + 1000, 10_000, 9000, "anthropic");
turn(session, "b2", FP_A, undefined, undefined, T0 + 2000, 10_500, 10_000, "anthropic");
turn(session, "b3", FP_B, undefined, undefined, T0 + 3000, 11_000, 0, "anthropic");
assert.equal(lineOf(session, 3).cause, "prompt");
const r = buildSessionCacheReport(session);
assert.equal(r.promptSwitches.count, 1);
Expand All @@ -193,6 +196,32 @@ test("lanes without a canonical fingerprint keep the legacy host-side reading (#
assert.ok(led2.lines.every((l) => l.cf === undefined && l.pf === undefined));
});

test("a stale responses canon never leaks into a non-responses settle — host edit stays host-attributed (#2973)", () => {
const session = makeSession();
session.metadata.lastModel = "gpt-6.1-sol";
turn(session, "b1", FP_A, CANON, "plugin", T0 + 1000, 10_000, 9_000);
turn(session, "b2", FP_A, CANON, "plugin", T0 + 2000, 10_500, 10_000);
// The session switches off the responses wire; the metadata slots still
// carry the last responses request's canon fp + mode stamp. The host edits
// ITS system prompt on the anthropic wire: pre-#2973 the stale canon made
// settle read this as bili's own projection flip — now the legacy host
// reading wins, and neither slot value leaks onto the line.
turn(session, "b3", FP_B, undefined, undefined, T0 + 3000, 11_000, 0, "anthropic");
const l3 = lineOf(session, 3);
assert.equal(l3.cause, "prompt");
assert.equal(l3.sf, 1);
assert.equal(l3.pf, undefined);
assert.equal(l3.cf, undefined);
assert.equal(l3.pm, undefined); // stale mode slot must not leak either
const r = buildSessionCacheReport(session);
assert.equal(r.promptSwitches.count, 1);
assert.equal(r.projSwitches.count, 0);
assert.deepEqual(r.projSwitches.events, []);
assert.equal(r.invalidation.prompt, 10_500);
assert.equal(r.invalidation.projection, 0);
assert.equal(r.totals.balanced, true);
});

test("a model change outranks a co-occurring projection flip; the shadowed counter stays silent (#2867 #2784)", () => {
const session = makeSession();
session.metadata.lastModel = "gpt-6.1-sol";
Expand Down Expand Up @@ -223,18 +252,28 @@ test("a model change outranks a co-occurring projection flip; the shadowed count
test("a projection flip outranks a co-occurring wire switch (#2867)", () => {
const session = makeSession();
session.metadata.lastModel = "gpt-6.1-sol";
turn(session, "b1", FP_A, CANON, "plugin", T0 + 1000, 10_000, 9_000, "openai");
turn(session, "b2", FP_A, CANON, "plugin", T0 + 2000, 10_500, 10_000, "openai");
turn(session, "b3", FP_B, CANON, "proxy", T0 + 3000, 11_000, 0, "anthropic");
// A baseline on the responses wire anchors the canonical fp …
turn(session, "b1", FP_A, CANON, "plugin", T0 + 1000, 10_000, 9_000);
// … a detour off it …
turn(session, "b2", FP_A, undefined, undefined, T0 + 2000, 10_500, 10_000, "anthropic");
// … and the return-to-responses round co-fires the mode flip: the fresh
// change wins the line as projection; the wire flag stays observable on
// the line but its counter stays shadowed (#2784 one-line-one-cause).
turn(session, "b3", FP_B, CANON, "proxy", T0 + 3000, 11_000, 0);
const r = buildSessionCacheReport(session);
assert.equal(lineOf(session, 3).cause, "projection");
assert.equal(lineOf(session, 3).pf, 1);
assert.equal(lineOf(session, 3).pw, 1);
assert.equal(r.projSwitches.count, 1);
assert.equal(r.wireSwitches.count, 0);
assert.deepEqual(r.projSwitches.events.map((e) => [e.from, e.to]), [[FP_A, FP_B]]);
assert.equal(r.wireSwitches.count, 1); // b2's detour is its own event; b3's flag is shadowed
assert.equal(r.projSwitches.missedTokens, 10_500);
assert.equal(r.wireSwitches.missedTokens, 0);
assert.equal(r.wireSwitches.missedTokens, 0); // b2 was warm: no residual to charge
assert.equal(r.invalidation.projection, 10_500);
assert.equal(r.invalidation.wire, 0);
assert.equal(r.promptSwitches.count, 0);
assert.equal(r.totals.residual, 0);
assert.equal(r.totals.balanced, true);
});

test("handleAcpCache surfaces PROJECTION SWITCHES without blaming the host (#2867)", () => {
Expand Down
21 changes: 20 additions & 1 deletion tests/cache-ledger.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { buildCacheReport, type CacheSample, type FoldEvent, type CompressionBlock } from "acp-kernel";
import { buildSessionCacheReport, getCacheLedger, handleAcpCache, recordCacheFoldsFromBlocks, recordCacheSample, settleUsageReport } from "../src/cache-ledger.ts";
import { buildSessionCacheReport, canonicalSysFpForSettle, getCacheLedger, handleAcpCache, recordCacheFoldsFromBlocks, recordCacheSample, settleUsageReport } from "../src/cache-ledger.ts";
import { METADATA_CANONICAL_SYS_FP } from "../src/fold-reconcile.ts";
import type { Session } from "../src/session.ts";

let seq = 0;
Expand Down Expand Up @@ -786,3 +787,21 @@ test("pre-#1847 ledger lines keep their historical per-event attribution (#1847)
assert.equal(r.modelSwitches.events[0].attributed, 40000, "legacy sw line keeps its historical charge display");
assert.doesNotMatch(handleAcpCache(session).text, /cold rounds/, "legacy charge is not mislabeled as post-switch cold tail");
});

test("canonicalSysFpForSettle is gated to the responses wire only (#2973)", () => {
// A session that ran on responses then switched lanes still holds the last
// responses request's fp in the persisted metadata slot — that stale value
// must NOT leak into non-responses settles (#2973 / #2867 attribution).
const session = makeSession();
session.metadata[METADATA_CANONICAL_SYS_FP] = { fp: "deadbeefcafe1234", size: 12 };
assert.equal(canonicalSysFpForSettle(session, "responses"), "deadbeefcafe1234");
assert.equal(canonicalSysFpForSettle(session, "anthropic"), undefined, "anthropic settle must not carry the stale responses fp");
assert.equal(canonicalSysFpForSettle(session, "openai"), undefined);
assert.equal(canonicalSysFpForSettle(session, "google"), undefined);
assert.equal(canonicalSysFpForSettle(session, undefined), undefined);
// Empty/absent slot yields nothing even on responses.
const empty = makeSession();
empty.metadata[METADATA_CANONICAL_SYS_FP] = { fp: "", size: 0 };
assert.equal(canonicalSysFpForSettle(empty, "responses"), undefined);
assert.equal(canonicalSysFpForSettle(makeSession(), "responses"), undefined);
});
31 changes: 30 additions & 1 deletion tests/update-desktop-inplace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import * as tar from "tar";
// discipline as update-backoff.test.ts).
const __cacheRoot = mkdtempSync(path.join(tmpdir(), "bc-desktop-inplace-cache-"));
process.env.XDG_CACHE_HOME = path.join(__cacheRoot, "cache");
const { installViaTarball, readDiskVersion, refreshDshDesktopCopy } = await import("../src/update.ts");
const { installViaTarball, readDiskVersion, refreshDshDesktopCopy, dshDesktopCopyPathMatches } = await import("../src/update.ts");
import { refreshDshProfileBundles, syncDshProfileManifestSpec } from "../src/dsh-channel.ts";
import { rmrf } from "./tmp-rm.ts";

Expand Down Expand Up @@ -361,3 +361,32 @@ test("syncDshProfileManifestSpec: style-preserving convergence, pins and odd spe
rmrf(root);
}
});

test("syncDshProfileManifestSpec writes atomically — converges and leaves no orphan tmp (#2972-M1)", () => {
const root = mkdtempSync(path.join(tmpdir(), "bc-desktop-atomic-"));
try {
const dir = mkdtempSync(path.join(root, "profile-"));
writeFileSync(path.join(dir, "package.json"), JSON.stringify({ name: "@dsh/profile-test", dependencies: { "billion-context": "^0.1.195" } }, null, 2) + "\n");
assert.equal(syncDshProfileManifestSpec(dir, "0.1.196"), undefined);
assert.equal((JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")) as { dependencies: Record<string, string> }).dependencies["billion-context"], "^0.1.196");
assert.ok(!readdirSync(dir).some((f) => f.endsWith(".tmp")), `orphan tmp file left in ${dir}`);
} finally {
rmrf(root);
}
});

test("dshDesktopCopyPathMatches honors Windows case-insensitivity (#2972-L3)", () => {
const anchor = "/home/u/.dsh/profiles/desktop";
const suffix = "/node_modules/billion-context";
const hit = "/home/u/.dsh/profiles/desktop/node_modules/billion-context";
// POSIX (ci=false): byte-exact — exact case matches; a mismatched case on
// BOTH candidate paths does not (only one matching path is enough to hit).
assert.equal(dshDesktopCopyPathMatches(hit, hit, anchor, suffix, false), true);
assert.equal(dshDesktopCopyPathMatches("/HOME/U/.DSH/profiles/Desktop/node_modules/billion-context", "/HOME/U/.DSH/profiles/Desktop/node_modules/billion-context", anchor, suffix, false), false);
// Windows (ci=true): case must NOT matter — a DSH_HOME spelled differently still matches.
assert.equal(dshDesktopCopyPathMatches(hit, hit, "/HOME/U/.DSH/profiles/Desktop", suffix, true), true);
assert.equal(dshDesktopCopyPathMatches("/HOME/U/.DSH/profiles/Desktop/node_modules/billion-context", hit, "/home/u/.dsh/profiles/desktop", suffix, true), true);
// `real` (resolved symlink) matching also counts; non-members never match.
assert.equal(dshDesktopCopyPathMatches("/nope", hit, anchor, suffix, false), true);
assert.equal(dshDesktopCopyPathMatches("/elsewhere/a", "/elsewhere/b", anchor, suffix, true), false);
});
Loading