AI 代码审查实战:JavaScript VP-tree 的中位切分与最近邻剪枝证明
让 AI 生成一棵 VP-tree,最危险的结果往往不是代码报错,而是树看起来平衡、普通样例全部通过,却悄悄漏掉一个并列最近邻。本文把任务缩小到一个可以审查到底的版本:JavaScript 静态字符串索引,距离采用逐码点、单位代价的 Levenshtein 编辑距离,只返回一个最近邻;距离相等时,数值 ID 较小的记录获胜。
本文的审查练习是自行设计的教学案例,不冒充某个模型的真实对话记录。与按整数距离挂多路分支的 BK-tree 不同,这里要检查的是相对支点距离的中位切分;与依赖坐标轴的 k-d tree 不同,这里只有距离函数,没有可以拿来切平面的坐标。我们不重写这两类索引,而是追踪 VP-tree 特有的一条证据链:切分承诺什么,三角不等式给出什么下界,程序究竟在什么条件下才允许跳过子树。

以下九段代码都可单独保存为 example01.cjs 至 example09.cjs,并执行 node example01.cjs 等命令。它们各自包含所需函数,没有隐藏导入、第三方包、跨段变量或待补全省略号;为方便独立复现,核心函数会重复出现。所有展示输出都来自实际运行,验证环境为 Node.js v24.19.0。
一、先固定输入契约,别让距离偷偷换了单位
首先让 AI 写清楚一个编辑动作究竟作用于什么。JavaScript 的字符串长度和索引使用 UTF-16 码元,而字符串迭代器按码点前进;因此本例用 Array.from 把文本转换为码点字符串数组。一个补充平面 emoji 删除一次的距离是 1,不能因为它占两个码元而算成 2。这一行为对应 ECMAScript 字符串迭代器规范。
码点也不等于用户看见的一个字。组合音标、零宽连接符序列仍可能含多个码点。我们不自动执行 NFC,不折叠大小写,不去掉空格;预组合的 é 与 e 加组合重音的距离就是 2。对 JavaScript 允许出现的孤立代理项,也按迭代器产出的一个独立符号处理,不把它修复为替换字符。这个选择未必符合每个产品的搜索体验,但它是明确、可复现的契约;若业务要规范化,应在建索引与查询两端实施同一规则,并重新说明相等关系。
下面的滚动数组只负责精确整数距离。每格取删除、插入、替换三种代价的最小值,不做阈值截断,也不把过大距离替换成某个哨兵。树的半径和查询到支点的距离必须是真实距离;把一个近似值拿去做几何下界,可能直接破坏正确性。
独立示例 1:保存为 example01.cjs。
"use strict";
const assert = require("node:assert/strict");
function lev(a, b) {
if (a.length < b.length) [a, b] = [b, a];
if (!b.length) return a.length;
const row = Array.from({length: b.length + 1}, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diagonal = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const above = row[j];
row[j] = Math.min(above + 1, row[j - 1] + 1,
diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
diagonal = above;
}
}
return row[b.length];
}
const distance = (a, b) => lev(Array.from(a), Array.from(b));
assert.equal(distance("kitten", "sitting"), 3);
assert.equal(distance("😀", ""), 1);
assert.equal(distance("é", "e\u0301"), 2);
assert.equal(distance("\ud800", ""), 1);
console.log(JSON.stringify({utf16: "😀".length, codepoints: [..."😀"].length,
emojiDeletion: distance("😀", ""), composedVsDecomposed: distance("é", "e\u0301")}));实际输出:
{"utf16":2,"codepoints":1,"emojiDeletion":1,"composedVsDecomposed":2}二、把度量前提写成证明,再用有限域检查实现
为什么能够剪枝?因为这里的单位代价编辑距离满足三角不等式:把从文本甲到文本乙的一条最短编辑序列,与乙到丙的最短序列接起来,得到了一条甲到丙的合法路径;最短路径当然不会比这条拼接路径更长。插入与删除互为逆操作,替换可以反向,所以距离对称;没有编辑时距离为零,不同码点序列至少需要一次编辑。这些才是可以使用度量下界的依据。
Wagner 与 Fischer 的原始论文讨论了字符串纠错与动态规划;本文采用其中常见的单位操作成本设置。不要把随手设计的相似度分数、除以最大长度的归一化值或增加新操作后的递推直接塞进树里。换掉距离函数,相当于换掉证明的前提,必须重新检查所需性质。
这个小程序穷举由 a、b 组成、长度不超过二的七个字符串,检查全部三元组,同时拿另一份递归记忆化距离实现核对。有限测试不能证明对所有输入都成立,却能发现滚动数组更新顺序、空串处理和替换代价等常见实现失误。审查时应同时保留数学论证与程序测试,不能让其中一个替另一个签字。
独立示例 2:保存为 example02.cjs。
"use strict";
const assert = require("node:assert/strict");
function lev(a, b) {
if (a.length < b.length) [a, b] = [b, a];
if (!b.length) return a.length;
const row = Array.from({length: b.length + 1}, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diagonal = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const above = row[j];
row[j] = Math.min(above + 1, row[j - 1] + 1,
diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
diagonal = above;
}
}
return row[b.length];
}
function referenceDistance(left, right) {
const a = [...left], b = [...right];
const memo = new Map();
function solve(i, j) {
if (i === a.length) return b.length - j;
if (j === b.length) return a.length - i;
const key = i + "," + j;
if (memo.has(key)) return memo.get(key);
const answer = a[i] === b[j] ? solve(i + 1, j + 1) :
1 + Math.min(solve(i + 1, j), solve(i, j + 1), solve(i + 1, j + 1));
memo.set(key, answer);
return answer;
}
return solve(0, 0);
}
function brute(records, query) {
const scored = records.map(r => ({id: r.id, text: r.text,
distance: referenceDistance(query, r.text)}));
scored.sort((a, b) => a.distance !== b.distance ?
(a.distance < b.distance ? -1 : 1) : (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
return scored[0] || null;
}
const words = ["", "a", "b", "aa", "ab", "ba", "bb"];
let triples = 0;
for (const a of words) for (const b of words) {
const ab = lev([...a], [...b]);
assert.equal(ab, referenceDistance(a, b));
assert.equal(ab, lev([...b], [...a]));
assert.equal(ab === 0, a === b);
for (const c of words) {
assert.ok(ab <= lev([...a], [...c]) + lev([...c], [...b]));
triples++;
}
}
console.log("metric triples=" + triples + " PASS");实际输出:
metric triples=343 PASS
三、partitionVP 的中位数是排名切分,不是简单过滤
每个节点先选一个支点,计算其余记录到支点的距离,再按距离和 ID 排序。本文固定选择当前集合中 ID 最小者作为支点,便于复现与比较输入顺序;这只是确定性策略,不保证搜索效果最佳。半径 mu 取排序后右半部分第一项的距离,左半与右半按数组位置分开,数量最多相差一。节点记录会从孩子集合中移除,递归规模因此严格缩小。
需要特别检查 AI 是否把以上过程改成两次 filter:距离小于 mu 的全进左侧,其余全进右侧。若大量距离等于中位数,这种写法会把几乎全部记录塞进一边;它可以保持某种距离划分,却不再拥有本文按数量平分的高度保证。更糟的写法是两边都用严格不等号,直接丢掉等于半径的记录。
按排名切分意味着两边都可能有距离恰好等于 mu 的记录。正确的不变量是左侧所有记录满足距离不大于 mu,右侧所有记录满足距离不小于 mu;等号在两边都被允许。下例中四条记录距离全部为 1,仍被分为二对二。这个闭边界约定会一直传递到查询代码,不能在搜索时突然换成另一套开区间假设。
独立示例 3:保存为 example03.cjs。
"use strict";
const assert = require("node:assert/strict");
function lev(a, b) {
if (a.length < b.length) [a, b] = [b, a];
if (!b.length) return a.length;
const row = Array.from({length: b.length + 1}, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diagonal = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const above = row[j];
row[j] = Math.min(above + 1, row[j - 1] + 1,
diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
diagonal = above;
}
}
return row[b.length];
}
function prepare(records) {
if (!Array.isArray(records)) throw new TypeError("records must be an array");
const ids = new Set();
return records.map(r => {
if (!r || !Number.isSafeInteger(r.id) || r.id < 0 ||
typeof r.text !== "string" || ids.has(r.id)) {
throw new TypeError("unique nonnegative safe ID and string required");
}
ids.add(r.id);
return Object.freeze({id: r.id, text: r.text,
cp: Object.freeze(Array.from(r.text))});
});
}
function partitionVP(points) {
if (!points.length) return null;
const vp = points.reduce((a, b) => a.id < b.id ? a : b);
const ranked = points.filter(p => p.id !== vp.id)
.map(p => ({p, radius: lev(vp.cp, p.cp)}))
.sort((a, b) => a.radius - b.radius || a.p.id - b.p.id);
const mid = Math.floor(ranked.length / 2);
const mu = ranked.length ? ranked[mid].radius : 0;
return {vp, mu,
inside: ranked.slice(0, mid).map(x => x.p),
outside: ranked.slice(mid).map(x => x.p)};
}
function build(points) {
const p = partitionVP(points);
return p && Object.freeze({vp: p.vp, mu: p.mu,
inside: build(p.inside), outside: build(p.outside)});
}
const points = prepare([
{id: 0, text: ""}, {id: 4, text: "d"}, {id: 2, text: "b"},
{id: 1, text: "a"}, {id: 3, text: "c"}
]);
const p = partitionVP(points);
assert.equal(p.mu, 1);
assert.deepEqual(p.inside.map(x => x.id), [1, 2]);
assert.deepEqual(p.outside.map(x => x.id), [3, 4]);
for (const x of p.inside) assert.ok(lev(p.vp.cp, x.cp) <= p.mu);
for (const x of p.outside) assert.ok(lev(p.vp.cp, x.cp) >= p.mu);
console.log(JSON.stringify({mu: p.mu, inside: p.inside.map(x => x.id),
outside: p.outside.map(x => x.id)}));实际输出:
{"mu":1,"inside":[1,2],"outside":[3,4]}四、审查整棵子树,而不只核对两个孩子
在构造阶段,我们验证记录 ID 为不重复的非负安全整数,文本为原始字符串,然后复制输入并缓存码点数组。相同文本可以拥有不同 ID,不能因为编辑距离为零就丢掉一条记录。这里的距离严格地说定义在码点序列上;映射到带 ID 的记录后,不同记录也可能零距离,形成伪度量。剪枝所需的对称性和三角不等式依然成立,最近邻的身份则由额外的 ID 规则确定。
build 返回冻结的节点和冻结的文本快照,不提供插入、删除或原地更新接口。若要修改数据,先重新建树;随意改动某个节点文本会使祖先的半径承诺失效。只冻结顶层对象并不足够,所以码点数组与记录对象也被冻结,外部原始记录则不会被排序或改写。
审计函数收集每棵子树的全部记录,逐一核对它们与当前祖先支点的关系。只检查直接孩子太弱:错误记录可能藏在孙节点以下。同时核对节点总数、ID 唯一性、两侧规模、空树及输入倒序后的树形。三十一条完全相同的文本得到高度五,说明排名切分在零距离集中时仍保持结构平衡;这尚未证明查询就会很快。
独立示例 4:保存为 example04.cjs。
"use strict";
const assert = require("node:assert/strict");
function lev(a, b) {
if (a.length < b.length) [a, b] = [b, a];
if (!b.length) return a.length;
const row = Array.from({length: b.length + 1}, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diagonal = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const above = row[j];
row[j] = Math.min(above + 1, row[j - 1] + 1,
diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
diagonal = above;
}
}
return row[b.length];
}
function prepare(records) {
if (!Array.isArray(records)) throw new TypeError("records must be an array");
const ids = new Set();
return records.map(r => {
if (!r || !Number.isSafeInteger(r.id) || r.id < 0 ||
typeof r.text !== "string" || ids.has(r.id)) {
throw new TypeError("unique nonnegative safe ID and string required");
}
ids.add(r.id);
return Object.freeze({id: r.id, text: r.text,
cp: Object.freeze(Array.from(r.text))});
});
}
function partitionVP(points) {
if (!points.length) return null;
const vp = points.reduce((a, b) => a.id < b.id ? a : b);
const ranked = points.filter(p => p.id !== vp.id)
.map(p => ({p, radius: lev(vp.cp, p.cp)}))
.sort((a, b) => a.radius - b.radius || a.p.id - b.p.id);
const mid = Math.floor(ranked.length / 2);
const mu = ranked.length ? ranked[mid].radius : 0;
return {vp, mu,
inside: ranked.slice(0, mid).map(x => x.p),
outside: ranked.slice(mid).map(x => x.p)};
}
function build(points) {
const p = partitionVP(points);
return p && Object.freeze({vp: p.vp, mu: p.mu,
inside: build(p.inside), outside: build(p.outside)});
}
function audit(node) {
if (!node) return {points: [], height: 0};
const a = audit(node.inside), b = audit(node.outside);
assert.ok(Math.abs(a.points.length - b.points.length) <= 1);
for (const p of a.points) assert.ok(lev(node.vp.cp, p.cp) <= node.mu);
for (const p of b.points) assert.ok(lev(node.vp.cp, p.cp) >= node.mu);
return {points: [node.vp, ...a.points, ...b.points],
height: 1 + Math.max(a.height, b.height)};
}
const records = Array.from({length: 31}, (_, id) => ({id, text: "相同"}));
const snapshot = JSON.stringify(records);
const root = build(prepare(records));
const report = audit(root);
assert.equal(report.points.length, 31);
assert.equal(new Set(report.points.map(p => p.id)).size, 31);
assert.equal(JSON.stringify(records), snapshot);
assert.deepEqual(build(prepare([...records].reverse())), root);
assert.equal(build(prepare([])), null);
console.log("nodes=" + report.points.length + " height=" + report.height + " PASS");实际输出:
nodes=31 height=5 PASS
五、从反三角不等式推导两侧下界
设查询为 q,当前支点为 v,delta 是二者的精确距离,tau 是目前最佳答案的距离。对任意左子树记录 x,已知 x 到 v 不大于 mu。由三角不等式可得,q 到 x 至少为 delta 减去 x 到 v 的距离,所以至少为 delta 减 mu;再利用距离非负,左侧下界就是 max(0, delta − mu)。同理,右侧记录到 v 不小于 mu,其查询距离至少为 max(0, mu − delta)。
只有当整棵子树的下界严格大于 tau,里面才不可能藏着更好的结果。下界等于 tau 时仍要访问,因为其中可能存在距离相同而 ID 更小的记录。代码因此把继续搜索条件写成 lower 不大于 best.distance。每访问一个支点,先根据距离与 ID 更新答案,再计算分支顺序;查询在半径内优先左侧,否则优先右侧,让比较有希望的一边尽早收紧 tau。
优先顺序只影响效率,不影响证明。遍历另一侧之前必须读取当前最佳距离,而不是进入父节点时捕获的旧值。使用旧的较大半径通常导致多访问,不一定漏解,但会使性能判断失真。下面给出完整的单最近邻实现,空索引返回 null,不把无结果伪装成距离为零的记录。
独立示例 5:保存为 example05.cjs。
"use strict";
const assert = require("node:assert/strict");
function lev(a, b) {
if (a.length < b.length) [a, b] = [b, a];
if (!b.length) return a.length;
const row = Array.from({length: b.length + 1}, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diagonal = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const above = row[j];
row[j] = Math.min(above + 1, row[j - 1] + 1,
diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
diagonal = above;
}
}
return row[b.length];
}
function prepare(records) {
if (!Array.isArray(records)) throw new TypeError("records must be an array");
const ids = new Set();
return records.map(r => {
if (!r || !Number.isSafeInteger(r.id) || r.id < 0 ||
typeof r.text !== "string" || ids.has(r.id)) {
throw new TypeError("unique nonnegative safe ID and string required");
}
ids.add(r.id);
return Object.freeze({id: r.id, text: r.text,
cp: Object.freeze(Array.from(r.text))});
});
}
function partitionVP(points) {
if (!points.length) return null;
const vp = points.reduce((a, b) => a.id < b.id ? a : b);
const ranked = points.filter(p => p.id !== vp.id)
.map(p => ({p, radius: lev(vp.cp, p.cp)}))
.sort((a, b) => a.radius - b.radius || a.p.id - b.p.id);
const mid = Math.floor(ranked.length / 2);
const mu = ranked.length ? ranked[mid].radius : 0;
return {vp, mu,
inside: ranked.slice(0, mid).map(x => x.p),
outside: ranked.slice(mid).map(x => x.p)};
}
function build(points) {
const p = partitionVP(points);
return p && Object.freeze({vp: p.vp, mu: p.mu,
inside: build(p.inside), outside: build(p.outside)});
}
function nearest(root, query, stats = {calls: 0}) {
if (typeof query !== "string") throw new TypeError("query must be a string");
const q = Array.from(query);
let best = null;
function visit(node) {
if (!node) return;
stats.calls++;
const delta = lev(q, node.vp.cp);
if (!best || delta < best.distance ||
(delta === best.distance && node.vp.id < best.id)) {
best = {id: node.vp.id, text: node.vp.text, distance: delta};
}
const branches = [
{node: node.inside, lower: Math.max(0, delta - node.mu)},
{node: node.outside, lower: Math.max(0, node.mu - delta)}
];
if (delta >= node.mu) branches.reverse();
for (const branch of branches) {
// Read the latest best after the first recursive call.
if (branch.node && branch.lower <= best.distance) visit(branch.node);
}
}
visit(root);
return best;
}
const records = [{id: 8, text: "book"}, {id: 2, text: "back"},
{id: 5, text: "books"}, {id: 1, text: "cake"}];
const root = build(prepare(records));
assert.equal(nearest(root, "boon").id, 8);
assert.equal(nearest(null, "anything"), null);
console.log(JSON.stringify(nearest(root, "boon")));实际输出:
{"id":8,"text":"book","distance":1}六、用三条记录抓住等号错误
把上一段继续搜索条件中的小于等于改成小于,看上去只是一点优化,却会改变答案。这个反例不需要高维数据,也不需要随机运气:支点为空串,ID 为 0;左侧为 a,ID 为 2;右侧为 aaa,ID 为 1;查询为 aa。支点到查询的距离为 2,中位半径为 3。先访问左侧后得到距离 1 的答案,右侧下界也恰好为 1。
右侧的 aaa 同样距离查询 1,但 ID 更小,因此应该取代 a。严格小于版本在这个地方把整个右子树剪掉,最终给出错误身份。代码保留一个明确标为 brokenNearest 的故障副本,仅用于回归测试;它不是可选择的运行模式,也不应加入正式接口。这比让 AI 再解释一遍三角不等式更有效,因为错误必须在可运行的输入和输出上被看见。
如果产品允许任意并列结果,某些严格边界策略可能另有证明;本文契约要求 ID 最小,不能借用另一种接口语义的优化结论。审查的重点并非背下一个不等号,而是让构造边界、返回规则和剪枝逻辑描述同一个问题。
独立示例 6:保存为 example06.cjs。
"use strict";
const assert = require("node:assert/strict");
function lev(a, b) {
if (a.length < b.length) [a, b] = [b, a];
if (!b.length) return a.length;
const row = Array.from({length: b.length + 1}, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diagonal = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const above = row[j];
row[j] = Math.min(above + 1, row[j - 1] + 1,
diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
diagonal = above;
}
}
return row[b.length];
}
function prepare(records) {
if (!Array.isArray(records)) throw new TypeError("records must be an array");
const ids = new Set();
return records.map(r => {
if (!r || !Number.isSafeInteger(r.id) || r.id < 0 ||
typeof r.text !== "string" || ids.has(r.id)) {
throw new TypeError("unique nonnegative safe ID and string required");
}
ids.add(r.id);
return Object.freeze({id: r.id, text: r.text,
cp: Object.freeze(Array.from(r.text))});
});
}
function partitionVP(points) {
if (!points.length) return null;
const vp = points.reduce((a, b) => a.id < b.id ? a : b);
const ranked = points.filter(p => p.id !== vp.id)
.map(p => ({p, radius: lev(vp.cp, p.cp)}))
.sort((a, b) => a.radius - b.radius || a.p.id - b.p.id);
const mid = Math.floor(ranked.length / 2);
const mu = ranked.length ? ranked[mid].radius : 0;
return {vp, mu,
inside: ranked.slice(0, mid).map(x => x.p),
outside: ranked.slice(mid).map(x => x.p)};
}
function build(points) {
const p = partitionVP(points);
return p && Object.freeze({vp: p.vp, mu: p.mu,
inside: build(p.inside), outside: build(p.outside)});
}
function nearest(root, query, stats = {calls: 0}) {
if (typeof query !== "string") throw new TypeError("query must be a string");
const q = Array.from(query);
let best = null;
function visit(node) {
if (!node) return;
stats.calls++;
const delta = lev(q, node.vp.cp);
if (!best || delta < best.distance ||
(delta === best.distance && node.vp.id < best.id)) {
best = {id: node.vp.id, text: node.vp.text, distance: delta};
}
const branches = [
{node: node.inside, lower: Math.max(0, delta - node.mu)},
{node: node.outside, lower: Math.max(0, node.mu - delta)}
];
if (delta >= node.mu) branches.reverse();
for (const branch of branches) {
// Read the latest best after the first recursive call.
if (branch.node && branch.lower <= best.distance) visit(branch.node);
}
}
visit(root);
return best;
}
function brokenNearest(root, query, stats = {calls: 0}) {
if (typeof query !== "string") throw new TypeError("query must be a string");
const q = Array.from(query);
let best = null;
function visit(node) {
if (!node) return;
stats.calls++;
const delta = lev(q, node.vp.cp);
if (!best || delta < best.distance ||
(delta === best.distance && node.vp.id < best.id)) {
best = {id: node.vp.id, text: node.vp.text, distance: delta};
}
const branches = [
{node: node.inside, lower: Math.max(0, delta - node.mu)},
{node: node.outside, lower: Math.max(0, node.mu - delta)}
];
if (delta >= node.mu) branches.reverse();
for (const branch of branches) {
// Read the latest best after the first recursive call.
if (branch.node && branch.lower < best.distance) visit(branch.node);
}
}
visit(root);
return best;
}
const root = build(prepare([{id: 0, text: ""},
{id: 2, text: "a"}, {id: 1, text: "aaa"}]));
const good = nearest(root, "aa"), bad = brokenNearest(root, "aa");
assert.deepEqual(good, {id: 1, text: "aaa", distance: 1});
assert.equal(bad.id, 2);
console.log("closed boundary ID=" + good.id + "; strict boundary ID=" + bad.id);实际输出:
closed boundary ID=1; strict boundary ID=2
七、重复文本、Unicode 与快照要一起测
业务数据通常不是理想化的互异单词集合。两条内容相同的记录可以有不同来源,空字符串可以是一条有效值,emoji 与组合字符也可能同时出现。下面将这些情况放进同一棵树,用独立的全表扫描结果核对每次查询;两条 emoji 记录距离都为零时,ID 为 3 的记录必须胜出。遇到零距离就立即返回并不普遍安全,因为更小 ID 的零距离记录可能还没被访问。
样例还修改原始数组的一条文本,确认索引继续使用建树时的快照,并验证重复 ID、非整数 ID、非字符串文本与非法查询会被拒绝。这里拒绝重复 ID 不是在拒绝重复内容:ID 承担稳定身份和并列排序职责,而文本决定距离。混淆这两层,常会导致去重逻辑把合法记录吞掉。
独立裁判不会调用被测的 lev、partitionVP 或 nearest,也不使用树的中间状态。它重新拆分原始文本,用递归记忆化求距离,再扫描全部记录排序。它仍然基于同一编辑距离定义,但采用不同控制流和数据结构,能减少两套代码共享同一个实现失误的机会。
独立示例 7:保存为 example07.cjs。
"use strict";
const assert = require("node:assert/strict");
function lev(a, b) {
if (a.length < b.length) [a, b] = [b, a];
if (!b.length) return a.length;
const row = Array.from({length: b.length + 1}, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diagonal = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const above = row[j];
row[j] = Math.min(above + 1, row[j - 1] + 1,
diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
diagonal = above;
}
}
return row[b.length];
}
function prepare(records) {
if (!Array.isArray(records)) throw new TypeError("records must be an array");
const ids = new Set();
return records.map(r => {
if (!r || !Number.isSafeInteger(r.id) || r.id < 0 ||
typeof r.text !== "string" || ids.has(r.id)) {
throw new TypeError("unique nonnegative safe ID and string required");
}
ids.add(r.id);
return Object.freeze({id: r.id, text: r.text,
cp: Object.freeze(Array.from(r.text))});
});
}
function partitionVP(points) {
if (!points.length) return null;
const vp = points.reduce((a, b) => a.id < b.id ? a : b);
const ranked = points.filter(p => p.id !== vp.id)
.map(p => ({p, radius: lev(vp.cp, p.cp)}))
.sort((a, b) => a.radius - b.radius || a.p.id - b.p.id);
const mid = Math.floor(ranked.length / 2);
const mu = ranked.length ? ranked[mid].radius : 0;
return {vp, mu,
inside: ranked.slice(0, mid).map(x => x.p),
outside: ranked.slice(mid).map(x => x.p)};
}
function build(points) {
const p = partitionVP(points);
return p && Object.freeze({vp: p.vp, mu: p.mu,
inside: build(p.inside), outside: build(p.outside)});
}
function nearest(root, query, stats = {calls: 0}) {
if (typeof query !== "string") throw new TypeError("query must be a string");
const q = Array.from(query);
let best = null;
function visit(node) {
if (!node) return;
stats.calls++;
const delta = lev(q, node.vp.cp);
if (!best || delta < best.distance ||
(delta === best.distance && node.vp.id < best.id)) {
best = {id: node.vp.id, text: node.vp.text, distance: delta};
}
const branches = [
{node: node.inside, lower: Math.max(0, delta - node.mu)},
{node: node.outside, lower: Math.max(0, node.mu - delta)}
];
if (delta >= node.mu) branches.reverse();
for (const branch of branches) {
// Read the latest best after the first recursive call.
if (branch.node && branch.lower <= best.distance) visit(branch.node);
}
}
visit(root);
return best;
}
function referenceDistance(left, right) {
const a = [...left], b = [...right];
const memo = new Map();
function solve(i, j) {
if (i === a.length) return b.length - j;
if (j === b.length) return a.length - i;
const key = i + "," + j;
if (memo.has(key)) return memo.get(key);
const answer = a[i] === b[j] ? solve(i + 1, j + 1) :
1 + Math.min(solve(i + 1, j), solve(i, j + 1), solve(i + 1, j + 1));
memo.set(key, answer);
return answer;
}
return solve(0, 0);
}
function brute(records, query) {
const scored = records.map(r => ({id: r.id, text: r.text,
distance: referenceDistance(query, r.text)}));
scored.sort((a, b) => a.distance !== b.distance ?
(a.distance < b.distance ? -1 : 1) : (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
return scored[0] || null;
}
const records = [{id: 9, text: "😀"}, {id: 3, text: "😀"},
{id: 12, text: "é"}, {id: 4, text: "e\u0301"}, {id: 7, text: ""},
{id: 14, text: "👩💻"}, {id: 20, text: "\ud800"}];
const root = build(prepare(records));
for (const q of ["😀", "", "é", "e\u0301", "👩💻", "中", "\ud800"]) {
assert.deepEqual(nearest(root, q), brute(records, q));
}
assert.equal(nearest(root, "😀").id, 3);
records[1].text = "changed after build";
assert.equal(nearest(root, "😀").id, 3);
assert.throws(() => prepare([{id: 1, text: "a"}, {id: 1, text: "b"}]));
assert.throws(() => prepare([{id: 2.5, text: "a"}]));
assert.throws(() => prepare([{id: 1, text: 42}]));
assert.throws(() => nearest(root, null));
console.log("Unicode, zero distance, ID tie, snapshot, validation PASS");实际输出:
Unicode, zero distance, ID tie, snapshot, validation PASS
八、穷举小空间,再用固定种子扩展覆盖面
只展示一个拼写纠错案例,远不足以审查索引正确性。下面穷举长度零至三的所有记录序列,每条文本取自七个短串,允许内容重复;每个集合用全部七个短串查询,总计二千八百次。ID 特意采用非递增顺序,避免测试永远让先遇到的候选天然获胜。这里的穷举范围是明确有限的,不把它描述成对所有可能字符串的证明。
随后加入四百组固定种子的随机数据,每组十次查询,覆盖空集合、重复内容、补充平面字符、组合音标和不同文本长度。与不记录种子的随机测试相比,固定种子能让故障重放;与只比较距离相比,完整对象比较还能发现错误 ID、错误文本或返回值结构变化。这个生成器只是测试工具,不用于密码学或安全随机数。
测试通过说明本文列出的样例、有限穷举域和随机样本都没有发现偏差。它不能承诺任意数据上的运行速度,也不能替代前面的边界证明。若以后调整支点策略、改用选择算法或增加缓存,应保留同一套独立裁判,再新增针对变化的最小反例。
独立示例 8:保存为 example08.cjs。
"use strict";
const assert = require("node:assert/strict");
function lev(a, b) {
if (a.length < b.length) [a, b] = [b, a];
if (!b.length) return a.length;
const row = Array.from({length: b.length + 1}, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diagonal = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const above = row[j];
row[j] = Math.min(above + 1, row[j - 1] + 1,
diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
diagonal = above;
}
}
return row[b.length];
}
function prepare(records) {
if (!Array.isArray(records)) throw new TypeError("records must be an array");
const ids = new Set();
return records.map(r => {
if (!r || !Number.isSafeInteger(r.id) || r.id < 0 ||
typeof r.text !== "string" || ids.has(r.id)) {
throw new TypeError("unique nonnegative safe ID and string required");
}
ids.add(r.id);
return Object.freeze({id: r.id, text: r.text,
cp: Object.freeze(Array.from(r.text))});
});
}
function partitionVP(points) {
if (!points.length) return null;
const vp = points.reduce((a, b) => a.id < b.id ? a : b);
const ranked = points.filter(p => p.id !== vp.id)
.map(p => ({p, radius: lev(vp.cp, p.cp)}))
.sort((a, b) => a.radius - b.radius || a.p.id - b.p.id);
const mid = Math.floor(ranked.length / 2);
const mu = ranked.length ? ranked[mid].radius : 0;
return {vp, mu,
inside: ranked.slice(0, mid).map(x => x.p),
outside: ranked.slice(mid).map(x => x.p)};
}
function build(points) {
const p = partitionVP(points);
return p && Object.freeze({vp: p.vp, mu: p.mu,
inside: build(p.inside), outside: build(p.outside)});
}
function nearest(root, query, stats = {calls: 0}) {
if (typeof query !== "string") throw new TypeError("query must be a string");
const q = Array.from(query);
let best = null;
function visit(node) {
if (!node) return;
stats.calls++;
const delta = lev(q, node.vp.cp);
if (!best || delta < best.distance ||
(delta === best.distance && node.vp.id < best.id)) {
best = {id: node.vp.id, text: node.vp.text, distance: delta};
}
const branches = [
{node: node.inside, lower: Math.max(0, delta - node.mu)},
{node: node.outside, lower: Math.max(0, node.mu - delta)}
];
if (delta >= node.mu) branches.reverse();
for (const branch of branches) {
// Read the latest best after the first recursive call.
if (branch.node && branch.lower <= best.distance) visit(branch.node);
}
}
visit(root);
return best;
}
function referenceDistance(left, right) {
const a = [...left], b = [...right];
const memo = new Map();
function solve(i, j) {
if (i === a.length) return b.length - j;
if (j === b.length) return a.length - i;
const key = i + "," + j;
if (memo.has(key)) return memo.get(key);
const answer = a[i] === b[j] ? solve(i + 1, j + 1) :
1 + Math.min(solve(i + 1, j), solve(i, j + 1), solve(i + 1, j + 1));
memo.set(key, answer);
return answer;
}
return solve(0, 0);
}
function brute(records, query) {
const scored = records.map(r => ({id: r.id, text: r.text,
distance: referenceDistance(query, r.text)}));
scored.sort((a, b) => a.distance !== b.distance ?
(a.distance < b.distance ? -1 : 1) : (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
return scored[0] || null;
}
const words = ["", "a", "b", "aa", "ab", "ba", "bb"];
let exhaustive = 0, random = 0;
function check(records, queries, isRandom) {
const root = build(prepare(records));
for (const q of queries) {
assert.deepEqual(nearest(root, q), brute(records, q));
if (isRandom) random++; else exhaustive++;
}
}
function enumerate(records, depth) {
check(records, words, false);
if (depth === 3) return;
for (const text of words) enumerate([...records,
{id: [9, 1, 5][depth], text}], depth + 1);
}
enumerate([], 0);
let state = 0x5eed1234;
function rand(n) {
state ^= state << 13; state ^= state >>> 17; state ^= state << 5;
return (state >>> 0) % n;
}
const alphabet = ["a", "b", "😀", "é", "\u0301", "中"];
function word() {
const n = rand(6);
return Array.from({length: n}, () => alphabet[rand(alphabet.length)]).join("");
}
for (let trial = 0; trial < 400; trial++) {
const bag = Array.from({length: rand(30)}, (_, i) => ({id: 100 - i, text: word()}));
if (bag.length > 1) bag[1].text = bag[0].text;
check(bag, Array.from({length: 10}, word), true);
}
console.log("exhaustive=" + exhaustive + " random=" + random + " PASS");实际输出:
exhaustive=2800 random=4000 PASS
九、树高是对数,不代表查询必然是对数
最容易被 AI 的解释带偏的地方,是把平衡树高度直接当成查询复杂度。最近邻搜索可能同时访问两边,所以最坏情况下仍会访问全部 n 个节点。下面把所有文本设为 a,查询也为 a;每个半径和每个下界都为零,闭边界策略会访问全部节点。三组输出分别是三十一、一百二十七、五百一十一次查询距离计算。它们只统计查询阶段,不混入构建开销,也不拿机器耗时伪装成可移植的性能结论。
这个具体重复数据例子可以再利用全局最小 ID 与零距离等信息提前结束,但本文没有加入这种额外优化;示例证明的是当前实现确实会线性访问,而不是声称任何实现对重复数据都无法优化。一般度量数据上的最坏线性访问风险仍不能靠平衡性消除。Yianilos 的 VP-tree 原始研究作者上传页也把对数期望搜索表现放在特定条件下讨论,不能简化为无条件保证。
还要把一次距离调用的真实成本算回来。查询码点长度为 m,访问记录的码点长度为 li,本实现查询总时间可写成 O(m + V + Σ m·li),求和只覆盖被访问的 V 条记录;空串通过快捷返回处理。两个非空长度 m、li 的滚动动态规划仍需要 O(m·li) 时间,辅助行空间为 O(min(m,li))。树索引保存全部文本码点,空间为 O(n + Σ li),查询还需要查询数组、递归栈及当前动态规划工作区。
构造方面,每层重新计算相对当前支点的距离,平衡递归合计 O(n log n) 次距离调用;这些调用也必须乘上各自字符串长度的代价。本文每层使用完整排序,在通常 O(s log s) 比较排序成本模型下,还会累计 O(n log² n) 的排序工作,不能照搬采用线性选择划分的实现所对应的构建时间。缓存码点减少重复解码,却不会让编辑距离变成常数时间。面对很小的数据集、很长的文本或剪枝很弱的分布,应实际比较全表扫描与建树加查询的总成本,再决定是否采用索引。
独立示例 9:保存为 example09.cjs。
"use strict";
const assert = require("node:assert/strict");
function lev(a, b) {
if (a.length < b.length) [a, b] = [b, a];
if (!b.length) return a.length;
const row = Array.from({length: b.length + 1}, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diagonal = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const above = row[j];
row[j] = Math.min(above + 1, row[j - 1] + 1,
diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
diagonal = above;
}
}
return row[b.length];
}
function prepare(records) {
if (!Array.isArray(records)) throw new TypeError("records must be an array");
const ids = new Set();
return records.map(r => {
if (!r || !Number.isSafeInteger(r.id) || r.id < 0 ||
typeof r.text !== "string" || ids.has(r.id)) {
throw new TypeError("unique nonnegative safe ID and string required");
}
ids.add(r.id);
return Object.freeze({id: r.id, text: r.text,
cp: Object.freeze(Array.from(r.text))});
});
}
function partitionVP(points) {
if (!points.length) return null;
const vp = points.reduce((a, b) => a.id < b.id ? a : b);
const ranked = points.filter(p => p.id !== vp.id)
.map(p => ({p, radius: lev(vp.cp, p.cp)}))
.sort((a, b) => a.radius - b.radius || a.p.id - b.p.id);
const mid = Math.floor(ranked.length / 2);
const mu = ranked.length ? ranked[mid].radius : 0;
return {vp, mu,
inside: ranked.slice(0, mid).map(x => x.p),
outside: ranked.slice(mid).map(x => x.p)};
}
function build(points) {
const p = partitionVP(points);
return p && Object.freeze({vp: p.vp, mu: p.mu,
inside: build(p.inside), outside: build(p.outside)});
}
function nearest(root, query, stats = {calls: 0}) {
if (typeof query !== "string") throw new TypeError("query must be a string");
const q = Array.from(query);
let best = null;
function visit(node) {
if (!node) return;
stats.calls++;
const delta = lev(q, node.vp.cp);
if (!best || delta < best.distance ||
(delta === best.distance && node.vp.id < best.id)) {
best = {id: node.vp.id, text: node.vp.text, distance: delta};
}
const branches = [
{node: node.inside, lower: Math.max(0, delta - node.mu)},
{node: node.outside, lower: Math.max(0, node.mu - delta)}
];
if (delta >= node.mu) branches.reverse();
for (const branch of branches) {
// Read the latest best after the first recursive call.
if (branch.node && branch.lower <= best.distance) visit(branch.node);
}
}
visit(root);
return best;
}
for (const n of [31, 127, 511]) {
const root = build(prepare(Array.from({length: n}, (_, id) => ({id, text: "a"}))));
const stats = {calls: 0};
const answer = nearest(root, "a", stats);
assert.equal(answer.id, 0);
assert.equal(answer.distance, 0);
assert.equal(stats.calls, n);
console.log("n=" + n + " queryDistanceCalls=" + stats.calls);
}实际输出:
n=31 queryDistanceCalls=31 n=127 queryDistanceCalls=127 n=511 queryDistanceCalls=511
把 AI 生成代码的审查,变成一份可执行的证据链
这份实现的核心不是树的名字,而是四个互相咬合的约定:距离按明确的码点序列计算;中位切分按排名保证规模,同时允许边界重复;三角不等式导出的下界必须保守;并列规则要求相等边界仍被搜索。任何一个约定改变,都应该回到相关证明和测试,而不是只改一行代码再看普通案例是否还通过。
实际审查时,可以让 AI 先列出每个节点的不变量,再说明每次剪枝排除的集合,最后交出一个能让错误版本失败的最小测试。人负责判断契约与证明是否一致,程序负责穷举和重放。这样得到的不是一句泛泛的可用评价,而是一组读者能独立运行、能在未来改动后继续保护结果的检查。

