From 32e7d041ad60347e8f91e763476bd3bfadd49a97 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Wed, 14 Oct 2026 21:22:01 -0700 Subject: [PATCH 01/12] 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 + }) +}) From f2443445aa7921261f118df0c1ef73d9453084aa Mon Sep 17 00:00:00 2001 From: NolanHo Date: Wed, 14 Oct 2026 21:26:20 -0700 Subject: [PATCH 02/12] test(sidechat): real-validator acceptance for the compaction-tail seed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Session.create must accept the rebased seed exactly as the routes pass it (isSeeded + the inherited cut): this is the layer that once caught a seed whose surfaceOp markers were stripped, so it gates every envelope decision the rebasing makes — degraded replaces, remapped citations, kept tool pairs. The constructor's appended end-seed marker lands as the child's first own event, same shape as today's full-copy threads. --- tests/sidechat-compaction-seed.spec.ts | 33 ++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index 295db6e9..9e75f10c 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -14,7 +14,8 @@ */ import { describe, expect, it } from 'vitest' import { foldSurface } from '@deepseek-ai/dsh-session/surface' -import type { SessionEvent } from '@deepseek-ai/dsh-session' +import { Session, SessionLogOffset, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' import { buildSidechatInheritance } from '../src/sidechat-core.ts' import type { SidebarSessionEvent } from '../src/context-types.ts' @@ -37,7 +38,7 @@ function assistantMessage(text: string): Record { id: `m-${text}`, role: 'assistant', content: [{ type: 'text', text }], - source: { kind: 'model', stream: [] }, + source: { kind: 'model', provider: 'test', model: 'model-x' }, } } @@ -95,13 +96,13 @@ interface CompactedLog { */ function compactedLog(): CompactedLog { const events: SidebarSessionEvent[] = [ - sf('system/message', 0, { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'system prompt' }], source: { kind: 'system' } }), + sf('system/message', 0, { message: { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'system prompt' }], source: { kind: 'system-prompt' } } }), ] 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 seq = events.length const shadowed = old.nodes events.push(lo('compaction/start', seq, { compactionId: 'cp1', turn: null })) events.push(lo('compaction/summary', seq + 1, { @@ -207,11 +208,33 @@ describe('buildSidechatInheritance compaction tail', () => { void full }) + it('is accepted by the real dsh-session seed validator', () => { + const { events } = compactedLog() + const { seed } = buildSidechatInheritance(events) + // The REAL validator, exactly as the routes call it (isSeeded + the + // inherited cut) — this is the layer that once rejected a seed whose + // surfaceOp markers were stripped, so it gates every envelope decision + // the rebasing makes. + const id = 'session-compaction-seed-acceptance' + const session = Session.create( + id as SessionId, + seed as never, + { version: SESSION_FORMAT_VERSION, id: id as SessionId, createdAt: Date.now(), isSeeded: true }, + SessionLogOffset(seed.length), + ) + // The constructor appends the inherited-cut marker right after the seed, + // and that marker is the child's first own event (log position = the + // inherited count) — same shape as today's full-copy threads. + expect(session.snapshotEvents()).toHaveLength(seed.length + 1) + expect(session.ownEvents()).toHaveLength(1) + expect(session.ownEvents()[0]?.type).toBe('session/end-seed') + }) + 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 + const 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: '{}' })) From b025331b99177d07d1ecdcfa85efce5a648bbb5a Mon Sep 17 00:00:00 2001 From: NolanHo Date: Wed, 14 Oct 2026 21:30:06 -0700 Subject: [PATCH 03/12] docs(sidechat): compaction-tail seed plan; test: discriminate remap and interleave paths - plan doc: measured problem, the surface-equivalence argument, the construction (surface-order head emission, tail rebase with honest degradation, foldSurface self-verification, full-copy fallback), the explicit non-goals, and the deployment e2e gate. - spec: assert the trim fires in the remap case (a replace fully inside the tail must stay a REMAPPED replace, not degrade into the fallback copy) and pin the interleave fallback (a tail replace covering a surviving pre-cut node). --- ...026-10-13-sidechat-compaction-tail-seed.md | 62 +++++++++++++++++++ src/sidechat-core.ts | 26 ++++---- tests/sidechat-compaction-seed.spec.ts | 55 ++++++++++++++++ 3 files changed, 132 insertions(+), 11 deletions(-) create mode 100644 docs/plans/2026-10-13-sidechat-compaction-tail-seed.md diff --git a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md new file mode 100644 index 00000000..c103b68f --- /dev/null +++ b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md @@ -0,0 +1,62 @@ +# 侧边对话启动慢:种子改为从最后一次 compaction 切尾(可验证等价) + +> 2026-10-13 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts` + +## 问题 + +`sidechat.start` 把父会话的**整份事件日志**复制进子会话当种子(`buildSidechatInheritance` → `copyEvents` 全量),且宿主 `agents.create({ seed })` 会把它**物理落盘**。在一个真实部署上(生产库只读实测): + +- 最大的侧边对话子会话 `seed_length = 32,674`,`events` 表物理 **32,675 行**——每个 fork 都复制了一遍父日志; +- 36 个播种会话合计复制 **303,018 行 / 276.5 MB(zstd 后)**,而全库 `events` 只有 292 万行、3.8 GB——fork 的写放大同时是**库膨胀**的主导项之一; +- 被频繁 fork 的主会话 35,992 事件,且还在增长;宿主侧建会话成本与种子规模线性相关(`sidechat-routes.ts` 的 `CREATE_TIMEOUT_MS = 15_000` 就是对它的防御)。 + +## 为什么「从 compaction 切」是安全的 + +DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): + +- 四种 `compaction/*` 事件都是 **log-only**(不进模型可见面); +- 真正的 surface 替换者是紧跟 `compaction/summary` 之后那条 **checkpoint `user/message`**(携带 `surfaceOp: replace`,相邻性是 shadow-price 契约)——它把被压缩的旧段从**模型可见面**上换掉; +- 被替换的旧事件只留在日志里供确定性回放,**模型从此看不到它们**。 + +因此判据是:**只要子会话折叠出的 surface 与父当前 surface 逐节点相同,模型请求与 provider 上下文缓存前缀就和全量 fork 完全一致**——不需要逐字段论证请求装配。最近的测量也支持收益:主会话最后一个 summary 在 seq 34,324 / 日志 35,992,切尾后事件量约 4–15× 下降(取决于 compaction 新鲜度)。 + +## 设计 + +`buildSidechatInheritance` 先尝试 `compactionTail(events)`,成功则以**重基后的日志**走原有逻辑(开轮闭合、dangling tool-call 快照等全部原样复用),失败则回退今天的全量拷贝: + +``` +父日志: [sys][被 shadow 的旧轮…][keep-window 轮…][compaction 组+checkpoint][尾部轮…] +重基后: [sys][checkpoint(降级为 append)][keep-window 轮…][尾部轮…] + ↑按父 surface 的节点顺序发射 ↑log 序 + 引用手术 +``` + +1. **切割点** = 最后一个 `compaction/summary` 的下一条事件(checkpoint),形状不符则回退; +2. **头部**(父 surface 上 checkpoint 表位之前/之后的**存活**前切点节点,通常是系统头 + keep-window)按 surface 顺序降级为 `append` 重发——它们当初没被 shadow,append 即精确;存活的 `tool/result` 补插自己的 `tool/call`(call 是 log-only,fold 不会保留); +3. **尾部**(checkpoint 之后的事件)按 log 序重基:seq 按位置重编号(seed 契约要求从 0 连续,宿主不重编号);`surfaceOp: replace` 的范围、`sourceEventSeqs`、`developer/message.headerSeq` 等**向后引用**能全部映射则平移,映射不到则**诚实降级**(replace→append、引用删除),`headerSeq` 无法降级则整体回退; +4. **自证**:用宿主公开导出的真折叠 `foldSurface`(`@deepseek-ai/dsh-session/surface`,浏览器安全子路径)分别折父日志与重基结果,**逐节点比对可见消息序列**;不等价或折叠抛错 → 回退全量。新事件类型带来的「向后引用」长尾由此整体中和:要么折得过去,要么验证失败回退,永远不会产出坏子会话; +5. **回退** = 现行全量拷贝,行为逐字不变(无 compaction 的会话永远走这条路)。 + +## 明确不做 + +- 不做任意「最近 K 轮」截断——那会改变模型可见上下文与 provider 缓存前缀; +- 不做引用式继承(子会话直接引用父会话物理行)——需要动 dsh-session/session-persistence/format 的宿主变更,超出插件贡献面; +- 不加配置开关——回退路径本身就是安全阀;若上游评审要求可配置再加。 + +## 测试(`tests/sidechat-compaction-seed.spec.ts`,8 例) + +夹具覆盖:系统头(受 surface 0 位保护)、带 tool 配对的被 shadow 旧轮、带 tool 配对的 keep-window、compaction 组、带 tool 配对的尾部轮。 + +1. 切尾发生:被 shadow 旧段(含其 `tool/call`)整体消失,keep-window 的 `call→result` 顺序保留,checkpoint 降级为 `append`、无残留引用,seq 从 0 连续; +2. **surface 等价**(核心不变量):`foldSurface(重基种子)` 的可见序列 == 父日志的可见序列; +3. 无 compaction → 全量逐字拷贝(回归守卫); +4. 回退:尾部 `developer/message` 引用被丢弃的头部 → 全量拷贝; +5. **真实验证器**:`Session.create(isSeeded + inherited cut)` 接受重基种子(历史上 surfaceOp 剥离 bug 的检出层);构造器补的 `session/end-seed` 落为子会话第一个 own event,与现行全量线程同形; +6. 开轮 dangling tool-call → 照旧切在轮前 + 结构化快照; +7. **重映射**:尾部 replace 范围完全在尾内 → 保留为重基后的 replace(非降级),等价仍成立; +8. **交错回退**:尾部 replace 覆盖存活的前切点节点(会重排 surface)→ 回退全量。 + +判别性(已逐条实测):关掉「头部按 surface 顺序发射」→ 例 1 当场红;毁掉尾部 replace 的重映射/降级分支 → 例 7 当场红。**披露**:`sameVisibleSequence` 终验单独变异不可由行为测试变红(它是纵深防御,只有与构造缺陷叠加才可观察——例 7 的变异正是被终验拦截的实例);表面 0 位保护、`system-prompt`/`model` 消息源等形状约束由例 5 的真实验证器背书。 + +## 部署验证 + +构建装进 3097+ 口的独立第二实例(独立 `DSH_HOME` + 会话库快照)端到端验证:fork 一个带 compaction 的大会话,断言 (a) 子会话事件数显著小于父会话、(b) 子会话能收到带完整上下文的首答(边界提示之后的回答引用旧轮内容)、(c) 生产实例 PID 全程不动。 diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index c2d3f9f9..9320ce52 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -4,17 +4,21 @@ * node test environment can import it. * * A side thread is a child session the plugin creates ITSELF with a custom - * seed — the parent session's FULL event log up to the click moment - * (completed turns, the unanswered user message, and — when the parent is - * mid-turn — the in-progress assistant output and tool activity). The log - * model forbids open-turn seeds, so an in-flight parent turn is copied - * verbatim and CLOSED with synthetic `step/end` + `turn/end{reason: - * 'interrupted'}` events: the child sees the partial turn as honestly - * frozen ("cut off"), never as a completed answer. The one case that cannot - * be closed honestly — a tool call still executing (no `tool/result` yet; - * providers reject dangling assistant calls) — falls back to cutting before - * the open turn and carrying the partial content as a structured text - * snapshot inside the boundary prompt. + * seed — the parent's model-visible history up to the click moment. When the + * parent has summarized (its last compaction checkpoint replaces the + * shadowed span on the surface), the seed is REBASED onto that checkpoint: + * surviving pre-cut surface nodes, the checkpoint, and the post-compaction + * tail — proven equivalent to a full-log fork by folding both (compactionTail) + * — instead of physically duplicating the whole log. Without a compaction, + * or whenever the rebasing cannot be proven, the seed is the parent's FULL + * event log verbatim. The log model forbids open-turn seeds, so an + * in-flight parent turn is copied verbatim and CLOSED with synthetic + * `step/end` + `turn/end{reason: 'interrupted'}` events: the child sees the + * partial turn as honestly frozen ("cut off"), never as a completed answer. + * The one case that cannot be closed honestly — a tool call still executing + * (no `tool/result` yet; providers reject dangling assistant calls) — falls + * back to cutting before the open turn and carrying the partial content as + * a structured text snapshot inside the boundary prompt. */ import type { SidebarHistoryEntry, SidebarSessionSummary } from './context-types.ts' import type { AssistantLiveChunk } from './assistant-live.ts' diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index 9e75f10c..071d0e01 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -208,6 +208,61 @@ describe('buildSidechatInheritance compaction tail', () => { void full }) + it('remaps replace operations that stay inside the tail', () => { + const { events } = compactedLog() + // One more closed tail turn, then a replacement user/message whose + // replace range covers ONLY that turn's tail nodes: the range rebases + // intact, the fold still shows the same transitions, the trim fires. + const tailTurn = turn(events.length, 4) + const replacedSeqs = tailTurn.nodes + events.push(...tailTurn.events) + const replacementSeq = events.length + events.push({ + type: 'user/message', + seq: replacementSeq, + time: replacementSeq * 1000, + data: userMessage('m-edited', 'edited tail question'), + surfaceOp: { op: 'replace', startSeq: replacedSeqs[0] ?? 0, endSeq: replacedSeqs[replacedSeqs.length - 1] ?? 0 }, + sourceEventSeqs: replacedSeqs, + } as SidebarSessionEvent) + const parent = visibleSequence(events) + const { seed } = buildSidechatInheritance(events) + // The trim must still fire here (the replace reorders only tail nodes — + // no fallback), which is what makes the remap assertions below meaningful. + expect(seed.length).toBeLessThan(events.length) + expect(visibleSequence(seed)).toEqual(parent) + const rebased = seed.find(event => { + const op = (event as { surfaceOp?: unknown }).surfaceOp + return typeof op === 'object' && op !== null && (op as { op?: unknown }).op === 'replace' + }) as { surfaceOp?: { startSeq: number; endSeq: number }; seq?: number } | undefined + // Not degraded: the range survived as a REMAPPED replace bound to the + // rebased positions (not to the parent's dropped-head seq space). + expect(rebased).toBeDefined() + expect(rebased?.surfaceOp?.startSeq).toBeLessThan(rebased?.seq ?? 0) + expect(rebased?.surfaceOp?.endSeq).toBeLessThan(rebased?.seq ?? 0) + }) + + it('falls back to the full copy when a tail replace reorders surviving nodes', () => { + const { events } = compactedLog() + // A replacement whose range covers a SURVIVING pre-cut node: the parent + // fold removes that node and repositions the replacement at its slot, + // which appending cannot reproduce — the verified equivalence must + // reject the trim and fall back to today's verbatim full copy. + const keepUserSeq = events.findIndex(event => JSON.stringify(event).includes('m-q2')) + const replacementSeq = events.length + events.push({ + type: 'user/message', + seq: replacementSeq, + time: replacementSeq * 1000, + data: userMessage('m-resurfaced', 'resurfaced edit'), + surfaceOp: { op: 'replace', startSeq: keepUserSeq, endSeq: keepUserSeq }, + sourceEventSeqs: [keepUserSeq], + } as SidebarSessionEvent) + const { seed } = buildSidechatInheritance(events) + expect(seed.some(event => JSON.stringify(event).includes('old result'))).toBe(true) + expect(seed.length).toBe(events.length + 0) + }) + it('is accepted by the real dsh-session seed validator', () => { const { events } = compactedLog() const { seed } = buildSidechatInheritance(events) From 90d04f7aa00f7c772dee028a506ceedc07f3b690 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Wed, 14 Oct 2026 22:40:47 -0700 Subject: [PATCH 04/12] fix(sidechat): keep turn/step skeletons in the compaction-tail seed (review round 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two independent reviews converged on one blocking root cause: the first construction kept only surface nodes, so the open turn's turn/start — which an automatic compaction necessarily precedes (it fires inside the open turn) — was dropped, silently bypassing the dangling-tool-call guard and the synthetic interrupted-closers, and the seed violated the host's requireOpenStep relational invariant. Construction v2 drops only the forgotten span and keeps everything else verbatim: the surviving head is wrapped in its enclosing turn/step skeleton (closers recovered from the log), the checkpoint lands at its surface slot as a plain append, and the keep window + tail keep their skeletons — so lastTurnBoundary, the closers, and the snapshot path run on the rebased log exactly as on the full copy. One uniform rebase for every kept event; orphaned summaries rescan to the previous complete compaction; the consumed group's log-only records ride out with the span they priced. Spec rewritten to host-shaped fixtures (system/message {turn, step, message}), adds the mid-turn automatic-compaction cases (closers + dangling snapshot), the real relational-invariant harness, and structural fallback assertions. Mutation-checked: skeleton wrap, remap branch, and orphan rescan each turn their case red. --- ...026-10-13-sidechat-compaction-tail-seed.md | 80 +-- src/sidechat-core.ts | 276 +++++++---- tests/sidechat-compaction-seed.spec.ts | 455 ++++++++++++------ 3 files changed, 536 insertions(+), 275 deletions(-) diff --git a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md index c103b68f..bb88d6ec 100644 --- a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md +++ b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md @@ -1,6 +1,6 @@ # 侧边对话启动慢:种子改为从最后一次 compaction 切尾(可验证等价) -> 2026-10-13 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts` +> 2026-10-13 起,2026-10-15 二审后重构为 v2 构造 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts`(11 例) ## 问题 @@ -8,33 +8,43 @@ - 最大的侧边对话子会话 `seed_length = 32,674`,`events` 表物理 **32,675 行**——每个 fork 都复制了一遍父日志; - 36 个播种会话合计复制 **303,018 行 / 276.5 MB(zstd 后)**,而全库 `events` 只有 292 万行、3.8 GB——fork 的写放大同时是**库膨胀**的主导项之一; -- 被频繁 fork 的主会话 35,992 事件,且还在增长;宿主侧建会话成本与种子规模线性相关(`sidechat-routes.ts` 的 `CREATE_TIMEOUT_MS = 15_000` 就是对它的防御)。 +- 被频繁 fork 的主会话 35,992 事件且持续增长;宿主侧建会话成本与种子规模线性相关(`CREATE_TIMEOUT_MS = 15_000` 就是对它的防御)。 ## 为什么「从 compaction 切」是安全的 DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): - 四种 `compaction/*` 事件都是 **log-only**(不进模型可见面); -- 真正的 surface 替换者是紧跟 `compaction/summary` 之后那条 **checkpoint `user/message`**(携带 `surfaceOp: replace`,相邻性是 shadow-price 契约)——它把被压缩的旧段从**模型可见面**上换掉; +- 真正的 surface 替换者是紧跟 `compaction/summary` 之后那条 **checkpoint `user/message`**(携带 `surfaceOp: replace`,相邻性是 shadow-price 契约)——它把被压缩的旧段从**模型可见面**上换掉;受保护的 0 号节点(system 头)不被 region 覆盖; - 被替换的旧事件只留在日志里供确定性回放,**模型从此看不到它们**。 -因此判据是:**只要子会话折叠出的 surface 与父当前 surface 逐节点相同,模型请求与 provider 上下文缓存前缀就和全量 fork 完全一致**——不需要逐字段论证请求装配。最近的测量也支持收益:主会话最后一个 summary 在 seq 34,324 / 日志 35,992,切尾后事件量约 4–15× 下降(取决于 compaction 新鲜度)。 +因此判据是:**只要子会话折叠出的 surface 与父当前 surface 逐节点相同,模型请求与 provider 上下文缓存前缀就和全量 fork 完全一致**。最近的测量也支持收益:主会话最后一个 summary 在 seq 34,324 / 日志 35,992,切尾后事件量约 4–15× 下降(取决于 compaction 新鲜度)。 -## 设计 +## 设计(v2:只丢「被遗忘区段」,其余逐字保留) -`buildSidechatInheritance` 先尝试 `compactionTail(events)`,成功则以**重基后的日志**走原有逻辑(开轮闭合、dangling tool-call 快照等全部原样复用),失败则回退今天的全量拷贝: +`buildSidechatInheritance` 先尝试 `compactionTail(events)`,成功则以**重基后的日志**走原有逻辑(开轮闭合、dangling tool-call 快照全部原样复用),失败则回退今天的全量拷贝: ``` -父日志: [sys][被 shadow 的旧轮…][keep-window 轮…][compaction 组+checkpoint][尾部轮…] -重基后: [sys][checkpoint(降级为 append)][keep-window 轮…][尾部轮…] - ↑按父 surface 的节点顺序发射 ↑log 序 + 引用手术 +父日志: [turn1: sys头+旧内容(被shadow)][keep-window 轮…][compaction 组+checkpoint][尾部…] +重基后: [turn1 骨架: turn/start,step/start,sys头,step/end,turn/end] ← 头部骨架包裹(关闭,因为关闭件在被丢弃区段里) + [checkpoint(降级为 append,置于其 surface 表位——被遗忘区段的起点)] + [keep-window 起(含其 turn/start)…切点)逐字] ← 骨架自然保留 + [切点后 …] 逐字(剔除本组 compaction 三个 log-only 记录) ``` -1. **切割点** = 最后一个 `compaction/summary` 的下一条事件(checkpoint),形状不符则回退; -2. **头部**(父 surface 上 checkpoint 表位之前/之后的**存活**前切点节点,通常是系统头 + keep-window)按 surface 顺序降级为 `append` 重发——它们当初没被 shadow,append 即精确;存活的 `tool/result` 补插自己的 `tool/call`(call 是 log-only,fold 不会保留); -3. **尾部**(checkpoint 之后的事件)按 log 序重基:seq 按位置重编号(seed 契约要求从 0 连续,宿主不重编号);`surfaceOp: replace` 的范围、`sourceEventSeqs`、`developer/message.headerSeq` 等**向后引用**能全部映射则平移,映射不到则**诚实降级**(replace→append、引用删除),`headerSeq` 无法降级则整体回退; -4. **自证**:用宿主公开导出的真折叠 `foldSurface`(`@deepseek-ai/dsh-session/surface`,浏览器安全子路径)分别折父日志与重基结果,**逐节点比对可见消息序列**;不等价或折叠抛错 → 回退全量。新事件类型带来的「向后引用」长尾由此整体中和:要么折得过去,要么验证失败回退,永远不会产出坏子会话; -5. **回退** = 现行全量拷贝,行为逐字不变(无 compaction 的会话永远走这条路)。 +1. **切割点** = 最后一个「后随 user/message」的 `compaction/summary` 的下一条事件(孤立 summary 回扫到上一个完整的); +2. **头部** = 父最终 surface 上 checkpoint 表位之前的存活节点(通常就是受保护的 system 头),**包裹其所在 turn/step 骨架**:`turn/start + step/start + 节点 + step/end + turn/end`——关闭件从日志里取回,因为宿主会话关系不变量(`@deepseek-ai/dsh-session/invariant` 的 `requireOpenStep`)要求轮内事件必须点名一个打开的 turn/step,即便该轮其余内容已被压缩遗忘。头部跨多个 step/turn 的形状不构造(回退); +3. **keep-window 与尾部逐字保留**:`lastTurnBoundary`/`hasDanglingToolCall`/合成闭合器因此**在重基日志上照常工作**(自动 compaction 必发生在打开的轮内——`compaction-basic` 由 `agent/pre-step` 触发且 region 强制 enclosed-in-turn——开轮的骨架在切点之前,逐字保留意味着永远不丢); +4. **统一重基**:全部保留事件走同一个 `rebaseEvent`——seq 按位置重编号(seed 契约要求从 0 连续,宿主不重编号),`surfaceOp: replace` 范围、`sourceEventSeqs`、`developer/message.headerSeq` 等**向后引用**能映射则平移、映射不到则**诚实降级**(replace→append、引用删除),`headerSeq` 无法降级则整体回退; +5. **自证**:用宿主公开导出的真折叠 `foldSurface`(`@deepseek-ai/dsh-session/surface`,浏览器安全子路径)分别折父日志与重基结果,**逐节点比对可见消息序列**;不等价或折叠抛错 → 回退全量。新事件类型带来的「向后引用」长尾由此整体中和:要么折得过去,要么验证失败回退,永远不会产出坏子会话; +6. **回退** = 现行全量拷贝,行为逐字不变(无 compaction 的会话永远走这条路;探针实测五种形状回退输出与改前逐字节一致)。 + +### 证明范围与披露 + +- 等价证明覆盖**可见节点内容序列**;`request/header`/`request/context` 等模型装配输入中 log-only 的部分,keep-window 与尾部内的会随逐字保留带过去,更老的随区段丢弃——实测(二审探针,6 组工具集变化组合):子会话首个请求经宿主 `projectToolUpdates` 投影后与全量 fork **完全一致**(子会话自建的 header 重置 declaration series),今天无可观测差异;此推理链无测试 pin,属已知边界。 +- 日志含 `image/offload` 等 **MESSAGE_PROJECTION 事件类型**时 `foldSurface`(无 projections)抛错 → 回退全量(安全,但含图长会话拿不到收益)。同理,未来插件自定义 projection 不在 core 集合内时证明会失真为「回退」而非「假通过」。 +- 孤立 compaction 组(summary 后替换未落地)的 log-only 记录随尾部保留(折叠不可见,保留宿主 metering 历史);构造时剔除的只有**本次消费的那一组**。 +- 第二个 system 头(checkpoint 表位之前的其他存活节点)实测受支持(二审探针 E:trim 生效、等价、validator 接受)。 ## 明确不做 @@ -42,21 +52,37 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): - 不做引用式继承(子会话直接引用父会话物理行)——需要动 dsh-session/session-persistence/format 的宿主变更,超出插件贡献面; - 不加配置开关——回退路径本身就是安全阀;若上游评审要求可配置再加。 -## 测试(`tests/sidechat-compaction-seed.spec.ts`,8 例) +## 测试(`tests/sidechat-compaction-seed.spec.ts`,11 例) -夹具覆盖:系统头(受 surface 0 位保护)、带 tool 配对的被 shadow 旧轮、带 tool 配对的 keep-window、compaction 组、带 tool 配对的尾部轮。 +夹具为宿主真实形状:`system/message {turn, step, message}`(`source.kind: 'system-prompt'`)、`tool/result` 挂 `message`、assistant 消息带 `model` source;compaction 组含手动(`turn: null`)与自动(`turn: `)两种形态,且**开轮的 turn/start 与首条消息在切点之前**(二审 B1 的触发形状)。 -1. 切尾发生:被 shadow 旧段(含其 `tool/call`)整体消失,keep-window 的 `call→result` 顺序保留,checkpoint 降级为 `append`、无残留引用,seq 从 0 连续; -2. **surface 等价**(核心不变量):`foldSurface(重基种子)` 的可见序列 == 父日志的可见序列; -3. 无 compaction → 全量逐字拷贝(回归守卫); -4. 回退:尾部 `developer/message` 引用被丢弃的头部 → 全量拷贝; -5. **真实验证器**:`Session.create(isSeeded + inherited cut)` 接受重基种子(历史上 surfaceOp 剥离 bug 的检出层);构造器补的 `session/end-seed` 落为子会话第一个 own event,与现行全量线程同形; -6. 开轮 dangling tool-call → 照旧切在轮前 + 结构化快照; -7. **重映射**:尾部 replace 范围完全在尾内 → 保留为重基后的 replace(非降级),等价仍成立; -8. **交错回退**:尾部 replace 覆盖存活的前切点节点(会重排 surface)→ 回退全量。 +1. 切尾发生:被 shadow 旧段(含 `tool/call`)整体消失,头部以闭合骨架 `[turn/start, step/start, system/message, step/end, turn/end]` 保留,keep-window 的 call→result 顺序保留,checkpoint 降级为 `append`、无残留引用,seq 从 0 连续; +2. **surface 等价**(核心不变量):`foldSurface(重基种子)` 可见序列 == 父日志可见序列; +3. **真实验证器 + 真实关系不变量**:`Session.create(isSeeded + inherited cut)` 接受;`@deepseek-ai/dsh-session/invariant` 对父日志、切尾种子、全量对照全部零失败; +4. 无 compaction → 全量逐字拷贝(回归守卫); +5. 回退(尾部 `developer/message` 引用被丢弃区段)→ 与改前行为**逐事件相同**(类型序列全等断言,非仅文本查找); +6. 回退(尾部 replace 覆盖存活的前切点节点)→ 同上; +7. **轮内 compaction + 开轮普通消息** → trim 照常发生 + 合成 `step/end`/`turn/end{interrupted}` 闭合器照常落盘 + 不变量零失败; +8. **轮内 compaction + 悬空 tool call** → trim 照常发生 + 截在开轮前 + 结构化快照照常交付(providers 拒绝悬空 assistant 调用的保护不因切尾失效); +9. **重映射**:尾部 replace 范围完全在尾内 → 保留为重基后的 replace(非降级),trim 必须发生、等价必须成立; +10. **孤立 summary 回扫**:最新 compaction 的替换未落地 → 沿用上一个完整 compaction(trim 仍生效),死组的 log-only 记录随尾部保留; +11. 真实验证器验收(`Session.create` + end-seed 标记落为子会话第一个 own event,与全量线程同形)。 -判别性(已逐条实测):关掉「头部按 surface 顺序发射」→ 例 1 当场红;毁掉尾部 replace 的重映射/降级分支 → 例 7 当场红。**披露**:`sameVisibleSequence` 终验单独变异不可由行为测试变红(它是纵深防御,只有与构造缺陷叠加才可观察——例 7 的变异正是被终验拦截的实例);表面 0 位保护、`system-prompt`/`model` 消息源等形状约束由例 5 的真实验证器背书。 +判别性(全部实测过红): +- 去掉「头部按 surface 序发射/骨架包裹」→ 例 1 / 例 3 当场红(后者由 invariant 拒绝); +- 毁掉尾部 replace 重映射/降级分支 → 例 9 当场红; +- 孤儿 summary 不回扫 → 例 10 当场红。 +**披露**:`sameVisibleSequence` 终验单独变异不可由行为测试变红(它是纵深防御,只有与构造缺陷叠加才可观察——二审的 B1 修复前正是「构造缺陷 + 守卫被绕过」的叠加形态,例 7/8 就是为此而设)。 -## 部署验证 +## 独立审查记录(两轮,双 corpus 投票) -构建装进 3097+ 口的独立第二实例(独立 `DSH_HOME` + 会话库快照)端到端验证:fork 一个带 compaction 的大会话,断言 (a) 子会话事件数显著小于父会话、(b) 子会话能收到带完整上下文的首答(边界提示之后的回答引用旧轮内容)、(c) 生产实例 PID 全程不动。 +一审(2026-10-15,Standards + Spec 双轴,独立 subagent):两票均 **CHANGES_REQUIRED**,blocking 收敛于同一根因——v1 构造只保留 surface 节点,把前切点的 turn/step 骨架丢掉:(a) 自动 compaction 必在打开的轮内,开轮的 `turn/start` 被丢后 `lastTurnBoundary` 返回 -1,悬空 tool-call 守卫与合成闭合器被静默绕过;(b) 违反宿主 `requireOpenStep` 关系不变量。两位审查者各留树外证据脚本(`check-midturn` / `check-invariant` / `probe1-5`),v2 修复后全部转绿(见上)。二审记录于 PR。 + +## 部署验证(已执行,2026-10-15) + +第二实例(3097 端口、独立 `DSH_HOME`、生产库 `sqlite3 .backup` 在线快照、生产 PID 全程 669050 未动;凭据 `.credentials.yaml` 复制后重启): + +- 对真实主会话(35,992 事件、14 次 summary compaction)`POST /sidebar/api/sidechat.start` → **701 ms** 返回; +- 子会话 `seed_length = 2,641`、物理 2,643 行——**13.6×**(旧式同父 fork 为 32,674); +- 请求装配(`system/message`、user 消息、`request/header`、`request/context`)全通过真实管线; +- 重启 staging 后**冷恢复**该切尾子会话并提问,模型凭被压缩的旧历史(只存在于 checkpoint 摘要中)给出准确回答(Mint vs Tinker loss 分歧、GLM-5.3 304B LoRA SFT、Megatron-LM #43 等细节)——上下文等价的行为级证明。 diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index 9320ce52..dcbcade9 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -281,17 +281,20 @@ 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. + * model-visible surface, so a child needs only the surviving head skeleton + * (with its turn/step scaffolding — the session relational invariants demand + * it), the checkpoint itself, and the keep-window + post-compaction tail + * VERBATIM — the forgotten span never has to be physically copied again, + * while every kept event keeps its enclosing structure. 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. + * verbatim full copy — no compaction in the log, a reference the rebase + * cannot resolve, 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. */ @@ -300,74 +303,69 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] 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) + 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 head: number[] = [] + let keepFirst: number | undefined + let sawTailNode = false + for (let index = 0; index < parentNodes.length; index++) { + if (index === surfaceIndex) continue + const seq = parentNodes[index] as number + if (seq >= cut) { + if (index < surfaceIndex) return undefined + sawTailNode = true + continue } - headWithCalls.push(event) + // Surface order is [head nodes][checkpoint][keep-window nodes][tail in + // log order]; anything else cannot be reproduced and degrades to the + // full copy. + if (sawTailNode) return undefined + if (index < surfaceIndex) head.push(seq) + else if (keepFirst === undefined) keepFirst = seq } - // 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 headEvents = headSkeleton(events, head) + if (headEvents === undefined) return undefined + const keepStart = enclosingTurnStart(events, keepFirst) + const groupId = dataOf(events[cut - 1]!).compactionId + // Positional renumbering over the kept set; every emitted event passes the + // same rebase: seq references remap when the map can serve them, and a + // reference into the dropped span degrades honestly (replace → append, + // dropped citations) — except `developer/message.headerSeq`, whose + // referent cannot be degraded: that aborts the whole tail. 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 + let aborted = false + const emit = (event: SidechatLogEvent | undefined): void => { + if (aborted || event === undefined) return + const rebased = rebaseEvent(event, seed.length, rebase) + if (rebased === undefined) { + aborted = true + return + } rebase.set(event.seq, seed.length) seed.push(rebased) } + for (const event of headEvents) emit(event) + emit(checkpoint) + for (let index = keepStart; index < cut; index++) { + const event = events[index] + if (event !== undefined && !isCompactionGroupEvent(event, groupId)) emit(event) + } + for (let index = cut + 1; index < events.length; index++) { + const event = events[index] + if (event !== undefined && !isCompactionGroupEvent(event, groupId)) emit(event) + } + if (aborted) return undefined // 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 { @@ -379,30 +377,116 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] return seed } +/** + * The surviving pre-cut head as a state-machine-complete event list: the + * head nodes (surface order == log order for surviving appends) wrapped in + * their enclosing turn/step scaffolding when that scaffolding itself lies in + * the dropped span — the session invariants require in-turn messages to + * name an open turn/step even when the rest of that turn is forgotten. Only + * a single enclosing step/turn is supported (the protected system head); + * anything wider falls back to the full copy. + * @param events - the parent's log. + * @param head - seqs of the surviving pre-cut surface nodes before the + * checkpoint's surface slot. + * @returns the head segment's events, or undefined when the shape is not + * representable. + */ +function headSkeleton(events: readonly SidechatLogEvent[], head: readonly number[]): SidechatLogEvent[] | undefined { + if (head.length === 0) return [] + const first = events[head[0] as number] + const last = events[head[head.length - 1] as number] + if (first === undefined || last === undefined) return undefined + let turnStart: SidechatLogEvent | undefined + let stepStart: SidechatLogEvent | undefined + for (let index = head[0]! - 1; index >= 0; index--) { + const event = events[index] + if (event === undefined) break + if (event.type === 'turn/end') break + if (event.type === 'step/end') { + // An earlier step of the same turn closed: the head node's step opens + // after it, but the step/start we want still lies between. + stepStart = undefined + continue + } + if (event.type === 'step/start' && stepStart === undefined) stepStart = event + if (event.type === 'turn/start') { + turnStart = event + break + } + } + const parts: SidechatLogEvent[] = [] + if (turnStart !== undefined) { + parts.push(turnStart) + const turn = dataOf(turnStart).turn + if (typeof turn !== 'number') return undefined + // Nodes must all sit in this one step/turn; a wider head is not a shape + // this builder represents. + for (const seq of head) { + const node = events[seq] + if (node === undefined) return undefined + const nodeData = dataOf(node) + if (nodeData.turn !== turn && nodeData.turn !== undefined) return undefined + } + if (stepStart !== undefined) parts.push(stepStart) + for (const seq of head) parts.push(events[seq]!) + // Close the skeleton when its closers are dropped with the span: the + // first step/end / turn/end of this step/turn after the last node. + const step = stepStart !== undefined ? dataOf(stepStart).step : undefined + let closedStep = false + for (let index = head[head.length - 1]! + 1; index < events.length; index++) { + const event = events[index] + if (event === undefined) break + if (!closedStep && event.type === 'step/end' && typeof step === 'number' && dataOf(event).step === step) { + parts.push(event) + closedStep = true + continue + } + if (event.type === 'turn/end' && dataOf(event).turn === turn) { + parts.push(event) + break + } + if (event.type === 'turn/start') break + } + return closedStep || step === undefined ? parts : undefined + } + // No enclosing turn: out-of-turn events are legal as-is. + for (const seq of head) { + const node = events[seq] + if (node === undefined) return undefined + parts.push(node) + } + return parts +} + +/** Log index of the turn/start enclosing one seq, or the seq itself when the + * node sits between turns — the keep window then starts verbatim at its + * own skeleton root. */ +function enclosingTurnStart(events: readonly SidechatLogEvent[], seq: number | undefined): number { + if (seq === undefined) return events.length + for (let index = seq - 1; index >= 0; index--) { + const event = events[index] + if (event === undefined) return seq + if (event.type === 'turn/start') return index + if (event.type === 'turn/end') return seq + } + return seq +} + +/** Whether one event belongs to the compaction group being consumed (its + * log-only start/summary/end records leave with the span they priced). */ +function isCompactionGroupEvent(event: SidechatLogEvent, groupId: unknown): boolean { + if (!event.type.startsWith('compaction/')) return false + return groupId === undefined ? true : dataOf(event).compactionId === groupId +} + /** 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. */ + * the event right after a `compaction/summary` — that adjacency is the + * shadow-price contract. An orphaned summary (its replacement never + * landed) is skipped in favor of the previous complete one. */ 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 + if (events[index + 1]?.type === 'user/message') return index + 1 } return undefined } @@ -433,24 +517,25 @@ function sameVisibleSequence( } /** - * 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. + * Copy one kept 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 span) 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 kept 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 { +function rebaseEvent(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) + const headerSeq = sourceData.headerSeq + if (event.type === 'developer/message' && typeof headerSeq === 'number') { + const mapped = rebase.get(headerSeq) if (mapped === undefined) return undefined seed.data = { ...seed.data, headerSeq: mapped } } @@ -462,7 +547,8 @@ function rebaseTailEvent(event: SidechatLogEvent, seq: number, rebase: Map typeof item === 'number' ? rebase.get(item) : undefined) - // Citations the rebase cannot serve referenced the dropped head; the + // Citations the rebase cannot serve referenced the dropped span; the // field is optional and only has to cover a live replace range. if (!mapped.includes(undefined)) seed.sourceEventSeqs = mapped as number[] } diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index 071d0e01..fc455d28 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -4,17 +4,19 @@ * * 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. + * [surviving head skeleton + checkpoint + keep-window + tail verbatim] + * folds to the SAME surface as the parent — identical model-visible + * conversation, same provider context-cache prefix — while the shadowed + * bulk never lands in the durable copy. The construction is verified with + * the REAL fold (`foldSurface` from `@deepseek-ai/dsh-session/surface`) and + * pinned against the REAL session relational invariants + * (`@deepseek-ai/dsh-session/invariant`): when the tail cannot be proven + * equivalent, 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 { Session, SessionLogOffset, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant' import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' import { buildSidechatInheritance } from '../src/sidechat-core.ts' import type { SidebarSessionEvent } from '../src/context-types.ts' @@ -33,11 +35,15 @@ function userMessage(id: string, text: string): Record { return { id, role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } } } -function assistantMessage(text: string): Record { +function assistantMessage(text: string, over: { callId?: string } = {}): Record { + const content: Array> = [{ type: 'text', text }] + if (over.callId !== undefined) { + content.unshift({ type: 'tool-call', callId: over.callId, name: 'bash', arguments: {} }) + } return { id: `m-${text}`, role: 'assistant', - content: [{ type: 'text', text }], + content, source: { kind: 'model', provider: 'test', model: 'model-x' }, } } @@ -53,12 +59,12 @@ function toolResultMessage(callId: string, text: string): Record expect(event.seq).toBe(index)) } +/** Run the REAL session relational invariants over one candidate log and + * return the failure messages (empty = the log satisfies them). */ +function invariantFailures(log: readonly SidebarSessionEvent[]): string[] { + const failures: string[] = [] + const session = { snapshotEvents: () => log } + const ctx = { + sessions: { list: () => [session] }, + on: () => {}, + invariants: { + register: (_pkg: string, installer: (c: unknown, f: (m: string) => void) => void) => { + installer(ctx, (message: string) => { failures.push(message) }) + return () => {} + }, + }, + } + void SessionInvariant.apply(ctx as never) + return failures +} + describe('buildSidechatInheritance compaction tail', () => { it('reuses the last summarizing compaction instead of copying the shadowed span', () => { - const { events, checkpoint } = compactedLog() + const events = 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. + // The shadowed old turn is dropped entirely — its visible nodes AND its + // log-only scaffolding and tool/call — while the protected head keeps + // its turn/step skeleton (closed, because the closers were dropped too). 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. + expect(seed.map(event => event.type).slice(0, 5)).toEqual([ + 'turn/start', 'step/start', 'system/message', 'step/end', 'turn/end', + ]) + // The keep window survives VERBATIM: its own tool call stays right + // 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')) + const cp = seed.find(event => JSON.stringify(event).includes('old turns 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 events = compactedLog() const parent = visibleSequence(events) expect(parent.length).toBeGreaterThan(0) const { seed } = buildSidechatInheritance(events) @@ -181,90 +279,17 @@ describe('buildSidechatInheritance compaction tail', () => { 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' }) + it('satisfies the real session relational invariants', () => { + const events = compactedLog() 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('remaps replace operations that stay inside the tail', () => { - const { events } = compactedLog() - // One more closed tail turn, then a replacement user/message whose - // replace range covers ONLY that turn's tail nodes: the range rebases - // intact, the fold still shows the same transitions, the trim fires. - const tailTurn = turn(events.length, 4) - const replacedSeqs = tailTurn.nodes - events.push(...tailTurn.events) - const replacementSeq = events.length - events.push({ - type: 'user/message', - seq: replacementSeq, - time: replacementSeq * 1000, - data: userMessage('m-edited', 'edited tail question'), - surfaceOp: { op: 'replace', startSeq: replacedSeqs[0] ?? 0, endSeq: replacedSeqs[replacedSeqs.length - 1] ?? 0 }, - sourceEventSeqs: replacedSeqs, - } as SidebarSessionEvent) - const parent = visibleSequence(events) - const { seed } = buildSidechatInheritance(events) - // The trim must still fire here (the replace reorders only tail nodes — - // no fallback), which is what makes the remap assertions below meaningful. expect(seed.length).toBeLessThan(events.length) - expect(visibleSequence(seed)).toEqual(parent) - const rebased = seed.find(event => { - const op = (event as { surfaceOp?: unknown }).surfaceOp - return typeof op === 'object' && op !== null && (op as { op?: unknown }).op === 'replace' - }) as { surfaceOp?: { startSeq: number; endSeq: number }; seq?: number } | undefined - // Not degraded: the range survived as a REMAPPED replace bound to the - // rebased positions (not to the parent's dropped-head seq space). - expect(rebased).toBeDefined() - expect(rebased?.surfaceOp?.startSeq).toBeLessThan(rebased?.seq ?? 0) - expect(rebased?.surfaceOp?.endSeq).toBeLessThan(rebased?.seq ?? 0) - }) - - it('falls back to the full copy when a tail replace reorders surviving nodes', () => { - const { events } = compactedLog() - // A replacement whose range covers a SURVIVING pre-cut node: the parent - // fold removes that node and repositions the replacement at its slot, - // which appending cannot reproduce — the verified equivalence must - // reject the trim and fall back to today's verbatim full copy. - const keepUserSeq = events.findIndex(event => JSON.stringify(event).includes('m-q2')) - const replacementSeq = events.length - events.push({ - type: 'user/message', - seq: replacementSeq, - time: replacementSeq * 1000, - data: userMessage('m-resurfaced', 'resurfaced edit'), - surfaceOp: { op: 'replace', startSeq: keepUserSeq, endSeq: keepUserSeq }, - sourceEventSeqs: [keepUserSeq], - } as SidebarSessionEvent) - const { seed } = buildSidechatInheritance(events) - expect(seed.some(event => JSON.stringify(event).includes('old result'))).toBe(true) - expect(seed.length).toBe(events.length + 0) + expect(invariantFailures(events)).toEqual([]) + expect(invariantFailures(seed)).toEqual([]) + expect(invariantFailures(buildSidechatInheritance(turn(0, 1, { callId: 'c1' }).events).seed)).toEqual([]) }) it('is accepted by the real dsh-session seed validator', () => { - const { events } = compactedLog() + const events = compactedLog() const { seed } = buildSidechatInheritance(events) // The REAL validator, exactly as the routes call it (isSeeded + the // inherited cut) — this is the layer that once rejected a seed whose @@ -285,18 +310,142 @@ describe('buildSidechatInheritance compaction tail', () => { expect(session.ownEvents()[0]?.type).toBe('session/end-seed') }) - 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. - const 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: '{}' })) + it('falls back to the verbatim full copy when the log has no compaction', () => { + const events = turn(0, 1, { callId: 'c1' }).events + 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 span', () => { + const events = compactedLog() + // A developer/message citing a pre-cut request/header: the reference + // cannot be renumbered, so the tail is not provably equivalent. The + // fallback must equal TODAY's behavior on this very log: the verbatim + // copy, event for event. + const withDangling = [...events, sf('developer/message', events.length, { + id: 'm-dev', + role: 'developer', + content: [{ type: 'text', text: 'dev' }], + source: { kind: 'developer' }, + headerSeq: 1, + })] + const { seed, snapshot } = buildSidechatInheritance(withDangling) + expect(snapshot).toBeNull() + expect(seed.map(event => event.type)).toEqual(withDangling.map(event => event.type)) + expect(seed.some(event => JSON.stringify(event).includes('old result'))).toBe(true) + }) + + it('falls back to the verbatim full copy when a tail replace reorders surviving nodes', () => { + const events = compactedLog() + // A replacement whose range covers a SURVIVING pre-cut node: the parent + // fold removes that node and repositions the replacement at its slot, + // which dropping the span cannot reproduce. + const keepUserSeq = events.findIndex(event => JSON.stringify(event).includes('m-q2')) + const replacementSeq = events.length + events.push({ + type: 'user/message', + seq: replacementSeq, + time: replacementSeq * 1000, + data: userMessage('m-resurfaced', 'resurfaced edit'), + surfaceOp: { op: 'replace', startSeq: keepUserSeq, endSeq: keepUserSeq }, + sourceEventSeqs: [keepUserSeq], + } as SidebarSessionEvent) const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.map(event => event.type)).toEqual(events.map(event => event.type)) + }) + + it('keeps the open-turn closers on the trimmed tail (mid-turn compaction)', () => { + const events = midTurnLog('closers') + // Automatic compaction ran inside the still-open turn; the fork happens + // mid-turn with a plain pending assistant message. The trim must fire + // AND the synthetic interrupted-closers must land — the open turn's + // skeleton is kept verbatim, so the open-turn detection still sees it. + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + expectContiguous(seed) + expect(seed.at(-2)?.type).toBe('step/end') + expect(seed.at(-1)?.type).toBe('turn/end') + expect((seed.at(-1) as { data?: { reason?: { kind?: string } } }).data?.reason?.kind).toBe('interrupted') + expect(invariantFailures(seed)).toEqual([]) + }) + + it('delivers the dangling-tool snapshot on the trimmed tail (mid-turn compaction)', () => { + const events = midTurnLog('dangling') + // Same shape but the open turn ends on a tool call with no result yet: + // providers reject dangling assistant calls, so the builder must cut + // before the open turn and deliver the structured snapshot — exactly as + // the full-copy path does. + const { seed, snapshot } = buildSidechatInheritance(events) + expect(seed.length).toBeLessThan(events.length) expectContiguous(seed) expect(seed.at(-1)?.type).not.toBe('tool/call') expect(snapshot).not.toBeNull() - void checkpoint + expect(JSON.stringify(snapshot)).toContain('bash') + }) + + it('remaps replace operations that stay inside the tail', () => { + const events = compactedLog() + // One more closed tail turn, then a replacement user/message whose + // replace range covers ONLY that turn's tail nodes: the range rebases + // intact, the fold still shows the same transitions, the trim fires. + const tailTurn = turn(events.length, 5) + const replacedSeqs = tailTurn.nodes + events.push(...tailTurn.events) + const replacementSeq = events.length + events.push({ + type: 'user/message', + seq: replacementSeq, + time: replacementSeq * 1000, + data: userMessage('m-edited', 'edited tail question'), + surfaceOp: { op: 'replace', startSeq: replacedSeqs[0] ?? 0, endSeq: replacedSeqs[replacedSeqs.length - 1] ?? 0 }, + sourceEventSeqs: replacedSeqs, + } as SidebarSessionEvent) + const parent = visibleSequence(events) + const { seed } = buildSidechatInheritance(events) + // The trim must still fire here (the replace reorders only tail nodes — + // no fallback), which is what makes the remap assertions meaningful. + expect(seed.length).toBeLessThan(events.length) + expect(visibleSequence(seed)).toEqual(parent) + const rebased = seed.find(event => { + const op = (event as { surfaceOp?: unknown }).surfaceOp + return typeof op === 'object' && op !== null && (op as { op?: unknown }).op === 'replace' + }) as { surfaceOp?: { startSeq: number; endSeq: number }; seq?: number } | undefined + // Not degraded: the range survived as a REMAPPED replace bound to the + // rebased positions (not to the parent's dropped-span seq space). + expect(rebased).toBeDefined() + expect(rebased?.surfaceOp?.startSeq).toBeLessThan(rebased?.seq ?? 0) + expect(rebased?.surfaceOp?.endSeq).toBeLessThan(rebased?.seq ?? 0) + }) + + it('reuses the previous compaction when the newest summary is orphaned', () => { + const events = compactedLog() + const at = events.length + // A second compaction whose replacement never landed (summary + error + // end, no checkpoint): the builder must fall back to the EARLIER + // complete compaction instead of the full copy. + events.push( + lo('compaction/start', at, { compactionId: 'cp-dead', turn: null }), + lo('compaction/summary', at + 1, { + compactionId: 'cp-dead', + summary: [{ type: 'text', text: 'never landed' }], + shadowedRange: { start: 3, end: 3 }, + shadowedSeqs: [3], + shadowedTokenCount: 10, + provider: 'deepseek', + model: 'test-model', + rawOutput: [], + llmStreamCall: true, + }), + lo('compaction/end', at + 2, { compactionId: 'cp-dead', turn: null, error: 'summarizer failed' }), + ) + const { seed } = buildSidechatInheritance(events) + // The trim fired through the EARLIER compaction: the old span is gone + // while the orphaned group's log-only records may ride along (the fold + // never sees them, and they keep the parent's metering history honest). + expect(seed.length).toBeLessThan(events.length) + expect(seed.some(event => JSON.stringify(event).includes('old result'))).toBe(false) }) }) From 0f9772a0d9d80040710eb3ef9afd1b6461fb038c Mon Sep 17 00:00:00 2001 From: NolanHo Date: Wed, 14 Oct 2026 23:10:44 -0700 Subject: [PATCH 05/12] fix(sidechat): renumber turns over the dropped gap and keep mid-span regions (review round 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two fresh reviews converged on a new blocking: the v2 head skeleton closes turn 1 while the keep window keeps its original turn/start{N}, so the seed's turn counter jumps (1, N) — both of the branch's own self-checks (foldSurface equivalence, Session.create) miss it, but the host's relational invariant throws InvariantError in sessions.create on every host that loads the invariant companion. The spec's invariant case passed only because its fixture put the keep window at turn 2 — the one continuous shape. Also from the same round: the host's compaction region boundary is only tool-pairing balanced, so it can end mid-turn — the keep interval then re-emits the shadowed early nodes of its first turn and the verification fell back (measured: only turn-aligned cut points ever trimmed). v3: renumber data.turn over the gap (first kept turn/start scanned in the keep interval AND the tail, since a head-only survivor set leaves the keep interval empty); skip shadowed surface events and orphaned tool/calls inside the keep interval; gate the result with turnSequenceValid — turn counters contiguous, steps opening/closing inside their turn, in-turn messages naming the open turn/step — the same semantics as the host invariant. Fixtures now use the real turn gap (shadowed whole turn between head and keep) plus a mid-span case; mutation-checked: turning the renumbering off reddens the real-gap invariant case. --- ...026-10-13-sidechat-compaction-tail-seed.md | 24 ++- src/sidechat-core.ts | 156 +++++++++++++++--- tests/sidechat-compaction-seed.spec.ts | 103 ++++++++++-- 3 files changed, 234 insertions(+), 49 deletions(-) diff --git a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md index bb88d6ec..aa73272b 100644 --- a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md +++ b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md @@ -1,6 +1,6 @@ # 侧边对话启动慢:种子改为从最后一次 compaction 切尾(可验证等价) -> 2026-10-13 起,2026-10-15 二审后重构为 v2 构造 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts`(11 例) +> 2026-10-13 起,2026-10-15 两轮独立审查后重构为 v3 构造 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts`(12 例) ## 问题 @@ -35,13 +35,15 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): 1. **切割点** = 最后一个「后随 user/message」的 `compaction/summary` 的下一条事件(孤立 summary 回扫到上一个完整的); 2. **头部** = 父最终 surface 上 checkpoint 表位之前的存活节点(通常就是受保护的 system 头),**包裹其所在 turn/step 骨架**:`turn/start + step/start + 节点 + step/end + turn/end`——关闭件从日志里取回,因为宿主会话关系不变量(`@deepseek-ai/dsh-session/invariant` 的 `requireOpenStep`)要求轮内事件必须点名一个打开的 turn/step,即便该轮其余内容已被压缩遗忘。头部跨多个 step/turn 的形状不构造(回退); 3. **keep-window 与尾部逐字保留**:`lastTurnBoundary`/`hasDanglingToolCall`/合成闭合器因此**在重基日志上照常工作**(自动 compaction 必发生在打开的轮内——`compaction-basic` 由 `agent/pre-step` 触发且 region 强制 enclosed-in-turn——开轮的骨架在切点之前,逐字保留意味着永远不丢); -4. **统一重基**:全部保留事件走同一个 `rebaseEvent`——seq 按位置重编号(seed 契约要求从 0 连续,宿主不重编号),`surfaceOp: replace` 范围、`sourceEventSeqs`、`developer/message.headerSeq` 等**向后引用**能映射则平移、映射不到则**诚实降级**(replace→append、引用删除),`headerSeq` 无法降级则整体回退; -5. **自证**:用宿主公开导出的真折叠 `foldSurface`(`@deepseek-ai/dsh-session/surface`,浏览器安全子路径)分别折父日志与重基结果,**逐节点比对可见消息序列**;不等价或折叠抛错 → 回退全量。新事件类型带来的「向后引用」长尾由此整体中和:要么折得过去,要么验证失败回退,永远不会产出坏子会话; +4. **统一重基**:全部保留事件走同一个 `rebaseEvent`——seq 按位置重编号(seed 契约要求从 0 连续,宿主不重编号);**`data.turn` 重编号**(宿主 turn 计数器必须连续跑 1,2,3…,被丢弃区段留下的轮号空洞由 keep/尾部整体下移填补;`step` 按轮重置故逐字保留即可);`surfaceOp: replace` 范围、`sourceEventSeqs`、`developer/message.headerSeq` 等**向后引用**能映射则平移、映射不到则**诚实降级**(replace→append、引用删除),`headerSeq` 无法降级则整体回退。首个被保留的 `turn/start` 可能在 keep 区间**或**(pre-cut 存活者只有受保护头时)只在尾部,两段都要扫; +5. **中段切点**(宿主 region 边界只受 tool-pairing 平衡约束、可止于轮中):keep 区间内**跳过被 checkpoint shadow 掉的 surface 事件**(同轮早期节点)与**孤儿 tool/call**(其 result 未存活),骨架照发——空 step 合法; +6. **自证**:用宿主公开导出的真折叠 `foldSurface`(`@deepseek-ai/dsh-session/surface`,浏览器安全子路径)分别折父日志与重基结果,**逐节点比对可见消息序列**(`headerSeq`/`turn`/`step` 是信封元数据、非模型可见内容,比对时豁免);再加一道**关系门** `turnSequenceValid`——轮号连续、step 开合于所属轮、轮内消息事件点名开轮/开步,与宿主 `@deepseek-ai/dsh-session/invariant` 的计数器同语义。不等价、折叠抛错或关系门失败 → 回退全量。新事件类型带来的「向后引用」长尾由此整体中和:要么折得过去,要么验证失败回退,永远不会产出坏子会话; 6. **回退** = 现行全量拷贝,行为逐字不变(无 compaction 的会话永远走这条路;探针实测五种形状回退输出与改前逐字节一致)。 ### 证明范围与披露 - 等价证明覆盖**可见节点内容序列**;`request/header`/`request/context` 等模型装配输入中 log-only 的部分,keep-window 与尾部内的会随逐字保留带过去,更老的随区段丢弃——实测(二审探针,6 组工具集变化组合):子会话首个请求经宿主 `projectToolUpdates` 投影后与全量 fork **完全一致**(子会话自建的 header 重置 declaration series),今天无可观测差异;此推理链无测试 pin,属已知边界。 +- **回退(安全、无收益)的已知形状**(三轮探针实测):受保护 system 头被**后期改写**到别的轮(宿主 system-prompt projection 的 mid-session 改写形态,头节点不在 turn 1 step 1);**单轮父会话**(compaction 发生在唯一仍在打开的轮内、无 keep 区间);父日志本身违反关系不变量(子会话回退后与 legacy 逐字节一致 = parity)。中段切点与 context-overflow(keep 只剩末节点)**已支持**(二审 E 例:trim 生效、等价、invariant 0/0)。 - 日志含 `image/offload` 等 **MESSAGE_PROJECTION 事件类型**时 `foldSurface`(无 projections)抛错 → 回退全量(安全,但含图长会话拿不到收益)。同理,未来插件自定义 projection 不在 core 集合内时证明会失真为「回退」而非「假通过」。 - 孤立 compaction 组(summary 后替换未落地)的 log-only 记录随尾部保留(折叠不可见,保留宿主 metering 历史);构造时剔除的只有**本次消费的那一组**。 - 第二个 system 头(checkpoint 表位之前的其他存活节点)实测受支持(二审探针 E:trim 生效、等价、validator 接受)。 @@ -52,7 +54,7 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): - 不做引用式继承(子会话直接引用父会话物理行)——需要动 dsh-session/session-persistence/format 的宿主变更,超出插件贡献面; - 不加配置开关——回退路径本身就是安全阀;若上游评审要求可配置再加。 -## 测试(`tests/sidechat-compaction-seed.spec.ts`,11 例) +## 测试(`tests/sidechat-compaction-seed.spec.ts`,12 例) 夹具为宿主真实形状:`system/message {turn, step, message}`(`source.kind: 'system-prompt'`)、`tool/result` 挂 `message`、assistant 消息带 `model` source;compaction 组含手动(`turn: null`)与自动(`turn: `)两种形态,且**开轮的 turn/start 与首条消息在切点之前**(二审 B1 的触发形状)。 @@ -66,17 +68,23 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): 8. **轮内 compaction + 悬空 tool call** → trim 照常发生 + 截在开轮前 + 结构化快照照常交付(providers 拒绝悬空 assistant 调用的保护不因切尾失效); 9. **重映射**:尾部 replace 范围完全在尾内 → 保留为重基后的 replace(非降级),trim 必须发生、等价必须成立; 10. **孤立 summary 回扫**:最新 compaction 的替换未落地 → 沿用上一个完整 compaction(trim 仍生效),死组的 log-only 记录随尾部保留; -11. 真实验证器验收(`Session.create` + end-seed 标记落为子会话第一个 own event,与全量线程同形)。 +11. **中段 keep-window**:region 止于 keep 首轮之内 → 被 shadow 的同轮早期节点与孤儿 tool/call 被跳过、骨架完整、等价成立、invariant 零失败; +12. 真实验证器验收(`Session.create` + end-seed 标记落为子会话第一个 own event,与全量线程同形)。 + +夹具使用**真实轮距**(受保护头 turn 1 + 被 shadow 的整轮 + keep 轮 3 起)——二审证明「keep 恰为 turn 2」的唯一连续夹具会让 invariant 用例假绿。 判别性(全部实测过红): -- 去掉「头部按 surface 序发射/骨架包裹」→ 例 1 / 例 3 当场红(后者由 invariant 拒绝); +- 去掉「头部骨架包裹」→ 例 1 / 例 3 当场红(后者由 invariant 拒绝); - 毁掉尾部 replace 重映射/降级分支 → 例 9 当场红; -- 孤儿 summary 不回扫 → 例 10 当场红。 +- 孤儿 summary 不回扫 → 例 10 当场红; +- 关闭 turn 重编号 → 例 3(真实轮距 invariant)当场红。 **披露**:`sameVisibleSequence` 终验单独变异不可由行为测试变红(它是纵深防御,只有与构造缺陷叠加才可观察——二审的 B1 修复前正是「构造缺陷 + 守卫被绕过」的叠加形态,例 7/8 就是为此而设)。 ## 独立审查记录(两轮,双 corpus 投票) -一审(2026-10-15,Standards + Spec 双轴,独立 subagent):两票均 **CHANGES_REQUIRED**,blocking 收敛于同一根因——v1 构造只保留 surface 节点,把前切点的 turn/step 骨架丢掉:(a) 自动 compaction 必在打开的轮内,开轮的 `turn/start` 被丢后 `lastTurnBoundary` 返回 -1,悬空 tool-call 守卫与合成闭合器被静默绕过;(b) 违反宿主 `requireOpenStep` 关系不变量。两位审查者各留树外证据脚本(`check-midturn` / `check-invariant` / `probe1-5`),v2 修复后全部转绿(见上)。二审记录于 PR。 +一审(2026-10-15,Standards + Spec 双轴,独立 subagent):两票均 **CHANGES_REQUIRED**,blocking 收敛于同一根因——v1 构造只保留 surface 节点,把前切点的 turn/step 骨架丢掉:(a) 自动 compaction 必在打开的轮内,开轮的 `turn/start` 被丢后 `lastTurnBoundary` 返回 -1,悬空 tool-call 守卫与合成闭合器被静默绕过;(b) 违反宿主 `requireOpenStep` 关系不变量。→ v2:只丢被遗忘区段,头部骨架包裹,keep/尾部逐字。 + +二审(同日,两位全新 fresh reviewer):两票再次 **CHANGES_REQUIRED**,独立收敛于新 blocking——**turn 编号断档**(v2 头部骨架收口后计数器期望 turn 2,keep 窗口逐字保留原始 `turn/start{N}`;两道自证 foldSurface/Session.create 都抓不到,真实 harness 在 `sessions.create` 抛 `InvariantError`);另指出中段切点(region 边界仅 tool-pairing 平衡)会静默回退。→ v3:turn 重编号(keep ∪ 尾双段扫描首个保留轮)、中段 keep-window 跳过被 shadow 节点与孤儿 call、运行时 `turnSequenceValid` 关系门、夹具换真实轮距。两轮审查者的全部树外证据脚本(`check-midturn` / `check-invariant` / `headline` / `probe1-5` / `probe2 B 扫描` / `probe3` / `probe4`)在 v3 上全部转绿或按设计回退(非法父日志形状与 legacy 逐字节 parity)。三审记录于 PR。 ## 部署验证(已执行,2026-10-15) diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index dcbcade9..adf0e2c5 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -22,7 +22,7 @@ */ import type { SidebarHistoryEntry, SidebarSessionSummary } from './context-types.ts' import type { AssistantLiveChunk } from './assistant-live.ts' -import { foldSurface } from '@deepseek-ai/dsh-session/surface' +import { foldSurface, isSurfaceEligibleType } 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: ' @@ -337,6 +337,42 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] if (headEvents === undefined) return undefined const keepStart = enclosingTurnStart(events, keepFirst) const groupId = dataOf(events[cut - 1]!).compactionId + // The keep interval is a LOG range; the region may have ended mid-turn, + // so the interval can re-carry surface nodes the checkpoint already + // shadowed (they precede the surviving ones inside the same turn). Skip + // exactly those, plus tool/calls whose result did not survive — an + // orphaned call fails the relational invariants just like a bare one. + const surviving = new Set(parentNodes as readonly number[]) + const survivingCallIds = new Set() + for (const seq of parentNodes as readonly number[]) { + const node = events[seq] + if (node === undefined || node.type !== 'tool/result') continue + const callId = toolResultCallIdOf(node) + if (callId !== undefined) survivingCallIds.add(callId) + } + // Turn renumbering: the host's turn counter must run 1, 2, 3… over the + // seed, but the dropped span leaves a gap between the head skeleton's + // turn and the keep window's first turn/start. Every kept event carrying + // a turn number at or past that first kept turn shifts down by the gap; + // head-side numbers (below it) stay untouched. `step` numbers restart per + // turn, so verbatim scaffolding inside a kept turn stays correct. + const expectedFirstKeptTurn = headEvents.length > 0 ? 2 : 1 + let firstKeptTurn: number | undefined + // The first kept turn/start can sit in the keep interval OR — when every + // pre-cut survivor is the protected head — only in the tail after the + // consumed group; scan both ranges. + for (const [from, to] of [[keepStart, cut], [cut + 2, events.length]] as const) { + for (let index = from; index < to; index++) { + const event = events[index] + if (event === undefined || event.type !== 'turn/start') continue + const turn = dataOf(event).turn + if (typeof turn === 'number') firstKeptTurn = turn + index = to + break + } + if (firstKeptTurn !== undefined) break + } + const turnOffset = firstKeptTurn === undefined ? 0 : Math.max(0, firstKeptTurn - expectedFirstKeptTurn) // Positional renumbering over the kept set; every emitted event passes the // same rebase: seq references remap when the map can serve them, and a // reference into the dropped span degrades honestly (replace → append, @@ -347,7 +383,7 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] let aborted = false const emit = (event: SidechatLogEvent | undefined): void => { if (aborted || event === undefined) return - const rebased = rebaseEvent(event, seed.length, rebase) + const rebased = rebaseEvent(event, seed.length, rebase, turnOffset, firstKeptTurn) if (rebased === undefined) { aborted = true return @@ -359,7 +395,10 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] emit(checkpoint) for (let index = keepStart; index < cut; index++) { const event = events[index] - if (event !== undefined && !isCompactionGroupEvent(event, groupId)) emit(event) + if (event === undefined || isCompactionGroupEvent(event, groupId)) continue + if (isSurfaceEligibleType(event.type) && !surviving.has(event.seq)) continue + if (event.type === 'tool/call' && !survivingCallIds.has(String(dataOf(event).callId))) continue + emit(event) } for (let index = cut + 1; index < events.length; index++) { const event = events[index] @@ -367,16 +406,62 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] } if (aborted) return undefined // Prove equivalence before the caller relies on it: the rebased sequence - // must fold without error and to the same visible nodes as the parent. + // must fold without error and to the same visible nodes as the parent, + // and its turn/step skeleton must satisfy the host's relational counter + // rules (turn/start runs 1, 2, …; steps open and close inside their turn; + // a trailing open turn is the caller's to close). try { const child = foldSurface(seed as unknown as Parameters[0]) if (!sameVisibleSequence(events, parentNodes, child.nodes, seed)) return undefined } catch { return undefined } + if (!turnSequenceValid(seed)) return undefined return seed } +/** Relational pre-check mirroring the session invariant's counters: turn + * numbers must run 1, 2, … with steps opening and closing inside the open + * turn, and in-turn message events must name the open turn/step when they + * carry numbers. A trailing open turn or step is legal — the caller closes + * it. */ +function turnSequenceValid(seed: readonly SeedEvent[]): boolean { + let nextTurn = 1 + let openTurn: number | undefined + let openStep: number | undefined + for (const event of seed) { + const data = dataOf(event) + if (event.type === 'turn/start') { + if (data.turn !== nextTurn) return false + openTurn = nextTurn + nextTurn += 1 + openStep = undefined + } else if (event.type === 'turn/end') { + if (openTurn === undefined || data.turn !== openTurn || openStep !== undefined) return false + openTurn = undefined + } else if (event.type === 'step/start') { + if (openTurn === undefined || data.turn !== openTurn || openStep !== undefined) return false + if (typeof data.step !== 'number') return false + openStep = data.step + } else if (event.type === 'step/end') { + if (openTurn === undefined || openStep === undefined || data.turn !== openTurn || data.step !== openStep) return false + openStep = undefined + } else if (isSurfaceEligibleType(event.type)) { + if (typeof data.turn === 'number' && data.turn !== openTurn) return false + if (typeof data.step === 'number' && data.step !== openStep) return false + } + } + return true +} + +/** The callId a tool/result event's message cites, when it carries one. */ +function toolResultCallIdOf(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 surviving pre-cut head as a state-machine-complete event list: the * head nodes (surface order == log order for surviving appends) wrapped in @@ -402,12 +487,7 @@ function headSkeleton(events: readonly SidechatLogEvent[], head: readonly number const event = events[index] if (event === undefined) break if (event.type === 'turn/end') break - if (event.type === 'step/end') { - // An earlier step of the same turn closed: the head node's step opens - // after it, but the step/start we want still lies between. - stepStart = undefined - continue - } + // The NEAREST step/start below the node is the one that encloses it. if (event.type === 'step/start' && stepStart === undefined) stepStart = event if (event.type === 'turn/start') { turnStart = event @@ -419,24 +499,28 @@ function headSkeleton(events: readonly SidechatLogEvent[], head: readonly number parts.push(turnStart) const turn = dataOf(turnStart).turn if (typeof turn !== 'number') return undefined - // Nodes must all sit in this one step/turn; a wider head is not a shape + const step = stepStart !== undefined ? dataOf(stepStart).step : undefined + if (stepStart !== undefined && typeof step !== 'number') return undefined + // Nodes must all sit in this ONE step/turn; a wider head (several steps + // or turns, or numbers that disagree with the skeleton) is not a shape // this builder represents. for (const seq of head) { const node = events[seq] if (node === undefined) return undefined const nodeData = dataOf(node) if (nodeData.turn !== turn && nodeData.turn !== undefined) return undefined + if (stepStart !== undefined && nodeData.step !== step && nodeData.step !== undefined) return undefined } if (stepStart !== undefined) parts.push(stepStart) for (const seq of head) parts.push(events[seq]!) // Close the skeleton when its closers are dropped with the span: the // first step/end / turn/end of this step/turn after the last node. - const step = stepStart !== undefined ? dataOf(stepStart).step : undefined let closedStep = false for (let index = head[head.length - 1]! + 1; index < events.length; index++) { const event = events[index] if (event === undefined) break - if (!closedStep && event.type === 'step/end' && typeof step === 'number' && dataOf(event).step === step) { + if (!closedStep && event.type === 'step/end' && typeof step === 'number' + && dataOf(event).step === step && dataOf(event).turn === turn) { parts.push(event) closedStep = true continue @@ -458,9 +542,9 @@ function headSkeleton(events: readonly SidechatLogEvent[], head: readonly number return parts } -/** Log index of the turn/start enclosing one seq, or the seq itself when the - * node sits between turns — the keep window then starts verbatim at its - * own skeleton root. */ +/** Log index of the turn/start enclosing one seq, the seq itself when the + * node sits between turns (the keep window then starts verbatim at its own + * skeleton root), or the log length when there is no keep window at all. */ function enclosingTurnStart(events: readonly SidechatLogEvent[], seq: number | undefined): number { if (seq === undefined) return events.length for (let index = seq - 1; index >= 0; index--) { @@ -473,10 +557,14 @@ function enclosingTurnStart(events: readonly SidechatLogEvent[], seq: number | u } /** Whether one event belongs to the compaction group being consumed (its - * log-only start/summary/end records leave with the span they priced). */ + * log-only start/summary/end records leave with the span they priced). + * Other groups' records stay — they meter history the child keeps. A + * summary without a `compactionId` is malformed; nothing is excluded for + * it and the equivalence check decides. */ function isCompactionGroupEvent(event: SidechatLogEvent, groupId: unknown): boolean { if (!event.type.startsWith('compaction/')) return false - return groupId === undefined ? true : dataOf(event).compactionId === groupId + if (typeof groupId !== 'string') return false + return dataOf(event).compactionId === groupId } /** Index of the checkpoint user/message of the last summarizing compaction: @@ -492,11 +580,14 @@ function lastCheckpointIndex(events: readonly SidechatLogEvent[]): number | unde } /** One `type` + message-content token per visible node, for comparing folds. - * `headerSeq` is envelope metadata the rebase rewrites, not content. */ + * `headerSeq` and `turn`/`step` are envelope metadata the rebase rewrites + * (the renderer projects `data.message`, not these), never content. */ function visibleToken(event: SidechatLogEvent | undefined): string { if (event === undefined) return 'missing' const data = { ...dataOf(event) } delete data.headerSeq + delete data.turn + delete data.step return `${event.type}:${JSON.stringify(data)}` } @@ -518,21 +609,36 @@ function sameVisibleSequence( /** * Copy one kept 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 span) 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. + * are remapped through the rebase map, `data.turn` numbers at or past the + * first kept turn shift down by the gap the dropped span left (the host's + * turn counter must stay contiguous), and a seq reference the map cannot + * serve (it points into the dropped span) 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 kept event to copy. * @param seq - the event's position in the rebased sequence. * @param rebase - old seq → rebased position over the kept set. + * @param turnOffset - turns removed before the keep window (0 = no shift). + * @param firstKeptTurn - the first kept turn number; smaller numbers are + * head-side and never shift. * @returns the rebased event, or undefined when the tail is not provable. */ -function rebaseEvent(event: SidechatLogEvent, seq: number, rebase: Map): SeedEvent | undefined { +function rebaseEvent( + event: SidechatLogEvent, + seq: number, + rebase: Map, + turnOffset: number, + firstKeptTurn: number | undefined, +): 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 (turnOffset > 0 && typeof sourceData.turn === 'number' + && firstKeptTurn !== undefined && sourceData.turn >= firstKeptTurn) { + seed.data = { ...seed.data, turn: sourceData.turn - turnOffset } + } const headerSeq = sourceData.headerSeq if (event.type === 'developer/message' && typeof headerSeq === 'number') { const mapped = rebase.get(headerSeq) diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index fc455d28..a3ebfebd 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -174,11 +174,47 @@ function oldSpan(): { events: SidebarSessionEvent[]; nodes: number[] } { */ function compactedLog(): SidebarSessionEvent[] { const events = [...systemHead(), ...oldSpan().events] - const keep = turn(9, 2, { callId: 'c-keep', result: 'keep result' }) + // A whole shadowed turn between the head and the keep window: the seed's + // turn numbers must be renumbered to run 1, 2, 3… over the gap. + const shadowTurn = turn(9, 2, { callId: 'c-shadow', result: 'shadow result' }) + events.push(...shadowTurn.events) + // The keep window is appended BEFORE the compaction group (the group + // lands at the log's end at compaction time); the tail follows it. + const keep = turn(17, 3, { callId: 'c-keep', result: 'keep result' }) events.push(...keep.events) - // The region shadows the old span's nodes but NOT the protected head. - events.push(...compactionGroup(events.length, [3, 5, 6])) - events.push(...turn(events.length, 3, { callId: 'c-tail', result: 'tail result' }).events) + // The region shadows the old span's and the middle turn's nodes but NOT + // the protected head. + events.push(...compactionGroup(events.length, [3, 5, 6, 11, 13, 14])) + events.push(...turn(events.length, 4, { callId: 'c-tail', result: 'tail result' }).events) + return events +} + +/** + * The mid-span shape: the region ends INSIDE the keep window's first turn + * (the host's boundary is only tool-pairing balanced, not turn aligned), so + * that turn's early nodes are shadowed while its later ones survive — the + * keep interval must skip the shadowed surface events and the orphaned + * tool/call instead of re-emitting them. + */ +function midSpanLog(): SidebarSessionEvent[] { + const events = [...systemHead(), ...oldSpan().events] + // Turn 2's first step is shadowed (user + tool pair); its second step's + // assistant survives — the region ends inside the keep window's first + // turn, which precedes the compaction group like every keep window does. + events.push( + lo('turn/start', 9, { turn: 2 }), + lo('step/start', 10, { turn: 2, step: 1 }), + sf('user/message', 11, userMessage('m-q2', 'q2 mid')), + lo('tool/call', 12, { turn: 2, step: 1, callId: 'c-mid', name: 'bash', arguments: '{}' }), + sf('tool/result', 13, { turn: 2, step: 1, message: toolResultMessage('c-mid', 'mid result') }), + lo('step/end', 14, { turn: 2, step: 1 }), + lo('step/start', 15, { turn: 2, step: 2 }), + sf('assistant/message', 16, { turn: 2, step: 2, message: assistantMessage('a2 kept'), stream: [] }), + lo('step/end', 17, { turn: 2, step: 2 }), + lo('turn/end', 18, { turn: 2, reason: { kind: 'completed' } }), + ) + events.push(...compactionGroup(19, [3, 5, 6, 11, 13])) + events.push(...turn(23, 3, { callId: 'c-tail', result: 'tail result' }).events) return events } @@ -191,31 +227,41 @@ function compactedLog(): SidebarSessionEvent[] { */ function midTurnLog(kind: 'closers' | 'dangling'): SidebarSessionEvent[] { const events = [...systemHead(), ...oldSpan().events] + const shadowTurn = turn(9, 2, { callId: 'c-shadow', result: 'shadow result' }) + events.push(...shadowTurn.events) const seq = events.length events.push( - lo('turn/start', seq, { turn: 2 }), - lo('step/start', seq + 1, { turn: 2, step: 1 }), - sf('user/message', seq + 2, userMessage('m-q2', 'q2')), + lo('turn/start', seq, { turn: 3 }), + lo('step/start', seq + 1, { turn: 3, step: 1 }), + sf('user/message', seq + 2, userMessage('m-q3', 'q3')), ) - events.push(...compactionGroup(seq + 3, [3, 5, 6], { id: 'cp-auto', turn: 2, summary: 'auto summarized' })) + events.push(...compactionGroup(seq + 3, [3, 5, 6, 11, 13, 14], { id: 'cp-auto', turn: 3, summary: 'auto summarized' })) const tail = events.length if (kind === 'closers') { - events.push(sf('assistant/message', tail, { turn: 2, step: 1, message: assistantMessage('open answer'), stream: [] })) + events.push(sf('assistant/message', tail, { turn: 3, step: 1, message: assistantMessage('open answer'), stream: [] })) } else { events.push( - sf('assistant/message', tail, { turn: 2, step: 1, message: assistantMessage('with tool', { callId: 'c-open' }), stream: [] }), - lo('tool/call', tail + 1, { turn: 2, step: 1, callId: 'c-open', name: 'bash', arguments: '{}' }), + sf('assistant/message', tail, { turn: 3, step: 1, message: assistantMessage('with tool', { callId: 'c-open' }), stream: [] }), + lo('tool/call', tail + 1, { turn: 3, step: 1, callId: 'c-open', name: 'bash', arguments: '{}' }), ) } return events } -/** The model-visible sequence a fold produces: one `type:data` token per node. */ +/** The model-visible sequence a fold produces: one `type:data` token per + * node, with the envelope fields the rebase rewrites (`headerSeq`, + * `turn`/`step` — the renderer projects `data.message`, not these) + * excluded, mirroring the builder's own comparison. */ 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)}` + if (event === undefined) return `missing:${seq}` + const data = { ...(event.data as Record) } + delete data.headerSeq + delete data.turn + delete data.step + return `${event.type}:${JSON.stringify(data)}` }) } @@ -253,6 +299,8 @@ describe('buildSidechatInheritance compaction tail', () => { 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) + expect(seed.some(event => JSON.stringify(event).includes('shadow result'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('c-shadow'))).toBe(false) expect(seed.map(event => event.type).slice(0, 5)).toEqual([ 'turn/start', 'step/start', 'system/message', 'step/end', 'turn/end', ]) @@ -332,8 +380,11 @@ describe('buildSidechatInheritance compaction tail', () => { })] const { seed, snapshot } = buildSidechatInheritance(withDangling) expect(snapshot).toBeNull() - expect(seed.map(event => event.type)).toEqual(withDangling.map(event => event.type)) - expect(seed.some(event => JSON.stringify(event).includes('old result'))).toBe(true) + // Event-for-event deep equality with the verbatim copy (envelope fields + // plus the shared data objects), not just a type sequence. + expect(seed.map(event => [event.type, event.seq, event.time, event.data])).toEqual( + withDangling.map(event => [event.type, event.seq, event.time, event.data]), + ) }) it('falls back to the verbatim full copy when a tail replace reorders surviving nodes', () => { @@ -353,7 +404,9 @@ describe('buildSidechatInheritance compaction tail', () => { } as SidebarSessionEvent) const { seed, snapshot } = buildSidechatInheritance(events) expect(snapshot).toBeNull() - expect(seed.map(event => event.type)).toEqual(events.map(event => event.type)) + expect(seed.map(event => [event.type, event.seq, event.time, event.data])).toEqual( + events.map(event => [event.type, event.seq, event.time, event.data]), + ) }) it('keeps the open-turn closers on the trimmed tail (mid-turn compaction)', () => { @@ -386,6 +439,24 @@ describe('buildSidechatInheritance compaction tail', () => { expect(JSON.stringify(snapshot)).toContain('bash') }) + it('skips shadowed nodes and orphaned calls when the region ends mid-turn', () => { + const events = midSpanLog() + const { seed, snapshot } = buildSidechatInheritance(events) + // The region ended inside turn 2: its early user+tool pair are shadowed, + // the later assistant survives. The trim must fire, the keep interval + // must NOT re-emit the shadowed events (nor the orphaned tool/call), + // and the skeleton of the partially-shadowed turn stays complete. + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + expect(seed.some(event => JSON.stringify(event).includes('q2 mid'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('c-mid'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('mid result'))).toBe(false) + expect(seed.some(event => JSON.stringify(event).includes('a2 kept'))).toBe(true) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expectContiguous(seed) + expect(invariantFailures(seed)).toEqual([]) + }) + it('remaps replace operations that stay inside the tail', () => { const events = compactedLog() // One more closed tail turn, then a replacement user/message whose From 98c42971a27b8e3fd3eaf86321a21d0ee2baec90 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Wed, 14 Oct 2026 23:50:01 -0700 Subject: [PATCH 06/12] fix(sidechat): normalize the head skeleton and mirror the host invariant core (review round 3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round 3 (two fresh reviewers) converged on: the head skeleton kept the rewritten system head's ORIGINAL step number (a mid-session rewrite can live at turn 1 step >= 2), the relational gate lacked the host's nextStep/pendingCalls rules (a wide head's tool/result without its call slipped through), kept compaction metering records carried stale shadowedRange/shadowedSeqs (violating the compaction invariant companion), and the gate was STRICTER than the host on non-append tool/results — so the default-loaded pruner's replacements silently disabled the trim. v4: the head skeleton normalizes to turn 1 step 1, rewriting only the envelope numbers an event already carries (a user/message never gains fields — its whole data object IS the model-visible message; the equivalence token now mirrors the renderer's projection exactly: user messages compare their full data, everything else data.message). The gate mirrors the host invariant's counter and pairing core: contiguous turns, no nested open turn, sequential steps, in-turn naming with the host's non-append tool/result exemption, and pending-call consumption. Compaction metering records rebase their citations; when the span they priced did not survive, the record is dropped. A surface node that is a kept replacement's fold TARGET is no longer skipped, so pruner replacements replay their transition instead of degrading into an append stranded after a closed step — that shape now trims. Pinned by new spec cases (rewritten head, pruner-rewritten keep-window result) and by all three review rounds' out-of-tree probes. --- ...026-10-13-sidechat-compaction-tail-seed.md | 23 ++- src/sidechat-core.ts | 154 ++++++++++++++---- tests/sidechat-compaction-seed.spec.ts | 109 ++++++++++++- 3 files changed, 235 insertions(+), 51 deletions(-) diff --git a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md index aa73272b..24cb03bf 100644 --- a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md +++ b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md @@ -1,6 +1,6 @@ # 侧边对话启动慢:种子改为从最后一次 compaction 切尾(可验证等价) -> 2026-10-13 起,2026-10-15 两轮独立审查后重构为 v3 构造 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts`(12 例) +> 2026-10-13 起,2026-10-15 三轮独立审查后为 v4 构造 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts`(14 例) ## 问题 @@ -35,15 +35,17 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): 1. **切割点** = 最后一个「后随 user/message」的 `compaction/summary` 的下一条事件(孤立 summary 回扫到上一个完整的); 2. **头部** = 父最终 surface 上 checkpoint 表位之前的存活节点(通常就是受保护的 system 头),**包裹其所在 turn/step 骨架**:`turn/start + step/start + 节点 + step/end + turn/end`——关闭件从日志里取回,因为宿主会话关系不变量(`@deepseek-ai/dsh-session/invariant` 的 `requireOpenStep`)要求轮内事件必须点名一个打开的 turn/step,即便该轮其余内容已被压缩遗忘。头部跨多个 step/turn 的形状不构造(回退); 3. **keep-window 与尾部逐字保留**:`lastTurnBoundary`/`hasDanglingToolCall`/合成闭合器因此**在重基日志上照常工作**(自动 compaction 必发生在打开的轮内——`compaction-basic` 由 `agent/pre-step` 触发且 region 强制 enclosed-in-turn——开轮的骨架在切点之前,逐字保留意味着永远不丢); -4. **统一重基**:全部保留事件走同一个 `rebaseEvent`——seq 按位置重编号(seed 契约要求从 0 连续,宿主不重编号);**`data.turn` 重编号**(宿主 turn 计数器必须连续跑 1,2,3…,被丢弃区段留下的轮号空洞由 keep/尾部整体下移填补;`step` 按轮重置故逐字保留即可);`surfaceOp: replace` 范围、`sourceEventSeqs`、`developer/message.headerSeq` 等**向后引用**能映射则平移、映射不到则**诚实降级**(replace→append、引用删除),`headerSeq` 无法降级则整体回退。首个被保留的 `turn/start` 可能在 keep 区间**或**(pre-cut 存活者只有受保护头时)只在尾部,两段都要扫; +4. **统一重基**:全部保留事件走同一个 `rebaseEvent`——seq 按位置重编号(seed 契约要求从 0 连续,宿主不重编号);**`data.turn` 重编号**(宿主 turn 计数器必须连续跑 1,2,3…,被丢弃区段留下的轮号空洞由 keep/尾部整体下移填补;`step` 按轮重置故逐字保留即可);`surfaceOp: replace` 范围、`sourceEventSeqs`、`developer/message.headerSeq`、以及 **`compaction/summary|prune` 记录的 `shadowedRange`/`shadowedSeqs`** 等**向后引用**能映射则平移;映射不到时 `headerSeq` 整体回退,而 compaction 计量记录**整条丢弃**(它计量的区段在子会话里不存在)。首个被保留的 `turn/start` 可能在 keep 区间**或**(pre-cut 存活者只有受保护头时)只在尾部,两段都要扫; +4b. **头部骨架归一**:存活头部(含被 mid-session 改写的受保护 system 头,任意原始 turn/step)一律归一为 **turn 1 step 1**——只改写事件里**已有**的数字信封字段(user/message 从不带、也绝不注入,它的整份 data 就是模型可见消息);关闭件从日志取回、同样归一; +4c. **replace 目标不跳过**:keep 区间里被 checkpoint shadow 的 surface 节点跳过,**但仍是某个存活替换事件之 replace 目标的节点不跳**(pruner 的 tool/result 改写正是此形)——否则替换会被迫降级为落在已闭合 step 之后的 append,违反关系规则; 5. **中段切点**(宿主 region 边界只受 tool-pairing 平衡约束、可止于轮中):keep 区间内**跳过被 checkpoint shadow 掉的 surface 事件**(同轮早期节点)与**孤儿 tool/call**(其 result 未存活),骨架照发——空 step 合法; -6. **自证**:用宿主公开导出的真折叠 `foldSurface`(`@deepseek-ai/dsh-session/surface`,浏览器安全子路径)分别折父日志与重基结果,**逐节点比对可见消息序列**(`headerSeq`/`turn`/`step` 是信封元数据、非模型可见内容,比对时豁免);再加一道**关系门** `turnSequenceValid`——轮号连续、step 开合于所属轮、轮内消息事件点名开轮/开步,与宿主 `@deepseek-ai/dsh-session/invariant` 的计数器同语义。不等价、折叠抛错或关系门失败 → 回退全量。新事件类型带来的「向后引用」长尾由此整体中和:要么折得过去,要么验证失败回退,永远不会产出坏子会话; +6. **自证**:用宿主公开导出的真折叠 `foldSurface`(`@deepseek-ai/dsh-session/surface`,浏览器安全子路径)分别折父日志与重基结果,**逐节点比对模型可见内容**——token 镜像宿主投影:`user/message` 比整份 `data`,其余比 `data.message`(信封 turn/step/headerSeq 天然不在其中);再加一道**关系门** `turnSequenceValid`——镜像宿主 invariant 的**计数与配对核心**:轮号连续、无嵌套开轮、step 序号连续且开合于所属轮、轮内消息与 `tool/call` 点名开轮/开步(**非 append 的 `tool/result` 豁免**,宿主同款——pruner 替换携带旧 step)、`tool/result` 须消费本 step 的 pending call、step 不得带 pending 关闭。不等价、折叠抛错或关系门失败 → 回退全量。这是核心镜像而非宿主全契约——凡是门证明不了的,一律回退。 6. **回退** = 现行全量拷贝,行为逐字不变(无 compaction 的会话永远走这条路;探针实测五种形状回退输出与改前逐字节一致)。 ### 证明范围与披露 - 等价证明覆盖**可见节点内容序列**;`request/header`/`request/context` 等模型装配输入中 log-only 的部分,keep-window 与尾部内的会随逐字保留带过去,更老的随区段丢弃——实测(二审探针,6 组工具集变化组合):子会话首个请求经宿主 `projectToolUpdates` 投影后与全量 fork **完全一致**(子会话自建的 header 重置 declaration series),今天无可观测差异;此推理链无测试 pin,属已知边界。 -- **回退(安全、无收益)的已知形状**(三轮探针实测):受保护 system 头被**后期改写**到别的轮(宿主 system-prompt projection 的 mid-session 改写形态,头节点不在 turn 1 step 1);**单轮父会话**(compaction 发生在唯一仍在打开的轮内、无 keep 区间);父日志本身违反关系不变量(子会话回退后与 legacy 逐字节一致 = parity)。中段切点与 context-overflow(keep 只剩末节点)**已支持**(二审 E 例:trim 生效、等价、invariant 0/0)。 +- **回退(安全、无收益)的已知形状**(三轮探针实测):**宽头**(受保护头之外还有存活 pre-cut 节点且含 tool/result——需经公开 `compactRegion` 任意区间接缝或第三方 backend 才可达,随包 backend 的 region 恒起于 surface index 0/1);**单轮父会话**(compaction 发生在唯一仍在打开的轮内、无 keep 区间);父日志本身违反关系不变量(子会话回退后与 legacy 逐字节一致 = parity);审查者 p1-A 的多 step 中段复合形状。**已支持**(探针实证):中段切点(keep 首轮部分被 shadow,含跨多 step)、context-overflow(keep 只剩末节点)、**被改写的受保护头**(任意原始 turn/step,归一后 trim 生效)、**pruner 替换在 keep 窗口**(replace 目标保留重放 + 非 append 豁免 + 计量记录引用重映射或丢弃)、空 keep 区间、级联 compaction、孤立 summary 回扫。keep 窗口内 `request/header` + `developer/message.headerSeq` 成功重映射由三轮审查者探针钉住(`probe-header-remap`:指向重基后 header、trim、invariant 0/0)。 - 日志含 `image/offload` 等 **MESSAGE_PROJECTION 事件类型**时 `foldSurface`(无 projections)抛错 → 回退全量(安全,但含图长会话拿不到收益)。同理,未来插件自定义 projection 不在 core 集合内时证明会失真为「回退」而非「假通过」。 - 孤立 compaction 组(summary 后替换未落地)的 log-only 记录随尾部保留(折叠不可见,保留宿主 metering 历史);构造时剔除的只有**本次消费的那一组**。 - 第二个 system 头(checkpoint 表位之前的其他存活节点)实测受支持(二审探针 E:trim 生效、等价、validator 接受)。 @@ -54,7 +56,7 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): - 不做引用式继承(子会话直接引用父会话物理行)——需要动 dsh-session/session-persistence/format 的宿主变更,超出插件贡献面; - 不加配置开关——回退路径本身就是安全阀;若上游评审要求可配置再加。 -## 测试(`tests/sidechat-compaction-seed.spec.ts`,12 例) +## 测试(`tests/sidechat-compaction-seed.spec.ts`,14 例) 夹具为宿主真实形状:`system/message {turn, step, message}`(`source.kind: 'system-prompt'`)、`tool/result` 挂 `message`、assistant 消息带 `model` source;compaction 组含手动(`turn: null`)与自动(`turn: `)两种形态,且**开轮的 turn/start 与首条消息在切点之前**(二审 B1 的触发形状)。 @@ -69,7 +71,9 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): 9. **重映射**:尾部 replace 范围完全在尾内 → 保留为重基后的 replace(非降级),trim 必须发生、等价必须成立; 10. **孤立 summary 回扫**:最新 compaction 的替换未落地 → 沿用上一个完整 compaction(trim 仍生效),死组的 log-only 记录随尾部保留; 11. **中段 keep-window**:region 止于 keep 首轮之内 → 被 shadow 的同轮早期节点与孤儿 tool/call 被跳过、骨架完整、等价成立、invariant 零失败; -12. 真实验证器验收(`Session.create` + end-seed 标记落为子会话第一个 own event,与全量线程同形)。 +12. **改写头**(turn 1 后续 step 的 SystemPromptProjection.replace 形状)→ 归一为 turn 1 step 1 后 trim 照常、原 prompt 消失、等价、invariant 零失败; +13. **pruner 改写 keep 窗口结果**(两 step 之间的替换、携带原始 turn/step)→ replace 目标保留重放、替换 op 重映射、prune 记录引用重映射、等价、invariant 零失败; +14. 真实验证器验收(`Session.create` + end-seed 标记落为子会话第一个 own event,与全量线程同形)。 夹具使用**真实轮距**(受保护头 turn 1 + 被 shadow 的整轮 + keep 轮 3 起)——二审证明「keep 恰为 turn 2」的唯一连续夹具会让 invariant 用例假绿。 @@ -77,14 +81,17 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): - 去掉「头部骨架包裹」→ 例 1 / 例 3 当场红(后者由 invariant 拒绝); - 毁掉尾部 replace 重映射/降级分支 → 例 9 当场红; - 孤儿 summary 不回扫 → 例 10 当场红; -- 关闭 turn 重编号 → 例 3(真实轮距 invariant)当场红。 +- 关闭 turn 重编号 → 例 3(真实轮距 invariant)当场红; +- 三审的变异复验:关 turnOffset 5/12 红、去骨架包裹 6/12 红(含点名用例)。 **披露**:`sameVisibleSequence` 终验单独变异不可由行为测试变红(它是纵深防御,只有与构造缺陷叠加才可观察——二审的 B1 修复前正是「构造缺陷 + 守卫被绕过」的叠加形态,例 7/8 就是为此而设)。 ## 独立审查记录(两轮,双 corpus 投票) 一审(2026-10-15,Standards + Spec 双轴,独立 subagent):两票均 **CHANGES_REQUIRED**,blocking 收敛于同一根因——v1 构造只保留 surface 节点,把前切点的 turn/step 骨架丢掉:(a) 自动 compaction 必在打开的轮内,开轮的 `turn/start` 被丢后 `lastTurnBoundary` 返回 -1,悬空 tool-call 守卫与合成闭合器被静默绕过;(b) 违反宿主 `requireOpenStep` 关系不变量。→ v2:只丢被遗忘区段,头部骨架包裹,keep/尾部逐字。 -二审(同日,两位全新 fresh reviewer):两票再次 **CHANGES_REQUIRED**,独立收敛于新 blocking——**turn 编号断档**(v2 头部骨架收口后计数器期望 turn 2,keep 窗口逐字保留原始 `turn/start{N}`;两道自证 foldSurface/Session.create 都抓不到,真实 harness 在 `sessions.create` 抛 `InvariantError`);另指出中段切点(region 边界仅 tool-pairing 平衡)会静默回退。→ v3:turn 重编号(keep ∪ 尾双段扫描首个保留轮)、中段 keep-window 跳过被 shadow 节点与孤儿 call、运行时 `turnSequenceValid` 关系门、夹具换真实轮距。两轮审查者的全部树外证据脚本(`check-midturn` / `check-invariant` / `headline` / `probe1-5` / `probe2 B 扫描` / `probe3` / `probe4`)在 v3 上全部转绿或按设计回退(非法父日志形状与 legacy 逐字节 parity)。三审记录于 PR。 +二审(同日,两位全新 fresh reviewer):两票再次 **CHANGES_REQUIRED**,独立收敛于新 blocking——**turn 编号断档**(v2 头部骨架收口后计数器期望 turn 2,keep 窗口逐字保留原始 `turn/start{N}`;两道自证 foldSurface/Session.create 都抓不到,真实 harness 在 `sessions.create` 抛 `InvariantError`);另指出中段切点(region 边界仅 tool-pairing 平衡)会静默回退。→ v3:turn 重编号(keep ∪ 尾双段扫描首个保留轮)、中段 keep-window 跳过被 shadow 节点与孤儿 call、运行时 `turnSequenceValid` 关系门、夹具换真实轮距。 + +三审(同日,两位全新 fresh reviewer):两票 **CHANGES_REQUIRED**——(a) 头部骨架 step 号未归一(受保护头被改写到 turn 1 step ≥2 时产出宿主 invariant 拒绝的种子);(b) 宽头存活 `tool/result` 丢配对 `tool/call`;(c) keep/尾保留的 compaction 计量记录 `shadowedRange/shadowedSeqs` 未重映射(违反 dsh-compaction invariant);(d) 关系门对**非 append** `tool/result` 过严(pruner 替换会让 trim 无谓回退);(e) lint 死赋值。→ v4:头部归一 turn 1 step 1(只改写已有数字信封字段——期间发现并修复了「向 user/message 注入 turn/step」的真等价破坏,token 改为镜像宿主投影:user=整份 data、其余=data.message)、关系门补 nextStep/pendingCalls/嵌套开轮/非 append 豁免、compaction 记录引用重映射或整条丢弃、**replace 目标节点不跳过**(pruner 形状由此从回退转为生效)。三轮审查者的全部树外证据脚本(`check-midturn`/`check-invariant`/`headline`/`probe1-5`/`probe2 B 扫描`/`probe3`/`probe4`/`rev3-probe:*`/`rev3-sidechat:p1-p9`)在 v4 上全部转绿或按设计安全回退(非法父日志与 legacy 逐字节 parity)。**第四轮 fresh review 尚未运行**——PR 开立前应再跑一轮。 ## 部署验证(已执行,2026-10-15) diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index adf0e2c5..0c438e3a 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -350,6 +350,24 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] const callId = toolResultCallIdOf(node) if (callId !== undefined) survivingCallIds.add(callId) } + // Surface nodes a KEPT replacement still targets are not skippable: the + // replacement's fold transition (node appears, then is replaced) must + // replay — skipping its target would degrade the replacement to an + // append stranded after the step closed, which the relational rules + // reject. (The pruner's tool/result rewrites are exactly this shape.) + const replaceCovered = new Set() + for (const [from, to] of [[keepStart, cut], [cut + 1, events.length]] as const) { + for (let index = from; index < to; index++) { + const event = events[index] + if (event === undefined || isCompactionGroupEvent(event, groupId)) continue + const op = (event as { surfaceOp?: unknown }).surfaceOp + if (op === null || typeof op !== 'object' || (op as { op?: unknown }).op !== 'replace') continue + const start = (op as { startSeq?: unknown }).startSeq + const end = (op as { endSeq?: unknown }).endSeq + if (typeof start !== 'number' || typeof end !== 'number' || start > end) continue + for (let seq = Math.max(0, start); seq <= Math.min(end, events.length - 1); seq++) replaceCovered.add(seq) + } + } // Turn renumbering: the host's turn counter must run 1, 2, 3… over the // seed, but the dropped span leaves a gap between the head skeleton's // turn and the keep window's first turn/start. Every kept event carrying @@ -361,13 +379,12 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] // The first kept turn/start can sit in the keep interval OR — when every // pre-cut survivor is the protected head — only in the tail after the // consumed group; scan both ranges. - for (const [from, to] of [[keepStart, cut], [cut + 2, events.length]] as const) { + for (const [from, to] of [[keepStart, cut], [cut + 1, events.length]] as const) { for (let index = from; index < to; index++) { const event = events[index] if (event === undefined || event.type !== 'turn/start') continue const turn = dataOf(event).turn if (typeof turn === 'number') firstKeptTurn = turn - index = to break } if (firstKeptTurn !== undefined) break @@ -383,7 +400,8 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] let aborted = false const emit = (event: SidechatLogEvent | undefined): void => { if (aborted || event === undefined) return - const rebased = rebaseEvent(event, seed.length, rebase, turnOffset, firstKeptTurn) + const rebased: RebasedEvent = rebaseEvent(event, seed.length, rebase, turnOffset, firstKeptTurn) + if (rebased === DROPPED) return if (rebased === undefined) { aborted = true return @@ -396,7 +414,7 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] for (let index = keepStart; index < cut; index++) { const event = events[index] if (event === undefined || isCompactionGroupEvent(event, groupId)) continue - if (isSurfaceEligibleType(event.type) && !surviving.has(event.seq)) continue + if (isSurfaceEligibleType(event.type) && !surviving.has(event.seq) && !replaceCovered.has(event.seq)) continue if (event.type === 'tool/call' && !survivingCallIds.has(String(dataOf(event).callId))) continue emit(event) } @@ -420,32 +438,63 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] return seed } -/** Relational pre-check mirroring the session invariant's counters: turn - * numbers must run 1, 2, … with steps opening and closing inside the open - * turn, and in-turn message events must name the open turn/step when they - * carry numbers. A trailing open turn or step is legal — the caller closes - * it. */ +/** + * Relational pre-check mirroring the CORE of the session invariant's + * counters and tool pairing: turn numbers run 1, 2, … with no nested open + * turn; steps run 1, 2, … inside the open turn and close before their turn; + * in-turn message and tool/call events name the open turn/step when they + * carry numbers — except a NON-append tool/result, which the host exempts + * from step naming (pruner replacements carry their original step); a + * tool/result must consume a pending call of its step, and a step cannot + * close with calls pending. A trailing open turn or step is legal — the + * caller closes it. This is a core mirror, not the full host contract; + * anything it cannot prove falls back to the full copy. + */ function turnSequenceValid(seed: readonly SeedEvent[]): boolean { let nextTurn = 1 + let nextStep = 1 let openTurn: number | undefined let openStep: number | undefined + let pendingCalls = new Set() for (const event of seed) { const data = dataOf(event) if (event.type === 'turn/start') { - if (data.turn !== nextTurn) return false + if (openTurn !== undefined || data.turn !== nextTurn) return false openTurn = nextTurn nextTurn += 1 + nextStep = 1 openStep = undefined + pendingCalls = new Set() } else if (event.type === 'turn/end') { if (openTurn === undefined || data.turn !== openTurn || openStep !== undefined) return false openTurn = undefined } else if (event.type === 'step/start') { if (openTurn === undefined || data.turn !== openTurn || openStep !== undefined) return false - if (typeof data.step !== 'number') return false - openStep = data.step + if (data.step !== nextStep) return false + openStep = nextStep + nextStep += 1 + pendingCalls = new Set() } else if (event.type === 'step/end') { if (openTurn === undefined || openStep === undefined || data.turn !== openTurn || data.step !== openStep) return false + if (pendingCalls.size > 0) return false openStep = undefined + } else if (event.type === 'tool/call') { + if (typeof data.turn === 'number' && data.turn !== openTurn) return false + if (typeof data.step === 'number' && data.step !== openStep) return false + const callId = data.callId + if (typeof callId === 'string' && callId !== '') pendingCalls.add(callId) + } else if (event.type === 'tool/result') { + const op = (event as { surfaceOp?: unknown }).surfaceOp + if (op !== 'append') { + // The host exempts a replacing tool/result from step naming and + // pairing: it shadows the original call's slot, not a new one. + if (openTurn === undefined) return false + continue + } + if (typeof data.turn === 'number' && data.turn !== openTurn) return false + if (typeof data.step === 'number' && data.step !== openStep) return false + const callId = toolResultCallIdOf(event) + if (callId !== undefined && !pendingCalls.delete(callId)) return false } else if (isSurfaceEligibleType(event.type)) { if (typeof data.turn === 'number' && data.turn !== openTurn) return false if (typeof data.step === 'number' && data.step !== openStep) return false @@ -465,11 +514,14 @@ function toolResultCallIdOf(event: SidechatLogEvent): string | undefined { /** * The surviving pre-cut head as a state-machine-complete event list: the * head nodes (surface order == log order for surviving appends) wrapped in - * their enclosing turn/step scaffolding when that scaffolding itself lies in - * the dropped span — the session invariants require in-turn messages to - * name an open turn/step even when the rest of that turn is forgotten. Only - * a single enclosing step/turn is supported (the protected system head); - * anything wider falls back to the full copy. + * a turn/step skeleton NORMALIZED to turn 1 step 1 — the seed is a fresh + * log, the host's turn/step counters must start there, and the head node's + * original numbers are envelope metadata the rebase is free to rewrite + * (the protected system head can be a mid-session rewrite living in a later + * turn/step). Closers are recovered from the log when the skeleton's own + * closers were dropped with the span. A head wider than one step/turn (or + * numbers that disagree) is not a shape this builder represents and falls + * back to the full copy. * @param events - the parent's log. * @param head - seqs of the surviving pre-cut surface nodes before the * checkpoint's surface slot. @@ -494,16 +546,25 @@ function headSkeleton(events: readonly SidechatLogEvent[], head: readonly number break } } + // Rewrite envelope turn/step in place of the originals — only where the + // event already carries numbers (a user/message never does, and its whole + // data object IS the model-visible message, so injecting fields there + // would change the child's context) — keeping the data losslessly + // JSON-serializable (never writing explicit undefined). + const normalized = (event: SidechatLogEvent, over: { turn?: number; step?: number }): SidechatLogEvent => { + const data = { ...dataOf(event) } + if (over.turn !== undefined && typeof data.turn === 'number') data.turn = over.turn + if (over.step !== undefined && typeof data.step === 'number') data.step = over.step + return { ...event, data } as SidechatLogEvent + } const parts: SidechatLogEvent[] = [] if (turnStart !== undefined) { - parts.push(turnStart) const turn = dataOf(turnStart).turn if (typeof turn !== 'number') return undefined const step = stepStart !== undefined ? dataOf(stepStart).step : undefined if (stepStart !== undefined && typeof step !== 'number') return undefined - // Nodes must all sit in this ONE step/turn; a wider head (several steps - // or turns, or numbers that disagree with the skeleton) is not a shape - // this builder represents. + // Nodes must all sit in this ONE step/turn (by their ORIGINAL numbers); + // a wider head is not a shape this builder represents. for (const seq of head) { const node = events[seq] if (node === undefined) return undefined @@ -511,8 +572,9 @@ function headSkeleton(events: readonly SidechatLogEvent[], head: readonly number if (nodeData.turn !== turn && nodeData.turn !== undefined) return undefined if (stepStart !== undefined && nodeData.step !== step && nodeData.step !== undefined) return undefined } - if (stepStart !== undefined) parts.push(stepStart) - for (const seq of head) parts.push(events[seq]!) + parts.push(normalized(turnStart, { turn: 1 })) + if (stepStart !== undefined) parts.push(normalized(stepStart, { turn: 1, step: 1 })) + for (const seq of head) parts.push(normalized(events[seq]!, { turn: 1, ...(stepStart !== undefined ? { step: 1 } : {}) })) // Close the skeleton when its closers are dropped with the span: the // first step/end / turn/end of this step/turn after the last node. let closedStep = false @@ -521,12 +583,12 @@ function headSkeleton(events: readonly SidechatLogEvent[], head: readonly number if (event === undefined) break if (!closedStep && event.type === 'step/end' && typeof step === 'number' && dataOf(event).step === step && dataOf(event).turn === turn) { - parts.push(event) + parts.push(normalized(event, { turn: 1, step: 1 })) closedStep = true continue } if (event.type === 'turn/end' && dataOf(event).turn === turn) { - parts.push(event) + parts.push(normalized(event, { turn: 1 })) break } if (event.type === 'turn/start') break @@ -579,16 +641,15 @@ function lastCheckpointIndex(events: readonly SidechatLogEvent[]): number | unde return undefined } -/** One `type` + message-content token per visible node, for comparing folds. - * `headerSeq` and `turn`/`step` are envelope metadata the rebase rewrites - * (the renderer projects `data.message`, not these), never content. */ +/** One `type` + model-visible-content token per visible node, mirroring the + * renderer's projection: a user/message IS its whole data object, every + * other surface event projects `data.message` (its envelope turn/step and + * headerSeq are rewritten by the rebase and never reach the model). */ function visibleToken(event: SidechatLogEvent | undefined): string { if (event === undefined) return 'missing' - const data = { ...dataOf(event) } - delete data.headerSeq - delete data.turn - delete data.step - return `${event.type}:${JSON.stringify(data)}` + if (event.type === 'user/message') return `${event.type}:${JSON.stringify(dataOf(event))}` + const message = dataOf(event).message + return `${event.type}:${JSON.stringify(message ?? null)}` } /** Compare the parent's visible nodes with the rebased child's by content. */ @@ -624,13 +685,19 @@ function sameVisibleSequence( * head-side and never shift. * @returns the rebased event, or undefined when the tail is not provable. */ +/** Sentinel: the event is log-only metering whose referenced span did not + * survive the rebase — drop it instead of aborting the whole tail. */ +const DROPPED: unique symbol = Symbol('dropped') + +type RebasedEvent = SeedEvent | undefined | typeof DROPPED + function rebaseEvent( event: SidechatLogEvent, seq: number, rebase: Map, turnOffset: number, firstKeptTurn: number | undefined, -): SeedEvent | undefined { +): RebasedEvent { 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 @@ -639,6 +706,25 @@ function rebaseEvent( && firstKeptTurn !== undefined && sourceData.turn >= firstKeptTurn) { seed.data = { ...seed.data, turn: sourceData.turn - turnOffset } } + // Compaction metering records cite the surface span they priced. When the + // span survived the rebase, remap the citations; when it did not (the + // record predates the consumed compaction and its span lies in the + // dropped region), the record meters nothing that exists in the child — + // drop it rather than shipping stale seq references. + if (event.type === 'compaction/summary' || event.type === 'compaction/prune') { + const range = sourceData.shadowedRange as { start?: unknown; end?: unknown } | undefined + const cited = sourceData.shadowedSeqs + if (range === null || typeof range !== 'object' || !Array.isArray(cited)) return seed + const start = typeof range.start === 'number' ? rebase.get(range.start) : undefined + const end = typeof range.end === 'number' ? rebase.get(range.end) : undefined + const mapped = cited.map(item => typeof item === 'number' ? rebase.get(item) : undefined) + if (start === undefined || end === undefined || mapped.includes(undefined)) return DROPPED + seed.data = { + ...seed.data, + shadowedRange: { start, end }, + shadowedSeqs: mapped as number[], + } + } const headerSeq = sourceData.headerSeq if (event.type === 'developer/message' && typeof headerSeq === 'number') { const mapped = rebase.get(headerSeq) diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index a3ebfebd..31318a2b 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -248,20 +248,16 @@ function midTurnLog(kind: 'closers' | 'dangling'): SidebarSessionEvent[] { return events } -/** The model-visible sequence a fold produces: one `type:data` token per - * node, with the envelope fields the rebase rewrites (`headerSeq`, - * `turn`/`step` — the renderer projects `data.message`, not these) - * excluded, mirroring the builder's own comparison. */ +/** The model-visible sequence a fold produces, mirroring the renderer's + * projection exactly like the builder's own comparison: a user/message IS + * its whole data object; every other surface event projects `data.message`. */ function visibleSequence(events: readonly SidebarSessionEvent[]): string[] { const fold = foldSurface(events as unknown as readonly SessionEvent[]) return fold.nodes.map(seq => { const event = events[seq] if (event === undefined) return `missing:${seq}` - const data = { ...(event.data as Record) } - delete data.headerSeq - delete data.turn - delete data.step - return `${event.type}:${JSON.stringify(data)}` + if (event.type === 'user/message') return `${event.type}:${JSON.stringify(event.data)}` + return `${event.type}:${JSON.stringify((event.data as { message?: unknown }).message ?? null)}` }) } @@ -491,6 +487,101 @@ describe('buildSidechatInheritance compaction tail', () => { expect(rebased?.surfaceOp?.endSeq).toBeLessThan(rebased?.seq ?? 0) }) + it('trims when the protected head was rewritten mid-session (turn 1, later step)', () => { + // Host shape: SystemPromptProjection.replace rewrites surface node 0 in + // a LATER step of turn 1 — the surviving head node carries turn 1 / step + // >= 2. The skeleton normalizes to turn 1 step 1 (envelope numbers only; + // a user/message never gains fields) and the trim still fires. + const events = [ + lo('turn/start', 0, { turn: 1 }), + lo('step/start', 1, { turn: 1, step: 1 }), + sf('system/message', 2, { + turn: 1, step: 1, + message: { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'original prompt' }], source: { kind: 'system-prompt' } }, + }), + sf('user/message', 3, userMessage('m-q1', 'q1')), + sf('assistant/message', 4, { turn: 1, step: 1, message: assistantMessage('a1'), stream: [] }), + lo('step/end', 5, { turn: 1, step: 1 }), + lo('step/start', 6, { turn: 1, step: 2 }), + { + ...sf('system/message', 7, { + turn: 1, step: 2, + message: { id: 'm-sys2', role: 'system', content: [{ type: 'text', text: 'rewritten prompt' }], source: { kind: 'system-prompt' } }, + }), + surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 }, + sourceEventSeqs: [2], + } as SidebarSessionEvent, + lo('step/end', 8, { turn: 1, step: 2 }), + lo('turn/end', 9, { turn: 1, reason: { kind: 'completed' } }), + ] + const keep = turn(10, 2, { callId: 'c-keep', result: 'keep result' }) + events.push(...keep.events) + events.push(...compactionGroup(events.length, [3, 4])) + events.push(...turn(events.length, 3, { callId: 'c-tail', result: 'tail result' }).events) + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + // The surviving head is the REWRITTEN prompt, skeleton-normalized to + // turn 1 step 1; the original shadowed prompt is gone. + expect(seed.some(event => JSON.stringify(event).includes('rewritten prompt'))).toBe(true) + expect(seed.some(event => JSON.stringify(event).includes('original prompt'))).toBe(false) + const head = seed.find(event => event.type === 'system/message') as { data?: { turn?: number; step?: number } } + expect(head?.data?.turn).toBe(1) + expect(head?.data?.step).toBe(1) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expect(invariantFailures(seed)).toEqual([]) + }) + + it('trims when the pruner rewrote a keep-window tool result mid-turn', () => { + // Host shape: the tool-result-pruner appends a tool/result REPLACEMENT + // between steps, carrying the ORIGINAL turn/step and a replace op over + // its target. The target is not on the final surface, but it is the + // replacement's fold target — it must be emitted so the transition + // replays, and the record's citations must rebase. + const events = [...systemHead(), ...oldSpan().events] + // Turn 2 has two steps; the pruner runs at the pre-step boundary between + // them (turn still open) and rewrites step 1's over-budget result. + events.push( + lo('turn/start', 9, { turn: 2 }), + lo('step/start', 10, { turn: 2, step: 1 }), + sf('user/message', 11, userMessage('m-q2', 'q2')), + lo('tool/call', 12, { turn: 2, step: 1, callId: 'c-keep', name: 'bash', arguments: '{}' }), + sf('tool/result', 13, { turn: 2, step: 1, message: toolResultMessage('c-keep', 'keep result') }), + lo('step/end', 14, { turn: 2, step: 1 }), + lo('compaction/prune', 15, { + shadowedRange: { start: 13, end: 13 }, + shadowedSeqs: [13], + shadowedTokenCount: 40, + }), + { + ...sf('tool/result', 16, { turn: 2, step: 1, message: toolResultMessage('c-keep', 'pruned stub') }), + surfaceOp: { op: 'replace', startSeq: 13, endSeq: 13 }, + sourceEventSeqs: [13], + } as SidebarSessionEvent, + lo('step/start', 17, { turn: 2, step: 2 }), + sf('assistant/message', 18, { turn: 2, step: 2, message: assistantMessage('a2'), stream: [] }), + lo('step/end', 19, { turn: 2, step: 2 }), + lo('turn/end', 20, { turn: 2, reason: { kind: 'completed' } }), + ) + events.push(...compactionGroup(events.length, [3, 5, 6])) + events.push(...turn(events.length, 3, { callId: 'c-tail', result: 'tail result' }).events) + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + // Both the original result (fold target) and its replacement survive, + // the replacement keeps its replace op REMAPPED, and the prune record's + // citations rebase to the seed's seq space. + expect(seed.some(event => JSON.stringify(event).includes('keep result'))).toBe(true) + expect(seed.some(event => JSON.stringify(event).includes('pruned stub'))).toBe(true) + const replacement = seed.find(event => JSON.stringify(event).includes('pruned stub')) as { surfaceOp?: { op?: string; startSeq?: number }; seq?: number } + expect(replacement?.surfaceOp?.op).toBe('replace') + expect(replacement?.surfaceOp?.startSeq).toBeLessThan(replacement?.seq ?? 0) + const record = seed.find(event => event.type === 'compaction/prune') as { data?: { shadowedSeqs?: number[] } } + expect(record?.data?.shadowedSeqs?.[0]).toBe(replacement?.surfaceOp?.startSeq) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expect(invariantFailures(seed)).toEqual([]) + }) + it('reuses the previous compaction when the newest summary is orphaned', () => { const events = compactedLog() const at = events.length From b4e5c62f0458f3bf44eba8bca5403ac9d7f84693 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Thu, 15 Oct 2026 00:55:03 -0700 Subject: [PATCH 07/12] fix(sidechat): swallow the keep window's leading inbox inserts (real-data e2e catch) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The real loop order writes a turn's inbox INSERT before its turn/start and the CLAIM right after it; starting the keep window at the turn/start kept the claim while dropping its insert, and the host's positional durable-inbox fold rejected the seed at Session.create — caught on the deployment's real main session during the v4 e2e re-run (thread creation failed: invalid persisted inbox splice at session seq 7). The keep start now swallows the contiguous agent/inbox/spliced events preceding the skeleton root (they replay cleanly from an empty inbox), and a new inboxSplicesValid gate mirrors the host's fold — positional splice application with duplicate-id rejection — so any splice history that cannot replay falls back to the full copy instead of shipping a seed the host rejects. Pinned by a spec case in the real loop order. --- src/sidechat-core.ts | 43 +++++++++++++++++++++++++- tests/sidechat-compaction-seed.spec.ts | 42 +++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 1 deletion(-) diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index 0c438e3a..9a247486 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -335,7 +335,13 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] } const headEvents = headSkeleton(events, head) if (headEvents === undefined) return undefined - const keepStart = enclosingTurnStart(events, keepFirst) + let keepStart = enclosingTurnStart(events, keepFirst) + // The loop writes a turn's inbox INSERT before its turn/start and the + // CLAIM right after it; starting the keep window at the turn/start would + // keep the claim while dropping its insert, and the host's positional + // inbox fold would reject the seed. Swallow the contiguous splices that + // precede the skeleton root — they replay cleanly from an empty inbox. + while (keepStart > 0 && events[keepStart - 1]?.type === 'agent/inbox/spliced') keepStart -= 1 const groupId = dataOf(events[cut - 1]!).compactionId // The keep interval is a LOG range; the region may have ended mid-turn, // so the interval can re-carry surface nodes the checkpoint already @@ -435,9 +441,44 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] return undefined } if (!turnSequenceValid(seed)) return undefined + if (!inboxSplicesValid(seed)) return undefined return seed } +/** + * Relational pre-check mirroring the host's durable-inbox fold: every kept + * `agent/inbox/spliced` event replays POSITIONALLY over the pending inbox + * (splice.start/removedCount must stay in range, message ids unique). A + * seed whose splice history cannot replay from an empty inbox falls back + * to the full copy. + */ +function inboxSplicesValid(seed: readonly SeedEvent[]): boolean { + const nextTurn: Array> = [] + const nextStep: Array> = [] + for (const event of seed) { + if (event.type !== 'agent/inbox/spliced') continue + const data = dataOf(event) + const inbox = data.target === 'next-step' ? nextStep : nextTurn + const rawStart = data.start + const rawRemoved = data.removedCount + const removedCount = typeof rawRemoved === 'number' ? rawRemoved : 0 + const inserted = Array.isArray(data.inserted) ? data.inserted as Array> : [] + const start = typeof rawStart === 'number' ? rawStart : Number.NaN + if (!Number.isSafeInteger(start) || start < 0 || start > inbox.length + || !Number.isSafeInteger(removedCount) || removedCount < 0 + || start + removedCount > inbox.length) return false + inbox.splice(start, removedCount, ...inserted) + const ids = new Set() + for (const message of [...nextTurn, ...nextStep]) { + const id = message.id + if (typeof id !== 'string') continue + if (ids.has(id)) return false + ids.add(id) + } + } + return true +} + /** * Relational pre-check mirroring the CORE of the session invariant's * counters and tool pairing: turn numbers run 1, 2, … with no nested open diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index 31318a2b..5a4a32b5 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -582,6 +582,48 @@ describe('buildSidechatInheritance compaction tail', () => { expect(invariantFailures(seed)).toEqual([]) }) + it('trims when the keep window opens on a turn whose inbox insert precedes its turn/start', () => { + // Real loop order: [insert q][turn/start][claim q][step/start][user]. + // The keep window must swallow the insert ahead of the turn/start so + // the positional inbox fold replays; without it the claim dangles and + // Session.create rejects the seed (caught on the real deployment's + // main session during e2e). + const events = [...systemHead(), ...oldSpan().events] + const shadowTurn = turn(9, 2, { callId: 'c-shadow', result: 'shadow result' }) + events.push(...shadowTurn.events) + const at = events.length + events.push( + lo('agent/inbox/spliced', at, { target: 'next-turn', start: 0, removedCount: 0, inserted: [userMessage('m-q3', 'q3')] }), + lo('turn/start', at + 1, { turn: 3 }), + lo('agent/inbox/spliced', at + 2, { target: 'next-turn', start: 0, removedCount: 1, inserted: [] }), + lo('step/start', at + 3, { turn: 3, step: 1 }), + sf('user/message', at + 4, userMessage('m-q3', 'q3')), + sf('assistant/message', at + 5, { turn: 3, step: 1, message: assistantMessage('a3'), stream: [] }), + lo('step/end', at + 6, { turn: 3, step: 1 }), + lo('turn/end', at + 7, { turn: 3, reason: { kind: 'completed' } }), + ) + events.push(...compactionGroup(events.length, [3, 5, 6, 11, 13, 14])) + events.push(...turn(events.length, 4, { callId: 'c-tail', result: 'tail result' }).events) + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + // The insert rode along ahead of the keep window's turn/start, so the + // claim finds its message and the inbox fold replays. + const splices = seed.filter(event => event.type === 'agent/inbox/spliced') + expect(splices.length).toBeGreaterThanOrEqual(2) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expect(invariantFailures(seed)).toEqual([]) + // The real validator accepts (this is the layer that rejected the + // pre-fix seed on the real session). + const id = 'session-inbox-splice-acceptance' + Session.create( + id as SessionId, + seed as never, + { version: SESSION_FORMAT_VERSION, id: id as SessionId, createdAt: Date.now(), isSeeded: true }, + SessionLogOffset(seed.length), + ) + }) + it('reuses the previous compaction when the newest summary is orphaned', () => { const events = compactedLog() const at = events.length From a106e1964ed63d2228b002211ba9bcde13fe1530 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Thu, 15 Oct 2026 01:16:02 -0700 Subject: [PATCH 08/12] fix(sidechat): keep grouped records atomic and pin them with host-oracle tests (review round 4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round 4 (two fresh reviewers, pinned to both 657dcd5 and 196fa11) could not falsify the core equivalence (2100 generated shapes, 113 trims all passing the real session invariant, Session.create, the real durable-inbox projection, and node-by-node deriveEventMessage wire comparison; every non-trim byte-identical to the legacy full copy) but both votes converged on one root cause: host GROUPED records were split by record-level dropping. A kept compaction group could lose its summary to the dropped span and strand a successful compaction/end the host's compaction invariant companion rejects; a command/done could outlive its command/run the commands companion rejects — invisible to all three existing self-checks. The inbox fix from the e2e (196fa11) was verified: the positional durable-inbox projection is the layer the host rejects at, and the walk-back plus inboxSplicesValid hold. v5: bracketsValid mirrors the host's grouped-record rules (a successful compaction/end requires its compaction/summary; a command/done requires its prior command/run) so a split group falls back to the full copy; command/done.sourceEventSeq remaps onto the rebased run; expectedFirstKeptTurn is derived from the skeleton's actual turn/start (out-of-turn heads no longer renumber against a phantom turn 1); and inboxSplicesValid matches the host fold's strictness (known targets, numeric start/removedCount, array inserts, string ids). The spec's oracle now uses the host's own deriveEventMessage so a projection bug cannot hide from the equivalence cases, and two new cases pin the round-4 shapes (same-turn double compaction, command bracket split and its both-kept control with a remapped sourceEventSeq). --- ...026-10-13-sidechat-compaction-tail-seed.md | 20 ++- src/sidechat-core.ts | 52 ++++++- tests/sidechat-compaction-seed.spec.ts | 135 ++++++++++++++++-- 3 files changed, 187 insertions(+), 20 deletions(-) diff --git a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md index 24cb03bf..0d0fc9a3 100644 --- a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md +++ b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md @@ -1,6 +1,6 @@ # 侧边对话启动慢:种子改为从最后一次 compaction 切尾(可验证等价) -> 2026-10-13 起,2026-10-15 三轮独立审查后为 v4 构造 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts`(14 例) +> 2026-10-13 起,2026-10-15 四轮独立审查后为 v5 构造 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts`(17 例) ## 问题 @@ -39,13 +39,13 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): 4b. **头部骨架归一**:存活头部(含被 mid-session 改写的受保护 system 头,任意原始 turn/step)一律归一为 **turn 1 step 1**——只改写事件里**已有**的数字信封字段(user/message 从不带、也绝不注入,它的整份 data 就是模型可见消息);关闭件从日志取回、同样归一; 4c. **replace 目标不跳过**:keep 区间里被 checkpoint shadow 的 surface 节点跳过,**但仍是某个存活替换事件之 replace 目标的节点不跳**(pruner 的 tool/result 改写正是此形)——否则替换会被迫降级为落在已闭合 step 之后的 append,违反关系规则; 5. **中段切点**(宿主 region 边界只受 tool-pairing 平衡约束、可止于轮中):keep 区间内**跳过被 checkpoint shadow 掉的 surface 事件**(同轮早期节点)与**孤儿 tool/call**(其 result 未存活),骨架照发——空 step 合法; -6. **自证**:用宿主公开导出的真折叠 `foldSurface`(`@deepseek-ai/dsh-session/surface`,浏览器安全子路径)分别折父日志与重基结果,**逐节点比对模型可见内容**——token 镜像宿主投影:`user/message` 比整份 `data`,其余比 `data.message`(信封 turn/step/headerSeq 天然不在其中);再加一道**关系门** `turnSequenceValid`——镜像宿主 invariant 的**计数与配对核心**:轮号连续、无嵌套开轮、step 序号连续且开合于所属轮、轮内消息与 `tool/call` 点名开轮/开步(**非 append 的 `tool/result` 豁免**,宿主同款——pruner 替换携带旧 step)、`tool/result` 须消费本 step 的 pending call、step 不得带 pending 关闭。不等价、折叠抛错或关系门失败 → 回退全量。这是核心镜像而非宿主全契约——凡是门证明不了的,一律回退。 +6. **自证**:用宿主公开导出的真折叠 `foldSurface`(`@deepseek-ai/dsh-session/surface`,浏览器安全子路径)分别折父日志与重基结果,**逐节点比对模型可见内容**——token 镜像宿主投影:`user/message` 比整份 `data`,其余比 `data.message`(信封 turn/step/headerSeq 天然不在其中;spec 的 oracle 也用宿主 `deriveEventMessage`,不与实现共用投影);再加四道**关系门**——`turnSequenceValid`(镜像宿主 invariant 的计数与配对核心:轮号连续、无嵌套开轮、step 序号连续且开合于所属轮、轮内消息与 `tool/call` 点名开轮/开步、非 append `tool/result` 豁免、pending call 须被消费、step 不得带 pending 关闭);`inboxSplicesValid`(镜像宿主持久 inbox 折叠:位置拼接、已知 target、重复 id 拒绝);`bracketsValid`(镜像宿主成组记录:成功 `compaction/end` 须有同 id 的 `compaction/summary`、`command/done` 须有先行的 `command/run`——四审证明「只丢计量记录」会拆散成组记录、宿主 companion 拒绝而三道自证全盲);可见序列等价。不等价、折叠抛错或任一门失败 → 回退全量。这是核心镜像而非宿主全契约——凡是门证明不了的,一律回退。 6. **回退** = 现行全量拷贝,行为逐字不变(无 compaction 的会话永远走这条路;探针实测五种形状回退输出与改前逐字节一致)。 ### 证明范围与披露 - 等价证明覆盖**可见节点内容序列**;`request/header`/`request/context` 等模型装配输入中 log-only 的部分,keep-window 与尾部内的会随逐字保留带过去,更老的随区段丢弃——实测(二审探针,6 组工具集变化组合):子会话首个请求经宿主 `projectToolUpdates` 投影后与全量 fork **完全一致**(子会话自建的 header 重置 declaration series),今天无可观测差异;此推理链无测试 pin,属已知边界。 -- **回退(安全、无收益)的已知形状**(三轮探针实测):**宽头**(受保护头之外还有存活 pre-cut 节点且含 tool/result——需经公开 `compactRegion` 任意区间接缝或第三方 backend 才可达,随包 backend 的 region 恒起于 surface index 0/1);**单轮父会话**(compaction 发生在唯一仍在打开的轮内、无 keep 区间);父日志本身违反关系不变量(子会话回退后与 legacy 逐字节一致 = parity);审查者 p1-A 的多 step 中段复合形状。**已支持**(探针实证):中段切点(keep 首轮部分被 shadow,含跨多 step)、context-overflow(keep 只剩末节点)、**被改写的受保护头**(任意原始 turn/step,归一后 trim 生效)、**pruner 替换在 keep 窗口**(replace 目标保留重放 + 非 append 豁免 + 计量记录引用重映射或丢弃)、空 keep 区间、级联 compaction、孤立 summary 回扫。keep 窗口内 `request/header` + `developer/message.headerSeq` 成功重映射由三轮审查者探针钉住(`probe-header-remap`:指向重基后 header、trim、invariant 0/0)。 +- **回退(安全、无收益)的已知形状**(四轮探针实测):**宽头**(受保护头之外还有存活 pre-cut 节点且含 tool/result——需经公开 `compactRegion` 任意区间接缝或第三方 backend 才可达,随包 backend 的 region 恒起于 surface index 0/1);**单轮父会话**(compaction 发生在唯一仍在打开的轮内、无 keep 区间);**cut 之后被改写的受保护头**(存活 node 0 是 post-cut 替换、pre-cut 扫描找不到头——四审实测六个最重会话三个命中,含 32675 事件的旧式 fork 子会话;生产主会话不受影响);**同轮双成功 compaction 且后组吞掉前组 checkpoint**(前组 citations 全落在 keep 窗口之前——bracket 门回退;跨轮级联正常 trim);**命令括号被拆**(`command/run` 落在被遗忘区段而 `command/done` 存活——bracket 门回退);父日志本身违反关系不变量(子会话回退后与 legacy 逐字节一致 = parity);审查者 p1-A 的多 step 中段复合形状。**已支持**(探针实证):中段切点(keep 首轮部分被 shadow,含跨多 step)、context-overflow(keep 只剩末节点)、**被改写的受保护头**(原始 turn/step 任意、cut 之前——归一后 trim 生效)、**pruner 替换在 keep 窗口**(replace 目标保留重放 + 非 append 豁免 + 计量记录引用重映射或丢弃)、**keep 窗口起点的 inbox insert 回吞**(真实 loop 顺序 `[insert][turn/start][claim]`——v4 e2e 在生产主会话上抓到并修复)、空 keep 区间、**跨轮级联 compaction**、孤立 summary 回扫、命令 run+done 同窗(`sourceEventSeq` 重映射)。keep 窗口内 `request/header` + `developer/message.headerSeq` 成功重映射由三轮审查者探针钉住(`probe-header-remap`:指向重基后 header、trim、invariant 0/0)。 - 日志含 `image/offload` 等 **MESSAGE_PROJECTION 事件类型**时 `foldSurface`(无 projections)抛错 → 回退全量(安全,但含图长会话拿不到收益)。同理,未来插件自定义 projection 不在 core 集合内时证明会失真为「回退」而非「假通过」。 - 孤立 compaction 组(summary 后替换未落地)的 log-only 记录随尾部保留(折叠不可见,保留宿主 metering 历史);构造时剔除的只有**本次消费的那一组**。 - 第二个 system 头(checkpoint 表位之前的其他存活节点)实测受支持(二审探针 E:trim 生效、等价、validator 接受)。 @@ -56,7 +56,7 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): - 不做引用式继承(子会话直接引用父会话物理行)——需要动 dsh-session/session-persistence/format 的宿主变更,超出插件贡献面; - 不加配置开关——回退路径本身就是安全阀;若上游评审要求可配置再加。 -## 测试(`tests/sidechat-compaction-seed.spec.ts`,14 例) +## 测试(`tests/sidechat-compaction-seed.spec.ts`,17 例) 夹具为宿主真实形状:`system/message {turn, step, message}`(`source.kind: 'system-prompt'`)、`tool/result` 挂 `message`、assistant 消息带 `model` source;compaction 组含手动(`turn: null`)与自动(`turn: `)两种形态,且**开轮的 turn/start 与首条消息在切点之前**(二审 B1 的触发形状)。 @@ -73,7 +73,10 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): 11. **中段 keep-window**:region 止于 keep 首轮之内 → 被 shadow 的同轮早期节点与孤儿 tool/call 被跳过、骨架完整、等价成立、invariant 零失败; 12. **改写头**(turn 1 后续 step 的 SystemPromptProjection.replace 形状)→ 归一为 turn 1 step 1 后 trim 照常、原 prompt 消失、等价、invariant 零失败; 13. **pruner 改写 keep 窗口结果**(两 step 之间的替换、携带原始 turn/step)→ replace 目标保留重放、替换 op 重映射、prune 记录引用重映射、等价、invariant 零失败; -14. 真实验证器验收(`Session.create` + end-seed 标记落为子会话第一个 own event,与全量线程同形)。 +14. **keep 窗口起点的 inbox 括号**(`[insert][turn/start][claim]` 真实 loop 顺序)→ insert 回吞、位置折叠可重放(真投影由树外探针与 e2e 覆盖); +15. **同轮双成功 compaction、后组吞前组 checkpoint** → bracket 门回退(对照:去掉被消费组后 cp0 独立成切点、照常 trim); +16. **命令括号**:run 落被遗忘区段、done 存活 → 回退;run+done 同在 keep 窗口 → trim 且 `sourceEventSeq` 指向重基后的 run; +17. 真实验证器验收(`Session.create` + end-seed 标记落为子会话第一个 own event,与全量线程同形)。 夹具使用**真实轮距**(受保护头 turn 1 + 被 shadow 的整轮 + keep 轮 3 起)——二审证明「keep 恰为 turn 2」的唯一连续夹具会让 invariant 用例假绿。 @@ -82,7 +85,8 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): - 毁掉尾部 replace 重映射/降级分支 → 例 9 当场红; - 孤儿 summary 不回扫 → 例 10 当场红; - 关闭 turn 重编号 → 例 3(真实轮距 invariant)当场红; -- 三审的变异复验:关 turnOffset 5/12 红、去骨架包裹 6/12 红(含点名用例)。 +- 三审变异复验:关 turnOffset 5/12 红、去骨架包裹 6/12 红(含点名用例); +- 四审变异复验(树外隔离副本):抽 `replaceCovered.add` → 恰 pruner 用例红;去头部 step 归一 → 恰改写头用例红。 **披露**:`sameVisibleSequence` 终验单独变异不可由行为测试变红(它是纵深防御,只有与构造缺陷叠加才可观察——二审的 B1 修复前正是「构造缺陷 + 守卫被绕过」的叠加形态,例 7/8 就是为此而设)。 ## 独立审查记录(两轮,双 corpus 投票) @@ -91,7 +95,9 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): 二审(同日,两位全新 fresh reviewer):两票再次 **CHANGES_REQUIRED**,独立收敛于新 blocking——**turn 编号断档**(v2 头部骨架收口后计数器期望 turn 2,keep 窗口逐字保留原始 `turn/start{N}`;两道自证 foldSurface/Session.create 都抓不到,真实 harness 在 `sessions.create` 抛 `InvariantError`);另指出中段切点(region 边界仅 tool-pairing 平衡)会静默回退。→ v3:turn 重编号(keep ∪ 尾双段扫描首个保留轮)、中段 keep-window 跳过被 shadow 节点与孤儿 call、运行时 `turnSequenceValid` 关系门、夹具换真实轮距。 -三审(同日,两位全新 fresh reviewer):两票 **CHANGES_REQUIRED**——(a) 头部骨架 step 号未归一(受保护头被改写到 turn 1 step ≥2 时产出宿主 invariant 拒绝的种子);(b) 宽头存活 `tool/result` 丢配对 `tool/call`;(c) keep/尾保留的 compaction 计量记录 `shadowedRange/shadowedSeqs` 未重映射(违反 dsh-compaction invariant);(d) 关系门对**非 append** `tool/result` 过严(pruner 替换会让 trim 无谓回退);(e) lint 死赋值。→ v4:头部归一 turn 1 step 1(只改写已有数字信封字段——期间发现并修复了「向 user/message 注入 turn/step」的真等价破坏,token 改为镜像宿主投影:user=整份 data、其余=data.message)、关系门补 nextStep/pendingCalls/嵌套开轮/非 append 豁免、compaction 记录引用重映射或整条丢弃、**replace 目标节点不跳过**(pruner 形状由此从回退转为生效)。三轮审查者的全部树外证据脚本(`check-midturn`/`check-invariant`/`headline`/`probe1-5`/`probe2 B 扫描`/`probe3`/`probe4`/`rev3-probe:*`/`rev3-sidechat:p1-p9`)在 v4 上全部转绿或按设计安全回退(非法父日志与 legacy 逐字节 parity)。**第四轮 fresh review 尚未运行**——PR 开立前应再跑一轮。 +三审(同日,两位全新 fresh reviewer):两票 **CHANGES_REQUIRED**——(a) 头部骨架 step 号未归一(受保护头被改写到 turn 1 step ≥2 时产出宿主 invariant 拒绝的种子);(b) 宽头存活 `tool/result` 丢配对 `tool/call`;(c) keep/尾保留的 compaction 计量记录 `shadowedRange/shadowedSeqs` 未重映射(违反 dsh-compaction invariant);(d) 关系门对**非 append** `tool/result` 过严(pruner 替换会让 trim 无谓回退);(e) lint 死赋值。→ v4:头部归一 turn 1 step 1(只改写已有数字信封字段——期间发现并修复了「向 user/message 注入 turn/step」的真等价破坏,token 改为镜像宿主投影:user=整份 data、其余=data.message)、关系门补 nextStep/pendingCalls/嵌套开轮/非 append 豁免、compaction 记录引用重映射或整条丢弃、**replace 目标节点不跳过**(pruner 形状由此从回退转为生效)。 + +四审(同日,两位全新 fresh reviewer,对象 657dcd5 → tip 196fa11 两版钉证):核心等价性**未能证伪**(2100 生成形状、113 次 trim 全过真 session invariant + 真 Session.create + 真持久 inbox 投影 + 真 `deriveEventMessage` wire 比对;非 trim 全与 legacy 逐字节一致),但两票各在同一根因上给 blocking——**宿主「成组记录」被只丢计量记录拆散**:(a) 成功 `compaction/end` 失去同组 `compaction/summary`(同轮双 compaction 形状,随机实测命中 trim 的 18.6%,真 dsh-compaction invariant 拒绝而三道自证全盲);(b) 657dcd5 的 keep 窗口丢掉紧邻 turn/start 前的 inbox INSERT、保留其后的 CLAIM(真实持久 inbox 投影拒绝——**v4 e2e 在生产主会话上当场抓到**:`thread creation failed: invalid persisted inbox splice at session seq 7`)。→ v5:keepStart 回吞前置 splice + `inboxSplicesValid` 门(e2e 复测:**799 ms**、seed 3,457 = 35,992 的 **10.4×**、冷上下文回答再命中压缩摘要细节);`bracketsValid` 门(成组记录原子性:compaction bracket + command 配对);`command/done.sourceEventSeq` 重映射;spec oracle 换宿主 `deriveEventMessage`;补同轮双 compaction 与命令括号两用例(17 例)。Standards 另修:`expectedFirstKeptTurn` 按骨架实际 turn/start 判定(N2)、`inboxSplicesValid` 收紧到宿主严格度(N4)、post-cut 改写头回退形状入披露(S3,六会话三命中)。四轮审查者的全部树外证据脚本在 v5 上全部转绿或按设计安全回退。 ## 部署验证(已执行,2026-10-15) diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index 9a247486..05e5dd2d 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -380,7 +380,8 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] // a turn number at or past that first kept turn shifts down by the gap; // head-side numbers (below it) stay untouched. `step` numbers restart per // turn, so verbatim scaffolding inside a kept turn stays correct. - const expectedFirstKeptTurn = headEvents.length > 0 ? 2 : 1 + const headOwnsTurn1 = headEvents.some(event => event.type === 'turn/start') + const expectedFirstKeptTurn = headOwnsTurn1 ? 2 : 1 let firstKeptTurn: number | undefined // The first kept turn/start can sit in the keep interval OR — when every // pre-cut survivor is the protected head — only in the tail after the @@ -442,9 +443,41 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] } if (!turnSequenceValid(seed)) return undefined if (!inboxSplicesValid(seed)) return undefined + if (!bracketsValid(seed)) return undefined return seed } +/** + * Relational pre-check mirroring the host's grouped-record rules: a + * successful `compaction/end` requires a `compaction/summary` of the same + * compactionId earlier in the log, and a `command/done` requires its + * `command/run` (same commandId) before it. Dropping a summary or a run + * with the forgotten span while keeping its partner would ship a seed the + * host's invariant companions reject, so any unmatched partner falls back + * to the full copy. + */ +function bracketsValid(seed: readonly SeedEvent[]): boolean { + const summarized = new Set() + const ranCommands = new Set() + for (const event of seed) { + const data = dataOf(event) + if (event.type === 'compaction/summary') { + const id = data.compactionId + if (typeof id === 'string') summarized.add(id) + } else if (event.type === 'compaction/end') { + const id = data.compactionId + if (data.error === undefined && (typeof id !== 'string' || !summarized.has(id))) return false + } else if (event.type === 'command/run') { + const id = data.commandId + if (typeof id === 'string') ranCommands.add(id) + } else if (event.type === 'command/done') { + const id = data.commandId + if (typeof id !== 'string' || !ranCommands.has(id)) return false + } + } + return true +} + /** * Relational pre-check mirroring the host's durable-inbox fold: every kept * `agent/inbox/spliced` event replays POSITIONALLY over the pending inbox @@ -458,20 +491,24 @@ function inboxSplicesValid(seed: readonly SeedEvent[]): boolean { for (const event of seed) { if (event.type !== 'agent/inbox/spliced') continue const data = dataOf(event) + // Host strictness: only the two known targets, a numeric start and + // removedCount, and an array of messages with string ids. + if (data.target !== 'next-turn' && data.target !== 'next-step') return false const inbox = data.target === 'next-step' ? nextStep : nextTurn const rawStart = data.start const rawRemoved = data.removedCount - const removedCount = typeof rawRemoved === 'number' ? rawRemoved : 0 - const inserted = Array.isArray(data.inserted) ? data.inserted as Array> : [] + const removedCount = typeof rawRemoved === 'number' ? rawRemoved : Number.NaN + const inserted = Array.isArray(data.inserted) ? data.inserted as Array> : undefined const start = typeof rawStart === 'number' ? rawStart : Number.NaN - if (!Number.isSafeInteger(start) || start < 0 || start > inbox.length + if (inserted === undefined + || !Number.isSafeInteger(start) || start < 0 || start > inbox.length || !Number.isSafeInteger(removedCount) || removedCount < 0 || start + removedCount > inbox.length) return false inbox.splice(start, removedCount, ...inserted) const ids = new Set() for (const message of [...nextTurn, ...nextStep]) { const id = message.id - if (typeof id !== 'string') continue + if (typeof id !== 'string') return false if (ids.has(id)) return false ids.add(id) } @@ -747,6 +784,11 @@ function rebaseEvent( && firstKeptTurn !== undefined && sourceData.turn >= firstKeptTurn) { seed.data = { ...seed.data, turn: sourceData.turn - turnOffset } } + // A settled command cites the seq of the run it settled; remap it alongside. + if (event.type === 'command/done' && typeof sourceData.sourceEventSeq === 'number') { + const mapped = rebase.get(sourceData.sourceEventSeq) + if (mapped !== undefined) seed.data = { ...seed.data, sourceEventSeq: mapped } + } // Compaction metering records cite the surface span they priced. When the // span survived the rebase, remap the citations; when it did not (the // record predates the consumed compaction and its span lies in the diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index 5a4a32b5..1ca189f8 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -14,7 +14,7 @@ * equivalent, 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 { deriveEventMessage, foldSurface } from '@deepseek-ai/dsh-session/surface' import { Session, SessionLogOffset, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant' import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' @@ -248,16 +248,15 @@ function midTurnLog(kind: 'closers' | 'dangling'): SidebarSessionEvent[] { return events } -/** The model-visible sequence a fold produces, mirroring the renderer's - * projection exactly like the builder's own comparison: a user/message IS - * its whole data object; every other surface event projects `data.message`. */ +/** The model-visible sequence a fold produces, using the HOST's own + * `deriveEventMessage` projection as the oracle so the spec cannot share a + * projection bug with the implementation under test. */ function visibleSequence(events: readonly SidebarSessionEvent[]): string[] { const fold = foldSurface(events as unknown as readonly SessionEvent[]) return fold.nodes.map(seq => { const event = events[seq] if (event === undefined) return `missing:${seq}` - if (event.type === 'user/message') return `${event.type}:${JSON.stringify(event.data)}` - return `${event.type}:${JSON.stringify((event.data as { message?: unknown }).message ?? null)}` + return `${event.type}:${JSON.stringify(deriveEventMessage(event as unknown as SessionEvent))}` }) } @@ -586,8 +585,9 @@ describe('buildSidechatInheritance compaction tail', () => { // Real loop order: [insert q][turn/start][claim q][step/start][user]. // The keep window must swallow the insert ahead of the turn/start so // the positional inbox fold replays; without it the claim dangles and - // Session.create rejects the seed (caught on the real deployment's - // main session during e2e). + // the host's durable-inbox projection rejects the seed during thread + // creation (caught on the real deployment's main session during e2e; + // Session.create itself does not validate this face). const events = [...systemHead(), ...oldSpan().events] const shadowTurn = turn(9, 2, { callId: 'c-shadow', result: 'shadow result' }) events.push(...shadowTurn.events) @@ -624,6 +624,125 @@ describe('buildSidechatInheritance compaction tail', () => { ) }) + it('falls back when a kept compaction group would lose its summary to the dropped span', () => { + // Same-turn double compaction: cp0 completes mid-turn, cp1 (the consumed + // one) shadows cp0's checkpoint; cp0's records ride in the keep window + // but its citations name the dropped span, so dropping only the summary + // would strand a successful compaction/end — the bracket gate falls + // back to the full copy instead of shipping a seed the host's + // compaction invariant companion rejects. + const events = [ + lo('turn/start', 0, { turn: 1 }), + lo('step/start', 1, { turn: 1, step: 1 }), + sf('system/message', 2, { + turn: 1, step: 1, + message: { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'system prompt' }], source: { kind: 'system-prompt' } }, + }), + sf('user/message', 3, userMessage('m-q1', 'q1')), + sf('assistant/message', 4, { turn: 1, step: 1, message: assistantMessage('a1'), stream: [] }), + lo('step/end', 5, { turn: 1, step: 1 }), + lo('turn/end', 6, { turn: 1, reason: { kind: 'completed' } }), + lo('turn/start', 7, { turn: 2 }), + lo('step/start', 8, { turn: 2, step: 1 }), + sf('user/message', 9, userMessage('m-q2', 'q2')), + sf('assistant/message', 10, { turn: 2, step: 1, message: assistantMessage('a2'), stream: [] }), + lo('step/end', 11, { turn: 2, step: 1 }), + lo('compaction/start', 12, { compactionId: 'cp0', turn: 2 }), + lo('compaction/summary', 13, { + compactionId: 'cp0', + summary: [{ type: 'text', text: 'summary cp0' }], + shadowedRange: { start: 3, end: 4 }, + shadowedSeqs: [3, 4], + shadowedTokenCount: 10, + provider: 'deepseek', + model: 'model-x', + rawOutput: [], + llmStreamCall: true, + }), + { + ...sf('user/message', 14, { id: 'm-cp0', role: 'user', content: [{ type: 'text', text: 'summary cp0' }], source: { kind: 'compact-checkpoint', compactionId: 'cp0' } }), + surfaceOp: { op: 'replace', startSeq: 3, endSeq: 4 }, + sourceEventSeqs: [3, 4], + } as SidebarSessionEvent, + lo('compaction/end', 15, { compactionId: 'cp0', turn: 2 }), + lo('step/start', 16, { turn: 2, step: 2 }), + sf('assistant/message', 17, { turn: 2, step: 2, message: assistantMessage('a2b'), stream: [] }), + lo('step/end', 18, { turn: 2, step: 2 }), + lo('turn/end', 19, { turn: 2, reason: { kind: 'completed' } }), + ...turn(20, 3, { callId: 'c-tail', result: 'tail result' }).events, + ] + // The consumed compaction shadows cp0's checkpoint plus turn 1's nodes. + events.push(...compactionGroup(events.length, [3, 4, 14])) + const { seed } = buildSidechatInheritance(events) + expect(seed.length).toBe(events.length) + // Control: the same log without the consumed group (its four trailing + // events) cuts at cp0 instead and trims — only the bracket split, not + // the log, disables the optimization. + const control = events.slice(0, -4) + const controlSeed = buildSidechatInheritance(control).seed + expect(controlSeed.length).toBeLessThan(control.length) + }) + + it('falls back when a command/run is dropped while its command/done survives', () => { + // A slash command runs before turn 1 and settles inside turn 2; the + // consumed compaction shadows turn 1's surface, so the keep window + // keeps the done without its run — the bracket gate falls back instead + // of shipping a seed the host's commands invariant rejects. When both + // records ride the keep window, the done's sourceEventSeq remaps onto + // the rebased run. + const base = [ + lo('command/run', 0, { commandId: 'cmd1', name: 'compact', source: { kind: 'user' } }), + lo('turn/start', 1, { turn: 1 }), + lo('step/start', 2, { turn: 1, step: 1 }), + sf('system/message', 3, { + turn: 1, step: 1, + message: { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'system prompt' }], source: { kind: 'system-prompt' } }, + }), + sf('user/message', 4, userMessage('m-q1', 'q1')), + sf('assistant/message', 5, { turn: 1, step: 1, message: assistantMessage('a1'), stream: [] }), + lo('step/end', 6, { turn: 1, step: 1 }), + lo('turn/end', 7, { turn: 1, reason: { kind: 'completed' } }), + ] + const events = [ + ...base, + lo('turn/start', 8, { turn: 2 }), + lo('command/done', 9, { commandId: 'cmd1', kind: 'success', text: 'ok', sourceEventSeq: 4 }), + lo('step/start', 10, { turn: 2, step: 1 }), + sf('user/message', 11, userMessage('m-q2', 'q2')), + sf('assistant/message', 12, { turn: 2, step: 1, message: assistantMessage('a2'), stream: [] }), + lo('step/end', 13, { turn: 2, step: 1 }), + lo('turn/end', 14, { turn: 2, reason: { kind: 'completed' } }), + ...turn(15, 3, { callId: 'c-tail', result: 'tail result' }).events, + ] + events.push(...compactionGroup(events.length, [4, 5])) + const { seed } = buildSidechatInheritance(events) + expect(seed.length).toBe(events.length) + + // Together: a command that runs INSIDE the keep window and settles + // there — both records ride, and the done cites the rebased run. + const together = [ + ...base, + lo('turn/start', 8, { turn: 2 }), + lo('step/start', 9, { turn: 2, step: 1 }), + sf('user/message', 10, userMessage('m-q2', 'q2')), + lo('command/run', 11, { commandId: 'cmd1', name: 'compact', source: { kind: 'user' } }), + lo('command/done', 12, { commandId: 'cmd1', kind: 'success', text: 'ok', sourceEventSeq: 11 }), + sf('assistant/message', 13, { turn: 2, step: 1, message: assistantMessage('a2'), stream: [] }), + lo('step/end', 14, { turn: 2, step: 1 }), + lo('turn/end', 15, { turn: 2, reason: { kind: 'completed' } }), + ...turn(16, 3, { callId: 'c-tail', result: 'tail result' }).events, + ] + together.push(...compactionGroup(together.length, [4, 5])) + const trimmed = buildSidechatInheritance(together) + expect(trimmed.seed.length).toBeLessThan(together.length) + const done = trimmed.seed.find(event => event.type === 'command/done') as { data?: { sourceEventSeq?: number }; seq?: number } + const runIdx = trimmed.seed.findIndex(event => event.type === 'command/run') + expect(runIdx).toBeGreaterThanOrEqual(0) + expect(done?.data?.sourceEventSeq).toBe(runIdx) + expect(visibleSequence(trimmed.seed)).toEqual(visibleSequence(together)) + expect(invariantFailures(trimmed.seed)).toEqual([]) + }) + it('reuses the previous compaction when the newest summary is orphaned', () => { const events = compactedLog() const at = events.length From f320cdee837a80da66abe473fb3f6c59a3fff587 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Thu, 15 Oct 2026 01:37:01 -0700 Subject: [PATCH 09/12] fix(sidechat): drop grouped records atomically and honor the host's optional removedCount (round 5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The round-5 delta review and the real-data re-run exposed two v5 regressions that disabled the optimization exactly where it matters. First, the new bracket gate fell back on real multi-group sessions: a mid-keep compaction group's summary cites nodes a later group re-shadowed, so record-level dropping stranded its successful compaction/end and the gate rejected the whole tail — the deployment's main session forked at 9,077 ms with seed 35,993 (the full copy). The fix is the reviewers' other option, now data-backed: decide the emitted-seq set BEFORE emission and drop unmatched groups ATOMICALLY — a compaction bracket goes as a whole, a command/done losing its run goes alone. The fuzz suite recovers from 108 to 129 clean trims per 3000 cases (every one passing the real session, compaction, and commands invariants plus the real inbox projection), and the round-4 cascade counterexample flips from fallback to a clean trim. Second, v5 treated a missing removedCount as invalid, but the host contract makes it optional and defaults it to 0 — the host's own writer omits it for pure inserts, 54% of production splices are like that, and 38 of 89 real compaction sessions (including the e2e main session) fell back purely on this. Restored the ?? 0 default while keeping the rest of the host-fold strictness. The round-4 spec case is rewritten against the host's chained-replace semantics (the consumed group swallows the surface span as it exists at ITS fold moment), which turned it from an empty test — the fixture could not fold at all, so it pinned nothing — into a real pin: the atomic drop trims with the earlier group's records gone entirely. Final second-instance e2e on the real main session: 953 ms, seed 3,457 (10.4x), and a cold-context answer that only the compaction summaries could contain. --- src/sidechat-core.ts | 69 ++++++++++++++++++++++++-- tests/sidechat-compaction-seed.spec.ts | 44 ++++++++++------ 2 files changed, 94 insertions(+), 19 deletions(-) diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index 05e5dd2d..f2bb9e9b 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -374,6 +374,60 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] for (let seq = Math.max(0, start); seq <= Math.min(end, events.length - 1); seq++) replaceCovered.add(seq) } } + // The set of parent seqs the seed will carry, decided BEFORE emission: a + // grouped record whose citations cannot remap drops ATOMICALLY — its + // compaction bracket (start/summary/end) or its command pair goes + // together, never a lone partner that the host's invariant companions + // reject. Real multi-compaction sessions hit this on every mid-keep group + // (its summary cites nodes later groups re-shadowed), so record-level + // dropping would strand brackets on every real parent. + const emittedSeqs = new Set() + for (const event of headEvents) emittedSeqs.add(event.seq) + emittedSeqs.add(checkpoint.seq) + const keepSkip = (event: SidechatLogEvent): boolean => + (isSurfaceEligibleType(event.type) && !surviving.has(event.seq) && !replaceCovered.has(event.seq)) + || (event.type === 'tool/call' && !survivingCallIds.has(String(dataOf(event).callId))) + for (const [from, to] of [[keepStart, cut], [cut + 1, events.length]] as const) { + for (let index = from; index < to; index++) { + const event = events[index] + if (event === undefined) continue + if (isCompactionGroupEvent(event, groupId)) continue + if (index < cut && keepSkip(event)) continue + emittedSeqs.add(event.seq) + } + } + const droppedGroups = new Set() + const keptRunIds = new Set() + for (const seq of emittedSeqs) { + const event = events[seq] + if (event === undefined || event.type !== 'command/run') continue + const id = dataOf(event).commandId + if (typeof id === 'string') keptRunIds.add(id) + } + const droppedDones = new Set() + for (const seq of emittedSeqs) { + const event = events[seq] + if (event === undefined) continue + const data = dataOf(event) + if (event.type === 'compaction/summary' || event.type === 'compaction/prune') { + const range = data.shadowedRange as { start?: unknown; end?: unknown } | undefined + const cited = data.shadowedSeqs + if (range === null || typeof range !== 'object' || !Array.isArray(cited)) continue + const start = typeof range.start === 'number' ? emittedSeqs.has(range.start) : true + const end = typeof range.end === 'number' ? emittedSeqs.has(range.end) : true + const citedAll = cited.every(item => typeof item !== 'number' || emittedSeqs.has(item)) + if (!start || !end || !citedAll) { + const id = data.compactionId + if (typeof id === 'string') droppedGroups.add(id) + } + } else if (event.type === 'command/done') { + const id = data.commandId + const runSeq = data.sourceEventSeq + const runKept = (typeof id === 'string' && keptRunIds.has(id)) + || (typeof runSeq === 'number' && emittedSeqs.has(runSeq) && events[runSeq]?.type === 'command/run') + if (!runKept) droppedDones.add(event.seq) + } + } // Turn renumbering: the host's turn counter must run 1, 2, 3… over the // seed, but the dropped span leaves a gap between the head skeleton's // turn and the keep window's first turn/start. Every kept event carrying @@ -421,13 +475,17 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] for (let index = keepStart; index < cut; index++) { const event = events[index] if (event === undefined || isCompactionGroupEvent(event, groupId)) continue - if (isSurfaceEligibleType(event.type) && !surviving.has(event.seq) && !replaceCovered.has(event.seq)) continue - if (event.type === 'tool/call' && !survivingCallIds.has(String(dataOf(event).callId))) continue + if (keepSkip(event)) continue + if (droppedGroups.has(String(dataOf(event).compactionId))) continue + if (droppedDones.has(event.seq)) continue emit(event) } for (let index = cut + 1; index < events.length; index++) { const event = events[index] - if (event !== undefined && !isCompactionGroupEvent(event, groupId)) emit(event) + if (event === undefined || isCompactionGroupEvent(event, groupId)) continue + if (droppedGroups.has(String(dataOf(event).compactionId))) continue + if (droppedDones.has(event.seq)) continue + emit(event) } if (aborted) return undefined // Prove equivalence before the caller relies on it: the rebased sequence @@ -496,8 +554,9 @@ function inboxSplicesValid(seed: readonly SeedEvent[]): boolean { if (data.target !== 'next-turn' && data.target !== 'next-step') return false const inbox = data.target === 'next-step' ? nextStep : nextTurn const rawStart = data.start - const rawRemoved = data.removedCount - const removedCount = typeof rawRemoved === 'number' ? rawRemoved : Number.NaN + // The host contract makes removedCount optional and defaults it to 0 + // (its own writer omits it for pure inserts — 54% of real splices). + const removedCount = typeof data.removedCount === 'number' ? data.removedCount : 0 const inserted = Array.isArray(data.inserted) ? data.inserted as Array> : undefined const start = typeof rawStart === 'number' ? rawStart : Number.NaN if (inserted === undefined diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index 1ca189f8..0ef434a6 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -624,13 +624,14 @@ describe('buildSidechatInheritance compaction tail', () => { ) }) - it('falls back when a kept compaction group would lose its summary to the dropped span', () => { + it('drops a mid-keep compaction group atomically when its citations fall in the dropped span', () => { // Same-turn double compaction: cp0 completes mid-turn, cp1 (the consumed - // one) shadows cp0's checkpoint; cp0's records ride in the keep window - // but its citations name the dropped span, so dropping only the summary - // would strand a successful compaction/end — the bracket gate falls - // back to the full copy instead of shipping a seed the host's - // compaction invariant companion rejects. + // one) swallows cp0's checkpoint; cp0's records ride in the keep window + // but its citations name the dropped span. Record-level dropping would + // strand a successful compaction/end (the host's compaction invariant + // companion rejects it) — the group drops ATOMICALLY and the trim still + // fires, which is what real multi-compaction parents need (every + // mid-keep group cites nodes a later group re-shadowed). const events = [ lo('turn/start', 0, { turn: 1 }), lo('step/start', 1, { turn: 1, step: 1 }), @@ -671,19 +672,28 @@ describe('buildSidechatInheritance compaction tail', () => { lo('turn/end', 19, { turn: 2, reason: { kind: 'completed' } }), ...turn(20, 3, { callId: 'c-tail', result: 'tail result' }).events, ] - // The consumed compaction shadows cp0's checkpoint plus turn 1's nodes. - events.push(...compactionGroup(events.length, [3, 4, 14])) - const { seed } = buildSidechatInheritance(events) - expect(seed.length).toBe(events.length) + // The consumed compaction swallows the surface span as it exists at ITS + // fold moment: cp0's checkpoint (which replaced turn 1's nodes) plus + // turn 2 step 1's messages. + events.push(...compactionGroup(events.length, [14, 9, 10])) + const { seed, snapshot } = buildSidechatInheritance(events) + expect(snapshot).toBeNull() + expect(seed.length).toBeLessThan(events.length) + // cp0's whole bracket is gone — no lone end without its summary. + expect(seed.some(event => JSON.stringify(event).includes('cp0'))).toBe(false) + expect(seed.some(event => event.type === 'compaction/end' && (event.data as { compactionId?: string }).compactionId === 'cp1')).toBe(false) + const seedGroups = seed.filter(event => event.type === 'compaction/start' || event.type === 'compaction/summary' || event.type === 'compaction/end') + expect(seedGroups).toEqual([]) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expect(invariantFailures(seed)).toEqual([]) // Control: the same log without the consumed group (its four trailing - // events) cuts at cp0 instead and trims — only the bracket split, not - // the log, disables the optimization. + // events) cuts at cp0 instead and also trims. const control = events.slice(0, -4) const controlSeed = buildSidechatInheritance(control).seed expect(controlSeed.length).toBeLessThan(control.length) }) - it('falls back when a command/run is dropped while its command/done survives', () => { + it('drops a command/done atomically when its run falls in the dropped span', () => { // A slash command runs before turn 1 and settles inside turn 2; the // consumed compaction shadows turn 1's surface, so the keep window // keeps the done without its run — the bracket gate falls back instead @@ -716,7 +726,13 @@ describe('buildSidechatInheritance compaction tail', () => { ] events.push(...compactionGroup(events.length, [4, 5])) const { seed } = buildSidechatInheritance(events) - expect(seed.length).toBe(events.length) + // The done drops ATOMICALLY with its dropped run — no lone done the + // host's commands invariant rejects, and the trim still fires. + expect(seed.length).toBeLessThan(events.length) + expect(seed.some(event => event.type === 'command/done')).toBe(false) + expect(seed.some(event => event.type === 'command/run')).toBe(false) + expect(visibleSequence(seed)).toEqual(visibleSequence(events)) + expect(invariantFailures(seed)).toEqual([]) // Together: a command that runs INSIDE the keep window and settles // there — both records ride, and the done cites the rebased run. From b5e6d4daac5c8cf4c97466a23a4a81c3ae66f313 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Thu, 15 Oct 2026 01:38:05 -0700 Subject: [PATCH 10/12] docs(sidechat): record the round-5 atomic-drop rework and the real-data regressions it fixed --- docs/plans/2026-10-13-sidechat-compaction-tail-seed.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md index 0d0fc9a3..f6f98e58 100644 --- a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md +++ b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md @@ -1,6 +1,6 @@ # 侧边对话启动慢:种子改为从最后一次 compaction 切尾(可验证等价) -> 2026-10-13 起,2026-10-15 四轮独立审查后为 v5 构造 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts`(17 例) +> 2026-10-13 起,2026-10-15 五轮独立审查后为 v6 构造 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts`(17 例) ## 问题 @@ -45,7 +45,7 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): ### 证明范围与披露 - 等价证明覆盖**可见节点内容序列**;`request/header`/`request/context` 等模型装配输入中 log-only 的部分,keep-window 与尾部内的会随逐字保留带过去,更老的随区段丢弃——实测(二审探针,6 组工具集变化组合):子会话首个请求经宿主 `projectToolUpdates` 投影后与全量 fork **完全一致**(子会话自建的 header 重置 declaration series),今天无可观测差异;此推理链无测试 pin,属已知边界。 -- **回退(安全、无收益)的已知形状**(四轮探针实测):**宽头**(受保护头之外还有存活 pre-cut 节点且含 tool/result——需经公开 `compactRegion` 任意区间接缝或第三方 backend 才可达,随包 backend 的 region 恒起于 surface index 0/1);**单轮父会话**(compaction 发生在唯一仍在打开的轮内、无 keep 区间);**cut 之后被改写的受保护头**(存活 node 0 是 post-cut 替换、pre-cut 扫描找不到头——四审实测六个最重会话三个命中,含 32675 事件的旧式 fork 子会话;生产主会话不受影响);**同轮双成功 compaction 且后组吞掉前组 checkpoint**(前组 citations 全落在 keep 窗口之前——bracket 门回退;跨轮级联正常 trim);**命令括号被拆**(`command/run` 落在被遗忘区段而 `command/done` 存活——bracket 门回退);父日志本身违反关系不变量(子会话回退后与 legacy 逐字节一致 = parity);审查者 p1-A 的多 step 中段复合形状。**已支持**(探针实证):中段切点(keep 首轮部分被 shadow,含跨多 step)、context-overflow(keep 只剩末节点)、**被改写的受保护头**(原始 turn/step 任意、cut 之前——归一后 trim 生效)、**pruner 替换在 keep 窗口**(replace 目标保留重放 + 非 append 豁免 + 计量记录引用重映射或丢弃)、**keep 窗口起点的 inbox insert 回吞**(真实 loop 顺序 `[insert][turn/start][claim]`——v4 e2e 在生产主会话上抓到并修复)、空 keep 区间、**跨轮级联 compaction**、孤立 summary 回扫、命令 run+done 同窗(`sourceEventSeq` 重映射)。keep 窗口内 `request/header` + `developer/message.headerSeq` 成功重映射由三轮审查者探针钉住(`probe-header-remap`:指向重基后 header、trim、invariant 0/0)。 +- **回退(安全、无收益)的已知形状**(四轮探针实测):**宽头**(受保护头之外还有存活 pre-cut 节点且含 tool/result——需经公开 `compactRegion` 任意区间接缝或第三方 backend 才可达,随包 backend 的 region 恒起于 surface index 0/1);**单轮父会话**(compaction 发生在唯一仍在打开的轮内、无 keep 区间);**cut 之后被改写的受保护头**(存活 node 0 是 post-cut 替换、pre-cut 扫描找不到头——四审实测六个最重会话三个命中,含 32675 事件的旧式 fork 子会话;生产主会话不受影响);父日志本身违反关系不变量(子会话回退后与 legacy 逐字节一致 = parity);审查者 p1-A 的多 step 中段复合形状。**已支持**(探针实证):中段切点(keep 首轮部分被 shadow,含跨多 step)、context-overflow(keep 只剩末节点)、**被改写的受保护头**(原始 turn/step 任意、cut 之前——归一后 trim 生效)、**pruner 替换在 keep 窗口**(replace 目标保留重放 + 非 append 豁免 + 计量记录引用重映射或丢弃)、**keep 窗口起点的 inbox insert 回吞**(真实 loop 顺序 `[insert][turn/start][claim]`——v4 e2e 在生产主会话上抓到并修复)、空 keep 区间、**级联 compaction(含同轮后组吞前组 checkpoint——成组原子丢弃)**、**引用失配的孤立 summary 与命令括号(v6 起原子丢弃,fuzz/probe 实证 invariant 全清)**、命令 run+done 同窗(`sourceEventSeq` 重映射)、**真实多组会话**(主会话 14 组 compaction:953 ms、seed 3,457、fuzz 129 trim/3000 全清)。keep 窗口内 `request/header` + `developer/message.headerSeq` 成功重映射由三轮审查者探针钉住(`probe-header-remap`:指向重基后 header、trim、invariant 0/0)。 - 日志含 `image/offload` 等 **MESSAGE_PROJECTION 事件类型**时 `foldSurface`(无 projections)抛错 → 回退全量(安全,但含图长会话拿不到收益)。同理,未来插件自定义 projection 不在 core 集合内时证明会失真为「回退」而非「假通过」。 - 孤立 compaction 组(summary 后替换未落地)的 log-only 记录随尾部保留(折叠不可见,保留宿主 metering 历史);构造时剔除的只有**本次消费的那一组**。 - 第二个 system 头(checkpoint 表位之前的其他存活节点)实测受支持(二审探针 E:trim 生效、等价、validator 接受)。 @@ -97,6 +97,8 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): 三审(同日,两位全新 fresh reviewer):两票 **CHANGES_REQUIRED**——(a) 头部骨架 step 号未归一(受保护头被改写到 turn 1 step ≥2 时产出宿主 invariant 拒绝的种子);(b) 宽头存活 `tool/result` 丢配对 `tool/call`;(c) keep/尾保留的 compaction 计量记录 `shadowedRange/shadowedSeqs` 未重映射(违反 dsh-compaction invariant);(d) 关系门对**非 append** `tool/result` 过严(pruner 替换会让 trim 无谓回退);(e) lint 死赋值。→ v4:头部归一 turn 1 step 1(只改写已有数字信封字段——期间发现并修复了「向 user/message 注入 turn/step」的真等价破坏,token 改为镜像宿主投影:user=整份 data、其余=data.message)、关系门补 nextStep/pendingCalls/嵌套开轮/非 append 豁免、compaction 记录引用重映射或整条丢弃、**replace 目标节点不跳过**(pruner 形状由此从回退转为生效)。 +五审(delta 终验 + 真实数据复测,对象 cc11ce4 并对工作树并发改动钉版复核):抓到 v5 两处回归并当场修复。(a) bracket 门在真实多组会话上**全量回退**——e2e 实测主会话 seed=35,993、9,077 ms(全量拷贝旧路径);根因是真实多组会话的 mid-keep 组 summary 引用全指向被后续组 re-shadow 的节点,记录级丢弃拆散成组记录。→ 修法取审查者给的第二选项并经数据背书:**成组原子丢弃**(发射前定 emittedSeqs,引用失配的 compaction 组 start/summary/end 整组丢、失 run 的 command/done 单独丢);fuzz 3000 例 trim 108→129 全过真 session+compaction+commands invariant 与真 inbox 折叠、0 命中,四审级联反例 pG 从回退翻转为干净 trim。(b) v5 把缺失 `removedCount` 当非法——宿主契约它**可选、缺省 0**(宿主写入方对纯插入省略它;生产库 54% splice 如此;89 个真实 compaction 会话 38 个因此回退,含主会话)→ 还原 `?? 0`。五审实证 v5 在 89 个真实会话 trim 41→3 的覆盖率崩塌即此二回归合成。用例 15 夹具按宿主链式 replace 语义重写(吞**当时** surface span),从空测(夹具本身折不动、断言恒真)翻转为真钉子。终版 e2e(ad42628):**953 ms / seed 3,457(10.4×)**、冷上下文回答再命中 exp5 收尾细节(fsr-ge7-top5-5e5-allfix、1.02×→1.18× 分叉消失、2900x 收尾三件事)。 + 四审(同日,两位全新 fresh reviewer,对象 657dcd5 → tip 196fa11 两版钉证):核心等价性**未能证伪**(2100 生成形状、113 次 trim 全过真 session invariant + 真 Session.create + 真持久 inbox 投影 + 真 `deriveEventMessage` wire 比对;非 trim 全与 legacy 逐字节一致),但两票各在同一根因上给 blocking——**宿主「成组记录」被只丢计量记录拆散**:(a) 成功 `compaction/end` 失去同组 `compaction/summary`(同轮双 compaction 形状,随机实测命中 trim 的 18.6%,真 dsh-compaction invariant 拒绝而三道自证全盲);(b) 657dcd5 的 keep 窗口丢掉紧邻 turn/start 前的 inbox INSERT、保留其后的 CLAIM(真实持久 inbox 投影拒绝——**v4 e2e 在生产主会话上当场抓到**:`thread creation failed: invalid persisted inbox splice at session seq 7`)。→ v5:keepStart 回吞前置 splice + `inboxSplicesValid` 门(e2e 复测:**799 ms**、seed 3,457 = 35,992 的 **10.4×**、冷上下文回答再命中压缩摘要细节);`bracketsValid` 门(成组记录原子性:compaction bracket + command 配对);`command/done.sourceEventSeq` 重映射;spec oracle 换宿主 `deriveEventMessage`;补同轮双 compaction 与命令括号两用例(17 例)。Standards 另修:`expectedFirstKeptTurn` 按骨架实际 turn/start 判定(N2)、`inboxSplicesValid` 收紧到宿主严格度(N4)、post-cut 改写头回退形状入披露(S3,六会话三命中)。四轮审查者的全部树外证据脚本在 v5 上全部转绿或按设计安全回退。 ## 部署验证(已执行,2026-10-15) From 37e0354d152384812d7c810b160ecad942fdfd35 Mon Sep 17 00:00:00 2001 From: NolanHo Date: Thu, 15 Oct 2026 01:45:35 -0700 Subject: [PATCH 11/12] fix(sidechat): drop a command/done whose citation fell in the dropped span (round 5, F2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The round-5 final report pinned a real bad-seed path on cc11ce4 and verified my in-flight atomic drops did not cover it: a command/done whose run SURVIVES while its numeric sourceEventSeq cites an earlier NON-command event in the dropped span kept the parent seq — a stale citation the host's commands invariant rejects (the contract: the citation names an earlier non-command event, never the run). Their real-data oracle found three such seeds among the forty genuinely trimming production sessions. The pre-decision now drops the done when either its run's commandId or its cited source seq is not in the emitted set (the run staying behind is legal — an open command), and rebaseEvent's runtime belt returns DROPPED for an unmappable citation instead of leaving the parent value. The spec's both-kept fixture is rewritten against the host contract: unique commandId per run and a citation pointing at the user message, asserting the remapped citation names a non-command event. A mutation that removes the droppedGroups filter reddens the mid-keep-group case, so the atomic-drop chain and the bracket gate now have an in-repo pin. --- ...026-10-13-sidechat-compaction-tail-seed.md | 2 +- src/sidechat-core.ts | 19 +++++++++++++------ tests/sidechat-compaction-seed.spec.ts | 17 ++++++++++------- 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md index f6f98e58..fc86b3de 100644 --- a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md +++ b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md @@ -97,7 +97,7 @@ DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): 三审(同日,两位全新 fresh reviewer):两票 **CHANGES_REQUIRED**——(a) 头部骨架 step 号未归一(受保护头被改写到 turn 1 step ≥2 时产出宿主 invariant 拒绝的种子);(b) 宽头存活 `tool/result` 丢配对 `tool/call`;(c) keep/尾保留的 compaction 计量记录 `shadowedRange/shadowedSeqs` 未重映射(违反 dsh-compaction invariant);(d) 关系门对**非 append** `tool/result` 过严(pruner 替换会让 trim 无谓回退);(e) lint 死赋值。→ v4:头部归一 turn 1 step 1(只改写已有数字信封字段——期间发现并修复了「向 user/message 注入 turn/step」的真等价破坏,token 改为镜像宿主投影:user=整份 data、其余=data.message)、关系门补 nextStep/pendingCalls/嵌套开轮/非 append 豁免、compaction 记录引用重映射或整条丢弃、**replace 目标节点不跳过**(pruner 形状由此从回退转为生效)。 -五审(delta 终验 + 真实数据复测,对象 cc11ce4 并对工作树并发改动钉版复核):抓到 v5 两处回归并当场修复。(a) bracket 门在真实多组会话上**全量回退**——e2e 实测主会话 seed=35,993、9,077 ms(全量拷贝旧路径);根因是真实多组会话的 mid-keep 组 summary 引用全指向被后续组 re-shadow 的节点,记录级丢弃拆散成组记录。→ 修法取审查者给的第二选项并经数据背书:**成组原子丢弃**(发射前定 emittedSeqs,引用失配的 compaction 组 start/summary/end 整组丢、失 run 的 command/done 单独丢);fuzz 3000 例 trim 108→129 全过真 session+compaction+commands invariant 与真 inbox 折叠、0 命中,四审级联反例 pG 从回退翻转为干净 trim。(b) v5 把缺失 `removedCount` 当非法——宿主契约它**可选、缺省 0**(宿主写入方对纯插入省略它;生产库 54% splice 如此;89 个真实 compaction 会话 38 个因此回退,含主会话)→ 还原 `?? 0`。五审实证 v5 在 89 个真实会话 trim 41→3 的覆盖率崩塌即此二回归合成。用例 15 夹具按宿主链式 replace 语义重写(吞**当时** surface span),从空测(夹具本身折不动、断言恒真)翻转为真钉子。终版 e2e(ad42628):**953 ms / seed 3,457(10.4×)**、冷上下文回答再命中 exp5 收尾细节(fsr-ge7-top5-5e5-allfix、1.02×→1.18× 分叉消失、2900x 收尾三件事)。 +五审(delta 终验 + 真实数据复测,对象 cc11ce4 并对工作树并发改动钉版复核):抓到 v5 两处回归并当场修复。(a) bracket 门在真实多组会话上**全量回退**——e2e 实测主会话 seed=35,993、9,077 ms(全量拷贝旧路径);根因是真实多组会话的 mid-keep 组 summary 引用全指向被后续组 re-shadow 的节点,记录级丢弃拆散成组记录。→ 修法取审查者给的第二选项并经数据背书:**成组原子丢弃**(发射前定 emittedSeqs,引用失配的 compaction 组 start/summary/end 整组丢、失 run 的 command/done 单独丢);fuzz 3000 例 trim 108→129 全过真 session+compaction+commands invariant 与真 inbox 折叠、0 命中,四审级联反例 pG 从回退翻转为干净 trim。(b) v5 把缺失 `removedCount` 当非法——宿主契约它**可选、缺省 0**(宿主写入方对纯插入省略它;生产库 54% splice 如此;89 个真实 compaction 会话 38 个因此回退,含主会话)→ 还原 `?? 0`。五审实证 v5 在 89 个真实会话 trim 41→3 的覆盖率崩塌即此二回归合成。用例 15 夹具按宿主链式 replace 语义重写(吞**当时** surface span),从空测(夹具本身折不动、断言恒真)翻转为真钉子。终版 e2e(ad42628):**953 ms / seed 3,457(10.4×)**、冷上下文回答再命中 exp5 收尾细节(fsr-ge7-top5-5e5-allfix、1.02×→1.18× 分叉消失、2900x 收尾三件事)。五审终稿另定级 F2(blocking,两审一致):`command/done.sourceEventSeq` 映射不到时留父 seq——宿主契约它指向**更早的非命令事件**(commands invariant 拒陈旧引用),且真实数据 40 个 trim 中 3 个命中 → 修复:done 引用的数值 sourceSeq 落在被遗忘区段时**随 run 一起原子丢弃**(运行时兜底同样 DROPPED),`pM` 探针由「trim + 违反 commands invariant」翻转为「trim + 无陈旧引用」;用例 16 后半夹具按契约重写(唯一 commandId、sourceEventSeq 指向 user 消息)。变异 M6(去掉 droppedGroups 过滤)→ 用例 15 当场红,证明原子丢弃链与 bracket 门在仓内套件有钉子。 四审(同日,两位全新 fresh reviewer,对象 657dcd5 → tip 196fa11 两版钉证):核心等价性**未能证伪**(2100 生成形状、113 次 trim 全过真 session invariant + 真 Session.create + 真持久 inbox 投影 + 真 `deriveEventMessage` wire 比对;非 trim 全与 legacy 逐字节一致),但两票各在同一根因上给 blocking——**宿主「成组记录」被只丢计量记录拆散**:(a) 成功 `compaction/end` 失去同组 `compaction/summary`(同轮双 compaction 形状,随机实测命中 trim 的 18.6%,真 dsh-compaction invariant 拒绝而三道自证全盲);(b) 657dcd5 的 keep 窗口丢掉紧邻 turn/start 前的 inbox INSERT、保留其后的 CLAIM(真实持久 inbox 投影拒绝——**v4 e2e 在生产主会话上当场抓到**:`thread creation failed: invalid persisted inbox splice at session seq 7`)。→ v5:keepStart 回吞前置 splice + `inboxSplicesValid` 门(e2e 复测:**799 ms**、seed 3,457 = 35,992 的 **10.4×**、冷上下文回答再命中压缩摘要细节);`bracketsValid` 门(成组记录原子性:compaction bracket + command 配对);`command/done.sourceEventSeq` 重映射;spec oracle 换宿主 `deriveEventMessage`;补同轮双 compaction 与命令括号两用例(17 例)。Standards 另修:`expectedFirstKeptTurn` 按骨架实际 turn/start 判定(N2)、`inboxSplicesValid` 收紧到宿主严格度(N4)、post-cut 改写头回退形状入披露(S3,六会话三命中)。四轮审查者的全部树外证据脚本在 v5 上全部转绿或按设计安全回退。 diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index f2bb9e9b..e2b71397 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -422,10 +422,14 @@ function compactionTail(events: readonly SidechatLogEvent[]): SidechatLogEvent[] } } else if (event.type === 'command/done') { const id = data.commandId - const runSeq = data.sourceEventSeq - const runKept = (typeof id === 'string' && keptRunIds.has(id)) - || (typeof runSeq === 'number' && emittedSeqs.has(runSeq) && events[runSeq]?.type === 'command/run') - if (!runKept) droppedDones.add(event.seq) + const sourceSeq = data.sourceEventSeq + // The host contract: sourceEventSeq cites an earlier NON-command + // event, and the commands invariant rejects a stale or out-of-range + // citation. A done whose run or whose cited source falls in the + // dropped span drops ATOMICALLY with it. + const runKept = typeof id === 'string' && keptRunIds.has(id) + const sourceKept = typeof sourceSeq !== 'number' || emittedSeqs.has(sourceSeq) + if (!runKept || !sourceKept) droppedDones.add(event.seq) } } // Turn renumbering: the host's turn counter must run 1, 2, 3… over the @@ -843,10 +847,13 @@ function rebaseEvent( && firstKeptTurn !== undefined && sourceData.turn >= firstKeptTurn) { seed.data = { ...seed.data, turn: sourceData.turn - turnOffset } } - // A settled command cites the seq of the run it settled; remap it alongside. + // A settled command cites an earlier non-command event by seq; remap it + // alongside, and drop the done when the cited event did not survive — a + // stale citation is something the host's commands invariant rejects. if (event.type === 'command/done' && typeof sourceData.sourceEventSeq === 'number') { const mapped = rebase.get(sourceData.sourceEventSeq) - if (mapped !== undefined) seed.data = { ...seed.data, sourceEventSeq: mapped } + if (mapped === undefined) return DROPPED + seed.data = { ...seed.data, sourceEventSeq: mapped } } // Compaction metering records cite the surface span they priced. When the // span survived the rebase, remap the citations; when it did not (the diff --git a/tests/sidechat-compaction-seed.spec.ts b/tests/sidechat-compaction-seed.spec.ts index 0ef434a6..3e1fa8b5 100644 --- a/tests/sidechat-compaction-seed.spec.ts +++ b/tests/sidechat-compaction-seed.spec.ts @@ -735,14 +735,16 @@ describe('buildSidechatInheritance compaction tail', () => { expect(invariantFailures(seed)).toEqual([]) // Together: a command that runs INSIDE the keep window and settles - // there — both records ride, and the done cites the rebased run. + // there — both records ride, and the done's citation remaps onto the + // rebased event it names. The host contract: sourceEventSeq cites an + // earlier NON-command event, and commandIds are unique per run. const together = [ ...base, lo('turn/start', 8, { turn: 2 }), lo('step/start', 9, { turn: 2, step: 1 }), sf('user/message', 10, userMessage('m-q2', 'q2')), - lo('command/run', 11, { commandId: 'cmd1', name: 'compact', source: { kind: 'user' } }), - lo('command/done', 12, { commandId: 'cmd1', kind: 'success', text: 'ok', sourceEventSeq: 11 }), + lo('command/run', 11, { commandId: 'cmd2', name: 'compact', source: { kind: 'user' } }), + lo('command/done', 12, { commandId: 'cmd2', kind: 'success', text: 'ok', sourceEventSeq: 10 }), sf('assistant/message', 13, { turn: 2, step: 1, message: assistantMessage('a2'), stream: [] }), lo('step/end', 14, { turn: 2, step: 1 }), lo('turn/end', 15, { turn: 2, reason: { kind: 'completed' } }), @@ -751,10 +753,11 @@ describe('buildSidechatInheritance compaction tail', () => { together.push(...compactionGroup(together.length, [4, 5])) const trimmed = buildSidechatInheritance(together) expect(trimmed.seed.length).toBeLessThan(together.length) - const done = trimmed.seed.find(event => event.type === 'command/done') as { data?: { sourceEventSeq?: number }; seq?: number } - const runIdx = trimmed.seed.findIndex(event => event.type === 'command/run') - expect(runIdx).toBeGreaterThanOrEqual(0) - expect(done?.data?.sourceEventSeq).toBe(runIdx) + const done = trimmed.seed.find(event => event.type === 'command/done') as { data?: { sourceEventSeq?: number } } + const citedIdx = trimmed.seed.findIndex((event, index) => index === (done?.data?.sourceEventSeq ?? -1)) + expect(citedIdx).toBeGreaterThanOrEqual(0) + // The citation names a non-command event (the user message), not the run. + expect(trimmed.seed[citedIdx]?.type).toBe('user/message') expect(visibleSequence(trimmed.seed)).toEqual(visibleSequence(together)) expect(invariantFailures(trimmed.seed)).toEqual([]) }) From aacb2b247eeb689a80df1ffc11761e34b2628815 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Fri, 16 Oct 2026 21:17:13 +0800 Subject: [PATCH 12/12] =?UTF-8?q?docs:=20=E7=A7=BB=E9=99=A4=20sidechat=20c?= =?UTF-8?q?ompaction-tail=20seed=20=E8=AE=BE=E8=AE=A1=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...026-10-13-sidechat-compaction-tail-seed.md | 111 ------------------ 1 file changed, 111 deletions(-) delete mode 100644 docs/plans/2026-10-13-sidechat-compaction-tail-seed.md diff --git a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md b/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md deleted file mode 100644 index fc86b3de..00000000 --- a/docs/plans/2026-10-13-sidechat-compaction-tail-seed.md +++ /dev/null @@ -1,111 +0,0 @@ -# 侧边对话启动慢:种子改为从最后一次 compaction 切尾(可验证等价) - -> 2026-10-13 起,2026-10-15 五轮独立审查后为 v6 构造 · 配套变更:`src/sidechat-core.ts` `compactionTail` + `tests/sidechat-compaction-seed.spec.ts`(17 例) - -## 问题 - -`sidechat.start` 把父会话的**整份事件日志**复制进子会话当种子(`buildSidechatInheritance` → `copyEvents` 全量),且宿主 `agents.create({ seed })` 会把它**物理落盘**。在一个真实部署上(生产库只读实测): - -- 最大的侧边对话子会话 `seed_length = 32,674`,`events` 表物理 **32,675 行**——每个 fork 都复制了一遍父日志; -- 36 个播种会话合计复制 **303,018 行 / 276.5 MB(zstd 后)**,而全库 `events` 只有 292 万行、3.8 GB——fork 的写放大同时是**库膨胀**的主导项之一; -- 被频繁 fork 的主会话 35,992 事件且持续增长;宿主侧建会话成本与种子规模线性相关(`CREATE_TIMEOUT_MS = 15_000` 就是对它的防御)。 - -## 为什么「从 compaction 切」是安全的 - -DSH 的 compaction 机制(`dsh-compaction` / `compaction-basic`): - -- 四种 `compaction/*` 事件都是 **log-only**(不进模型可见面); -- 真正的 surface 替换者是紧跟 `compaction/summary` 之后那条 **checkpoint `user/message`**(携带 `surfaceOp: replace`,相邻性是 shadow-price 契约)——它把被压缩的旧段从**模型可见面**上换掉;受保护的 0 号节点(system 头)不被 region 覆盖; -- 被替换的旧事件只留在日志里供确定性回放,**模型从此看不到它们**。 - -因此判据是:**只要子会话折叠出的 surface 与父当前 surface 逐节点相同,模型请求与 provider 上下文缓存前缀就和全量 fork 完全一致**。最近的测量也支持收益:主会话最后一个 summary 在 seq 34,324 / 日志 35,992,切尾后事件量约 4–15× 下降(取决于 compaction 新鲜度)。 - -## 设计(v2:只丢「被遗忘区段」,其余逐字保留) - -`buildSidechatInheritance` 先尝试 `compactionTail(events)`,成功则以**重基后的日志**走原有逻辑(开轮闭合、dangling tool-call 快照全部原样复用),失败则回退今天的全量拷贝: - -``` -父日志: [turn1: sys头+旧内容(被shadow)][keep-window 轮…][compaction 组+checkpoint][尾部…] -重基后: [turn1 骨架: turn/start,step/start,sys头,step/end,turn/end] ← 头部骨架包裹(关闭,因为关闭件在被丢弃区段里) - [checkpoint(降级为 append,置于其 surface 表位——被遗忘区段的起点)] - [keep-window 起(含其 turn/start)…切点)逐字] ← 骨架自然保留 - [切点后 …] 逐字(剔除本组 compaction 三个 log-only 记录) -``` - -1. **切割点** = 最后一个「后随 user/message」的 `compaction/summary` 的下一条事件(孤立 summary 回扫到上一个完整的); -2. **头部** = 父最终 surface 上 checkpoint 表位之前的存活节点(通常就是受保护的 system 头),**包裹其所在 turn/step 骨架**:`turn/start + step/start + 节点 + step/end + turn/end`——关闭件从日志里取回,因为宿主会话关系不变量(`@deepseek-ai/dsh-session/invariant` 的 `requireOpenStep`)要求轮内事件必须点名一个打开的 turn/step,即便该轮其余内容已被压缩遗忘。头部跨多个 step/turn 的形状不构造(回退); -3. **keep-window 与尾部逐字保留**:`lastTurnBoundary`/`hasDanglingToolCall`/合成闭合器因此**在重基日志上照常工作**(自动 compaction 必发生在打开的轮内——`compaction-basic` 由 `agent/pre-step` 触发且 region 强制 enclosed-in-turn——开轮的骨架在切点之前,逐字保留意味着永远不丢); -4. **统一重基**:全部保留事件走同一个 `rebaseEvent`——seq 按位置重编号(seed 契约要求从 0 连续,宿主不重编号);**`data.turn` 重编号**(宿主 turn 计数器必须连续跑 1,2,3…,被丢弃区段留下的轮号空洞由 keep/尾部整体下移填补;`step` 按轮重置故逐字保留即可);`surfaceOp: replace` 范围、`sourceEventSeqs`、`developer/message.headerSeq`、以及 **`compaction/summary|prune` 记录的 `shadowedRange`/`shadowedSeqs`** 等**向后引用**能映射则平移;映射不到时 `headerSeq` 整体回退,而 compaction 计量记录**整条丢弃**(它计量的区段在子会话里不存在)。首个被保留的 `turn/start` 可能在 keep 区间**或**(pre-cut 存活者只有受保护头时)只在尾部,两段都要扫; -4b. **头部骨架归一**:存活头部(含被 mid-session 改写的受保护 system 头,任意原始 turn/step)一律归一为 **turn 1 step 1**——只改写事件里**已有**的数字信封字段(user/message 从不带、也绝不注入,它的整份 data 就是模型可见消息);关闭件从日志取回、同样归一; -4c. **replace 目标不跳过**:keep 区间里被 checkpoint shadow 的 surface 节点跳过,**但仍是某个存活替换事件之 replace 目标的节点不跳**(pruner 的 tool/result 改写正是此形)——否则替换会被迫降级为落在已闭合 step 之后的 append,违反关系规则; -5. **中段切点**(宿主 region 边界只受 tool-pairing 平衡约束、可止于轮中):keep 区间内**跳过被 checkpoint shadow 掉的 surface 事件**(同轮早期节点)与**孤儿 tool/call**(其 result 未存活),骨架照发——空 step 合法; -6. **自证**:用宿主公开导出的真折叠 `foldSurface`(`@deepseek-ai/dsh-session/surface`,浏览器安全子路径)分别折父日志与重基结果,**逐节点比对模型可见内容**——token 镜像宿主投影:`user/message` 比整份 `data`,其余比 `data.message`(信封 turn/step/headerSeq 天然不在其中;spec 的 oracle 也用宿主 `deriveEventMessage`,不与实现共用投影);再加四道**关系门**——`turnSequenceValid`(镜像宿主 invariant 的计数与配对核心:轮号连续、无嵌套开轮、step 序号连续且开合于所属轮、轮内消息与 `tool/call` 点名开轮/开步、非 append `tool/result` 豁免、pending call 须被消费、step 不得带 pending 关闭);`inboxSplicesValid`(镜像宿主持久 inbox 折叠:位置拼接、已知 target、重复 id 拒绝);`bracketsValid`(镜像宿主成组记录:成功 `compaction/end` 须有同 id 的 `compaction/summary`、`command/done` 须有先行的 `command/run`——四审证明「只丢计量记录」会拆散成组记录、宿主 companion 拒绝而三道自证全盲);可见序列等价。不等价、折叠抛错或任一门失败 → 回退全量。这是核心镜像而非宿主全契约——凡是门证明不了的,一律回退。 -6. **回退** = 现行全量拷贝,行为逐字不变(无 compaction 的会话永远走这条路;探针实测五种形状回退输出与改前逐字节一致)。 - -### 证明范围与披露 - -- 等价证明覆盖**可见节点内容序列**;`request/header`/`request/context` 等模型装配输入中 log-only 的部分,keep-window 与尾部内的会随逐字保留带过去,更老的随区段丢弃——实测(二审探针,6 组工具集变化组合):子会话首个请求经宿主 `projectToolUpdates` 投影后与全量 fork **完全一致**(子会话自建的 header 重置 declaration series),今天无可观测差异;此推理链无测试 pin,属已知边界。 -- **回退(安全、无收益)的已知形状**(四轮探针实测):**宽头**(受保护头之外还有存活 pre-cut 节点且含 tool/result——需经公开 `compactRegion` 任意区间接缝或第三方 backend 才可达,随包 backend 的 region 恒起于 surface index 0/1);**单轮父会话**(compaction 发生在唯一仍在打开的轮内、无 keep 区间);**cut 之后被改写的受保护头**(存活 node 0 是 post-cut 替换、pre-cut 扫描找不到头——四审实测六个最重会话三个命中,含 32675 事件的旧式 fork 子会话;生产主会话不受影响);父日志本身违反关系不变量(子会话回退后与 legacy 逐字节一致 = parity);审查者 p1-A 的多 step 中段复合形状。**已支持**(探针实证):中段切点(keep 首轮部分被 shadow,含跨多 step)、context-overflow(keep 只剩末节点)、**被改写的受保护头**(原始 turn/step 任意、cut 之前——归一后 trim 生效)、**pruner 替换在 keep 窗口**(replace 目标保留重放 + 非 append 豁免 + 计量记录引用重映射或丢弃)、**keep 窗口起点的 inbox insert 回吞**(真实 loop 顺序 `[insert][turn/start][claim]`——v4 e2e 在生产主会话上抓到并修复)、空 keep 区间、**级联 compaction(含同轮后组吞前组 checkpoint——成组原子丢弃)**、**引用失配的孤立 summary 与命令括号(v6 起原子丢弃,fuzz/probe 实证 invariant 全清)**、命令 run+done 同窗(`sourceEventSeq` 重映射)、**真实多组会话**(主会话 14 组 compaction:953 ms、seed 3,457、fuzz 129 trim/3000 全清)。keep 窗口内 `request/header` + `developer/message.headerSeq` 成功重映射由三轮审查者探针钉住(`probe-header-remap`:指向重基后 header、trim、invariant 0/0)。 -- 日志含 `image/offload` 等 **MESSAGE_PROJECTION 事件类型**时 `foldSurface`(无 projections)抛错 → 回退全量(安全,但含图长会话拿不到收益)。同理,未来插件自定义 projection 不在 core 集合内时证明会失真为「回退」而非「假通过」。 -- 孤立 compaction 组(summary 后替换未落地)的 log-only 记录随尾部保留(折叠不可见,保留宿主 metering 历史);构造时剔除的只有**本次消费的那一组**。 -- 第二个 system 头(checkpoint 表位之前的其他存活节点)实测受支持(二审探针 E:trim 生效、等价、validator 接受)。 - -## 明确不做 - -- 不做任意「最近 K 轮」截断——那会改变模型可见上下文与 provider 缓存前缀; -- 不做引用式继承(子会话直接引用父会话物理行)——需要动 dsh-session/session-persistence/format 的宿主变更,超出插件贡献面; -- 不加配置开关——回退路径本身就是安全阀;若上游评审要求可配置再加。 - -## 测试(`tests/sidechat-compaction-seed.spec.ts`,17 例) - -夹具为宿主真实形状:`system/message {turn, step, message}`(`source.kind: 'system-prompt'`)、`tool/result` 挂 `message`、assistant 消息带 `model` source;compaction 组含手动(`turn: null`)与自动(`turn: `)两种形态,且**开轮的 turn/start 与首条消息在切点之前**(二审 B1 的触发形状)。 - -1. 切尾发生:被 shadow 旧段(含 `tool/call`)整体消失,头部以闭合骨架 `[turn/start, step/start, system/message, step/end, turn/end]` 保留,keep-window 的 call→result 顺序保留,checkpoint 降级为 `append`、无残留引用,seq 从 0 连续; -2. **surface 等价**(核心不变量):`foldSurface(重基种子)` 可见序列 == 父日志可见序列; -3. **真实验证器 + 真实关系不变量**:`Session.create(isSeeded + inherited cut)` 接受;`@deepseek-ai/dsh-session/invariant` 对父日志、切尾种子、全量对照全部零失败; -4. 无 compaction → 全量逐字拷贝(回归守卫); -5. 回退(尾部 `developer/message` 引用被丢弃区段)→ 与改前行为**逐事件相同**(类型序列全等断言,非仅文本查找); -6. 回退(尾部 replace 覆盖存活的前切点节点)→ 同上; -7. **轮内 compaction + 开轮普通消息** → trim 照常发生 + 合成 `step/end`/`turn/end{interrupted}` 闭合器照常落盘 + 不变量零失败; -8. **轮内 compaction + 悬空 tool call** → trim 照常发生 + 截在开轮前 + 结构化快照照常交付(providers 拒绝悬空 assistant 调用的保护不因切尾失效); -9. **重映射**:尾部 replace 范围完全在尾内 → 保留为重基后的 replace(非降级),trim 必须发生、等价必须成立; -10. **孤立 summary 回扫**:最新 compaction 的替换未落地 → 沿用上一个完整 compaction(trim 仍生效),死组的 log-only 记录随尾部保留; -11. **中段 keep-window**:region 止于 keep 首轮之内 → 被 shadow 的同轮早期节点与孤儿 tool/call 被跳过、骨架完整、等价成立、invariant 零失败; -12. **改写头**(turn 1 后续 step 的 SystemPromptProjection.replace 形状)→ 归一为 turn 1 step 1 后 trim 照常、原 prompt 消失、等价、invariant 零失败; -13. **pruner 改写 keep 窗口结果**(两 step 之间的替换、携带原始 turn/step)→ replace 目标保留重放、替换 op 重映射、prune 记录引用重映射、等价、invariant 零失败; -14. **keep 窗口起点的 inbox 括号**(`[insert][turn/start][claim]` 真实 loop 顺序)→ insert 回吞、位置折叠可重放(真投影由树外探针与 e2e 覆盖); -15. **同轮双成功 compaction、后组吞前组 checkpoint** → bracket 门回退(对照:去掉被消费组后 cp0 独立成切点、照常 trim); -16. **命令括号**:run 落被遗忘区段、done 存活 → 回退;run+done 同在 keep 窗口 → trim 且 `sourceEventSeq` 指向重基后的 run; -17. 真实验证器验收(`Session.create` + end-seed 标记落为子会话第一个 own event,与全量线程同形)。 - -夹具使用**真实轮距**(受保护头 turn 1 + 被 shadow 的整轮 + keep 轮 3 起)——二审证明「keep 恰为 turn 2」的唯一连续夹具会让 invariant 用例假绿。 - -判别性(全部实测过红): -- 去掉「头部骨架包裹」→ 例 1 / 例 3 当场红(后者由 invariant 拒绝); -- 毁掉尾部 replace 重映射/降级分支 → 例 9 当场红; -- 孤儿 summary 不回扫 → 例 10 当场红; -- 关闭 turn 重编号 → 例 3(真实轮距 invariant)当场红; -- 三审变异复验:关 turnOffset 5/12 红、去骨架包裹 6/12 红(含点名用例); -- 四审变异复验(树外隔离副本):抽 `replaceCovered.add` → 恰 pruner 用例红;去头部 step 归一 → 恰改写头用例红。 -**披露**:`sameVisibleSequence` 终验单独变异不可由行为测试变红(它是纵深防御,只有与构造缺陷叠加才可观察——二审的 B1 修复前正是「构造缺陷 + 守卫被绕过」的叠加形态,例 7/8 就是为此而设)。 - -## 独立审查记录(两轮,双 corpus 投票) - -一审(2026-10-15,Standards + Spec 双轴,独立 subagent):两票均 **CHANGES_REQUIRED**,blocking 收敛于同一根因——v1 构造只保留 surface 节点,把前切点的 turn/step 骨架丢掉:(a) 自动 compaction 必在打开的轮内,开轮的 `turn/start` 被丢后 `lastTurnBoundary` 返回 -1,悬空 tool-call 守卫与合成闭合器被静默绕过;(b) 违反宿主 `requireOpenStep` 关系不变量。→ v2:只丢被遗忘区段,头部骨架包裹,keep/尾部逐字。 - -二审(同日,两位全新 fresh reviewer):两票再次 **CHANGES_REQUIRED**,独立收敛于新 blocking——**turn 编号断档**(v2 头部骨架收口后计数器期望 turn 2,keep 窗口逐字保留原始 `turn/start{N}`;两道自证 foldSurface/Session.create 都抓不到,真实 harness 在 `sessions.create` 抛 `InvariantError`);另指出中段切点(region 边界仅 tool-pairing 平衡)会静默回退。→ v3:turn 重编号(keep ∪ 尾双段扫描首个保留轮)、中段 keep-window 跳过被 shadow 节点与孤儿 call、运行时 `turnSequenceValid` 关系门、夹具换真实轮距。 - -三审(同日,两位全新 fresh reviewer):两票 **CHANGES_REQUIRED**——(a) 头部骨架 step 号未归一(受保护头被改写到 turn 1 step ≥2 时产出宿主 invariant 拒绝的种子);(b) 宽头存活 `tool/result` 丢配对 `tool/call`;(c) keep/尾保留的 compaction 计量记录 `shadowedRange/shadowedSeqs` 未重映射(违反 dsh-compaction invariant);(d) 关系门对**非 append** `tool/result` 过严(pruner 替换会让 trim 无谓回退);(e) lint 死赋值。→ v4:头部归一 turn 1 step 1(只改写已有数字信封字段——期间发现并修复了「向 user/message 注入 turn/step」的真等价破坏,token 改为镜像宿主投影:user=整份 data、其余=data.message)、关系门补 nextStep/pendingCalls/嵌套开轮/非 append 豁免、compaction 记录引用重映射或整条丢弃、**replace 目标节点不跳过**(pruner 形状由此从回退转为生效)。 - -五审(delta 终验 + 真实数据复测,对象 cc11ce4 并对工作树并发改动钉版复核):抓到 v5 两处回归并当场修复。(a) bracket 门在真实多组会话上**全量回退**——e2e 实测主会话 seed=35,993、9,077 ms(全量拷贝旧路径);根因是真实多组会话的 mid-keep 组 summary 引用全指向被后续组 re-shadow 的节点,记录级丢弃拆散成组记录。→ 修法取审查者给的第二选项并经数据背书:**成组原子丢弃**(发射前定 emittedSeqs,引用失配的 compaction 组 start/summary/end 整组丢、失 run 的 command/done 单独丢);fuzz 3000 例 trim 108→129 全过真 session+compaction+commands invariant 与真 inbox 折叠、0 命中,四审级联反例 pG 从回退翻转为干净 trim。(b) v5 把缺失 `removedCount` 当非法——宿主契约它**可选、缺省 0**(宿主写入方对纯插入省略它;生产库 54% splice 如此;89 个真实 compaction 会话 38 个因此回退,含主会话)→ 还原 `?? 0`。五审实证 v5 在 89 个真实会话 trim 41→3 的覆盖率崩塌即此二回归合成。用例 15 夹具按宿主链式 replace 语义重写(吞**当时** surface span),从空测(夹具本身折不动、断言恒真)翻转为真钉子。终版 e2e(ad42628):**953 ms / seed 3,457(10.4×)**、冷上下文回答再命中 exp5 收尾细节(fsr-ge7-top5-5e5-allfix、1.02×→1.18× 分叉消失、2900x 收尾三件事)。五审终稿另定级 F2(blocking,两审一致):`command/done.sourceEventSeq` 映射不到时留父 seq——宿主契约它指向**更早的非命令事件**(commands invariant 拒陈旧引用),且真实数据 40 个 trim 中 3 个命中 → 修复:done 引用的数值 sourceSeq 落在被遗忘区段时**随 run 一起原子丢弃**(运行时兜底同样 DROPPED),`pM` 探针由「trim + 违反 commands invariant」翻转为「trim + 无陈旧引用」;用例 16 后半夹具按契约重写(唯一 commandId、sourceEventSeq 指向 user 消息)。变异 M6(去掉 droppedGroups 过滤)→ 用例 15 当场红,证明原子丢弃链与 bracket 门在仓内套件有钉子。 - -四审(同日,两位全新 fresh reviewer,对象 657dcd5 → tip 196fa11 两版钉证):核心等价性**未能证伪**(2100 生成形状、113 次 trim 全过真 session invariant + 真 Session.create + 真持久 inbox 投影 + 真 `deriveEventMessage` wire 比对;非 trim 全与 legacy 逐字节一致),但两票各在同一根因上给 blocking——**宿主「成组记录」被只丢计量记录拆散**:(a) 成功 `compaction/end` 失去同组 `compaction/summary`(同轮双 compaction 形状,随机实测命中 trim 的 18.6%,真 dsh-compaction invariant 拒绝而三道自证全盲);(b) 657dcd5 的 keep 窗口丢掉紧邻 turn/start 前的 inbox INSERT、保留其后的 CLAIM(真实持久 inbox 投影拒绝——**v4 e2e 在生产主会话上当场抓到**:`thread creation failed: invalid persisted inbox splice at session seq 7`)。→ v5:keepStart 回吞前置 splice + `inboxSplicesValid` 门(e2e 复测:**799 ms**、seed 3,457 = 35,992 的 **10.4×**、冷上下文回答再命中压缩摘要细节);`bracketsValid` 门(成组记录原子性:compaction bracket + command 配对);`command/done.sourceEventSeq` 重映射;spec oracle 换宿主 `deriveEventMessage`;补同轮双 compaction 与命令括号两用例(17 例)。Standards 另修:`expectedFirstKeptTurn` 按骨架实际 turn/start 判定(N2)、`inboxSplicesValid` 收紧到宿主严格度(N4)、post-cut 改写头回退形状入披露(S3,六会话三命中)。四轮审查者的全部树外证据脚本在 v5 上全部转绿或按设计安全回退。 - -## 部署验证(已执行,2026-10-15) - -第二实例(3097 端口、独立 `DSH_HOME`、生产库 `sqlite3 .backup` 在线快照、生产 PID 全程 669050 未动;凭据 `.credentials.yaml` 复制后重启): - -- 对真实主会话(35,992 事件、14 次 summary compaction)`POST /sidebar/api/sidechat.start` → **701 ms** 返回; -- 子会话 `seed_length = 2,641`、物理 2,643 行——**13.6×**(旧式同父 fork 为 32,674); -- 请求装配(`system/message`、user 消息、`request/header`、`request/context`)全通过真实管线; -- 重启 staging 后**冷恢复**该切尾子会话并提问,模型凭被压缩的旧历史(只存在于 checkpoint 摘要中)给出准确回答(Mint vs Tinker loss 分歧、GLM-5.3 304B LoRA SFT、Megatron-LM #43 等细节)——上下文等价的行为级证明。