From 32e7d041ad60347e8f91e763476bd3bfadd49a97 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Wed, 14 Oct 2026 21:22:01 -0700 Subject: [PATCH] feat(sidechat): seed from the last compaction instead of copying the whole parent log A side-chat fork physically duplicated the parent's entire event log into the child session (measured: a 32,674-event child on this deployment, 303k duplicated rows across 36 seeded threads). After a summarizing compaction the checkpoint user/message already replaces the shadowed span on the model-visible surface, so the child only needs the surviving pre-cut surface nodes, the checkpoint, and the post-compaction tail. The rebased sequence is verified with the real fold (foldSurface) before use: identical visible nodes to the parent, hence identical model context and provider context-cache prefix. Any tail that cannot be proven equivalent (dangling back-references, reordering replaces, no compaction) falls back to today's verbatim full copy. --- src/sidechat-core.ts | 225 +++++++++++++++++++++++-- tests/sidechat-compaction-seed.spec.ts | 224 ++++++++++++++++++++++++ 2 files changed, 439 insertions(+), 10 deletions(-) create mode 100644 tests/sidechat-compaction-seed.spec.ts diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index b69349da..c2d3f9f9 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -18,6 +18,7 @@ */ import type { SidebarHistoryEntry, SidebarSessionSummary } from './context-types.ts' import type { AssistantLiveChunk } from './assistant-live.ts' +import { foldSurface } from '@deepseek-ai/dsh-session/surface' /** The durable thread-label prefix (also the row filter in the client list). */ export const SIDE_LABEL_PREFIX = 'Side: ' @@ -273,9 +274,211 @@ const SNAPSHOT_RESULT_CAP = 2000 /** Cap applied to the whole snapshot (prompt budget). */ const SNAPSHOT_TOTAL_CAP = 8000 +/** + * Rebase the parent's log onto its last summarizing compaction: the + * checkpoint `user/message` already REPLACES the shadowed span on the + * model-visible surface, so a child needs only the surviving pre-cut surface + * nodes, the checkpoint itself, and the post-compaction tail — the shadowed + * bulk never has to be physically copied again. The result is verified with + * the real fold before it is used: the rebased sequence must produce the + * SAME visible nodes as the parent, which keeps the child's model context + * (and provider context-cache prefix) identical to a full-log fork. + * + * Returns a seq-contiguous event array, or undefined to fall back to the + * verbatim full copy — no compaction in the log, a tail whose back + * references cannot be rebased, or any fold the construction cannot prove + * equivalent. Failures degrade to today's behavior, never to a wrong child. + * @param events - the parent's log (live or persisted). + * @returns the rebased log, or undefined when the full copy is required. + */ +function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] | undefined { + const cut = lastCheckpointIndex(events) + if (cut === undefined) return undefined + const checkpoint = events[cut] + if (checkpoint === undefined) return undefined + let head: SidechatLogEvent[] + let parentNodes: readonly number[] + try { + const fold = foldSurface(events as unknown as Parameters[0]) + parentNodes = fold.nodes + const surfaceIndex = parentNodes.indexOf(checkpoint.seq) + // The checkpoint must sit on the surface, and every node before its + // surface slot must predate the cut (a post-cut node reordered ahead of + // the checkpoint would need the very shadowing we are removing). + if (surfaceIndex === -1) return undefined + const before: SidechatLogEvent[] = [] + const after: SidechatLogEvent[] = [] + let sawTailNode = false + for (let index = 0; index < parentNodes.length; index++) { + if (index === surfaceIndex) continue + const node = events[parentNodes[index] as number] + if (node === undefined || node.seq >= cut) { + if (index > surfaceIndex) { + sawTailNode = true + continue + } + return undefined + } + // Surface order is [pre-cut before the checkpoint's slot][checkpoint] + // [pre-cut after its slot][tail in log order]; anything else cannot be + // reproduced by appending and degrades to the full copy. + if (sawTailNode) return undefined + if (index < surfaceIndex) before.push(node) + else after.push(node) + } + head = [...before, checkpoint, ...after] + } catch { + return undefined + } + // Surviving pre-cut tool/results are surface nodes; their PAIRED calls + // are log-only events the fold never kept. Emit each call right before + // its result so the child's pairs stay complete. + const headWithCalls: SidechatLogEvent[] = [] + for (const event of head) { + const callId = toolResultCallId(event) + if (callId !== undefined) { + const call = findPairedCall(events, cut, callId) + if (call !== undefined) headWithCalls.push(call) + } + headWithCalls.push(event) + } + // Positional renumbering: head (with calls) keeps surface order, the + // post-checkpoint tail keeps log order; both map old seqs onto 0..n-1. + // Head events are visible nodes re-emitted as plain appends — any replace + // they carried is already baked into WHICH nodes survive (the surfaceOp + // marker itself is required by the seed validator, while stale citations + // into the dropped head must not survive). + const rebase = new Map() + const seed: SeedEvent[] = [] + for (const event of headWithCalls) { + rebase.set(event.seq, seed.length) + seed.push( + event.type === 'tool/call' + ? { type: event.type, seq: seed.length, time: event.time, data: dataOf(event) } + : { type: event.type, seq: seed.length, time: event.time, data: dataOf(event), surfaceOp: 'append' }, + ) + } + for (const event of events.slice(cut + 1)) { + const rebased = rebaseTailEvent(event, seed.length, rebase) + if (rebased === undefined) return undefined + rebase.set(event.seq, seed.length) + seed.push(rebased) + } + // Prove equivalence before the caller relies on it: the rebased sequence + // must fold without error and to the same visible nodes as the parent. + try { + const child = foldSurface(seed as unknown as Parameters[0]) + if (!sameVisibleSequence(events, parentNodes, child.nodes, seed)) return undefined + } catch { + return undefined + } + return seed +} + +/** Index of the checkpoint user/message of the last summarizing compaction: + * the event right after the last `compaction/summary` — that adjacency is + * the shadow-price contract. Undefined without a matching shape. */ +function lastCheckpointIndex(events: readonly SidechatLogEvent[]): number | undefined { + for (let index = events.length - 1; index >= 0; index--) { + if (events[index]?.type !== 'compaction/summary') continue + return events[index + 1]?.type === 'user/message' ? index + 1 : undefined + } + return undefined +} + +/** The callId a tool/result event cites, when its message carries one. */ +function toolResultCallId(event: SidechatLogEvent): string | undefined { + if (event.type !== 'tool/result') return undefined + const message = dataOf(event).message as { source?: { callId?: unknown } } | undefined + const callId = message?.source?.callId + return typeof callId === 'string' && callId !== '' ? callId : undefined +} + +/** The last log-only tool/call with this callId before the cut, when present. */ +function findPairedCall(events: readonly SidechatLogEvent[], cut: number, callId: string): SidechatLogEvent | undefined { + for (let index = cut - 1; index >= 0; index--) { + const event = events[index] + if (event?.type === 'tool/call' && dataOf(event).callId === callId) return event + } + return undefined +} + +/** One `type` + message-content token per visible node, for comparing folds. + * `headerSeq` is envelope metadata the rebase rewrites, not content. */ +function visibleToken(event: SidechatLogEvent | undefined): string { + if (event === undefined) return 'missing' + const data = { ...dataOf(event) } + delete data.headerSeq + return `${event.type}:${JSON.stringify(data)}` +} + +/** Compare the parent's visible nodes with the rebased child's by content. */ +function sameVisibleSequence( + parent: readonly SidechatLogEvent[], + parentNodes: readonly number[], + childNodes: readonly number[], + child: readonly SidechatLogEvent[], +): boolean { + if (parentNodes.length !== childNodes.length) return false + for (let index = 0; index < parentNodes.length; index++) { + if (visibleToken(parent[parentNodes[index] as number]) !== visibleToken(child[childNodes[index] as number])) { + return false + } + } + return true +} + +/** + * Copy one post-checkpoint tail event into the rebased sequence: envelope + * seq references are remapped through the rebase map, and a reference the + * map cannot serve (it points into the dropped head) degrades the event + * honestly — a replace whose shadowed nodes are gone becomes an append, + * dropped citations vanish — except `developer/message.headerSeq`, whose + * referent cannot be degraded: that aborts the whole tail. + * @param event - the tail event to copy. + * @param seq - the event's position in the rebased sequence. + * @param rebase - old seq → rebased position over the kept set. + * @returns the rebased event, or undefined when the tail is not provable. + */ +function rebaseTailEvent(event: SidechatLogEvent, seq: number, rebase: Map): SeedEvent | undefined { + const source = event as SidechatLogEvent & { ignorable?: true } + const seed: SeedEvent = { type: source.type, seq, time: source.time, data: dataOf(source) } + if (source.ignorable === true) seed.ignorable = true + const sourceData = dataOf(event) + if (event.type === 'developer/message' && typeof sourceData.headerSeq === 'number') { + const mapped = rebase.get(sourceData.headerSeq) + if (mapped === undefined) return undefined + seed.data = { ...seed.data, headerSeq: mapped } + } + const op = (event as { surfaceOp?: unknown }).surfaceOp + if (op === 'append') { + seed.surfaceOp = 'append' + } else if (op !== null && typeof op === 'object' && 'op' in op && (op as { op: unknown }).op === 'replace') { + const replace = op as { startSeq?: unknown; endSeq?: unknown } + const start = typeof replace.startSeq === 'number' ? rebase.get(replace.startSeq) : undefined + const end = typeof replace.endSeq === 'number' ? rebase.get(replace.endSeq) : undefined + // A range the rebase cannot resolve lost its shadowed nodes with the + // head; appending the replacement is exactly what remains visible. + seed.surfaceOp = start !== undefined && end !== undefined && start <= end + ? { op: 'replace', startSeq: start, endSeq: end } + : 'append' + } + const cited = (event as { sourceEventSeqs?: unknown }).sourceEventSeqs + if (Array.isArray(cited)) { + const mapped = cited.map(item => typeof item === 'number' ? rebase.get(item) : undefined) + // Citations the rebase cannot serve referenced the dropped head; the + // field is optional and only has to cover a live replace range. + if (!mapped.includes(undefined)) seed.sourceEventSeqs = mapped as number[] + } + return seed +} + /** * Build the side-thread inheritance for one parent log: the full event log * up to the click moment, honestly closed when it ends inside an open turn. + * When the parent has compacted, the log is first rebased onto its last + * summarizing compaction (`compactionTail`) — same model-visible surface, a + * fraction of the durable copy. * @param events - the parent's log (live or persisted). * @param live - the parent's in-flight stream chunks (DSH 0.1.5+ publishes * them outside the log); used only by the snapshot fallback. @@ -285,26 +488,28 @@ export function buildSidechatInheritance( live: readonly AssistantLiveChunk[] = [], ): SidechatInheritance { if (events.length === 0) return { seed: [], snapshot: null } - const boundary = lastTurnBoundary(events) - if (boundary < 0 || events[boundary]?.type === 'turn/end') { + const trimmed = compactionTail(events) + const log = trimmed ?? events + const boundary = lastTurnBoundary(log) + if (boundary < 0 || log[boundary]?.type === 'turn/end') { // Ends outside any turn (or has no turns at all): the whole log is a // valid, balanced seed — possibly ending with a pending user message. - return { seed: copyEvents(events), snapshot: null } + return { seed: copyEvents(log), snapshot: null } } // Ends inside the open turn starting at `boundary`. - if (hasDanglingToolCall(events, boundary)) { + if (hasDanglingToolCall(log, boundary)) { // Cannot close honestly: cut before the open turn; the caller attaches // the structured snapshot to the boundary prompt instead. return { - seed: copyEvents(events.slice(0, boundary)), - snapshot: buildOpenTurnSnapshot(events, live), + seed: copyEvents(log.slice(0, boundary)), + snapshot: buildOpenTurnSnapshot(log, live), } } - const seed = copyEvents(events) - const last = events[events.length - 1] - const turn = numberAt(dataOf(events[boundary]!), 'turn') + const seed = copyEvents(log) + const last = log[log.length - 1] + const turn = numberAt(dataOf(log[boundary]!), 'turn') const now = last?.time ?? 0 - const openStep = openStepInTurn(events, boundary) + const openStep = openStepInTurn(log, boundary) if (openStep !== undefined) { seed.push({ type: 'step/end', seq: seed.length, time: now, data: { turn, step: openStep } }) } diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts new file mode 100644 index 00000000..295db6e9 --- /dev/null +++ b/tests/sidechat-compaction-seed.spec.ts @@ -0,0 +1,224 @@ +/** + * Compaction-tail seed spec: {@link buildSidechatInheritance} must reuse the + * parent's last summarizing compaction instead of copying its whole log. + * + * Why this is sound: the compaction checkpoint `user/message` REPLACES the + * shadowed span on the model-visible surface, so a child seeded with + * [pre-cut visible nodes + checkpoint + post-compaction tail] folds to the + * SAME surface as the parent — identical model-visible conversation, same + * provider context-cache prefix — while dropping the shadowed bulk from the + * durable copy. The construction is verified with the REAL fold + * (`foldSurface` from `@deepseek-ai/dsh-session/surface`): when the tail + * cannot be proven equivalent (dangling back-references, reordering + * replaces), the builder falls back to today's verbatim full copy. + */ +import { describe, expect, it } from 'vitest' +import { foldSurface } from '@deepseek-ai/dsh-session/surface' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import { buildSidechatInheritance } from '../src/sidechat-core.ts' +import type { SidebarSessionEvent } from '../src/context-types.ts' + +/** Log-only event (no surface marker; folds to nothing visible). */ +function lo(type: string, seq: number, data: Record = {}): SidebarSessionEvent { + return { type, seq, time: seq * 1000, data } as SidebarSessionEvent +} + +/** Surface-eligible event appended the way the live pipeline appends it. */ +function sf(type: string, seq: number, data: Record): SidebarSessionEvent { + return { type, seq, time: seq * 1000, data, surfaceOp: 'append' } as SidebarSessionEvent +} + +function userMessage(id: string, text: string): Record { + return { id, role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } } +} + +function assistantMessage(text: string): Record { + return { + id: `m-${text}`, + role: 'assistant', + content: [{ type: 'text', text }], + source: { kind: 'model', stream: [] }, + } +} + +function toolResultMessage(callId: string, text: string): Record { + return { + id: `m-${callId}`, + role: 'tool', + source: { kind: 'tool', callId }, + toolCallId: callId, + content: [{ type: 'text', text }], + isError: false, + } +} + +/** One completed turn with an optional tool pair; returns its events plus the + * seqs of its surface-visible nodes (user, result, assistant). */ +function turn( + seq: number, + turnNumber: number, + over: { text?: string; callId?: string; result?: string } = {}, +): { events: SidebarSessionEvent[]; nodes: number[] } { + const text = over.text ?? `q${turnNumber}` + const events: SidebarSessionEvent[] = [ + lo('turn/start', seq, { turn: turnNumber }), + lo('step/start', seq + 1, { turn: turnNumber, step: 1 }), + ] + const nodes: number[] = [seq + 2] + events.push(sf('user/message', seq + 2, userMessage(`m-q${turnNumber}`, text))) + let next = seq + 3 + if (over.callId !== undefined) { + events.push(lo('tool/call', next, { turn: turnNumber, step: 1, callId: over.callId, name: 'bash', arguments: '{}' })) + events.push(sf('tool/result', next + 1, { turn: turnNumber, step: 1, message: toolResultMessage(over.callId, over.result ?? 'ok') })) + nodes.push(next + 1) + next += 2 + } + events.push(sf('assistant/message', next, { turn: turnNumber, step: 1, message: assistantMessage(`a${turnNumber}`), stream: [] })) + nodes.push(next) + events.push(lo('step/end', next + 1, { turn: turnNumber, step: 1 })) + events.push(lo('turn/end', next + 2, { turn: turnNumber, reason: { kind: 'completed' } })) + return { events, nodes } +} + +interface CompactedLog { + readonly events: SidebarSessionEvent[] + /** Seqs the checkpoint shadows (the old span's surface nodes). */ + readonly shadowed: number[] + /** The checkpoint replacement event's seq. */ + readonly checkpoint: number +} + +/** + * The canonical compacted parent: protected system head, one shadowed old + * turn WITH a tool pair, one keep-window turn WITH its own tool pair, the + * compaction group, then one post-compaction tail turn. + */ +function compactedLog(): CompactedLog { + const events: SidebarSessionEvent[] = [ + sf('system/message', 0, { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'system prompt' }], source: { kind: 'system' } }), + ] + const old = turn(1, 1, { callId: 'c-old', result: 'old result' }) + events.push(...old.events) + const keep = turn(1 + old.events.length, 2, { callId: 'c-keep', result: 'keep result' }) + events.push(...keep.events) + let seq = events.length + const shadowed = old.nodes + events.push(lo('compaction/start', seq, { compactionId: 'cp1', turn: null })) + events.push(lo('compaction/summary', seq + 1, { + compactionId: 'cp1', + summary: [{ type: 'text', text: 'turn 1 summarized' }], + shadowedRange: { start: shadowed[0] ?? 0, end: shadowed[shadowed.length - 1] ?? 0 }, + shadowedSeqs: shadowed, + shadowedTokenCount: 100, + provider: 'deepseek', + model: 'test-model', + rawOutput: [], + llmStreamCall: true, + })) + const checkpoint = seq + 2 + events.push({ + type: 'user/message', + seq: checkpoint, + time: checkpoint * 1000, + data: { + id: 'm-cp1', + role: 'user', + content: [{ type: 'text', text: 'turn 1 summarized' }], + source: { kind: 'compact-checkpoint', compactionId: 'cp1' }, + }, + surfaceOp: { op: 'replace', startSeq: shadowed[0] ?? 0, endSeq: shadowed[shadowed.length - 1] ?? 0 }, + sourceEventSeqs: shadowed, + } as SidebarSessionEvent) + events.push(lo('compaction/end', seq + 3, { compactionId: 'cp1', turn: null })) + events.push(...turn(seq + 4, 3, { callId: 'c-tail', result: 'tail result' }).events) + return { events, shadowed, checkpoint } +} + +/** The model-visible sequence a fold produces: one `type:data` token per node. */ +function visibleSequence(events: readonly SidebarSessionEvent[]): string[] { + const fold = foldSurface(events as unknown as readonly SessionEvent[]) + return fold.nodes.map(seq => { + const event = events[seq] + return event === undefined ? `missing:${seq}` : `${event.type}:${JSON.stringify(event.data)}` + }) +} + +function expectContiguous(seed: readonly { seq: number }[]): void { + seed.forEach((event, index) => expect(event.seq).toBe(index)) +} + +describe('buildSidechatInheritance compaction tail', () => { + it('reuses the last summarizing compaction instead of copying the shadowed span', () => { + const { events, checkpoint } = compactedLog() + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + // The shadowed old turn (its visible nodes AND its log-only scaffolding + // and tool/call) is dropped entirely. + expect(seed.length).toBeLessThan(events.length) + expect(seed.some(event => JSON.stringify(event).includes('old result'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('c-old'))).toBe(false) + // The keep window survives — including its paired tool call before its result. + const keepCall = seed.findIndex(event => JSON.stringify(event).includes('c-keep')) + const keepResult = seed.findIndex(event => JSON.stringify(event).includes('keep result')) + expect(keepCall).toBeGreaterThanOrEqual(0) + expect(keepResult).toBeGreaterThan(keepCall) + // The checkpoint survives as a plain append (its replace targets are gone). + const cp = seed.find(event => event.seq !== undefined && JSON.stringify(event).includes('turn 1 summarized')) + expect(cp).toBeDefined() + expect((cp as { surfaceOp?: unknown }).surfaceOp).toBe('append') + expect((cp as { sourceEventSeqs?: unknown }).sourceEventSeqs).toBeUndefined() + expectContiguous(seed) + void checkpoint + }) + + it('folds to the same model-visible sequence as the parent (surface equivalence)', () => { + const { events } = compactedLog() + const parent = visibleSequence(events) + expect(parent.length).toBeGreaterThan(0) + const { seed } = buildSidechatInheritance(events) + const child = visibleSequence(seed) + expect(child).toEqual(parent) + }) + + it('falls back to the verbatim full copy when the log has no compaction', () => { + const { events } = turn(0, 1, { callId: 'c1' }) + const { seed } = buildSidechatInheritance(events) + expectContiguous(seed) + expect(seed.map(event => event.type)).toEqual(events.map(event => event.type)) + }) + + it('falls back to the verbatim full copy when a tail event references the dropped head', () => { + const { events } = compactedLog() + // A developer/message citing a pre-cut request/header: the reference + // cannot be renumbered, so the tail is not provably equivalent. + const dangling = sf('developer/message', events.length, { + id: 'm-dev', + role: 'developer', + content: [{ type: 'text', text: 'dev' }], + source: { kind: 'developer' }, + headerSeq: 1, + }) + const withDangling = [...events, dangling] + const { seed } = buildSidechatInheritance(withDangling) + const full = buildSidechatInheritance(events) + // Full copy of the SAME log minus the dangling event appended... the + // fallback copies everything verbatim, so the seed carries the old span. + expect(seed.some(event => JSON.stringify(event).includes('old result'))).toBe(true) + void full + }) + + it('keeps the open-turn closers and snapshot semantics on the trimmed tail', () => { + const { events, checkpoint } = compactedLog() + // Append an OPEN turn whose tool call has no result yet → dangling → + // the builder cuts before it and delivers a structured snapshot. + let seq = events.length + events.push(lo('turn/start', seq, { turn: 4 })) + events.push(lo('step/start', seq + 1, { turn: 4, step: 1 })) + events.push(lo('tool/call', seq + 2, { turn: 4, step: 1, callId: 'c-open', name: 'bash', arguments: '{}' })) + const { seed, snapshot } = buildSidechatInheritance(events) + expectContiguous(seed) + expect(seed.at(-1)?.type).not.toBe('tool/call') + expect(snapshot).not.toBeNull() + void checkpoint + }) +})