Skip to content
Open
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
45 changes: 45 additions & 0 deletions docs/session-identity.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,51 @@ From then on:
claude/codex/dsh need nothing here: they share one session id across
subagents or have no child-session concept at all.

## Persona-lane drift: when re-anchoring is impossible (#5844)

The order resolver keeps the live conversation on the raw id through persona
text changes whenever it can verify continuation (head continuity,
header-corroborated model switch, positional fragment runs, fragment- or
content-verified tails — `src/session-resolve.ts`). When the host destroys ALL
byte-level evidence in the same turn it rotates its system prompt — e.g. an
upgrade that changes both the system prompt and the message-record layout
(#5844), or a grown+shifted replay (#5714) — the conversation forks onto
`<id>|sub:<fp>` with empty compression state. That fork is by design:
mis-attribution is the most expensive failure in this system (MESSAGE-IDENTITY).

The "content-verified" tail compares the last ≤8 turns in canonical form —
the identity chain's own hashing input (`neutralTurnCanonical`): kind plus
logical text/calls. For an assistant turn carrying tool calls the canonical
form is calls+role only (cross-wire neutrality — OpenAI renders such turns
with `content: null`), so a prose-only difference inside a calls turn is
invisible to this rung exactly as it is to the rest of the chain that shares
the same canonical form. A different conversation must still replay identical
user questions, tool results and tool calls across the whole tail window to be
accepted; record regrouping alone can never do that.

**There is no supported command to re-attach a derived lane to its parent,
and no config knob for it.** The resolution is decided per request from
evidence only; after a drift, the only sanctioned path is surgery on the
persisted skeleton:

1. Stop the proxy first — the running daemon silently rewrites
`<state dir>/session-order.json` from its in-memory skeletons, so any edit
made while it runs is lost (state dir = `$XDG_STATE_HOME/billion-context`,
default `~/.local/state/billion-context/`).
2. In `session-order.json`, set the parent entry's `tagHash` to the sha256 hex
digest of the host's CURRENT full system text (the field stores the full
digest, not a truncated fingerprint), or delete the entry entirely to let
the raw id be claimed fresh on the next request.
3. Restart the proxy; the next request re-anchors onto the raw id and the
fold state stored under it becomes live again.
4. Remove the orphaned derived lane: `bili sessions rm <id>|sub:<fp>`
(its rows are otherwise inert but keep growing).

Do NOT merge lanes when the replay content genuinely diverged (a different
conversation riding the same client id) — that is exactly what the fork
exists to prevent; the procedure above is for "same conversation, evidence
destroyed by the host".

## Future direction

The durable fix is a **client-side identity signal**: a stable
Expand Down
15 changes: 15 additions & 0 deletions docs/session-identity.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,21 @@

claude/codex/dsh 在这里不需要任何信号:它们的 subagent 共享同一个会话 id,或根本没有子会话概念。

## 派生车道漂移:无法重新锚定时怎么办(#5844)

顺序解析器在能验证延续性时(头部延续、头部佐证的模型切换、逐位 fragment 连续段、fragment 或内容校验的尾部——`src/session-resolve.ts`)会把活会话留在原始 id 上。但当宿主在轮换 system prompt 的同一轮里销毁了**全部**字节级证据——例如一次升级同时改了 system prompt 和消息记录布局(#5844),或增长+位移的重放(#5714)——会话就会分叉到 `<id>|sub:<fp>`,压缩状态为空。这是有意设计:误归属(mis-attribution)是本系统代价最高的失败(MESSAGE-IDENTITY)。

「内容校验」的尾部比较的是最后 ≤8 轮的**规范化形式**——身份链自有的 hash 输入(`neutralTurnCanonical`):kind 加逻辑文本/调用。对携带工具调用的 assistant 轮,规范化形式只含 calls+role(跨线中性——OpenAI 会把这类轮渲染为 `content: null`),因此 calls 轮内**仅散文不同**对本档不可见,这与共享同一规范化形式的身份链其余部分完全一致。另一个对话要能被接受,仍须在整段尾窗上重放逐字一致的用户提问、工具结果与工具调用;单纯的消息重打包做不到这一点。

**目前没有任何受支持的命令能把派生车道重新挂回父会话,也没有对应的配置项。** 解析结果每轮只由证据决定;漂移发生后,唯一被认可的恢复路径是对持久化骨架做手术:

1. 先停代理——运行中的守护进程会用内存里的骨架悄悄重写 `<state 目录>/session-order.json`,运行期间做的任何编辑都会丢失(state 目录 = `$XDG_STATE_HOME/billion-context`,默认 `~/.local/state/billion-context/`)。
2. 在 `session-order.json` 里,把父条目的 `tagHash` 设为宿主**当前**完整 system 文本的 sha256 hex 摘要(该字段存的是完整摘要,不是截断指纹);或者直接删掉整个条目,让原始 id 在下一次请求时重新认领。
3. 重启代理;下一次请求重新锚定到原始 id,其下已存储的折叠状态随之复活。
4. 删除孤儿派生车道:`bili sessions rm <id>|sub:<fp>`(其行数据虽不再被使用,但会持续增长)。

如果重放内容与记录**确实**分叉了(同一客户端 id 上跑着另一个对话),不要合并车道——这正是分叉机制要防止的事;上面的流程只适用于「同一对话、证据被宿主销毁」的情形。

## 未来方向

持久的修复是**客户端侧身份信号**:由客户端自身提供的稳定 per-conversation
Expand Down
61 changes: 52 additions & 9 deletions src/session-resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ import { createHash } from "node:crypto";
// never lets a shallow side request clobber a deeper persisted entry.
import { prefixAffinity } from "./prefix-affinity.js";
import { isClaudeLaneToken } from "./claude-lane-token.js";
import { neutralTurns, type NeutralTurn } from "./affinity-neutral.js";
import { neutralTurns, neutralTurnCanonical, type NeutralTurn } from "./affinity-neutral.js";
import { log as loggerLog } from "./logger.js";
// #3397: skeleton persistence hook (deferred-use ESM cycle with
// src/order-persist.ts — each side calls the other only inside function
Expand Down Expand Up @@ -210,14 +210,24 @@ export type SessionOrderResolution = {
reason?: string;
};

type Recorded = { kinds: string[]; frags: string[]; tagHash: string; model?: string; lastSeen: number };
type Recorded = { kinds: string[]; frags: string[]; canon?: string[]; tagHash: string; model?: string; lastSeen: number };

/** #3397: persona-tag identity is carried by its sha256 (the raw text can be
* tens of KB of host system prompt; the persisted snapshot must not carry it
* and the resolver only ever compares tags for equality). "" = non-anchoring. */
const tagHashOf = (tag: string): string =>
tag === "" ? "" : createHash("sha256").update(tag, "utf8").digest("hex");

/** Per-turn canonical fingerprint (#5844): sha256 of neutralTurnCanonical —
* the identity chain's own hashing input (kind + logical text/calls), so it
* survives a host regrouping messages into different records while the
* per-source-message `frags` do not. */
const canonFp = (turns: NeutralTurn[]): string[] =>
turns.map((t) => createHash("sha256").update(neutralTurnCanonical(t), "utf8").digest("hex"));

/** #5844: the persisted canon column's element shape (sha256 hex digest). */
const CANON_FP_RE = /^[0-9a-f]{64}$/;

/** Order skeletons. #3397: no longer process-memory-only — every mutation is
* debounced-persisted (src/order-persist.ts) and hydrated on boot, so a
* restart can no longer re-run the cold-start claim race that flipped the
Expand All @@ -229,13 +239,15 @@ export interface OrderSkeletonEntry {
id: string;
kinds: string[];
frags: string[];
/** #5844: per-turn canonical fingerprints — absent on pre-change snapshots. */
canon?: string[];
tagHash: string;
model?: string;
lastSeen: number;
}

function record(rawId: string, turns: NeutralTurn[], tagHash: string, model?: string): void {
skeletons.set(rawId, { kinds: turns.map((t) => t.kind), frags: fragsOf(turns), tagHash, model, lastSeen: Date.now() });
skeletons.set(rawId, { kinds: turns.map((t) => t.kind), frags: fragsOf(turns), canon: canonFp(turns), tagHash, model, lastSeen: Date.now() });
scheduleOrderPersist();
}

Expand Down Expand Up @@ -353,6 +365,21 @@ export function resolveSessionOrder(rawId: string, history: unknown, personaTag?
const b = recorded.frags.slice(-w);
return a.length === b.length && a.every((f, i) => f === b[i]);
};
// #5844: logical-turn twin of fragTailEquals — the last ≤TAIL_WINDOW turns
// compared by CANONICAL form (kind + logical text/calls, the identity
// chain's own hashing input) instead of per-source-message fragments. A
// host upgrade that regroups messages into different records (dsh
// 0.2.2-rc.1: assistant text segments merged into adjacent records)
// destroys the per-message granularity while every logical turn stays
// byte-identical; the canonical comparison sees through the repack. Old
// persisted skeletons carry no canon column → false → pre-change path.
const canonTailEquals = (n: number): boolean => {
if (recorded.canon === undefined) return false;
const w = Math.min(TAIL_WINDOW, n);
const a = canonFp(turns.slice(-w));
const b = recorded.canon.slice(-w);
return a.length === b.length && a.every((c, i) => c === b[i]);
};
const tagChanged = tagHash !== "" && tagHash !== recorded.tagHash;
// An EMPTY incoming tag (system-less / instructions-less request) is
// the old ladder's non-anchoring path: it rides whatever the id holds
Expand Down Expand Up @@ -473,7 +500,7 @@ export function resolveSessionOrder(rawId: string, history: unknown, personaTag?
record(rawId, turns, tagHash, effectiveModel);
return { key: rawId, action: "reanchor", reason: "persona text changed but the recorded history continues inside the incoming — anchor migrated (#4778)" };
}
// #5686: fifth rung — the composite field failure behind the
// #5686: sixth rung — the composite field failure behind the
// |sub:-drift cluster (#5517/#5656 reports): a native-compaction
// checkpoint LANDS (head cells replaced by one summary message) while
// the host simultaneously rotates its per-turn system prompt (dsh NEXT
Expand All @@ -486,9 +513,19 @@ export function resolveSessionOrder(rawId: string, history: unknown, personaTag?
// mirror of the tag-LESS shorter-reanchor below (same two tests, same
// TAIL_WINDOW, no extra floor): a byte-identical fragment-verified
// tail cannot belong to a different conversation (MESSAGE-IDENTITY).
if (kinds.length > 0 && kinds.length < recorded.kinds.length && tailAligns(kinds, recorded.kinds) && fragTailEquals(kinds.length)) {
record(rawId, turns, tagHash, effectiveModel);
return { key: rawId, action: "reanchor", reason: "persona text changed but the shorter incoming keeps the recorded conversation's fragment-verified tail — head rewrite under a new system prompt, anchor kept (#5686)" };
if (kinds.length > 0 && kinds.length < recorded.kinds.length && tailAligns(kinds, recorded.kinds)) {
const fragOk = fragTailEquals(kinds.length);
const canonOk = !fragOk && canonTailEquals(kinds.length);
if (fragOk || canonOk) {
record(rawId, turns, tagHash, effectiveModel);
return {
key: rawId,
action: "reanchor",
reason: canonOk
? "persona text changed but the shorter incoming keeps the recorded conversation's content-verified tail (host repacked the message records, logical turns intact) — anchor kept (#5686/#5844)"
: "persona text changed but the shorter incoming keeps the recorded conversation's fragment-verified tail — head rewrite under a new system prompt, anchor kept (#5686)",
};
}
}
// #5719: every byte-level escape needs EVIDENCE (fragments/cells/
// chain continuity) that the composite field failure destroys in the
Expand Down Expand Up @@ -582,7 +619,7 @@ export function resetSessionOrderForTest(): void {

/** #3397: persisted-snapshot surface (src/order-persist.ts wire shape). */
export function orderSnapshot(): OrderSkeletonEntry[] {
return [...skeletons.entries()].map(([id, r]) => ({ id, kinds: r.kinds, frags: r.frags, tagHash: r.tagHash, model: r.model, lastSeen: r.lastSeen }));
return [...skeletons.entries()].map(([id, r]) => ({ id, kinds: r.kinds, frags: r.frags, ...(r.canon !== undefined ? { canon: r.canon } : {}), tagHash: r.tagHash, model: r.model, lastSeen: r.lastSeen }));
}

/** Merge a hydrated snapshot: per-id newer lastSeen wins. Returns imported count. */
Expand All @@ -591,7 +628,13 @@ export function applyOrderSnapshot(entries: OrderSkeletonEntry[]): number {
for (const e of entries) {
const cur = skeletons.get(e.id);
if (!cur || e.lastSeen > cur.lastSeen) {
skeletons.set(e.id, { kinds: e.kinds, frags: e.frags, tagHash: e.tagHash, model: e.model, lastSeen: e.lastSeen });
// #5844: pre-change snapshots carry no canon column; a malformed
// one degrades to absent (byte-fragment path only), never trusted.
// The writers keep canon 1:1 with kinds (both derive from the same
// turn list in record()), so a length mismatch means the column is
// shifted/corrupted — trust nothing from it.
const canon = Array.isArray(e.canon) && e.canon.length > 0 && e.canon.length === e.kinds.length && e.canon.every((c) => typeof c === "string" && CANON_FP_RE.test(c)) ? e.canon : undefined;
skeletons.set(e.id, { kinds: e.kinds, frags: e.frags, canon, tagHash: e.tagHash, model: e.model, lastSeen: e.lastSeen });
imported++;
}
}
Expand Down
Loading
Loading