@240xu/dsh-message-ops 0.48.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  computeShadowed,
20
20
  messageText,
21
21
  messageTextFull,
22
+ collapsedSnippet,
22
23
  turnBounds,
23
24
  markCommitted,
24
25
  readReplaceOp,
@@ -54,7 +55,7 @@ import {
54
55
  webAuthGate,
55
56
  } from './ops-core.js'
56
57
  import { captureServices, serviceOf, resetCapturedServicesForTests } from './host-services.js'
57
- import { applyDerivedBatch, derivedTextsOf, primeDerivedIncremental, NotIncrementalError } from './derived-incremental.js'
58
+ import { applyDerivedBatch, derivedTextsOf, NotIncrementalError } from './derived-incremental.js'
58
59
  import { withSessionLock, withWriteLock } from './write-lock.js'
59
60
  import { deleteSessionToTrash, listTrash, restoreTrash, purgeTrash, resolveSessionTitle } from './session-trash.js'
60
61
 
@@ -876,8 +877,96 @@ function withResolveDiag(err, diag) {
876
877
  // 缓存对象本身永不被改写 —— 跨请求零串扰。
877
878
  // 0.33.4(perf-audit #6):16 → 48。顺序浏览 20 个会话时 16 会 0% 命中
878
879
  // (每次 miss 都把自己下次要用的条目挤出去),48 覆盖一次翻页。
880
+ //
881
+ // 0.49.0(内存):条目数上限之外再加**估算字节上限**。0.48.x 的 LRU 只按条数
882
+ // 淘汰 —— 48 条大会话全部驻留没有上界:28.2MB 日志的派生实测常驻 13.8MB(本版
883
+ // 修掉 snippet 的 cons 链后;修前 39.3MB),48 条就是 0.66~1.9GB 堆。字节上限
884
+ // 让「最近 N 条小会话 + 最近一条大会话」自然成立:小会话按条数上限走,大会话
885
+ // 按字节预算淘汰最久未用的条目。淘汰只影响下次是否重算(冷读),**不改变任何
886
+ // 对外结果**,因此不涉及语义;条目超预算时至少保留最近一条,避免单条大会话
887
+ // 每次请求都重读。
879
888
  const DERIVED_CACHE_MAX = 48
889
+ const DERIVED_CACHE_MAX_BYTES = 96 * 1024 * 1024
880
890
  const derivedCache = new Map() // logPath -> { mtimeMs, size, promise }
891
+ /** derived 对象 → 估算驻留字节(与 derived 同生共死,不进 derived 字段)。 */
892
+ const derivedBytes = new WeakMap()
893
+ /**
894
+ * derived 对象 → 搜索语料估算字节(`/search` 首次访问时才建,见 searchCorpusOf)。
895
+ * 语料里的 `lower`(小写副本)是**额外**驻留的字符量,必须计入同一份缓存预算:
896
+ * 否则 48 条大会话各搜一次就是「派生 14MB + 语料 10MB」× N,字节上限形同虚设。
897
+ */
898
+ const derivedCorpusBytes = new WeakMap()
899
+
900
+ /** 缓存条目当前计入预算的估算字节(派生 + 搜索语料)。 */
901
+ function entryBytesOf(entry) {
902
+ if (!entry || !entry.value) return 0
903
+ return (derivedBytes.get(entry.value) || 0) + (derivedCorpusBytes.get(entry.value) || 0)
904
+ }
905
+
906
+ /**
907
+ * derived 对象 → 估算驻留字节(**仅用于缓存淘汰,不进 derived 字段**)。
908
+ *
909
+ * 口径:字符串按 UTF-16 上限 2 字节/字符 + 固定开销估(V8 对纯拉丁文本实际
910
+ * 1 字节/字符,故这是上界);行对象按 160 字节、文本索引条目按 48 字节、遮蔽
911
+ * 集合/回合表按 16/64 字节计。实测 28.2MB 日志(7572 行 / 950 万字符全文索引)
912
+ * 的派生对象估算 24.2MB、`--expose-gc` 实测常驻 13.8MB —— 上界约 1.75 倍,
913
+ * 对「防失控」这个用途足够保守,又不会把中等会话过早淘汰。
914
+ * 只在缓存插入 / 写后增量接管时算一次(7572 行约 0.5ms),命中路径零成本。
915
+ * @param {object} derived deriveFromEvents 的返回值
916
+ * @param {Map<number,string>|undefined} texts 消息全文索引
917
+ * @returns {number} 估算字节
918
+ */
919
+ function estimateDerivedBytes(derived, texts) {
920
+ let bytes = 256 // 对象壳 / header / turnEndSeq 对象
921
+ const messages = Array.isArray(derived && derived.messages) ? derived.messages : []
922
+ for (const row of messages) {
923
+ bytes += 160
924
+ for (const key of ['type', 'role', 'id', 'snippet', 'fullText', 'sourceKind']) {
925
+ const value = row && row[key]
926
+ if (typeof value === 'string') bytes += 16 + value.length * 2
927
+ }
928
+ if (row && row.range) bytes += 64
929
+ if (row && Array.isArray(row.pendingTurns)) bytes += 48 * row.pendingTurns.length
930
+ }
931
+ if (texts instanceof Map) {
932
+ for (const text of texts.values()) {
933
+ bytes += 48
934
+ if (typeof text === 'string') bytes += text.length * 2
935
+ }
936
+ }
937
+ const shadowed = derived && derived.shadowed
938
+ if (shadowed && typeof shadowed.size === 'number') bytes += shadowed.size * 16
939
+ const turns = derived && derived.turnEndSeq
940
+ if (turns && typeof turns === 'object') bytes += Object.keys(turns).length * 64
941
+ return bytes
942
+ }
943
+
944
+ /**
945
+ * 淘汰派生缓存直到同时满足条数与字节上限;`pinKey` 对应的条目永不淘汰。
946
+ *
947
+ * 至少保留一条(即使它自己就超字节预算):否则单个超大会话会在每次请求时
948
+ * 被删掉重算,把「内存上限」变成「永久冷读」。
949
+ * @param {string} [pinKey] 刚插入/刚命中的 logPath
950
+ * @returns {void}
951
+ */
952
+ function trimDerivedCache(pinKey) {
953
+ let bytes = 0
954
+ for (const entry of derivedCache.values()) {
955
+ bytes += entryBytesOf(entry)
956
+ }
957
+ while ((derivedCache.size > DERIVED_CACHE_MAX || bytes > DERIVED_CACHE_MAX_BYTES) && derivedCache.size > 1) {
958
+ let victim = null
959
+ for (const entry of derivedCache.entries()) {
960
+ if (entry[0] === pinKey) continue
961
+ victim = entry
962
+ break
963
+ }
964
+ if (!victim) break
965
+ derivedCache.delete(victim[0])
966
+ bytes -= entryBytesOf(victim[1])
967
+ }
968
+ }
969
+
881
970
 
882
971
  /**
883
972
  * derived 对象 → 消息全文索引(seq → messageTextFull)。
@@ -910,9 +999,14 @@ async function buildDerived(logPath) {
910
999
  const derived = deriveFromEvents(header, events)
911
1000
  derived.frameCount = frameCount
912
1001
  derived.partial = partial
913
- // 0.44.0(D6):把增量状态的建表(20k 事件约 32ms)摊进这次本来就要 19.5s 的读盘,
914
- // 之后写后 apply 是稳态 ~1.5ms;失败返回 false 不影响读路径。
915
- primeDerivedIncremental(derived, events)
1002
+ // 0.49.0(内存/重复计算):**不再在这里预建增量状态**。预建要对全部 events 再跑
1003
+ // buildRestoreIndex + computeShadowed + turnBounds + 一次全量扫描(20k 事件实测
1004
+ // 45ms,且 100k 事件按 O(n) 涨),而它只服务于「本次读盘之后、本插件又写了一次」
1005
+ // 这一条路径 —— 写路径反向读盘时手里本来就有 events(runDiskWrite 的 read.events),
1006
+ // 首次 applyDerivedBatch 会就地建状态(见 adoptIncrementalCache 的 ctx.events)。
1007
+ // 也就是说预建只把 45ms 从「罕见的写后路径」搬到「每次冷读」,冷读是用户可见的
1008
+ // 热点,写路径本来就要全量读盘,45ms 在 19.5s 量级的读盘里不可见。
1009
+ // 失败语义不变:buildState 校验不通过仍抛 NotIncrementalError → 下一次 GET 全量重建。
916
1010
  return derived
917
1011
  }
918
1012
 
@@ -937,7 +1031,9 @@ function deriveFromEvents(header, events) {
937
1031
  const seqText = messages.some(m => m.marker === true) ? new Map() : null
938
1032
  const restoreIndex = seqText ? buildRestoreIndex(events) : null
939
1033
  // 0.27.0:一次折叠算出「已被后续回撤取代」的 marker(与 planRestore 的 409 闸同源)。
940
- const superseded = seqText ? supersededMarkers(events) : null
1034
+ // 0.49.0:复用 buildRestoreIndex 里已折好的 surface 节点表 —— 旧实现这里又
1035
+ // foldSurfaceNodes 全量扫一遍(20k 事件实测 +9.8ms,100k 合成事件 +74ms)。
1036
+ const superseded = seqText ? supersededMarkers(events, restoreIndex && restoreIndex.fold) : null
941
1037
  for (const e of seqText ? events : []) {
942
1038
  if (!e || typeof e.seq !== 'number') continue
943
1039
  if (e.type !== 'user/message' && e.type !== 'assistant/message') continue
@@ -948,8 +1044,13 @@ function deriveFromEvents(header, events) {
948
1044
  // (这条困惑正是 0.10.1 修 commit 生命周期的起因)。
949
1045
  // `sourceKind === 'user'` 是一等字段,只放真实用户输入;assistant 全放(模型输出非注入)。
950
1046
  if (e.type === 'user/message' && ((e.data || {}).source || {}).kind !== 'user') continue
1047
+ // 0.49.0(重复计算):预览只需前 80 字符,旧实现对每条消息的**全文**跑
1048
+ // `trim().replace(/\s+/g,' ')` —— 28MB 夹具实测 171ms,且随文本长度线性涨。
1049
+ // collapsedSnippet 与 `replace(/\s+/g,' ').trim().slice(0,80)` 逐字符等价
1050
+ //(test/snippet-collapse.test.js 用旧实现做过 12000 组随机对拍),但凑满
1051
+ // 80 字符即停:同一夹具 171ms → 19ms。
951
1052
  const t = messageText(e)
952
- if (t && t.trim()) seqText.set(e.seq, t.trim().replace(/\s+/g, ' ').slice(0, 80))
1053
+ if (t && t.trim()) seqText.set(e.seq, collapsedSnippet(t, 80))
953
1054
  }
954
1055
  // 0.9.1:**reverted** = opencode 语义「回撤边界及其后」。
955
1056
  //
@@ -1165,13 +1266,17 @@ async function loadDerived(logPath) {
1165
1266
  const entry = { mtimeMs: st.mtimeMs, size: st.size, promise: null, value: null }
1166
1267
  entry.promise = buildDerived(logPath).then(derived => {
1167
1268
  entry.value = derived
1269
+ // 0.49.0:派生对象解析完才知道字节估算(估算要读 rows/texts),这里登记并按
1270
+ // 「条数 + 估算字节」双重上限裁剪;`loadDerived` 自身是最新条目,pin 住不裁。
1271
+ derivedBytes.set(derived, estimateDerivedBytes(derived, derivedTexts.get(derived)))
1272
+ trimDerivedCache(logPath)
1168
1273
  return derived
1169
1274
  })
1170
1275
  derivedCache.delete(logPath)
1171
1276
  derivedCache.set(logPath, entry)
1172
- while (derivedCache.size > DERIVED_CACHE_MAX) {
1173
- derivedCache.delete(derivedCache.keys().next().value)
1174
- }
1277
+ // 在途条目没有 value(字节按 0 计):插入时只裁剪已解析的旧条目,保证条数上限
1278
+ // 在并发冷读时也不会被突破。
1279
+ trimDerivedCache(logPath)
1175
1280
  // 失败不粘住:读错/半截文件只影响本次,下次 stat 仍会重试。
1176
1281
  entry.promise.catch(() => {
1177
1282
  if (derivedCache.get(logPath) === entry) derivedCache.delete(logPath)
@@ -1254,6 +1359,12 @@ async function opsList(targetCtx, sessionId, opts = {}) {
1254
1359
  committed: m.committed === true,
1255
1360
  // 0.27.0:已被后续回撤取代的 marker —— dock 必须隐藏(同 planRestore 的 409 闸)
1256
1361
  superseded: m.superseded === true,
1362
+ // 0.49.0:恢复重放出的副本(`source.replayedFrom` 原消息 seq)。它在 surface 上、
1363
+ // 是合法回滚目标(planRevert 只要求 seq 在 surface),但面板需要能把它与真人
1364
+ // 这次发言区分开(例如标注「恢复副本」)。全量视图早已带这两个字段,compact
1365
+ // 之前漏投影 → 面板拿不到。
1366
+ replayed: m.replayed === true,
1367
+ replayedFrom: Number.isSafeInteger(m.replayedFrom) ? m.replayedFrom : null,
1257
1368
  }))
1258
1369
  : messages
1259
1370
 
@@ -1302,8 +1413,11 @@ function searchCorpusOf(derived) {
1302
1413
  const texts = derivedTexts.get(derived) || new Map()
1303
1414
  const { messages, shadowed } = derived
1304
1415
  const corpus = []
1416
+ let lowerChars = 0
1305
1417
  for (const m of messages) {
1306
1418
  const text = texts.get(m.seq) || m.snippet || ''
1419
+ const lower = text.toLowerCase()
1420
+ lowerChars += lower.length
1307
1421
  corpus.push({
1308
1422
  seq: m.seq,
1309
1423
  type: m.type,
@@ -1311,10 +1425,17 @@ function searchCorpusOf(derived) {
1311
1425
  marker: m.marker === true,
1312
1426
  shadowed: shadowed.has(m.seq),
1313
1427
  text,
1314
- lower: text.toLowerCase(),
1428
+ lower,
1315
1429
  })
1316
1430
  }
1317
1431
  searchCorpusCache.set(derived, corpus)
1432
+ // 0.49.0(内存):语料的小写副本计入缓存预算(`text` 是既有字符串的引用,不重复计)。
1433
+ // 估算口径同 estimateDerivedBytes:2 字节/字符(上界)+ 每行 128 字节。
1434
+ derivedCorpusBytes.set(derived, corpus.length * 128 + lowerChars * 2)
1435
+ // 建语料可能把总预算顶破(大会话的语料实测 10MB 级):立刻按同一上限裁剪。
1436
+ // 刚被 /search 用过的条目是 Map 里最新的(loadDerived 命中会 LRU touch),
1437
+ // 因此裁掉的是更久未用的条目,而不是当前会话。
1438
+ trimDerivedCache()
1318
1439
  return corpus
1319
1440
  }
1320
1441
 
@@ -1488,8 +1609,12 @@ function adoptIncrementalCache(logPath, preEvents, batch, statBefore) {
1488
1609
  if (registered && !derivedTexts.has(next)) derivedTexts.set(next, registered)
1489
1610
  statFile(logPath)
1490
1611
  .then(st => {
1612
+ // 0.49.0:增量结果也要登记字节估算并重新裁缓存 —— 写后条目与全量重建的
1613
+ // 条目按同一口径参与预算,否则连续写会让缓存悄悄突破字节上限。
1614
+ derivedBytes.set(next, estimateDerivedBytes(next, derivedTexts.get(next)))
1491
1615
  derivedCache.delete(logPath)
1492
1616
  derivedCache.set(logPath, { mtimeMs: st.mtimeMs, size: st.size, promise: Promise.resolve(next), value: next })
1617
+ trimDerivedCache(logPath)
1493
1618
  })
1494
1619
  .catch(() => {
1495
1620
  /* 拿不到新 stat 就不动缓存:下一次 GET 会因 mtime 不符而重建 */
@@ -1554,6 +1679,20 @@ export const _internals = {
1554
1679
  loadDerived,
1555
1680
  derivedTexts,
1556
1681
  derivedCache,
1682
+ // 0.49.0:缓存字节预算的观测口(测试与 bench/memory.mjs 用来验证「按规模淘汰」)。
1683
+ derivedBytesOf: derived => derivedBytes.get(derived),
1684
+ derivedCorpusBytesOf: derived => derivedCorpusBytes.get(derived),
1685
+ derivedCacheBytes: () => {
1686
+ let bytes = 0
1687
+ for (const entry of derivedCache.values()) bytes += entryBytesOf(entry)
1688
+ return bytes
1689
+ },
1690
+ // 测试钩子:直接对缓存条目做一次预算裁剪(不需要构造 >96MB 的真实派生)。
1691
+ trimDerivedCache,
1692
+ derivedBytes,
1693
+ estimateDerivedBytes,
1694
+ DERIVED_CACHE_MAX,
1695
+ DERIVED_CACHE_MAX_BYTES,
1557
1696
  searchCorpusOf,
1558
1697
  }
1559
1698
 
package/src/ops-core.js CHANGED
@@ -856,9 +856,12 @@ export function buildRestoreIndex(events) {
856
856
  if (isReplayableMessage(e)) {
857
857
  // 0.26.0:判据与 planRestore 对齐 —— 首段为空但后段有内容的也算候选
858
858
  // (实测 0 条「首段空而全文非空」,但口径必须一处,否则未来必分裂)。
859
- if (messageTextFull(e).trim()) {
859
+ // 0.49.0:只取一次全文 —— 多段消息的 messageTextFull 会 join 出新串,
860
+ // 旧实现调用两次等于白算一次(100k 合成事件上约 10ms 级)。
861
+ const text = messageTextFull(e)
862
+ if (text.trim()) {
860
863
  candidates.push(e.seq)
861
- textBySeq.set(e.seq, messageTextFull(e))
864
+ textBySeq.set(e.seq, text)
862
865
  }
863
866
  }
864
867
  const markerSeq = e.data && e.data.restoresSeq
@@ -1153,15 +1156,18 @@ export function supersededByMarker(fold, markerSeq) {
1153
1156
  * 与 `planRestore` 的 409 闸共用同一条语义(`supersededByMarker`)。
1154
1157
  *
1155
1158
  * @param {Array} events 全量事件
1159
+ * @param {{shadowedByMarker: Map<number, number[]>}|null} [fold] 已经折叠过的
1160
+ * surface 节点表(可选)。deriveFromEvents 手里有 buildRestoreIndex 的 fold,
1161
+ * 传进来可省掉一次 foldSurfaceNodes 全量扫描(20k 事件约 6ms、100k 约 74ms)。
1156
1162
  * @returns {Map<number, number>} marker seq → 取代它的 marker seq
1157
1163
  */
1158
- export function supersededMarkers(events) {
1159
- const fold = foldSurfaceNodes(events)
1164
+ export function supersededMarkers(events, fold = null) {
1165
+ const state = fold || foldSurfaceNodes(events)
1160
1166
  const out = new Map()
1161
1167
  for (const e of Array.isArray(events) ? events : []) {
1162
1168
  if (!e || !Number.isSafeInteger(e.seq)) continue
1163
1169
  if (!readReplaceOp(e)) continue
1164
- const superseder = supersededByMarker(fold, e.seq)
1170
+ const superseder = supersededByMarker(state, e.seq)
1165
1171
  if (superseder !== null) out.set(e.seq, superseder)
1166
1172
  }
1167
1173
  return out
@@ -363,6 +363,13 @@ export function findSessionDirs(sessionId) {
363
363
  * 语义必须保持:首部空白丢弃、连续空白折叠为一个空格、上限**包含**可能的尾部空格
364
364
  *(旧实现先 trim 再 slice,故第 limit 位若是空格会保留)。
365
365
  *
366
+ * 0.49.0(内存):按**连续非空白 run** 追加,末尾一次性 flatten(`(' ' + out).slice(1)`
367
+ * 会先复制成扁平串)。为什么必须 flatten:`out += ch` 逐字符追加会在 V8 里留下
368
+ * `limit` 个 ConsString 节点 —— 单个 160 字符摘要实测占约 3.3KB 堆(20 倍字符量),
369
+ * 7572 行的派生结果因此多驻留约 25MB(逐行 `flatten` 后 heap 从 39.3MB 降到 14.0MB)。
370
+ * 派生缓存(LRU 48)会把这些摘要长期留在服务端,所以这里不能用 cons 链。
371
+ * run 切片在 flatten 前只是临时引用;结果与逐字符版本逐字相等(见 test/snippet-collapse)。
372
+ *
366
373
  * @param {string} text 原始文本
367
374
  * @param {number} [limit] 摘要字符上限(默认 160)
368
375
  * @returns {string} 折叠后的摘要
@@ -375,22 +382,28 @@ export function collapsedSnippet(text, limit = 160) {
375
382
  ch === '\u205f' || ch === '\u3000' || ch === '\ufeff' || (ch >= '\u2000' && ch <= '\u200a')
376
383
  let out = ''
377
384
  let pendingSpace = false
378
- for (let i = 0; i < text.length; i += 1) {
379
- if (out.length >= limit) break
385
+ let i = 0
386
+ while (i < text.length && out.length < limit) {
380
387
  const ch = text[i]
381
388
  if (isSpace(ch)) {
382
389
  if (out.length > 0) pendingSpace = true
390
+ i += 1
383
391
  continue
384
392
  }
393
+ let end = i + 1
394
+ while (end < text.length && !isSpace(text[end])) end += 1
385
395
  if (pendingSpace) {
386
396
  if (out.length >= limit) break
387
397
  out += ' '
388
398
  pendingSpace = false
389
399
  if (out.length >= limit) break
390
400
  }
391
- out += ch
401
+ const take = Math.min(end - i, limit - out.length)
402
+ out += text.slice(i, i + take)
403
+ i = end
392
404
  }
393
- return out
405
+ // 空串不 flatten(保持 '' 的常量身份,调用方拿它做数组元素时零分配)。
406
+ return out.length === 0 ? out : (' ' + out).slice(1)
394
407
  }
395
408
 
396
409
  /**