dsh-knit 0.21.0 → 0.22.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/CHANGELOG.md +124 -0
- package/README.md +3 -2
- package/package.json +2 -2
- package/src/host/index-store.js +479 -0
- package/src/host/index.js +796 -68
- package/src/host/links.js +23 -10
- package/src/host/relations.js +12 -2
- package/test/fixture.mjs +50 -0
- package/test/index-incremental.test.mjs +504 -0
- package/test/index-store.test.mjs +340 -0
package/src/host/links.js
CHANGED
|
@@ -255,23 +255,36 @@ export async function buildLinkGraph(root, io) {
|
|
|
255
255
|
let skipped = 0
|
|
256
256
|
|
|
257
257
|
for (const doc of docs) {
|
|
258
|
+
// v0.22 修法 ①:条目/索引里已经带了抽取结果就直接用 —— `doc.refs.md` 正是
|
|
259
|
+
// `extractRefs()`(默认口径、只认 `.md` 目标)的产物,连 `io.read()` 都不用调。
|
|
260
|
+
// 没有它时才回落去要文本(旧调用方与单测的假条目走这条路)。
|
|
261
|
+
const cachedRefs = doc.refs && Array.isArray(doc.refs.md) ? doc.refs.md : null
|
|
258
262
|
let text = ''
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
263
|
+
if (!cachedRefs) {
|
|
264
|
+
try {
|
|
265
|
+
const r = await io.read(root, doc.rel)
|
|
266
|
+
if (!r || r.ok !== true) {
|
|
267
|
+
skipped += 1
|
|
268
|
+
continue
|
|
269
|
+
}
|
|
270
|
+
text = r.text || ''
|
|
271
|
+
} catch {
|
|
262
272
|
skipped += 1
|
|
263
273
|
continue
|
|
264
274
|
}
|
|
265
|
-
text = r.text || ''
|
|
266
|
-
} catch {
|
|
267
|
-
skipped += 1
|
|
268
|
-
continue
|
|
269
275
|
}
|
|
270
276
|
parsed += 1
|
|
271
277
|
const targets = new Set()
|
|
272
|
-
|
|
273
|
-
const
|
|
274
|
-
|
|
278
|
+
if (cachedRefs) {
|
|
279
|
+
for (const hit of cachedRefs) {
|
|
280
|
+
const rel = resolveRef(hit.raw, index, doc.rel)
|
|
281
|
+
if (rel && rel !== doc.rel) targets.add(rel)
|
|
282
|
+
}
|
|
283
|
+
} else {
|
|
284
|
+
for (const raw of extractRefs(text)) {
|
|
285
|
+
const rel = resolveRef(raw, index, doc.rel)
|
|
286
|
+
if (rel && rel !== doc.rel) targets.add(rel)
|
|
287
|
+
}
|
|
275
288
|
}
|
|
276
289
|
out.set(doc.rel, targets)
|
|
277
290
|
}
|
package/src/host/relations.js
CHANGED
|
@@ -255,13 +255,23 @@ export function buildRelationFacts(candidates, options = {}) {
|
|
|
255
255
|
const text = typeof doc.head === 'string' ? doc.head : ''
|
|
256
256
|
if (isMd(rel)) {
|
|
257
257
|
// 只有 Markdown 能当 `references` / `documents` 的**源**(D5):源这一侧不放开关。
|
|
258
|
-
|
|
258
|
+
//
|
|
259
|
+
// v0.22 修法 ①:`doc.refs.any` 就是 `extractRefsWithLines(text, { anyExt: true })`
|
|
260
|
+
// 的产物(读盘/索引还原那一刻算好的),有它就不必再扫一遍首部 —— 这也正是
|
|
261
|
+
// 「重启后不重新推导关系」的实现。`text` 只作为没有 `refs` 时的回落。
|
|
262
|
+
const refs = doc.refs && Array.isArray(doc.refs.any)
|
|
263
|
+
? doc.refs.any
|
|
264
|
+
: extractRefsWithLines(text, { anyExt: true })
|
|
265
|
+
for (const ref of refs) {
|
|
259
266
|
const other = resolveRef(ref.raw, index, rel, { anyExt: true })
|
|
260
267
|
if (!other || other === rel) continue
|
|
261
268
|
edge(rel, isMd(other) ? 'references' : 'documents', other, ref.line)
|
|
262
269
|
}
|
|
263
270
|
} else {
|
|
264
|
-
|
|
271
|
+
const imports = doc.refs && Array.isArray(doc.refs.imports)
|
|
272
|
+
? doc.refs.imports
|
|
273
|
+
: importsOf(text)
|
|
274
|
+
for (const imp of imports) {
|
|
265
275
|
const other = resolveSpec(imp.spec, rel, index)
|
|
266
276
|
if (!other || other === rel) continue
|
|
267
277
|
edge(rel, 'imports', other, imp.line)
|
package/test/fixture.mjs
CHANGED
|
@@ -71,3 +71,53 @@ function trackForCleanup(dir) {
|
|
|
71
71
|
LIVE_DIRS.clear()
|
|
72
72
|
})
|
|
73
73
|
}
|
|
74
|
+
|
|
75
|
+
/* ── 存储替身(v0.22 的增量索引需要一份「能重启」的介质)───────── */
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 一个最小的假 `kv` 后端,形状与 `dsh-storage` 的 JSON 后端一致
|
|
79
|
+
* (`open(descriptor)` → `loadAll / putRecord / deleteRecord`)。
|
|
80
|
+
*
|
|
81
|
+
* `medium` 与后端实例**分开**,于是「重启」= 同一份 medium + 一个全新的后端,
|
|
82
|
+
* 而 `duplicate-mount`(同名 unit 在**同一个**后端里开两次)也能如实复现。
|
|
83
|
+
*
|
|
84
|
+
* @param {{tables?: object}} [medium] - 介质(省略则新建一份空的)
|
|
85
|
+
* @param {{failOpen?: boolean, brokenLoad?: boolean}} [options] - 故障注入
|
|
86
|
+
* @returns {object} 假后端(含 `medium` / `writes` / `descriptors`)
|
|
87
|
+
*/
|
|
88
|
+
export function fakeStorageBackend(medium = { tables: {} }, options = {}) {
|
|
89
|
+
const opened = new Set()
|
|
90
|
+
const writes = []
|
|
91
|
+
const descriptors = []
|
|
92
|
+
const unitOf = (name) => ({
|
|
93
|
+
loadAll: async () => {
|
|
94
|
+
if (options.brokenLoad) throw new Error('malformed-medium')
|
|
95
|
+
return { unit: { name, version: 1 }, global: {}, tables: medium.tables }
|
|
96
|
+
},
|
|
97
|
+
putRecord: async (table, key, value) => {
|
|
98
|
+
writes.push(['put', table, key])
|
|
99
|
+
medium.tables[table] = medium.tables[table] || {}
|
|
100
|
+
medium.tables[table][key] = value
|
|
101
|
+
},
|
|
102
|
+
deleteRecord: async (table, key) => {
|
|
103
|
+
writes.push(['del', table, key])
|
|
104
|
+
if (medium.tables[table]) delete medium.tables[table][key]
|
|
105
|
+
},
|
|
106
|
+
setGlobal: async () => {},
|
|
107
|
+
close: async () => { opened.delete(name) },
|
|
108
|
+
})
|
|
109
|
+
return {
|
|
110
|
+
medium,
|
|
111
|
+
writes,
|
|
112
|
+
descriptors,
|
|
113
|
+
kv: {
|
|
114
|
+
open: async (descriptor) => {
|
|
115
|
+
descriptors.push(descriptor)
|
|
116
|
+
if (options.failOpen) throw new Error('medium-unavailable')
|
|
117
|
+
if (opened.has(descriptor.name)) throw new Error('duplicate-mount')
|
|
118
|
+
opened.add(descriptor.name)
|
|
119
|
+
return unitOf(descriptor.name)
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Knit · **增量上下文索引**(v0.22)的端到端测试
|
|
3
|
+
*
|
|
4
|
+
* 这一版要证明的是提示词 §6 的七条验收,而不是「跑得更快」。七条里每一条在这里都
|
|
5
|
+
* 有一个能**证伪**的断言(把对应实现删掉,这些用例必须变红):
|
|
6
|
+
*
|
|
7
|
+
* 1. 未修改文件 → 不重新读取 / 解析 / tokenize
|
|
8
|
+
* 2. 修改一个文件 → 只重新处理该文件
|
|
9
|
+
* 3. 新增 / 删除 / 重命名 → 下一次有效检索不返回过期结果
|
|
10
|
+
* 4. 重启 → 可恢复或安全重建
|
|
11
|
+
* 5. 丢失 watcher event → 对账可以修复(v0.22 没有 watcher,权威就是**每轮抽验**)
|
|
12
|
+
* 6. 索引损坏 / storage 不可用 → 回退路径仍可用,不能崩溃
|
|
13
|
+
* 7. 索引路径开启 / 关闭 → 同一语料上的 Context Pack 成员与排序一致
|
|
14
|
+
*
|
|
15
|
+
* 读数的两套证据:
|
|
16
|
+
* · **计数型**(`indexStatsFor()` 的 `readFiles/cached/reused/verified/put/del`)——
|
|
17
|
+
* 「整读了几次」是可证伪的整数,比墙钟时间稳定;
|
|
18
|
+
* · **结构型**(复用出来的条目 `body === ''`)—— 正文只可能来自整读,
|
|
19
|
+
* 所以「复用项没有正文」本身就是「没有整读」的直接证据,不依赖计数实现是否正确。
|
|
20
|
+
*
|
|
21
|
+
* ⚠️ 测试里默认把抽验预算设成 **0**(`setIndexVerifyBudget(0)`),让「整读次数」在断言里
|
|
22
|
+
* 没有歧义;**默认预算(8)的行为单独有用例守着**,见「抽验」那一节。
|
|
23
|
+
*
|
|
24
|
+
* ⚠️ **修法 ②(2026-10-10)**:索引只在「这一轮用不着正文」的路上查 —— 也就是
|
|
25
|
+
* `collectDocs()`(低层取数)与**时间序**扫描;相关检索要 BM25 的全部正文,索引复用在
|
|
26
|
+
* 那条路上是净开销,所以 `scan()` 在 `mode === 'relevance'` 时显式传 `{ index: false }`。
|
|
27
|
+
* 于是:本文件里断言「复用 / 整读次数」的用例走 `collectDocs()` 或 `timePageOf()`,
|
|
28
|
+
* 断言「这一页内容对不对」的用例走 `pageOf()`。两条路的职责见最后一节。
|
|
29
|
+
*/
|
|
30
|
+
import test from 'node:test'
|
|
31
|
+
import assert from 'node:assert/strict'
|
|
32
|
+
import { renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
|
|
33
|
+
import { join } from 'node:path'
|
|
34
|
+
|
|
35
|
+
import {
|
|
36
|
+
buildContextFor, collectDocs, indexStatsFor, indexStorageStatus, resetIndexMemory,
|
|
37
|
+
scan, setIndexRegistry, setIndexVerifyBudget,
|
|
38
|
+
} from '../src/host/index.js'
|
|
39
|
+
import { createIndexStore, refsShapeOk } from '../src/host/index-store.js'
|
|
40
|
+
import { fakeStorageBackend, makeWorkspace } from './fixture.mjs'
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 起一个「进程」:重置内存态 → 接上存储 → 设定抽验预算。
|
|
44
|
+
*
|
|
45
|
+
* `budget` 默认 **0**(关掉抽验 ⇒ `readFiles` 就是纯整读次数);要测生产默认值就传
|
|
46
|
+
* `defaultBudget: true`。两个都不能省,因为 `resetIndexMemory()` 会把预算也复位。
|
|
47
|
+
*
|
|
48
|
+
* @param {{tables: object}|null} medium - 介质(`null` = 没有存储)
|
|
49
|
+
* @param {{budget?: number, defaultBudget?: boolean}} [options] - 预算控制
|
|
50
|
+
* @returns {{store: object|null, medium: object|null}} 存储句柄(要 `await store.flush()`)
|
|
51
|
+
*/
|
|
52
|
+
function boot(medium, options = {}) {
|
|
53
|
+
resetIndexMemory()
|
|
54
|
+
const backend = medium ? fakeStorageBackend(medium) : null
|
|
55
|
+
const store = backend ? createIndexStore({ backend }) : null
|
|
56
|
+
setIndexRegistry(store)
|
|
57
|
+
if (options.defaultBudget !== true) {
|
|
58
|
+
setIndexVerifyBudget(options.budget == null ? 0 : options.budget)
|
|
59
|
+
}
|
|
60
|
+
return { store, medium: backend ? backend.medium : null }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 这一批语料里被索引的条目数(docs + code;media 不进索引)。 */
|
|
64
|
+
const indexed = (collected) => collected.docs.length + collected.code.length
|
|
65
|
+
|
|
66
|
+
/** 全部条目的 rel(文档 + 代码)。 */
|
|
67
|
+
const relsOf = (collected) => [...collected.docs, ...collected.code].map((doc) => doc.rel)
|
|
68
|
+
|
|
69
|
+
/** 跑一次相关检索并取出这一页的 rel(顺序即名次)。 */
|
|
70
|
+
const pageOf = async (root, query) => {
|
|
71
|
+
const payload = await scan(root, 40, { sort: 'relevance', kind: 'context', query })
|
|
72
|
+
return payload
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 跑一次**时间序**检索 —— 这条路上扫描会真的查索引(复用 + 对账都在这里)。 */
|
|
76
|
+
const timePageOf = async (root) => scan(root, 40, { sort: 'time', kind: 'context' })
|
|
77
|
+
|
|
78
|
+
/** 语料模型指纹:只比「索引本来就能提供的那几样」(rel / 标题 / 摘要 / 内容指纹)。 */
|
|
79
|
+
const corpusFingerprint = (collected) => JSON.stringify(
|
|
80
|
+
[...collected.docs, ...collected.code]
|
|
81
|
+
.map((doc) => [doc.rel, doc.title, doc.summary, doc.headHash])
|
|
82
|
+
.sort((a, b) => (a[0] < b[0] ? -1 : 1)),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
/** Context Pack 的指纹:四层的 rel 序列(成员 + 顺序都算进去)。 */
|
|
86
|
+
async function packFingerprint(root, query) {
|
|
87
|
+
const payload = await pageOf(root, query)
|
|
88
|
+
const pack = await buildContextFor(payload.hostRoot, {
|
|
89
|
+
ranked: payload.ranked, total: payload.total, task: payload.task, topic: payload.topic,
|
|
90
|
+
})
|
|
91
|
+
return JSON.stringify(['pinned', 'primary', 'supporting', 'related']
|
|
92
|
+
.map((tier) => (pack[tier] || []).map((item) => item.rel)))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/* ── 1 · 核心声明:重启后未变化的文件不再整读 ─────────── */
|
|
96
|
+
|
|
97
|
+
test('冷启整读每一篇;「重启」后未变化的文件**一次整读都没有**(§6 第 1、4 条)', async () => {
|
|
98
|
+
const root = makeWorkspace()
|
|
99
|
+
const medium = { tables: {} }
|
|
100
|
+
|
|
101
|
+
const cold = boot(medium)
|
|
102
|
+
const coldOut = await collectDocs(root)
|
|
103
|
+
await cold.store.flush()
|
|
104
|
+
const coldStats = indexStatsFor(root)
|
|
105
|
+
assert.equal(coldStats.readFiles, indexed(coldOut), '冷启动必须逐篇读一遍')
|
|
106
|
+
assert.equal(coldStats.reused, 0)
|
|
107
|
+
assert.equal(coldStats.put, indexed(coldOut), '第一次要把整份索引写下去')
|
|
108
|
+
assert.ok(indexed(coldOut) > 0)
|
|
109
|
+
|
|
110
|
+
// 「重启」= 同一份介质 + 全新的后端与 store
|
|
111
|
+
const warm = boot(medium)
|
|
112
|
+
const warmOut = await collectDocs(root)
|
|
113
|
+
const warmStats = indexStatsFor(root)
|
|
114
|
+
assert.equal(warmStats.readFiles, 0, '未修改的文件一次都不许整读')
|
|
115
|
+
assert.equal(warmStats.reused, indexed(warmOut), '逐条都该由索引复用')
|
|
116
|
+
assert.equal(warmStats.cached, 0, '进程内缓存已清空 ⇒ 复用只能来自索引')
|
|
117
|
+
assert.equal(warmStats.put, 0, '没有任何变化 ⇒ 不该写回一条记录')
|
|
118
|
+
assert.equal(warmStats.del, 0)
|
|
119
|
+
assert.deepEqual(relsOf(warmOut).sort(), relsOf(coldOut).sort(), '语料成员必须逐字一致')
|
|
120
|
+
|
|
121
|
+
// 结构型证据:复用出来的条目**没有正文**(正文只可能来自整读),
|
|
122
|
+
// 也**没有原文首部**(修法 ①:索引只存抽取结果,不存 16KB 原文)
|
|
123
|
+
for (const doc of [...warmOut.docs, ...warmOut.code]) {
|
|
124
|
+
assert.equal(doc.body, '', `${doc.rel} 复用项不该带正文`)
|
|
125
|
+
assert.equal(doc.bodyReady, false)
|
|
126
|
+
assert.equal(doc.head, '', `${doc.rel} 复用项不该带原文首部`)
|
|
127
|
+
assert.equal(refsShapeOk(doc.refs), true, `${doc.rel} 复用项必须带抽取结果 refs`)
|
|
128
|
+
assert.match(doc.headHash, /^[0-9a-f]{16}$/)
|
|
129
|
+
}
|
|
130
|
+
// 抽取结果必须与冷启读盘时算出来的逐字相同 —— 关系与引用图就是靠它才不用重读
|
|
131
|
+
const before = new Map([...coldOut.docs, ...coldOut.code].map((doc) => [doc.rel, doc.refs]))
|
|
132
|
+
for (const doc of [...warmOut.docs, ...warmOut.code]) {
|
|
133
|
+
assert.deepEqual(doc.refs, before.get(doc.rel), `${doc.rel} 的引用抽取结果必须与读盘结果一致`)
|
|
134
|
+
}
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
test('同一进程内第二次扫描走的是**进程内 cache**,不是索引复用(别把旧能力记成新收益)', async () => {
|
|
138
|
+
const root = makeWorkspace()
|
|
139
|
+
boot(null) // 没有存储:这一条要证明 v0.20 就有的能力单独计数
|
|
140
|
+
const first = await collectDocs(root)
|
|
141
|
+
assert.equal(indexStatsFor(root).readFiles, indexed(first))
|
|
142
|
+
const second = await collectDocs(root)
|
|
143
|
+
const stats = indexStatsFor(root)
|
|
144
|
+
assert.equal(stats.cached, indexed(second), '第二次该命中内存 cache')
|
|
145
|
+
assert.equal(stats.readFiles, 0)
|
|
146
|
+
assert.equal(stats.reused, 0, '没有索引 ⇒ 复用数必须是 0')
|
|
147
|
+
assert.deepEqual(relsOf(second).sort(), relsOf(first).sort())
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
/* ── 2 · 抽验:mtime+size 不是唯一证据 ────────────────── */
|
|
151
|
+
|
|
152
|
+
test('默认预算(8):复用项会按指纹复核一遍(§6 第 5 条的权威就是对账)', async () => {
|
|
153
|
+
const root = makeWorkspace()
|
|
154
|
+
const medium = { tables: {} }
|
|
155
|
+
const cold = boot(medium)
|
|
156
|
+
await collectDocs(root)
|
|
157
|
+
await cold.store.flush()
|
|
158
|
+
|
|
159
|
+
boot(medium, { defaultBudget: true }) // 生产默认值就是 8
|
|
160
|
+
const out = await collectDocs(root)
|
|
161
|
+
const stats = indexStatsFor(root)
|
|
162
|
+
assert.equal(stats.reused, indexed(out))
|
|
163
|
+
assert.equal(stats.verified, stats.reused, '样本数少于预算 ⇒ 这一轮应该全部核到')
|
|
164
|
+
assert.equal(stats.repaired, 0, '没人被改过 ⇒ 不该有修复')
|
|
165
|
+
assert.equal(stats.readFiles, stats.verified, '抽验读的只有头部,次数等于核验项数')
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
test('抽验是**承重的**:同 mtime 同 size 的改写靠指纹抓得到;预算设 0 就会漏(§4 第 4 条)', async () => {
|
|
169
|
+
/**
|
|
170
|
+
* 造一个「内容变了但 mtime 与 size 都没变」的文件。
|
|
171
|
+
*
|
|
172
|
+
* 这不是人为刁难:`git checkout`、编辑器「保存格式」、脚本原地替换都可能撞上;
|
|
173
|
+
* 只要索引把 mtime+size 当唯一证据,这种改写就会被**静默交付成旧内容**。
|
|
174
|
+
*
|
|
175
|
+
* ⚠️ 观测量是 `title`(由 `# 陈旧 A` / `# 陈旧 B` 解析出来),不是 `head` ——
|
|
176
|
+
* 修法 ① 之后复用项不带原文首部,而标题正是「这条记录到底来自哪一版内容」的
|
|
177
|
+
* 用户可见证据。
|
|
178
|
+
*
|
|
179
|
+
* @param {number} budget - 抽验预算
|
|
180
|
+
* @returns {Promise<{title: string, stats: object}>} 复用出来的标题与统计
|
|
181
|
+
*/
|
|
182
|
+
const stale = async (budget) => {
|
|
183
|
+
const root = makeWorkspace([['docs/stale.md', '# 陈旧 A\n\nAAAA\n']])
|
|
184
|
+
const abs = join(root, 'docs/stale.md')
|
|
185
|
+
const before = statSync(abs)
|
|
186
|
+
|
|
187
|
+
const cold = boot({ tables: {} }, { budget })
|
|
188
|
+
await collectDocs(root)
|
|
189
|
+
await cold.store.flush()
|
|
190
|
+
|
|
191
|
+
writeFileSync(abs, '# 陈旧 B\n\nBBBB\n') // 与上一份**等长**
|
|
192
|
+
utimesSync(abs, before.atimeMs / 1000, before.mtimeMs / 1000) // mtime 还原
|
|
193
|
+
const after = statSync(abs)
|
|
194
|
+
assert.equal(after.size, before.size, '场景准备失败:两次内容不等长')
|
|
195
|
+
assert.ok(Math.abs(after.mtimeMs - before.mtimeMs) <= 1, '场景准备失败:mtime 没还原上')
|
|
196
|
+
|
|
197
|
+
boot(cold.medium, { budget }) // 「重启」
|
|
198
|
+
const out = await collectDocs(root)
|
|
199
|
+
return {
|
|
200
|
+
title: out.docs.find((doc) => doc.rel === 'docs/stale.md').title,
|
|
201
|
+
stats: indexStatsFor(root),
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const guarded = await stale(8)
|
|
206
|
+
assert.match(guarded.title, /B/, '默认预算下必须抓到改写并重建')
|
|
207
|
+
assert.equal(guarded.stats.repaired, 1, '抓到一个坏记录')
|
|
208
|
+
|
|
209
|
+
// **证伪**:把抽验预算设成 0,同一条路径就漏了 —— 证明这道守卫不是装饰。
|
|
210
|
+
const unguarded = await stale(0)
|
|
211
|
+
assert.match(unguarded.title, /A/, '预算 0 时索引会照旧交付陈旧记录(所以默认预算不能是 0)')
|
|
212
|
+
assert.equal(unguarded.stats.repaired, 0)
|
|
213
|
+
})
|
|
214
|
+
|
|
215
|
+
test('抽验预算是**硬上限**,且它只读头部(不改语料、不误报修复)', async () => {
|
|
216
|
+
const root = makeWorkspace([
|
|
217
|
+
['a.md', '# a\n'], ['b.md', '# b\n'], ['c.md', '# c\n'], ['d.md', '# d\n'], ['e.md', '# e\n'],
|
|
218
|
+
])
|
|
219
|
+
const medium = { tables: {} }
|
|
220
|
+
const cold = boot(medium)
|
|
221
|
+
const first = await collectDocs(root)
|
|
222
|
+
await cold.store.flush()
|
|
223
|
+
assert.ok(indexed(first) > 1, '样本要够多,否则测不出上限')
|
|
224
|
+
|
|
225
|
+
// 预算 1:三轮各核一条(游标轮转 ⇒ 不会每轮都核同一条,但这一点不可从外部观测,
|
|
226
|
+
// 这里只钉死可证伪的部分:核验数等于预算、不多核也不少核)。
|
|
227
|
+
for (let round = 0; round < 3; round += 1) {
|
|
228
|
+
boot(medium, { budget: 1 })
|
|
229
|
+
const out = await collectDocs(root)
|
|
230
|
+
const stats = indexStatsFor(root)
|
|
231
|
+
assert.equal(stats.verified, 1, '每轮只核一条')
|
|
232
|
+
assert.equal(stats.repaired, 0, '没人被改过 ⇒ 不许误报修复')
|
|
233
|
+
assert.equal(stats.readFiles, 1, '抽验读的只有头部这一次')
|
|
234
|
+
assert.deepEqual(relsOf(out).sort(), relsOf(first).sort())
|
|
235
|
+
}
|
|
236
|
+
})
|
|
237
|
+
|
|
238
|
+
/* ── 3 · 变化:只重建变化的那一个(§6 第 2 条)────────── */
|
|
239
|
+
|
|
240
|
+
test('改一个文件:只重新处理该文件,其余仍由索引复用', async () => {
|
|
241
|
+
const root = makeWorkspace()
|
|
242
|
+
const medium = { tables: {} }
|
|
243
|
+
const cold = boot(medium)
|
|
244
|
+
const first = await collectDocs(root)
|
|
245
|
+
await cold.store.flush()
|
|
246
|
+
|
|
247
|
+
const victim = first.docs[0].rel
|
|
248
|
+
const abs = join(root, victim)
|
|
249
|
+
const before = statSync(abs)
|
|
250
|
+
writeFileSync(abs, `${'# 改过了\n\n'}${'x'.repeat(Math.max(1, before.size - 12))}\n`)
|
|
251
|
+
utimesSync(abs, before.atimeMs / 1000, (before.mtimeMs + 5000) / 1000)
|
|
252
|
+
const after = statSync(abs)
|
|
253
|
+
assert.notEqual(after.mtimeMs, before.mtimeMs, '场景准备失败:mtime 没变')
|
|
254
|
+
|
|
255
|
+
boot(medium)
|
|
256
|
+
const second = await collectDocs(root)
|
|
257
|
+
const stats = indexStatsFor(root)
|
|
258
|
+
assert.equal(stats.readFiles, 1, '只许重建被改的那一篇')
|
|
259
|
+
assert.equal(stats.reused, indexed(second) - 1)
|
|
260
|
+
assert.equal(stats.put, 1, '差量只写一条')
|
|
261
|
+
assert.equal(stats.del, 0)
|
|
262
|
+
const doc = [...second.docs, ...second.code].find((item) => item.rel === victim)
|
|
263
|
+
assert.equal(doc.bodyReady, true, '被改的那篇必须真的读盘')
|
|
264
|
+
assert.ok(doc.body.length > 0)
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
test('新增一个文件:新记录入库,未变化的文件不重读', async () => {
|
|
268
|
+
const root = makeWorkspace()
|
|
269
|
+
const medium = { tables: {} }
|
|
270
|
+
const cold = boot(medium)
|
|
271
|
+
await collectDocs(root)
|
|
272
|
+
await cold.store.flush()
|
|
273
|
+
|
|
274
|
+
writeFileSync(join(root, 'docs/added.md'), '# 新来的\n\n刚加进来的文件。\n')
|
|
275
|
+
|
|
276
|
+
boot(medium)
|
|
277
|
+
const second = await collectDocs(root)
|
|
278
|
+
const stats = indexStatsFor(root)
|
|
279
|
+
assert.ok(relsOf(second).includes('docs/added.md'))
|
|
280
|
+
assert.equal(stats.readFiles, 1, '只有新文件需要读')
|
|
281
|
+
assert.ok(stats.put >= 1, '新记录要落盘')
|
|
282
|
+
assert.equal(stats.del, 0, '没人被删')
|
|
283
|
+
})
|
|
284
|
+
|
|
285
|
+
test('删除一个文件:下一次检索不返回它,索引项也清掉(§6 第 3 条)', async () => {
|
|
286
|
+
const root = makeWorkspace([['docs/gone.md', '# 独有的词 zebrakw\n\n只有这一篇有 zebrakw。\n']])
|
|
287
|
+
const medium = { tables: {} }
|
|
288
|
+
const cold = boot(medium)
|
|
289
|
+
const first = await collectDocs(root)
|
|
290
|
+
await cold.store.flush()
|
|
291
|
+
assert.ok(relsOf(first).includes('docs/gone.md'))
|
|
292
|
+
assert.equal((await cold.store.read(root)).has('docs/gone.md'), true, '先确认它真的进过索引')
|
|
293
|
+
|
|
294
|
+
rmSync(join(root, 'docs/gone.md'))
|
|
295
|
+
|
|
296
|
+
boot(medium)
|
|
297
|
+
// 相关检索这条路上(修法 ②)**不查索引**,所以「过期索引项被清掉」不是它的职责 ——
|
|
298
|
+
// 它只负责一件事:被删的文件不许出现在这一页、也不许留在名次里。
|
|
299
|
+
const payload = await pageOf(root, 'zebrakw')
|
|
300
|
+
assert.ok(!payload.docs.some((doc) => doc.rel === 'docs/gone.md'), '被删的不许出现在这一页')
|
|
301
|
+
assert.ok(!payload.ranked.some((doc) => doc.rel === 'docs/gone.md'), '也不许留在全量名次里')
|
|
302
|
+
// 对账(过期项的清理)发生在**查索引**的那条路上 —— 时间序扫描。
|
|
303
|
+
const timePage = await timePageOf(root)
|
|
304
|
+
assert.ok(!timePage.docs.some((doc) => doc.rel === 'docs/gone.md'), '时间序里也不许有它')
|
|
305
|
+
const stats = indexStatsFor(root)
|
|
306
|
+
assert.ok(stats.del >= 1, '过期索引项必须被清掉')
|
|
307
|
+
assert.equal((await indexStoreOf(root, medium)).has('docs/gone.md'), false, '存储里也不该再有它')
|
|
308
|
+
})
|
|
309
|
+
|
|
310
|
+
test('重命名 = 删旧 + 增新:旧 rel 不残留,新 rel 立刻可检索', async () => {
|
|
311
|
+
const root = makeWorkspace([['docs/old.md', '# 词 zebrakw\n\n重命名用例。\n']])
|
|
312
|
+
const medium = { tables: {} }
|
|
313
|
+
const cold = boot(medium)
|
|
314
|
+
await collectDocs(root)
|
|
315
|
+
await cold.store.flush()
|
|
316
|
+
|
|
317
|
+
renameSync(join(root, 'docs/old.md'), join(root, 'docs/new.md'))
|
|
318
|
+
|
|
319
|
+
boot(medium)
|
|
320
|
+
const payload = await pageOf(root, 'zebrakw')
|
|
321
|
+
const rels = payload.ranked.map((doc) => doc.rel)
|
|
322
|
+
assert.ok(rels.includes('docs/new.md'), '新路径必须立刻参与检索')
|
|
323
|
+
assert.ok(!rels.includes('docs/old.md'), '旧路径不许残留')
|
|
324
|
+
// 对账发生在**查索引**的那条路上 —— 时间序扫描(修法 ②)。
|
|
325
|
+
const timeRels = (await timePageOf(root)).docs.map((doc) => doc.rel)
|
|
326
|
+
assert.ok(timeRels.includes('docs/new.md') && !timeRels.includes('docs/old.md'))
|
|
327
|
+
const stats = indexStatsFor(root)
|
|
328
|
+
assert.ok(stats.del >= 1, '旧键要被删掉')
|
|
329
|
+
const stored = await indexStoreOf(root, medium)
|
|
330
|
+
assert.equal(stored.has('docs/old.md'), false)
|
|
331
|
+
assert.equal(stored.has('docs/new.md'), true)
|
|
332
|
+
})
|
|
333
|
+
|
|
334
|
+
/* ── 4 · 降级:坏存储不许把检索带崩(§6 第 6 条)──────── */
|
|
335
|
+
|
|
336
|
+
test('没有存储:功能照常,理由说清楚,且一条索引都不写', async () => {
|
|
337
|
+
const root = makeWorkspace()
|
|
338
|
+
boot(null)
|
|
339
|
+
const out = await collectDocs(root)
|
|
340
|
+
const stats = indexStatsFor(root)
|
|
341
|
+
assert.equal(stats.readFiles, indexed(out), '没有索引 ⇒ 只能全都读')
|
|
342
|
+
assert.equal(stats.put, 0)
|
|
343
|
+
assert.equal(stats.reused, 0)
|
|
344
|
+
assert.equal(indexStorageStatus().persisted, false)
|
|
345
|
+
assert.equal(indexStorageStatus().reason, 'no-storage')
|
|
346
|
+
const payload = await pageOf(root, '相关性排序')
|
|
347
|
+
assert.ok(payload.docs.length > 0, '检索照常出结果')
|
|
348
|
+
})
|
|
349
|
+
|
|
350
|
+
test('存储开不起来:退回全量扫描,不抛,理由为 open-failed', async () => {
|
|
351
|
+
const root = makeWorkspace()
|
|
352
|
+
resetIndexMemory()
|
|
353
|
+
const backend = fakeStorageBackend({ tables: {} }, { failOpen: true })
|
|
354
|
+
const store = createIndexStore({ backend })
|
|
355
|
+
setIndexRegistry(store)
|
|
356
|
+
setIndexVerifyBudget(0)
|
|
357
|
+
|
|
358
|
+
const out = await collectDocs(root)
|
|
359
|
+
assert.equal(indexStatsFor(root).readFiles, indexed(out))
|
|
360
|
+
assert.equal(indexStatsFor(root).reason, 'open-failed')
|
|
361
|
+
assert.equal(store.persisted, false)
|
|
362
|
+
assert.equal(await store.write('/w', { put: [{ rel: 'a.md' }], del: [] }), false)
|
|
363
|
+
})
|
|
364
|
+
|
|
365
|
+
test('介质损坏 / 记录缺指纹:当未验证重建,绝不抛', async () => {
|
|
366
|
+
const root = makeWorkspace()
|
|
367
|
+
const medium = { tables: {} }
|
|
368
|
+
const cold = boot(medium)
|
|
369
|
+
const first = await collectDocs(root)
|
|
370
|
+
await cold.store.flush()
|
|
371
|
+
|
|
372
|
+
// 把一条记录改成「只有 mtime+size」的 v1 形状(缺 headHash),再把另一条打成畸形
|
|
373
|
+
const table = medium.tables.files
|
|
374
|
+
const keys = Object.keys(table)
|
|
375
|
+
const victim = keys[0]
|
|
376
|
+
const victimRel = table[victim].rel
|
|
377
|
+
table[victim] = { ...table[victim], headHash: undefined }
|
|
378
|
+
table[keys[1]] = 'not-an-object'
|
|
379
|
+
|
|
380
|
+
boot(medium)
|
|
381
|
+
const second = await collectDocs(root)
|
|
382
|
+
const stats = indexStatsFor(root)
|
|
383
|
+
assert.deepEqual(relsOf(second).sort(), relsOf(first).sort(), '语料成员必须完好')
|
|
384
|
+
assert.ok(stats.readFiles >= 1, '缺指纹的那条必须重读')
|
|
385
|
+
const doc = [...second.docs, ...second.code].find((item) => item.rel === victimRel)
|
|
386
|
+
assert.match(doc.headHash, /^[0-9a-f]{16}$/, '重建之后指纹要补回来')
|
|
387
|
+
|
|
388
|
+
// `loadAll()` 直接抛(真实后端在介质损坏时报 `malformed-medium`):当空索引,照常检索
|
|
389
|
+
resetIndexMemory()
|
|
390
|
+
setIndexRegistry(createIndexStore({ backend: fakeStorageBackend({ tables: {} }, { brokenLoad: true }) }))
|
|
391
|
+
setIndexVerifyBudget(0)
|
|
392
|
+
const out = await collectDocs(root)
|
|
393
|
+
assert.equal(indexStatsFor(root).reason, 'read-failed')
|
|
394
|
+
assert.equal(indexStatsFor(root).readFiles, indexed(out))
|
|
395
|
+
assert.deepEqual(relsOf(out).sort(), relsOf(first).sort())
|
|
396
|
+
})
|
|
397
|
+
|
|
398
|
+
/* ── 5 · 一致性:索引开/关,Context Pack 必须一致(§6 第 7 条)── */
|
|
399
|
+
|
|
400
|
+
test('索引开启 / 关闭:同一语料同一任务,Context Pack 成员与排序逐字一致', async () => {
|
|
401
|
+
const root = makeWorkspace([
|
|
402
|
+
['docs/design.md', '# 排序设计\n\n相关性排序与 IDF 的设计说明,sidebar 也在这里。\n'],
|
|
403
|
+
['docs/impl.js', 'export function rankByRelevance() { return "sidebar 相关性排序" }\n'],
|
|
404
|
+
])
|
|
405
|
+
const query = '相关性排序 sidebar IDF'
|
|
406
|
+
const medium = { tables: {} }
|
|
407
|
+
|
|
408
|
+
// ① 有索引、且是热的
|
|
409
|
+
const cold = boot(medium)
|
|
410
|
+
await collectDocs(root)
|
|
411
|
+
await cold.store.flush()
|
|
412
|
+
boot(medium)
|
|
413
|
+
await collectDocs(root)
|
|
414
|
+
const warm = await packFingerprint(root, query)
|
|
415
|
+
|
|
416
|
+
// ② 冷启(索引刚建好那一轮)
|
|
417
|
+
boot(medium, { budget: 0 })
|
|
418
|
+
const withIndex = await packFingerprint(root, query)
|
|
419
|
+
assert.equal(withIndex, warm, '冷启与热索引在同一语料上必须给同一个包')
|
|
420
|
+
|
|
421
|
+
// ③ 完全没有索引
|
|
422
|
+
boot(null)
|
|
423
|
+
const without = await packFingerprint(root, query)
|
|
424
|
+
assert.equal(without, withIndex, '「索引开 / 关」两份 Context Pack 必须逐字相同')
|
|
425
|
+
assert.ok(JSON.parse(withIndex).some((tier) => tier.length > 0), '指纹不能是个空包')
|
|
426
|
+
|
|
427
|
+
// ④ 语料层一致性 —— **修法 ② 之后,这才是真正吃了索引的那条口径**。
|
|
428
|
+
// ①②③ 走的是相关检索,而它在修法 ② 里不查索引(两边走同一条路,相等是平凡的,
|
|
429
|
+
// 留在这里当回归守卫);低层取数(`collectDocs`,时间序扫描也走它)会真的复用,
|
|
430
|
+
// 它交出来的语料模型必须与「没有索引、全部整读」逐字一致。
|
|
431
|
+
boot(medium, { budget: 0 })
|
|
432
|
+
const reusedCorpus = await collectDocs(root)
|
|
433
|
+
assert.ok(indexStatsFor(root).reused > 0, '这条口径必须真的用上了索引,否则一致性是白证的')
|
|
434
|
+
boot(null)
|
|
435
|
+
const readCorpus = await collectDocs(root)
|
|
436
|
+
assert.equal(
|
|
437
|
+
corpusFingerprint(reusedCorpus), corpusFingerprint(readCorpus),
|
|
438
|
+
'复用来的语料与整读来的语料必须给出同一份模型(rel / 标题 / 摘要 / 内容指纹)',
|
|
439
|
+
)
|
|
440
|
+
})
|
|
441
|
+
|
|
442
|
+
/* ── 6 · 内存态:重置干净,别留下跨用例的鬼影 ─────────── */
|
|
443
|
+
|
|
444
|
+
/* ── 6 · 修法 ②:索引只在「用不着正文」的路上查(2026-10-10)── */
|
|
445
|
+
|
|
446
|
+
test('修法 ②:要正文的相关检索**不查索引**,时间序才吃索引(两条路都能证伪)', async () => {
|
|
447
|
+
const root = makeWorkspace([
|
|
448
|
+
['docs/a.md', '# 甲\n\nzebrakw 只在这一篇里。\n'],
|
|
449
|
+
['docs/b.md', '# 乙\n\n另一篇,用来凑候选数。\n'],
|
|
450
|
+
['docs/c.js', 'export const c = "zebrakw 也在代码里"\n'],
|
|
451
|
+
])
|
|
452
|
+
const medium = { tables: {} }
|
|
453
|
+
const cold = boot(medium)
|
|
454
|
+
await collectDocs(root)
|
|
455
|
+
await cold.store.flush()
|
|
456
|
+
|
|
457
|
+
// ① 相关检索(排序改「相关」+ 真的抽到关键词):BM25 要全部正文 ⇒ 整读,且不装载索引。
|
|
458
|
+
// 证伪方式:把 `scan()` 里的 `{ index: mode !== 'relevance' }` 换成不传,
|
|
459
|
+
// `skipped` 会变 false、`reused` 会大于 0,这一节立刻红。
|
|
460
|
+
boot(medium)
|
|
461
|
+
const page = await pageOf(root, 'zebrakw')
|
|
462
|
+
const rel = indexStatsFor(root)
|
|
463
|
+
assert.ok(page.docs.length > 0, '相关检索照常出结果')
|
|
464
|
+
assert.equal(rel.skipped, true, '要正文的路径**根本没查索引**')
|
|
465
|
+
assert.equal(rel.reused, 0, '也不许把没有正文的复用条目交给 BM25')
|
|
466
|
+
assert.equal(rel.readFiles, rel.candidates, '它只能整读全部候选')
|
|
467
|
+
|
|
468
|
+
// ② 时间序:完全吃索引里的字段 ⇒ 真的复用。
|
|
469
|
+
// 证伪方式:删掉 `collectDocs()` 里的 `useIndex` 判定(永远查索引),`readFiles`
|
|
470
|
+
// 会变成 0 而不是 candidates,这一节红。
|
|
471
|
+
boot(medium)
|
|
472
|
+
await timePageOf(root)
|
|
473
|
+
const t = indexStatsFor(root)
|
|
474
|
+
assert.equal(t.skipped, false, '时间序必须查索引')
|
|
475
|
+
assert.equal(t.reused + t.readFiles, t.candidates, '每条候选要么复用、要么整读')
|
|
476
|
+
assert.ok(t.reused > 0, '时间序必须真的复用到了索引,否则索引对这条路也白搭')
|
|
477
|
+
assert.equal(t.readFiles, 0, '预算 0 ⇒ 一条都不用整读(复用是真的)')
|
|
478
|
+
})
|
|
479
|
+
|
|
480
|
+
test('resetIndexMemory:统计清零、注册表断开、预算复位', async () => {
|
|
481
|
+
const root = makeWorkspace()
|
|
482
|
+
const medium = { tables: {} }
|
|
483
|
+
const cold = boot(medium)
|
|
484
|
+
await collectDocs(root)
|
|
485
|
+
await cold.store.flush()
|
|
486
|
+
assert.ok(indexStatsFor(root))
|
|
487
|
+
|
|
488
|
+
resetIndexMemory()
|
|
489
|
+
assert.equal(indexStatsFor(root), null, '统计必须清掉')
|
|
490
|
+
assert.equal(indexStorageStatus().persisted, false, '注册表要断开')
|
|
491
|
+
const again = await collectDocs(root)
|
|
492
|
+
assert.equal(indexStatsFor(root).readFiles, indexed(again), '重置后只能重新全读')
|
|
493
|
+
})
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* 直接读一次存储(断言「过期项真的不在盘上了」时用)。
|
|
497
|
+
* @param {string} root - 工作区根
|
|
498
|
+
* @param {{tables: object}} medium - 介质
|
|
499
|
+
* @returns {Promise<Map<string, object>>} rel → 记录
|
|
500
|
+
*/
|
|
501
|
+
async function indexStoreOf(root, medium) {
|
|
502
|
+
const store = createIndexStore({ backend: fakeStorageBackend(medium) })
|
|
503
|
+
return store.read(root)
|
|
504
|
+
}
|