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
33 changes: 30 additions & 3 deletions src/prefix-affinity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ import { createHash } from "node:crypto";
* usable conversation signal. Below it the request keeps the #286 400. */
const MIN_CANONICAL_BYTES = 24;

/** Upper bound on tracked chains (LRU-evicted, global — content is the
/** Upper bound on tracked chains (LRU-evicted, global — content is the
* only key, so there are no per-credential buckets). Chains are PERMANENT
* (#1724): the product promise is month- to year-level single sessions, so
Expand Down Expand Up @@ -149,6 +148,34 @@ function sortKeys(value: unknown): unknown {
return value;
}

/** Canonical form for IDENTITY hashing (#2188): sorted-key JSON with every
* `cache_control` field dropped. Claude Code stamps a `cache_control`
* breakpoint on its last message + last assistant message and MOVES them as
* the conversation grows, so a --resume/--fork replay of an earlier history
* differs from the parent's final live request ONLY by where those hints sit.
* They are transport-layer cache hints, not conversation content — hashing
* them made EVERY resume/fork miss findResumeParent (the shared prefix was no
* longer byte-stable across a breakpoint shift). Stripping them makes the
* identity chain invariant to breakpoint placement while still requiring the
* actual content to match byte-for-byte. */
function canonicalForHash(value: unknown): string {
return JSON.stringify(canonicalize(value));
}

function canonicalize(value: unknown): unknown {
if (Array.isArray(value)) return value.map(canonicalize);
if (value && typeof value === "object") {
const record = value as Record<string, unknown>;
const out: Record<string, unknown> = {};
for (const key of Object.keys(record).sort()) {
if (key === "cache_control") continue; // #2188: transport-layer hint, not content
out[key] = canonicalize(record[key]);
}
return out;
}
return value;
}

function sha256(text: string): string {
return createHash("sha256").update(text, "utf8").digest("hex");
}
Expand All @@ -163,7 +190,7 @@ function chainHashes(messages: unknown[]): string[] {
let prev = "";
let bytes = 0;
for (const message of messages) {
const canonical = stableStringify(message);
const canonical = canonicalForHash(message);
bytes += canonical.length;
prev = sha256(`${prev}\u0000${canonical}`);
hashes.push(prev);
Expand All @@ -176,7 +203,7 @@ function chainHashes(messages: unknown[]): string[] {
* cannot match across a truncation), these support lineage lookups: fork-LCP
* from index 0, and truncated-run detection strictly inside a stored chain. */
function perItemHashes(messages: unknown[]): string[] {
return messages.map((m) => sha256(stableStringify(m)));
return messages.map((m) => sha256(canonicalForHash(m)));
}

/** Length of the longest common prefix of two per-item hash arrays. */
Expand Down
57 changes: 57 additions & 0 deletions tests/prefix-affinity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,63 @@ test("prefix-affinity: equal-depth replay under a different id is NOT a resume (
assert.equal(r.findResumeParent(transcript, "sess-two"), null, "a byte-exact replay at the SAME depth under another id is a duplicate conversation, not a resume — linking it would adopt foreign blocks");
});

test("prefix-affinity: identity hash is invariant to cache_control placement (#2188)", () => {
const r = new PrefixAffinityResolver();
const base = [
{ role: "user", content: [{ type: "text", text: "hello there friend" }] },
{ role: "assistant", content: [{ type: "text", text: "hi, how can I help" }] },
];
const stamped = (where: number) => base.map((m, i) => ({
...m,
content: m.content.map((b, j) => (i === where && j === 0 ? { ...b, cache_control: { type: "ephemeral" } } : { ...b })),
}));
const f1 = r.chainFingerprint(stamped(1))!;
const f2 = r.chainFingerprint(stamped(0))!;
assert.equal(f1.tailHash, f2.tailHash, "moving a cache_control breakpoint must not change the identity chain");
assert.deepEqual(f1.itemHashes, f2.itemHashes, "per-item hashes must ignore cache_control too");
});

test("prefix-affinity: resume-fork survives a cache_control breakpoint shift (#2188)", () => {
const r = new PrefixAffinityResolver();
const mk = (role: "user" | "assistant", text: string, cc?: boolean) => ({
role,
content: [{ type: "text", text, ...(cc ? { cache_control: { type: "ephemeral" } } : {}) }],
});
// Parent's final LIVE request: 10 messages; Claude Code stamps cache_control
// on its trailing pair (last assistant message + last message).
const parentLive = [
mk("user", "parent turn 0 substance"),
mk("assistant", "parent reply 1"),
mk("user", "parent turn 2 substance"),
mk("assistant", "parent reply 3"),
mk("user", "parent turn 4 substance"),
mk("assistant", "parent reply 5"),
mk("user", "parent turn 6 substance"),
mk("assistant", "parent reply 7"),
mk("assistant", "parent reply 8", true),
mk("user", "parent turn 9 live prompt", true),
];
const fp = r.chainFingerprint(parentLive)!;
r.note("sess-parent", fp.depth, fp.tailHash, fp.itemHashes, true);
// Resume/fork replay of the SAME ten messages, but the breakpoints have
// moved past them (they are mid-history now, so they no longer carry
// cache_control); two fresh messages extend the tail, new breakpoint on it.
const stripCc = (m: ReturnType<typeof mk>) => ({
...m,
content: m.content.map((b) => { const c = { ...b }; delete c.cache_control; return c; }),
});
const childReplay = [
...parentLive.map(stripCc),
mk("assistant", "child reply after resume"),
mk("user", "child question after resume", true),
];
assert.deepEqual(
r.findResumeParent(childReplay, "sess-child"),
{ sessionId: "sess-parent", sharedDepth: 10 },
"a resume/fork differing from the parent ONLY by cache_control placement must still inherit",
);
});

test("prefix-affinity: anonymous resolution never adopts an identified chain (#1486 #309)", () => {
const r = new PrefixAffinityResolver();
const transcript = Array.from({ length: 10 }, (_, i) => user(`cross identity turn ${i} with substance`));
Expand Down
Loading