From 1b7e38020366801b0b452a2717f5d22fda6a4e5e Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sun, 11 Oct 2026 23:21:08 +0800 Subject: [PATCH] fix(affinity): append-continuation rung + hv2 ladder preference (#2807 regressions) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #2807 made the anonymous/identified identity chains hash the wire-NEUTRAL projection. That exposed three regressions (all three failing legs on the v0.1.193 release PR #2767): 1. The neutral projection MERGES a run of consecutive same-role messages into one turn (required for cross-wire equality — the anthropic render joins the run). A client that APPENDS another assistant message after an assistant tail (agent harnesses replaying model replies, fork follow-ups) re-renders the stored tail turn, so its item hash changes and the exact ladder fails by ONE item → fresh pfa-* mint → the fold ledger and the usage anchor are orphaned (spurious fork-of-fork children in fork-adoption-wires, 58701-vs-5000 sizing in issue2033-anonymous-anchor). Fix: per-source-message tail FRAGMENTS (fragmentHash) are now carried on every NeutralTurn, persisted on the chain (ChainEntry.tailFrags, snapshot round-trip included) and forwarded through note() from all resolve() paths. New rung 1.4 (append-continuation): a stored hv2 chain whose first K-1 items are byte-equal AND whose stored tail fragments are a strict PREFIX of the incoming turn-at-K-1 fragments is the same conversation extended in place → match instead of mint. 2. The v1 (pre-#2791 raw-wire) fallback rung could OUT-VOTE a matching hv2 chain by raw depth (raw counts MESSAGES, neutral counts TURNS — 16 vs 13 for the same history) and steal the request to a stale pre-upgrade duplicate session. Any user upgrading 0.1.192 → 0.1.193 hits this seam on their first post-upgrade request. Fix: within the ladder, hv2 candidates now take precedence over hv1; hv1 still resolves untouched when no neutral chain matches (legacy bridge). 3. Image placeholder text blocks were joined with "" into the neutral text, so the USER_IMAGE_PLACEHOLDER line filter could not strip them (issue2601 filter-branch replay). Placeholder blocks/parts are now dropped during neutral-text collection. Local: full targeted affinity sweep (27 suites) green; failing trio green. --- src/affinity-neutral.ts | 87 +++++++++++++++++++++++-------- src/prefix-affinity.ts | 111 ++++++++++++++++++++++++++++++++++++++-- src/server/handle.ts | 4 +- 3 files changed, 174 insertions(+), 28 deletions(-) diff --git a/src/affinity-neutral.ts b/src/affinity-neutral.ts index 944f700162..59c44b58cc 100644 --- a/src/affinity-neutral.ts +++ b/src/affinity-neutral.ts @@ -1,3 +1,6 @@ +import { createHash } from "node:crypto"; +import { USER_IMAGE_PLACEHOLDER } from "./fold-reconcile.js"; + /** * #2791: wire-neutral affinity projection. * @@ -47,6 +50,10 @@ * - client synthetic markers (dsh "[model changed: …]" user turns — * machinery notices, not user words) are dropped, same discipline as the * #1148 leading system run and the #2636 placeholder lines. + * - image-capability placeholder text blocks (#2636) are dropped from the + * turn text — the placeholder rides the tail on vision-capable renders + * only, so keeping it would fork identity on a capability switch (the + * #2601 line filter lifted into the neutral domain). * - google `contents[].parts[]` and responses `input[]` item shapes map to * the same turns; anything unrecognized falls back to canonical JSON of * the raw item (same-wire replays stay byte-stable even when a shape is @@ -58,8 +65,32 @@ * content still hashes differently — nothing here weakens the #1115/#629 * anti-adoption discipline (ownership still rests on the user's own words * and, for adoption, the #2265 anchor gate). + * + * #2807 append-stability: merging a consecutive assistant run into ONE + * turn makes the projection append-UNstable at the tail — a client that + * appends another assistant message after an assistant tail rewrites the + * stored tail turn's hash (solo turn → extended run) and the exact prefix + * ladder in prefix-affinity.ts fails by one item. Each turn therefore also + * carries `frags`: the per-SOURCE-MESSAGE fragment hashes it was built + * from (one fragment per message that contributed to the turn). The + * resolver's continuation rung uses them to recognize an in-place extension + * (stored tail fragments ⊂ incoming tail fragments) without weakening the + * byte-exact bar anywhere else. Capped at MAX_TURN_FRAGS per turn. */ +/** Fragment cap per turn — runs longer than this keep their FIRST + * fragments (prefix discipline: the continuation rung only ever asks + * whether the stored fragment list is a prefix of the incoming one). */ +export const MAX_TURN_FRAGS = 64; + +/** Fragment hash of ONE source message's neutral contribution to its turn + * (kind included — an assistant fragment never equals a user fragment of + * the same text). Deterministic per message, independent of neighbors — + * that is the whole point (#2807). */ +function fragmentHash(kind: string, text: string, calls: string[]): string { + return createHash("sha256").update(`v2f\u0000${canon({ calls, kind, text })}`).digest("hex"); +} + /** dsh-llm-pi-ai injects this notice into the transcript when the user * switches model mid-session ("[model changed: assistant turns above this * point were generated by glm-5.3; the session continues with glm-5.2]"). @@ -90,6 +121,11 @@ export interface NeutralTurn { text?: string; /** Assistant tool calls: `name\u0000canonicalJson(args)`, transcript order. */ calls?: string[]; + /** #2807: per-source-message fragment hashes this turn was built from + * (one per contributing message, transcript order, capped). Lets the + * resolver recognize a tail turn that GREW by an appended same-role + * message without re-hashing the chain. */ + frags?: string[]; } /** Deterministic JSON with recursively sorted keys (same discipline as @@ -157,26 +193,29 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] { const list = stripLeadingSystemRun(messages); const turns: NeutralTurn[] = []; let asst: NeutralTurn | null = null; + let asstFrags: string[] = []; const flushAssistant = (): void => { if (asst === null) return; if (asst.calls !== undefined && asst.calls.length === 0) { // no calls after all → plain assistant text turn - asst = { kind: "assistant", text: asst.text ?? "" }; + asst = { kind: "assistant", text: asst.text ?? "", frags: asstFrags.slice(0, MAX_TURN_FRAGS) }; } else if (asst.calls !== undefined) { // thinking text is renderer-divergent on tool turns — dropped delete asst.text; + asst.frags = asstFrags.slice(0, MAX_TURN_FRAGS); } turns.push(asst); asst = null; + asstFrags = []; }; - const pushTextTurn = (kind: string, text: string): void => { + const pushTextTurn = (kind: string, text: string, frags?: string[]): void => { if (kind === "user" && CLIENT_MARKER_RE.test(text)) return; // client machinery - turns.push({ kind, text }); + turns.push({ kind, text, ...(frags ? { frags } : {}) }); }; for (const message of list) { if (!message || typeof message !== "object") { - turns.push({ kind: "raw", text: canon(message) }); + turns.push({ kind: "raw", text: canon(message), frags: [fragmentHash("raw", canon(message), [])] }); continue; } const m = message as { @@ -203,7 +242,7 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] { for (const part of m.parts) { if (!part || typeof part !== "object") continue; const p = part as { text?: unknown; functionCall?: unknown; functionResponse?: unknown }; - if (typeof p.text === "string") texts.push(p.text); + if (typeof p.text === "string" && p.text !== USER_IMAGE_PLACEHOLDER) texts.push(p.text); if (p.functionCall && typeof p.functionCall === "object") { const fc = p.functionCall as { name?: unknown; args?: unknown }; calls.push(`${String(fc.name ?? "")}\u0000${canon(fc.args ?? {})}`); @@ -212,9 +251,9 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] { toolBody = canon((p.functionResponse as { response?: unknown }).response ?? p.functionResponse); } } - if (toolBody !== undefined) turns.push({ kind: "tool", text: toolBody }); - if (calls.length > 0) turns.push({ kind: "assistant", calls }); - else if (texts.length > 0) pushTextTurn(role, texts.join("")); + if (toolBody !== undefined) turns.push({ kind: "tool", text: toolBody, frags: [fragmentHash("tool", toolBody, [])] }); + if (calls.length > 0) turns.push({ kind: "assistant", calls, frags: [fragmentHash("assistant", "", calls)] }); + else if (texts.length > 0) pushTextTurn(role, texts.join(""), [fragmentHash(role, texts.join(""), [])]); continue; } @@ -222,12 +261,14 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] { // {type:"function_call_output", …} arrive as siblings of messages. if (typeof m.type === "string" && m.type === "function_call" && typeof m.name === "string") { flushAssistant(); - turns.push({ kind: "assistant", calls: [`${m.name}\u0000${canonicalCallArgs(m.arguments)}`] }); + const call = `${m.name}\u0000${canonicalCallArgs(m.arguments)}`; + turns.push({ kind: "assistant", calls: [call], frags: [fragmentHash("assistant", "", [call])] }); continue; } if (typeof m.type === "string" && (m.type === "function_call_output" || m.type === "local_shell_call_output")) { flushAssistant(); - turns.push({ kind: "tool", text: typeof m.output === "string" ? m.output : canon(m.output ?? "") }); + const body = typeof m.output === "string" ? m.output : canon(m.output ?? ""); + turns.push({ kind: "tool", text: body, frags: [fragmentHash("tool", body, [])] }); continue; } @@ -239,7 +280,7 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] { const body = typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content.map((b) => { const t = blockText(b); return t !== null ? t : canon(b); }).join("") : m.content === undefined || m.content === null ? "" : canon(m.content); - turns.push({ kind: "tool", text: body }); + turns.push({ kind: "tool", text: body, frags: [fragmentHash("tool", body, [])] }); continue; } @@ -253,12 +294,13 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] { const text = m.content ?? ""; if (role === "assistant") { asst = asst ?? { kind: "assistant", text: "", calls: [] }; - asst.text = (asst.text ?? "") + text; - if (typeof m.reasoning_content === "string") asst.text += m.reasoning_content; + const own = text + (typeof m.reasoning_content === "string" ? m.reasoning_content : ""); + asst.text = (asst.text ?? "") + own; + asstFrags.push(fragmentHash("assistant", own, [])); continue; } flushAssistant(); - pushTextTurn(role, text); + pushTextTurn(role, text, [fragmentHash(role, text, [])]); continue; } @@ -277,22 +319,24 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] { results.push(toolResultText(b.content)); } else { const t = blockText(b); + if (t === USER_IMAGE_PLACEHOLDER) continue; // #2636 capability churn — machinery, not content if (t !== null) texts.push(t); else foreign = true; // image/document/etc — canonicalize whole block below } } if (role === "assistant") { asst = asst ?? { kind: "assistant", text: "", calls: [] }; - asst.text = (asst.text ?? "") + texts.join(""); + const ownText = texts.join("") + (foreign ? "\u0000foreign:" + canon(m.content) : ""); + asst.text = (asst.text ?? "") + ownText; asst.calls = [...(asst.calls ?? []), ...calls]; - if (foreign) asst.text += "\u0000foreign:" + canon(m.content); + asstFrags.push(fragmentHash("assistant", ownText, calls)); continue; } flushAssistant(); - for (const r of results) turns.push({ kind: "tool", text: r }); // split multi-result messages - if (results.length > 0 && texts.length > 0 && role === "user") pushTextTurn("user", texts.join("")); - else if (results.length === 0 && texts.length > 0) pushTextTurn(role, texts.join("")); - else if (results.length === 0 && texts.length === 0 && role === "user" && foreign) pushTextTurn("user", canon(m.content)); + for (const r of results) turns.push({ kind: "tool", text: r, frags: [fragmentHash("tool", r, [])] }); // split multi-result messages + if (results.length > 0 && texts.length > 0 && role === "user") pushTextTurn("user", texts.join(""), [fragmentHash("user", texts.join(""), [])]); + else if (results.length === 0 && texts.length > 0) pushTextTurn(role, texts.join(""), [fragmentHash(role, texts.join(""), [])]); + else if (results.length === 0 && texts.length === 0 && role === "user" && foreign) pushTextTurn("user", canon(m.content), [fragmentHash("user", canon(m.content), [])]); continue; } @@ -304,13 +348,14 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] { .filter((tc): tc is { function?: { name?: unknown; arguments?: unknown } } => !!tc && typeof tc === "object") .map((tc) => `${String(tc.function?.name ?? "")}\u0000${canonicalCallArgs(tc.function?.arguments)}`); asst.calls = [...(asst.calls ?? []), ...calls]; + asstFrags.push(fragmentHash("assistant", "", calls)); continue; } } // unrecognized shape — canonical JSON keeps same-wire replays stable flushAssistant(); - turns.push({ kind: role, text: canon(m) }); + turns.push({ kind: role, text: canon(m), frags: [fragmentHash(role, canon(m), [])] }); } flushAssistant(); return turns; diff --git a/src/prefix-affinity.ts b/src/prefix-affinity.ts index dac7879fdd..fe54f58df8 100644 --- a/src/prefix-affinity.ts +++ b/src/prefix-affinity.ts @@ -1,6 +1,6 @@ import { createHash } from "node:crypto"; import { hammingHex, sketchForCanonical } from "./affinity-simhash.js"; -import { neutralTurnCanonical, neutralTurns, type NeutralTurn } from "./affinity-neutral.js"; +import { MAX_TURN_FRAGS, neutralTurnCanonical, neutralTurns, type NeutralTurn } from "./affinity-neutral.js"; import { USER_IMAGE_PLACEHOLDER, normalizeMessageText } from "./fold-reconcile.js"; /** @@ -124,6 +124,13 @@ export interface AnonymousAffinity { userFlags?: boolean[]; /** #2265: alignment statistics when via === "simhash" (observability). */ adoption?: { coverage: number; meanHamming: number }; + /** #2807: fragment hashes of the INCOMING list's final turn (one per + * source message, capped) — forwarded to note() so the stored chain + * can serve the append-continuation rung on its next request (a tail + * turn extended by an appended same-role message rewrites the tail + * hash; the fragments are the stable witness of what the tail was + * built from). See affinity-neutral.ts. */ + tailFragments?: string[]; /** Lineage for a NEW session: the discarded match candidates and why they * were abandoned. Recorded for UI/debug only — NEVER used for matching. */ lineage?: { parents: string[]; reason: "truncated" | "forked"; sharedPrefix?: number }; @@ -220,6 +227,13 @@ interface ChainEntry { * at user positions — user words are the conversation's fingerprint, * harness machinery is not. Present iff sketches are. */ userFlags?: boolean[]; + /** #2807: fragment hashes of the chain's FINAL turn (one per + * source message it was merged from, capped at MAX_TURN_FRAGS). The + * append-continuation rung in resolve() uses them to recognize a tail + * turn that GREW by an appended same-role message (see + * affinity-neutral.ts) — absent on chains noted before #2807, which + * simply keep exact-ladder behavior. */ + tailFrags?: string[]; } /** On-disk snapshot entry (#499 P1a): the tracked chains persisted across @@ -243,6 +257,8 @@ export interface AffinitySnapshotEntry { userFlags?: boolean[]; /** #2601: normalized tail fingerprint (see ChainEntry.normTailHash). */ normTailHash?: string; + /** #2807: tail-turn fragment hashes (see ChainEntry.tailFrags). */ + tailFrags?: string[]; } /** Deterministic JSON with recursively sorted object keys, so two replays @@ -548,12 +564,22 @@ export class PrefixAffinityResolver { const incUserFlags = fingerprints.userFlags; const storedItemHashes = incItemHashes.slice(-MAX_STORED_ITEMS); const tracked = this.trackedChains; + const tailFragments = turns.length > 0 ? turns[turns.length - 1]!.frags : undefined; // 1. Full-depth prefix match (the original radix-style resolution). // #2791: each candidate is judged in the hash domain it was // noted in — hv2 chains against the neutral chain hashes, // legacy hv1 chains against the raw-wire ones (both computed // above; the domains cannot collide, they are seeded apart). + // When BOTH domains carry a matching chain (an hv2 hit exists), + // the hv2 hit WINS regardless of raw depth: the conversation has + // already re-noted neutrally, so the hv1 copy is a stale + // pre-upgrade duplicate of the SAME conversation — its sessionId + // (pfa-) diverges from the live neutral one and would + // otherwise steal the request away from the session holding the + // fold ledger and the usage anchor. hv1 chains still resolve + // untouched when no neutral chain matches (the legacy bridge + // first post-upgrade request). let best: ChainEntry | undefined; for (const entry of tracked.values()) { if (entry.identified) continue; @@ -564,7 +590,10 @@ export class PrefixAffinityResolver { if (v1Depth === 0 || entry.depth > v1Depth) continue; if (v1Hashes[entry.depth - 1] !== entry.tailHash) continue; } - if (!best || entry.depth > best.depth || (entry.depth === best.depth && entry.lastSeen > best.lastSeen)) best = entry; + const better = !best + || (entry.hv === 2 && best.hv === 1) + || (entry.hv === best.hv && (entry.depth > best.depth || (entry.depth === best.depth && entry.lastSeen > best.lastSeen))); + if (better) best = entry; } if (best) { return { @@ -577,9 +606,70 @@ export class PrefixAffinityResolver { itemHashes: storedItemHashes, sketches: incSketches, userFlags: incUserFlags.slice(-MAX_STORED_ITEMS), + ...(tailFragments ? { tailFragments } : {}), }; } + // 1.4 #2807 append-continuation: the neutral projection MERGES a run + // of consecutive assistant messages into ONE turn (cross-wire + // equality — the anthropic render joins the run into a single + // message). The merge makes the projection append-UNstable at + // exactly one place: a client that APPENDS another assistant + // message after an assistant tail (a harness hard-coding model + // replies, a multi-step agent) re-renders the stored tail turn as + // an extended run, so the tail item's hash changes and the exact + // ladder above fails by ONE item — minting a fresh pfa-* session, + // orphaning the fold ledger and the usage anchor (the #2767 CI + // regressions: spurious fork-of-fork children, anchor-sized + // session re-folding). Continuation rule: a stored hv2 chain + // whose first K-1 per-item hashes are byte-equal AND whose + // stored tail FRAGMENTS (per-source-message hashes of its final + // turn) are a strict PREFIX of the incoming turn-at-K-1's + // fragments is the same conversation extended in place — match + // it; note() re-anchors tail hash, fragments and depth. A + // cross-wire boundary extension still mints (fragment split is + // wire-shaped) — same as before #2807, no adoption discipline + // is weakened: ownership still rests on byte-exact items plus + // the user-visible content of the tail run. + if (incomingDepth >= 2) { + let cont: ChainEntry | undefined; + for (const entry of tracked.values()) { + if (entry.identified || entry.hv !== 2) continue; + const storedFrags = entry.tailFrags; + if (storedFrags === undefined || storedFrags.length === 0) continue; + const depth = entry.depth; + if (depth < 2 || depth > MAX_STORED_ITEMS || incomingDepth < depth + 1) continue; + // K ≤ MAX_STORED_ITEMS → entry.itemHashes are positions 0..K-1 + let eq = true; + for (let i = 0; i < depth - 1; i++) { + if (incItemHashes[i] !== entry.itemHashes[i]) { eq = false; break; } + } + if (!eq) continue; + const incFrags = turns[depth - 1]?.frags; + if (incFrags === undefined || incFrags.length <= storedFrags.length) continue; + let prefix = true; + for (let i = 0; i < storedFrags.length; i++) { + if (incFrags[i] !== storedFrags[i]) { prefix = false; break; } + } + if (!prefix) continue; + if (!cont || depth > cont.depth || (depth === cont.depth && entry.lastSeen > cont.lastSeen)) cont = entry; + } + if (cont) { + return { + sessionId: cont.sessionId, + matchedDepth: cont.depth - 1, + storedDepth: cont.depth, + incomingDepth, + tailHash, + via: "prefix", + itemHashes: storedItemHashes, + sketches: incSketches, + userFlags: incUserFlags.slice(-MAX_STORED_ITEMS), + ...(tailFragments ? { tailFragments } : {}), + }; + } + } + // 1.5 #2265 simhash chain alignment — before minting fresh, try to // recognize the incoming list as a NEAR-SIMILAR REWRITE of a // tracked chain: same length (or a short tail append), every @@ -608,6 +698,7 @@ export class PrefixAffinityResolver { sketches: incSketches, userFlags: incUserFlags.slice(-MAX_STORED_ITEMS), adoption: { coverage: adopted.coverage, meanHamming: adopted.meanHamming }, + ...(tailFragments ? { tailFragments } : {}), }; } } @@ -670,6 +761,7 @@ export class PrefixAffinityResolver { itemHashes: storedItemHashes, sketches: incSketches, userFlags: incUserFlags.slice(-MAX_STORED_ITEMS), + ...(tailFragments ? { tailFragments } : {}), ...(lineage ? { lineage } : {}), ...(orphanSuspect ? { orphanSuspect } : {}), }; @@ -780,12 +872,12 @@ export class PrefixAffinityResolver { * #2791: note() always re-anchors on the WIRE-NEUTRAL hash domain * (hv2) — an entry that matched through the v1 fallback rung upgrades * here, so the legacy domain decays away as sessions return. */ - note(sessionId: string, depth: number, tailHash: string, itemHashes: string[], identified = false, sketches?: string[], userFlags?: boolean[], normTailHash?: string): void { + note(sessionId: string, depth: number, tailHash: string, itemHashes: string[], identified = false, sketches?: string[], userFlags?: boolean[], normTailHash?: string, tailFrags?: string[]): void { const tracked = this.trackedChains; tracked.delete(sessionId); const storedSketches = !identified && sketches && sketches.length > 0 ? sketches.slice(0, SKETCH_MAX_DEPTH) : undefined; const storedUsers = storedSketches !== undefined && userFlags && userFlags.length > 0 ? userFlags.slice(-MAX_STORED_ITEMS) : undefined; - tracked.set(sessionId, { sessionId, hv: 2, depth, tailHash, itemHashes, lastSeen: Date.now(), identified, sketches: storedSketches, userFlags: storedUsers, ...(normTailHash ? { normTailHash } : {}) }); + tracked.set(sessionId, { sessionId, hv: 2, depth, tailHash, itemHashes, lastSeen: Date.now(), identified, sketches: storedSketches, userFlags: storedUsers, ...(normTailHash ? { normTailHash } : {}), ...(tailFrags && tailFrags.length > 0 ? { tailFrags: tailFrags.slice(0, MAX_TURN_FRAGS) } : {}) }); // #2265 sketch retention: bound how many chains carry sketches. A // fresh note re-anchors the winner, so an eviction from the sketch // window only degrades that chain to exact-hash resolution. @@ -823,7 +915,7 @@ export class PrefixAffinityResolver { * the building block for tracking identified sessions and for * resume-fork detection. Null when the request is degenerate (below * MIN_CANONICAL_BYTES, no user message). */ - chainFingerprint(messages: unknown[]): { depth: number; tailHash: string; itemHashes: string[]; normTailHash?: string } | null { + chainFingerprint(messages: unknown[]): { depth: number; tailHash: string; itemHashes: string[]; normTailHash?: string; tailFrags?: string[] } | null { if (!hasUserMessage(normalizeAffinityMessages(messages))) return null; // #2791: identified-session chains fingerprint in the WIRE-NEUTRAL // domain — a CC resume-fork re-rendered across protocols (or a @@ -836,6 +928,7 @@ export class PrefixAffinityResolver { tailHash: fingerprints.hashes[fingerprints.hashes.length - 1]!, itemHashes: fingerprints.itemHashes.slice(-MAX_STORED_ITEMS), normTailHash: neutralTailHashOf(turns), + ...(turns[turns.length - 1]?.frags ? { tailFrags: turns[turns.length - 1]!.frags } : {}), }; } @@ -952,6 +1045,7 @@ export class PrefixAffinityResolver { lastSeen: e.lastSeen, identified: e.identified, ...(e.normTailHash ? { normTailHash: e.normTailHash } : {}), + ...(e.tailFrags && e.tailFrags.length > 0 ? { tailFrags: e.tailFrags } : {}), ...(e.sketches ? { sketches: e.sketches, ...(e.userFlags ? { userFlags: e.userFlags } : {}) } : {}), })); } @@ -1004,6 +1098,13 @@ export class PrefixAffinityResolver { ...(typeof e.normTailHash === "string" && /^[0-9a-f]{64}$/.test(e.normTailHash) ? { normTailHash: e.normTailHash } : {}), ...(userFlags ? { userFlags } : {}), }; + // #2807: optional tail-turn fragments for the append-continuation + // rung — hv2 only (a v1 entry's fragments were never noted), + // malformed lists degrade the entry to exact-ladder behavior. + if (hv === 2 && Array.isArray(e.tailFrags)) { + const validF = (e.tailFrags as unknown[]).filter((f): f is string => typeof f === "string" && /^[0-9a-f]{64}$/.test(f)); + if (validF.length > 0) entry.tailFrags = validF.slice(0, MAX_TURN_FRAGS); + } this.trackedChains.delete(entry.sessionId); this.trackedChains.set(entry.sessionId, entry); imported++; diff --git a/src/server/handle.ts b/src/server/handle.ts index 75a4189532..c6871d7c9f 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -1117,7 +1117,7 @@ async function handleRequest( session.metadata.rawInputTokens = estimateRawBodyTokens(parsed) + imageTokensInParsedBody(protocol, parsed, imageBillingFor(opts, upstreamOrigin), imageTokenCapFor(opts, upstreamOrigin)); } if (anonAffinity) { - prefixAffinity.note(sessionId, anonAffinity.incomingDepth, anonAffinity.tailHash, anonAffinity.itemHashes, false, anonAffinity.sketches, anonAffinity.userFlags); + prefixAffinity.note(sessionId, anonAffinity.incomingDepth, anonAffinity.tailHash, anonAffinity.itemHashes, false, anonAffinity.sketches, anonAffinity.userFlags, undefined, anonAffinity.tailFragments); scheduleAffinityPersist(); session.metadata.anonymousPrefixAffinity = { depth: anonAffinity.incomingDepth, @@ -1144,7 +1144,7 @@ async function handleRequest( // neutral turns, so the append-only comparison would // misjudge a version migration as a shrink. if (!tracked || tracked.hv !== 2 || fp.depth >= tracked.depth) { - prefixAffinity.note(sessionId, fp.depth, fp.tailHash, fp.itemHashes, true, undefined, undefined, fp.normTailHash); + prefixAffinity.note(sessionId, fp.depth, fp.tailHash, fp.itemHashes, true, undefined, undefined, fp.normTailHash, fp.tailFrags); scheduleAffinityPersist(); } }