深入理解 dsh/第 03 章
seq 就是数组下标,永不重编号
append-only 日志的第一条铁律,dsh 用一行代码就实现了:
const dataSnapshot = snapshotJsonValue(data) if (dataSnapshot === undefined) { throw new Error(`session event "${type}" carries non-JSON-serializable data`) } const event = deepFreeze({ type, seq: SessionSeq(this.log.length), // ← 就是这个 time: Date.now(), data: dataSnapshot, } as unknown as SessionEvent<T>) validateSessionEventData(event, `session event "${type}" at seq ${event.seq}`) this.commit(event as SessionEvent, entry) return event
seq = log.length:序号不是计数器,是下标。这三行推论一路贯穿到压缩(第 4 章):
| 推论 | 代码 | 意义 |
|---|---|---|
| 取事件 = 数组下标访问 | this.log[seq]! |
O(1),不需要 Map 索引 |
| 连续性可校验 | event.seq !== expectedSeq → 抛错 |
日志缺一条立刻发现 |
| 序号永不复用 | 只 push,不 splice | 任何 seq 永久指向同一事件 |
this.log[seq]! 那行注释写得很诚实:
this.log 构造——按构造法 seq 永远是合法下标。那个非空断言就是在表达这条不变式。index.ts:817-835(append 分配 seq)· :1009-1010(seq 即下标)
surface 只是一串指向日志的下标
模型看到的「对话历史」不是日志本身,而是日志的一个视图。这个视图的数据结构简单到只有三个字段:
export interface SessionSurface { /** Current surface event sequences in model-visible order. */ readonly nodes: readonly SessionSeq[] /** Monotonic count of committed positional replacements. */ readonly replaceGeneration: number /** Monotonic count of committed replacements and plugin-owned message changes. */ readonly contentGeneration: number }
nodes 是一串 seq,顺序即模型可见顺序。它不存消息内容,内容永远回日志里取。
所以「改历史」不是改消息,而是改这串下标。
| 操作 | 对 nodes 做什么 | 代际变化 |
|---|---|---|
append | nodes.push(seq) | 无 |
replace | nodes.splice(startIdx, count, newSeq) | replaceGeneration++ 且 contentGeneration++ |
project | 不动 nodes,改派生的消息副本 | 仅 contentGeneration++ |
if (plan?.kind === 'append') { state.nodes.push(plan.seq) } else if (plan?.kind === 'replace') { state.nodes.splice(plan.startIdx, plan.endIdx - plan.startIdx + 1, plan.seq) state.replaceGeneration += 1 state.contentGeneration += 1 } else if (plan?.kind === 'project') { for (const [seq, message] of plan.messages) state.projectedMessages.set(seq, message) state.projections.add(plan.projection) state.contentGeneration += 1 }
surface.ts:244-252(SessionSurface)· :567-577(三种折叠)
为什么需要两个代际
这是本章最精妙的一处。replaceGeneration 和 contentGeneration 几乎总是同步增长,
但有一个操作只动后者:project。
| 问题 | 该问哪个代际 | 为什么 |
|---|---|---|
| 「历史被裁剪过吗?」 | replaceGeneration |
压缩改变了范围,token 账要重算 |
| 「派生消息还能用吗?」 | contentGeneration |
只要内容变了缓存就失效,不管变的是范围还是内容 |
所以 deriveMessages() 的缓存看的是 contentGeneration——
它不关心「为什么变」,只关心「变没变」:
deriveMessages(): Message[] {
const surface = this.surface
const nodes = surface.nodes
const generation = surface.contentGeneration
if (generation !== this.derivedGeneration) {
this.derived = [] // 代际变了 → 整体重建
this.derivedNodes = 0
this.derivedGeneration = generation
}
for (const seq of nodes.slice(this.derivedNodes)) { // 否则只追加尾部
const msg = this.deriveEventMessage(this.log[seq]!)
if (msg) this.derived.push(msg)
}
this.derivedNodes = nodes.length
return [...this.derived]
}
两种路径,代价完全不同:
append 之后nodes.slice(derivedNodes) 只处理新增的尾部。
每次追加是 O(新增条数),不是 O(历史长度)。这是长会话能跑下去的物理原因。
replace / project 之后derived = []、derivedNodes = 0,整个历史重新派生一遍。
压缩一次的代价是 O(整段历史),但因为压缩本来就少,这个交换是划算的。
replace 是把一段节点换成一个新节点,中间那些消息派生结果要一起丢。
增量修补需要精确知道「哪几条受影响」——而那正是 surface 已经知道的事,重算一遍更简单且不会错。
[...this.derived] 而不是 this.derived:内部缓存数组不能交给外面,
否则调用方 push 一下就污染了缓存。消息对象本身是冻结共享的(策略是「不可变数据共享、容器复制」),
所以复制数组几乎不花钱。
index.ts:999-1019(deriveMessages 缓存)
replace 的边缘是「位置」,不是「序号大小」
这一节解释第 4 章那句让人困惑的话:「start 和 end 按 surface 位置命名,而不是数值 seq 顺序」。
原因就在这里——indexOf:
const startIdx = state.nodes.indexOf(op.startSeq) if (startIdx === -1) { // 不在 surface 上 → 抛错 } const endIdx = state.nodes.indexOf(op.endSeq)
关键:边缘是通过在节点数组里「找位置」确定的,不是比较数字。
于是 splice(startIdx, endIdx - startIdx + 1, newSeq) 天然就是「按可见顺序切一段」。
| 情形 | nodes | 结果 |
|---|---|---|
| 纯 append | [0,1,2,3,4] |
seq 单调递增,位置 = 序号大小 |
| 压缩掉 [1,2,3] | [0,9,4] |
非单调:9 在 4 前面 |
此时 indexOf(4) |
— | 返回 2,而 4 > 9 也成立——数字大小完全失去意义 |
所以任何「从 seq A 到 seq B」的逻辑都不能写成 for (let s = A; s <= B; s++)。
这个坑不是理论上的——第 4 章的 compactRegion 文档特意写了这句话警告调用方。
surface.ts:418-430(indexOf 定位)· compaction:170-171(非单调警告)
replace 的四条校验
「能改历史」是危险能力。dsh 用四条校验把它的边界钉死,全部在追加之前完成:
| 校验 | 规则 | 防什么 |
|---|---|---|
| 引用必须更早 | sourceEventSeqs 里每个 seq 都 < event.seq |
不许引用未来事件(否则日志不可重放) |
| 不许重复 | duplicates → 抛错 |
同一事件不能被同一替换引用两次 |
| 必须覆盖全部被遮蔽节点 | missing → 抛错(列出缺哪些) |
不能「悄悄」删掉一个节点而不声明它被谁替代 |
| system prompt 特殊 | node 0 只能被 system/message 且长度恰为 1 的替换改写 |
系统提示不能被压缩顺手吃掉 |
if (sources.size !== raw.length) { throw new Error('sourceEventSeqs must not contain duplicates') } if (nonEarlierSource !== undefined) { throw new Error(`sourceEventSeqs must reference earlier events: ${nonEarlierSource} >= current seq ${event.seq}`) } const missing = shadowedSeqs.filter(seq => !sources.has(seq)) if (missing.length > 0) { throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${missing.join(', ')}`) }
sourceEventSeqs 里出现——于是任何一段历史的消失,都能被追溯到是谁替代了它。
这是 recovery.html 里那种「删了但没人知道」问题在数据结构层的答案。
surface.ts:355-364(四条校验)· :492-506(system head 特例)
这套设计的账单
公平地说代价。dsh 没有选 pi 那种「树 + 父指针 + 分支」,而选了「单链 + replace」, 换来了能力,也换了复杂度:
| 得到 | 付出 | 具体账单 |
|---|---|---|
| 改历史的唯一入口 | 每个消费者都要考虑非单调 | 「A 到 B 之间」必须按位置查,不能按数值遍历 |
| 缓存命中率高 | 两个代际要分清 | 用错代际 → 要么缓存过期不失效,要么白重建 |
| 日志永不可变 | 派生逻辑成了一条第四种路径 | append / replace / project / 投影未加载 → 四种分支(见下) |
seq 恒定可寻址 |
日志只增不减 | 磁盘增长靠上层切分,不靠日志自己回收 |
「第四种路径」指的是 planSurfaceEvent 里那个容易漏的分支——
日志里出现了当前没加载插件的消息类型时,直接抛错而不是静默跳过:
一句话总结第 3 章:dsh 的「历史」有两种形态——永不改的日志(按 seq 寻址)和可改的视图(按位置寻址); 两个代际就是这两者之间的汇率。
surface.ts:529-531(缺投影即抛错)