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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag

## [Unreleased]

### Storage — 行身份与史官化(#4390,storage review 四个 p2 + 三个顺路 p3)

- **行身份去污染(D4-1)**:统一存储 messages 行新增 `identity` 列——跨保存 JOIN 键改为**位置无关**序列化(剥离 `id`/`wireIndex` 后哈希)。此前身份掺入 wire 位置元数据,客户端头部截断一条消息就会让后续全部行换血(旧行被清扫、seq 重铸、#4335 的区间账记随之抖动)。`content_hash` 保持字节忠实 CAS 键不变。存量库 v8 迁移:回填 identity 并合并 wireIndex 分裂世代(保最低 seq,重复行退还 CAS 引用)。MySQL 同款(information_schema 探测幂等 ALTER + 回填)。
- **权威集清扫改墓碑(D4-2)**:proxy 会话每轮全量保存不再物理 DELETE 缺席行,改为 `retired_at` 墓碑——rewind/undo 的历史在统一存储里**耐久保留**;同一身份回来时原地复活(保原 seq,含 completeLog-less 保存路径 remap 复活)。读面(getMessages/统一重放/视图)默认过滤 retired;CAS 引用不释放。deleteSession/archive/GC 继续拥有物理生命周期。
- **渲染接缝图片真指纹(D4-3)**:snapshot-render 的 identitySig 图片段从 `长度` 改为 `sha256(base64) 前 24 hex`——同尺寸截图不再可能连击假接缝造成静默截断。
- **fork 谱系入正史(D3-2)**:sessions 行的 `parent_session_id` 现在从信封 `metadata.derivedFromSessionId` 落库(此前恒 null,谱系只活在信封里,信封丢失=家族失忆)。
- **顺路**:gc full vacuum 走 `vacuum('full')`(带 TRUNCATE checkpoint,文件真正缩小,D5-1);loadLegacyView 尾指针缺行从静默缩水改为计数 + 三处加载路径 warn(D4-5);fold-reconcile 的 Pass 0 位置副本失步(存储 ids 与顺序骨架不再 1:1)从静默降级改为响亮 warn(此前无任何日志痕迹)。
- **审查修复(review)**:identity JOIN 迁移后,全量 ingest 对「identity 相同、字节不同」的行原本靠 INSERT OR IGNORE 静默保留旧世代——头部截断后存储世代带着旧 wireIndex 与活视图永久失配(采样校验漂移→水位反复清零→#4323 信封冻结的数据丢失向量),外部 CAS 损坏也永远无法自愈。现在全量路径在**同一 seq** 上采纳更新的字节(seq 稳定性不变,delta 追加路径仍只增不改);`tailGaps` 诊断键从 parity 摘要面剔除(存在性差异不再误报漂移)。
- 测试:`tests/storage-review-p2s.test.ts` 7 桩(截断保号/墓碑+复活/接缝指纹/谱系/迁移去重/gc checkpoint/缺行响亮);storage 全家族 + golden/snapshot/fold-reconcile/incremental/web 回归绿。

### Fixed

- **External summary: stop injecting the summary-writing rules into the conversation prompt (#4460).** With `compress.externalSummary.enabled`, the conversation model only selects ranges and the independent service writes the committed summary — yet every conversation request still carried `HOW TO COMPRESS`/`KEEP VERBATIM`/`DROP`/`PRIORITY` (~5.8K chars) plus the per-summary length budget, which the model's non-authoritative hint is never checked against. The conversation-side prompt now drops both while the chain is enabled (all five prompt assembly sites, function and hybrid builders, pack overrides included); philosophy, ACP tags, tools, summaries-in-context and marker integrity stay. The summary requests keep the full rules (`session.meta.summaryInstructions`), and classic mode is byte-identical. New tests/issue4460-external-summary-conversation-prompt.test.ts (7 cases, positive + negative).
Expand Down
2 changes: 2 additions & 0 deletions scripts/live-files.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
// KEEP IN SYNC: adding a process-spawning suite means adding it here (the
// tripwire fails CI until you do); slot = index here.
export const LIVE_FILES = [
"tests/codex-mcp-shell.test.ts",
"tests/codex-plugin-version-sync.test.ts",
"tests/session-transient-memory.test.ts",
"tests/auto-restart.test.ts",
"tests/bounded-storage-scale.test.ts",
Expand Down
21 changes: 18 additions & 3 deletions src/fold-reconcile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ import { simhashHex, hammingHex } from "./affinity-simhash.js";
import { reapDestroyedSubstrate, type Session } from "./session.js";
import { coveredRealHistoryIds, isResponsesTurnSeparatorId } from "./session.js";
import { dshNativeCompactionWitness, recordConflict } from "./conflict-watch.js";
import { log as loggerLog } from "./logger.js";

type FoldReconcileMode = "off" | "warn" | "repair";

Expand Down Expand Up @@ -369,6 +370,10 @@ interface ReconciliationPlan {
* caller's write-back (foldAnchorOrder / foldPositions rolling copy). */
newOrder: string[];
nextCanon: string[] | undefined;
/** #4390 p3: stored positional copy present with matching lengths but ids
* not 1:1 aligned with the order backbone → Pass 0 self-disabled. Flagged
* for the caller to log (the planner core stays pure). */
pass0Desync?: boolean;
/** #3641 census of the RESIDUAL unmatched (after every claim pass,
* including the shape pass): `absentEverywhere` = no unclaimed inbound
* candidate carries loose word evidence (the content is truly off the
Expand Down Expand Up @@ -747,9 +752,16 @@ export function planReconciliation(
// Pass 0's old-side coordinate system is only valid when the stored copy's
// ids align 1:1 with the order backbone. Self-contained storage makes the
// check exact: a desync (backbone semantics drift, partial write) disables
// Pass 0 instead of silently misaligning fingerprints.
const stored = positions !== undefined && positions.ids.length === oldOrder.length && positions.canon.length === oldOrder.length
&& positions.ids.every((id, i) => id === oldOrder[i]) ? positions.canon : undefined;
// Pass 0 instead of silently misaligning fingerprints. #4390 p3: flag it —
// the caller logs; this core stays pure.
let stored: string[] | undefined;
if (positions !== undefined && positions.ids.length === oldOrder.length && positions.canon.length === oldOrder.length) {
if (positions.ids.every((id, i) => id === oldOrder[i])) {
stored = positions.canon;
} else {
plan.pass0Desync = true;
}
}
const canon: string[] = [];
const newOrder: string[] = [];
const byId = new Map<string, CoreMessage>();
Expand Down Expand Up @@ -1539,6 +1551,9 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt
}

const plan = planReconciliation(oldOrder, anchors, msgs, covered, positions);
if (plan.pass0Desync) {
loggerLog("warn", `[fold-reconcile] Pass 0 disabled: stored positional copy desynced from order backbone (session=${session.id}, copyIds=${positions?.ids.length ?? -1}, backbone=${oldOrder.length})`);
}
if (process.env.FOLD_RECONCILE_DEBUG === "1") {
const active = blocks.filter((b) => b.active).length;
const sample = msgs.slice(0, 6).map((m) => `${m.role}/${m.contentType ?? "-"}/${m.id ?? "?"}`);
Expand Down
13 changes: 12 additions & 1 deletion src/server/snapshot-render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ const MAX_CHAIN_WALK = 8192;
* MIN_RESYNC_RUN in fold-reconcile (there 3, because reconcile matches on
* position alone; here the second consecutive match must ALSO line up with
* the view, which a stray duplicate cannot provide). */
import { sha256Hex } from "../storage/store.js";

const MIN_SEAM_RUN = 2;

/** #3658 canonical identity signature minus the hash: the tuple the kernel
Expand All @@ -69,10 +71,19 @@ const MIN_SEAM_RUN = 2;
* same bytes ⇒ same length; different images practically always differ). */
function identitySig(m: BiliMessage): string {
const text = typeof m.text === "string" ? m.text : "";
const img = m.imagePart === true ? `|img:${(m.imageBase64 ?? "").length}` : "";
// #4390: hash the image BYTES, never the length — same-size screenshots
// used to collide and chain a false seam (silent truncation). The walk
// only touches the tail region, so per-request hashing is bounded; a
// 24-hex prefix is far beyond collision reach for seam evidence.
const img = m.imagePart === true ? `|img:${sha256Hex(m.imageBase64 ?? "").slice(0, 24)}` : "";
return `${m.role}|${m.contentType}|${m.toolName ?? ""}|${text}${img}`;
}

/** Test seam (#4390): the seam fingerprint under test — see identitySig. */
export function identitySigForTest(m: BiliMessage): string {
return identitySig(m);
}

interface ViewRow {
seq: number;
msg: BiliMessage;
Expand Down
15 changes: 11 additions & 4 deletions src/storage/canonical.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ import { createHash } from "node:crypto";
* provenance (#2671), but its PRESENCE is new (corpus pins predate it),
* so masking the value like __VER__ cannot keep old pins green; the key
* is removed from digests altogether.
*
* NOT normalized (deliberately contract): every other byte — ref numbers,
* block ids, summaries, stats, metadata. A change to any of those in the
* round-trip is a migration regression and must fail the golden.
* - tailGaps (#4390) → dropped entirely — read-time diagnostic added by
* loadLegacyView (count of tail pointers whose row is missing); the live
* legacy leg of any parity comparison structurally lacks the key, so
* digesting its presence would report drift on every sampled save. Same
* class as storageMode: the PRESENCE, not the value, is the problem. A
* genuinely missing row still diverges the message arrays themselves.
*/
export function canonicalize(value: unknown): unknown {
return canonicalizeWithContext(value, undefined);
Expand All @@ -42,6 +44,11 @@ function canonicalizeWithContext(value: unknown, key: string | undefined): unkno
// unlike biliVersion its PRESENCE is new, so masking the value
// is not enough; drop the key from digests entirely.
if (k === "storageMode") continue;
// tailGaps (#4390) is read-time gap-count metadata from
// loadLegacyView — the live legacy leg structurally lacks the
// key, so digesting its presence would flag drift on every
// sampled save; drop it like storageMode.
if (k === "tailGaps") continue;
out[k] = canonicalizeWithContext(v, k);
}
return out;
Expand Down
102 changes: 102 additions & 0 deletions src/storage/identity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/**
* #4390: identity helpers for the unified store.
*
* The messages table carries TWO hashes with different jobs:
* - content_hash: the CAS key of the stored bytes (byte-faithful, includes
* sidecars; putContent refcounts by it). NEVER migrates.
* - identity: the cross-save JOIN key ("is this the message I already
* know?"). Its input STRIPS position metadata — m.id itself and the
* wireIndex the wire codecs stamp on every parse — because those change
* when the client truncates/edits ANYWHERE in the resent history while
* the message's logical content does not (#4390 D4-1: one head-truncation
* used to re-mint the whole surviving generation: new hashes, new seqs,
* block interval bounds built on sand).
*
* Same identity ⇒ same logical message ⇒ same row, same seq. A re-arrival
* with different bytes but the same identity (sidecar drift, a stale
* wireIndex after a head truncation, external CAS corruption) is healed by
* the FULL ingest path, which adopts the fresher bytes at the SAME seq —
* the parity oracle must observe the authoritative view again (#4390
* review); the append-only delta path never rewrites stored rows. A real
* edit changes the content-derived id and therefore the identity.
*/
import { createHash } from "node:crypto";

function sha256Hex(bytes: string | Buffer): string {
return createHash("sha256").update(bytes).digest("hex");
}

/**
* Media payloads below this size ride inline even inside raw sidecars —
* splitting them costs a CAS row + a join for a few hundred bytes (#4069).
*/
const MIN_MEDIA_URL_SPLIT_BYTES = 2048;
/** data:<mime>;base64,<payload> with the payload swapped for its CAS hash. */
const MEDIA_URL_MARKER_RE = new RegExp(
`data:([a-zA-Z0-9.+\\/-]+);base64,([A-Za-z0-9+/=]{${MIN_MEDIA_URL_SPLIT_BYTES},})`,
"g",
);

export function splitMediaContent(content: string): { content: string; hash: string; media: { hash: string; bytes: string }[] } {
let media: { hash: string; bytes: string }[] = [];
let split = content;
if (content.includes("\"imageBase64\"")) {
let parsed: { imageBase64?: unknown };
try {
parsed = JSON.parse(content) as { imageBase64?: unknown };
} catch {
parsed = undefined as unknown as { imageBase64?: unknown };
}
if (parsed) {
const bytes = parsed.imageBase64;
if (typeof bytes === "string" && bytes.length > 0) {
const mediaHash = sha256Hex(bytes);
parsed.imageBase64 = { $media: mediaHash };
split = JSON.stringify(parsed);
media.push({ hash: mediaHash, bytes });
}
}
}
// #4069: raw wire sidecars (rawOpenaiContent / rawOpenaiContentParts /
// rawResponsesItem / rawGoogleParts, …) carry the ORIGINAL part verbatim —
// for image parts that means the same base64 payload a second time, as a
// data URL. Swap every sufficiently large payload for its CAS hash, mime
// prefix and JSON structure untouched, so hydration is byte-identical.
if (split.includes(";base64,")) {
const byHash = new Map(media.map((m) => [m.hash, m.bytes]));
split = split.replace(MEDIA_URL_MARKER_RE, (_all: string, mime: string, payload: string) => {
const mediaHash = sha256Hex(payload);
if (!byHash.has(mediaHash)) {
byHash.set(mediaHash, payload);
media = [...media, { hash: mediaHash, bytes: payload }];
}
return `data:${mime};base64,{$media:${mediaHash}}`;
});
}
return { content: split, hash: sha256Hex(split), media };
}

/** Strip the position/identity metadata from a serialized CoreMessage.
* JSON.parse preserves key insertion order, so the stripped serialization
* is deterministic for the same object shape. */
function identityInputOf(raw: string): string {
let parsed: { id?: unknown; wireIndex?: unknown };
try {
parsed = JSON.parse(raw) as { id?: unknown; wireIndex?: unknown };
} catch {
return raw;
}
if (parsed.id === undefined && parsed.wireIndex === undefined) return raw;
delete parsed.id;
delete parsed.wireIndex;
return JSON.stringify(parsed);
}

/** Identity from a STORED content column (already media-split; may still
* carry id/wireIndex from pre-#4390 bytes). Strip and media-split
* commute, so this equals the identity the live intern pass computes for
* the same message — the migration backfill and the direct-caller
* fallbacks in store.ts rely on that equivalence. */
export function identityOfStoredContent(content: string): string {
return sha256Hex(identityInputOf(content));
}
Loading
Loading