fix(sidechat): keep turn/step skeletons in the compaction-tail seed (review round 1)

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.
This commit is contained in:
NolanHo authored and Atlas Zeng committed 2026-10-16 16:14:41 +08:00
1 parent b025331b99
commit 90d04f7aa0
3 files changed
+536 -275

No files matched your search

@@ -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: <open 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 等细节)——上下文等价的行为级证明。
+181 -95
View File
@@ -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<typeof foldSurface>[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<number, number>()
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<number, number>): SeedEvent | undefined {
function rebaseEvent(event: SidechatLogEvent, seq: number, rebase: Map<number, number>): 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<numbe
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.
// dropped span; appending the replacement is exactly what remains
// visible (the equivalence check still has to confirm it).
seed.surfaceOp = start !== undefined && end !== undefined && start <= end
? { op: 'replace', startSeq: start, endSeq: end }
: 'append'
@@ -470,7 +556,7 @@ function rebaseTailEvent(event: SidechatLogEvent, seq: number, rebase: Map<numbe
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
// 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[]
}
+302 -153
View File
@@ -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<string, unknown> {
return { id, role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } }
}
function assistantMessage(text: string): Record<string, unknown> {
function assistantMessage(text: string, over: { callId?: string } = {}): Record<string, unknown> {
const content: Array<Record<string, unknown>> = [{ 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<string, unknown
}
}
/** One completed turn with an optional tool pair; returns its events plus the
* seqs of its surface-visible nodes (user, result, assistant). */
/** 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 } = {},
over: { text?: string; callId?: string; result?: string; assistantCall?: string } = {},
): { events: SidebarSessionEvent[]; nodes: number[] } {
const text = over.text ?? `q${turnNumber}`
const events: SidebarSessionEvent[] = [
@@ -74,65 +80,134 @@ function turn(
nodes.push(next + 1)
next += 2
}
events.push(sf('assistant/message', next, { turn: turnNumber, step: 1, message: assistantMessage(`a${turnNumber}`), stream: [] }))
events.push(sf('assistant/message', next, {
turn: turnNumber,
step: 1,
message: assistantMessage(`a${turnNumber}`, over.assistantCall !== undefined ? { callId: over.assistantCall } : {}),
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 compaction group appended at `at`: start + summary + checkpoint +
* end, shadowing `shadowed` (the span's surface-node seqs). `turn: null`
* is the manual between-turns form; a number is the automatic mid-turn
* form, and the checkpoint adjacency is the shadow-price contract. */
function compactionGroup(
at: number,
shadowed: readonly number[],
over: { id?: string; turn?: number | null; summary?: string } = {},
): SidebarSessionEvent[] {
const id = over.id ?? 'cp1'
const first = shadowed[0] ?? 0
const last = shadowed[shadowed.length - 1] ?? 0
const summaryText = over.summary ?? 'old turns summarized'
const turnValue = over.turn === undefined ? null : over.turn
return [
lo('compaction/start', at, { compactionId: id, turn: turnValue }),
lo('compaction/summary', at + 1, {
compactionId: id,
summary: [{ type: 'text', text: summaryText }],
shadowedRange: { start: first, end: last },
shadowedSeqs: [...shadowed],
shadowedTokenCount: 100,
provider: 'deepseek',
model: 'test-model',
rawOutput: [],
llmStreamCall: true,
}),
{
type: 'user/message',
seq: at + 2,
time: (at + 2) * 1000,
data: {
id: `m-${id}`,
role: 'user',
content: [{ type: 'text', text: summaryText }],
source: { kind: 'compact-checkpoint', compactionId: id },
},
surfaceOp: { op: 'replace', startSeq: first, endSeq: last },
sourceEventSeqs: [...shadowed],
} as SidebarSessionEvent,
lo('compaction/end', at + 3, { compactionId: id, turn: turnValue }),
]
}
/**
* 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.
* Turn 1's opening, host-shaped: the protected `system/message` (carrying
* its turn/step) is the first request's first message, and the shadowable
* old span continues in the SAME step — `oldTurn` supplies the rest.
*/
function compactedLog(): CompactedLog {
const events: SidebarSessionEvent[] = [
sf('system/message', 0, { message: { id: 'm-sys', role: 'system', content: [{ type: 'text', text: 'system prompt' }], source: { kind: 'system-prompt' } } }),
function systemHead(): SidebarSessionEvent[] {
return [
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' } },
}),
]
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' })
}
/** The old span continuing turn 1's step: a tool pair + assistant, closed. */
function oldSpan(): { events: SidebarSessionEvent[]; nodes: number[] } {
const events: SidebarSessionEvent[] = [
sf('user/message', 3, userMessage('m-q1', 'q1')),
lo('tool/call', 4, { turn: 1, step: 1, callId: 'c-old', name: 'bash', arguments: '{}' }),
sf('tool/result', 5, { turn: 1, step: 1, message: toolResultMessage('c-old', 'old result') }),
sf('assistant/message', 6, { turn: 1, step: 1, message: assistantMessage('a1'), stream: [] }),
lo('step/end', 7, { turn: 1, step: 1 }),
lo('turn/end', 8, { turn: 1, reason: { kind: 'completed' } }),
]
return { events, nodes: [3, 5, 6] }
}
/**
* The canonical compacted parent, host-shaped: turn 1 carries the protected
* system head, turn 2 is the shadowed old span (with a tool pair), turn 3
* is the keep window with its own tool pair, then the manual compaction
* group, then one closed tail turn.
*/
function compactedLog(): SidebarSessionEvent[] {
const events = [...systemHead(), ...oldSpan().events]
const keep = turn(9, 2, { 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)
return events
}
/**
* The automatic-compaction shape: the group fires INSIDE a still-open turn
* (that turn's skeleton and first message sit BEFORE the cut), and the log
* ends inside that turn — `kind` picks how: a plain pending assistant
* message (synthetic closers) or a dangling tool call (structured
* snapshot).
*/
function midTurnLog(kind: 'closers' | 'dangling'): SidebarSessionEvent[] {
const events = [...systemHead(), ...oldSpan().events]
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, {
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 }
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')),
)
events.push(...compactionGroup(seq + 3, [3, 5, 6], { id: 'cp-auto', turn: 2, 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: [] }))
} 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: '{}' }),
)
}
return events
}
/** The model-visible sequence a fold produces: one `type:data` token per node. */
@@ -148,32 +223,55 @@ function expectContiguous(seed: readonly { seq: number }[]): void {
seed.forEach((event, index) => 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)
})
})