Compare commits

...

1 Commits

Author SHA1 Message Date
Sergey Ignatov
0ddb74ebf5 fix: link a compaction boundary to the preserved tail when its logical parent is missing
Claude Code can write a compact_boundary whose logicalParentUuid names a
record that is not in the transcript. The boundary then linked to nothing,
and a load or a `_session/read` silently started the history at it.

Now the link goes to compactMetadata.preservedSegment.tailUuid when the
transcript has that record. Without it, the link goes to the last uuid of
compactMetadata.preservedMessages.uuids when the transcript has that one.
Without both, the history starts at the boundary as before, and a warning
names the boundary once per process. A status poll reads the same boundary
on each poll. The rewind chain walks use the same link.

On a copy of a real session with two such boundaries, `_session/read` and
session/load now give 12,309 messages and 511 children instead of 135
messages and 11 children.
2026-12-03 23:19:59 +01:00
5 changed files with 239 additions and 8 deletions

View File

@@ -19,6 +19,7 @@ const TAIL_CHUNK_BYTES = 64 * 1024;
type ResumeLogger = {
log: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
warn?: (...args: unknown[]) => void;
};
export type ResumedSessionSnapshot = {
@@ -110,9 +111,15 @@ export async function readHistoryAcrossCompactions(
): Promise<SessionMessage[]> {
if (!isCompactSummaryMessage(messages[0])) return messages;
try {
const entries = (snapshot ?? (await loadFullSessionHistory(sessionId, dir))).map(
linkCompactBoundary,
const records = snapshot ?? (await loadFullSessionHistory(sessionId, dir));
const known = new Set(
records.flatMap((entry) => (typeof entry.uuid === "string" ? [entry.uuid] : [])),
);
const warn = (message: string) => {
const target = logger ?? console;
(target.warn ?? target.error).call(target, message);
};
const entries = records.map((entry) => linkCompactBoundary(entry, known, sessionId, warn));
const read = (records: SessionStoreEntry[]) =>
getSessionMessages(sessionId, {
dir,
@@ -161,8 +168,27 @@ export async function loadFullSessionHistory(
return entries;
}
/** The record unchanged, or a compaction boundary linked to the message before it. */
function linkCompactBoundary(entry: SessionStoreEntry): SessionStoreEntry {
/** The `${sessionId}/${boundaryUuid}` keys of the cut boundaries that a warning reported. */
const reportedCuts = new Set<string>();
/**
* The record unchanged, or a compaction boundary linked to the message before it.
*
* The boundary names that message in `logicalParentUuid`. Claude Code can
* write a boundary whose `logicalParentUuid` names a record that is not in the
* transcript. The link then goes to the last preserved message of the
* compaction when the transcript has it (see {@link logicalParentOf}): it is
* the last message before the boundary. Without it, the link goes to the
* missing record and the history starts at the boundary. `warn` then reports
* the cut, once per boundary in this process: each status poll reads the same
* boundary again.
*/
function linkCompactBoundary(
entry: SessionStoreEntry,
known: ReadonlySet<string>,
sessionId: string,
warn: (message: string) => void,
): SessionStoreEntry {
if (
entry.type !== "system" ||
entry.subtype !== "compact_boundary" ||
@@ -174,9 +200,45 @@ function linkCompactBoundary(entry: SessionStoreEntry): SessionStoreEntry {
typeof entry.compactMetadata === "object" && entry.compactMetadata !== null
? { ...entry.compactMetadata }
: {};
const parentUuid = logicalParentOf(entry, (uuid) => known.has(uuid))!;
const key = `${sessionId}/${String(entry.uuid)}`;
if (!known.has(parentUuid) && !reportedCuts.has(key)) {
reportedCuts.add(key);
warn(
`The compaction boundary ${String(entry.uuid)} of session ${sessionId} links to message ${entry.logicalParentUuid}, which is not in the transcript: the history starts at this boundary`,
);
}
delete compactMetadata.preservedSegment;
delete compactMetadata.preservedMessages;
return { ...entry, parentUuid: entry.logicalParentUuid, compactMetadata };
return { ...entry, parentUuid, compactMetadata };
}
/**
* The message before a record that has no `parentUuid`, such as a compaction
* boundary. This is `logicalParentUuid` when `has` finds it. Else it is the
* first that `has` finds of `compactMetadata.preservedSegment.tailUuid` and
* the last uuid of `compactMetadata.preservedMessages.uuids`. Else it is
* `logicalParentUuid` as it is, or undefined without one.
*/
export function logicalParentOf(
entry: SessionStoreEntry,
has: (uuid: string) => boolean,
): string | undefined {
const logical = entry.logicalParentUuid;
if (typeof logical !== "string") return undefined;
if (has(logical)) return logical;
const metadata = entry.compactMetadata as {
preservedSegment?: { tailUuid?: unknown } | null;
preservedMessages?: { uuids?: unknown } | null;
} | null;
const uuids = metadata?.preservedMessages?.uuids;
const candidates = [
metadata?.preservedSegment?.tailUuid,
Array.isArray(uuids) ? (uuids.at(-1) as unknown) : undefined,
];
return (
candidates.find((uuid): uuid is string => typeof uuid === "string" && has(uuid)) ?? logical
);
}
/** What a resume restores from the end of the local transcript. */

View File

@@ -33,6 +33,7 @@ import { isReplayHiddenMetaMessage } from "./message-filters.js";
import {
findTranscript,
loadFullSessionHistory,
logicalParentOf,
readHistoryAcrossCompactions,
} from "./resumed-session.js";
import { cursorMessageId, forkPointOf } from "./session-cursors.js";
@@ -328,9 +329,10 @@ export async function withoutRewoundBranch(
const point = await readRewindPoint(sessionId, logger);
if (!point) return entries;
const dropped = new Set<string>([point.droppedPromptUuid]);
const known = new Set(entries.map((entry) => entry.uuid));
return entries.filter((entry) => {
if (typeof entry.uuid !== "string") return true;
const parent = entry.parentUuid || entry.logicalParentUuid;
const parent = entry.parentUuid || logicalParentOf(entry, (uuid) => known.has(uuid));
const inDropped =
entry.uuid === point.droppedPromptUuid || (typeof parent === "string" && dropped.has(parent));
if (inDropped) dropped.add(entry.uuid);
@@ -581,7 +583,7 @@ function newestMainChainUuid(entries: SessionStoreEntry[]): string | undefined {
}
/** The uuids of `leaf` and of every entry it descends from. A compaction
* boundary has no `parentUuid`; its `logicalParentUuid` carries the chain on. */
* boundary has no `parentUuid`; {@link logicalParentOf} carries the chain on. */
function chainUuids(
leaf: string | undefined,
byUuid: ReadonlyMap<string, SessionStoreEntry>,
@@ -592,7 +594,7 @@ function chainUuids(
const entry = byUuid.get(cursor);
if (!entry) break;
chain.add(cursor);
const parent = entry.parentUuid || entry.logicalParentUuid;
const parent = entry.parentUuid || logicalParentOf(entry, (uuid) => byUuid.has(uuid));
cursor = typeof parent === "string" ? parent : undefined;
}
return chain;

View File

@@ -12,6 +12,7 @@ import os from "node:os";
import path from "node:path";
import {
findTranscript,
loadFullSessionHistory,
readHistoryAcrossCompactions,
readResumedTail,
readTranscriptEntries,
@@ -409,6 +410,102 @@ describe("readHistoryAcrossCompactions", () => {
expect(error).toHaveBeenCalledOnce();
});
describe("a boundary whose logicalParentUuid is not in the transcript", () => {
// Claude Code 2.1.332 can name a record that it never wrote. The preserved
// messages of the compaction then end at the last message before the
// boundary, as in this record of a real transcript.
type Kept = { segmentTail?: string; keptTail?: string };
const records = (b2: string, { segmentTail, keptTail }: Kept) => [
user("u1", "hi"),
assistant("a1", "Hello"),
boundary("b1", "a1"),
summary("s1"),
user("u2", "next"),
assistant("a2", "Next"),
user("u2b", "go on"),
boundary(b2, "gone", {
...(segmentTail
? { preservedSegment: { headUuid: "a2", anchorUuid: "s2", tailUuid: segmentTail } }
: {}),
...(keptTail
? {
preservedMessages: {
anchorUuid: "s2",
uuids: ["a2", keptTail],
allUuids: ["a2", keptTail, "gone"],
},
}
: {}),
}),
summary("s2"),
user("u3", "identify yourself"),
assistant("a3", "Claude"),
];
const full = [
"hi",
"Hello",
"Summary s1",
"next",
"Next",
"go on",
"Summary s2",
"identify yourself",
"Claude",
];
const cut = ["Summary s2", "identify yourself", "Claude"];
const logger = () => ({ log: vi.fn(), error: vi.fn(), warn: vi.fn() });
type Log = Parameters<typeof readHistoryAcrossCompactions>[2];
const read = async (kept: Kept, log: Log, given = false) => {
const b2 = crypto.randomUUID();
await transcript(records(b2, kept));
const chain = await getSessionMessages(sessionId);
const snapshot = given ? await loadFullSessionHistory(sessionId) : undefined;
return {
b2,
texts: texts(
await readHistoryAcrossCompactions(sessionId, chain, log, undefined, snapshot),
),
};
};
it.each([false, true])("links it to the preserved tail (records given: %s)", async (given) => {
const log = logger();
expect((await read({ segmentTail: "u2b", keptTail: "u2b" }, log, given)).texts).toEqual(full);
expect(log.warn).not.toHaveBeenCalled();
});
it("links it to the last preserved message without a preserved segment", async () => {
const log = logger();
expect((await read({ keptTail: "u2b" }, log)).texts).toEqual(full);
expect(log.warn).not.toHaveBeenCalled();
});
it.each([
["without a preserved tail", {}],
[
"when the preserved tail is not in the transcript either",
{ segmentTail: "lost", keptTail: "lost" },
],
])("starts the history at it and warns once %s", async (_, kept: Kept) => {
const log = logger();
const { b2, texts } = await read(kept, log);
expect(texts).toEqual(cut);
expect(log.warn).toHaveBeenCalledOnce();
expect(log.warn).toHaveBeenCalledWith(expect.stringContaining(b2));
const chain = await getSessionMessages(sessionId);
await readHistoryAcrossCompactions(sessionId, chain, log);
expect(log.warn).toHaveBeenCalledOnce();
});
it("reports the cut as an error to a logger without warn", async () => {
const log = { log: vi.fn(), error: vi.fn() };
const { b2, texts } = await read({}, log);
expect(texts).toEqual(cut);
expect(log.error).toHaveBeenCalledWith(expect.stringContaining(b2));
});
});
it("reads the transcript in the project directory it is given", async () => {
await transcript(
[

View File

@@ -10,6 +10,8 @@ import { writeRewindPoint } from "../session-rewind.js";
import {
parallelToolCallRecords,
transcriptAssistant,
transcriptCompactBoundary,
transcriptCompactSummary,
transcriptUser,
writeTranscript,
} from "./helpers.js";
@@ -175,6 +177,33 @@ describe("session read cursors", () => {
},
);
it("warns on the console about a compaction boundary that cuts the history", async () => {
const sessionId = randomUUID();
const dir = await mkdtemp(path.join(tmpdir(), "claude-acp-read-cut-boundary-"));
const project = path.join(dir, "projects", "-project");
vi.stubEnv("CLAUDE_CONFIG_DIR", dir);
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
await writeTranscript(project, sessionId, [
{ cwd: dir, ...transcriptUser("u1", "One") },
{ cwd: dir, ...transcriptAssistant("a1", "Answer one") },
{ cwd: dir, ...transcriptCompactBoundary("b1", "a1") },
{ cwd: dir, ...transcriptCompactSummary("s1") },
{ cwd: dir, ...transcriptUser("u2", "Two") },
{ cwd: dir, ...transcriptCompactBoundary("b2", "gone") },
{ cwd: dir, ...transcriptCompactSummary("s2") },
{ cwd: dir, ...transcriptUser("u3", "Three") },
]);
const { messages } = await readSessionTranscript(sessionId);
expect(messages.map((message) => message.uuid)).toEqual(["s2", "u3"]);
expect(warn).toHaveBeenCalledWith(expect.stringContaining("b2"));
} finally {
warn.mockRestore();
vi.unstubAllEnvs();
await rm(dir, { recursive: true, force: true });
}
});
it.each(["results", "third call", "streamed call", "skill text"] as const)(
"reads each record of parallel tool calls of the root in file order: %s",
async (variant) => {

View File

@@ -745,6 +745,47 @@ describe("a pending rewind point", () => {
});
});
describe("a rewind point before a boundary whose logicalParentUuid is not in the transcript", () => {
// Claude Code 2.1.332 can name a record that it never wrote. The preserved
// tail of the compaction then carries the chain on.
const point = { resumeSessionAt: "a1", droppedPromptUuid: "u2" };
beforeEach(async () => {
await writeTranscript(projectDir(), SESSION_ID, [
transcriptUser("u1", "first"),
transcriptAssistant("a1", "one"),
transcriptUser("u2", "second"),
transcriptAssistant("a2", "two"),
transcriptCompactBoundary("b1", "gone", {
preservedSegment: { headUuid: "u2", anchorUuid: "s1", tailUuid: "a2" },
preservedMessages: {
anchorUuid: "s1",
uuids: ["u2", "a2"],
allUuids: ["u2", "a2", "gone"],
},
}),
transcriptCompactSummary("s1"),
transcriptUser("u3", "third"),
transcriptAssistant("a3", "three"),
]);
await writeRewindPoint(SESSION_ID, point);
});
it("drops the records after the boundary with the dropped prompt", async () => {
const full = await loadFullSessionHistory(SESSION_ID);
expect(
(await withoutRewoundBranch(SESSION_ID, full)).flatMap((entry) =>
typeof entry.uuid === "string" ? [entry.uuid] : [],
),
).toEqual(["u1", "a1"]);
});
it("keeps the point pending for a resume", async () => {
expect(await prepareRewoundResume(SESSION_ID)).toBe("a1");
expect(await readRewindPoint(SESSION_ID)).toEqual(point);
});
});
describe("rewind read of a resolved transcript", () => {
it("reports an unreadable rewind file instead of showing the dropped branch", async () => {
const dir = await mkdtemp(path.join(os.tmpdir(), "claude-acp-strict-rewind-"));