AI 代码审查实战:JavaScript 最长公共子序列与可重放差异脚本
让 AI 写一个 diff 很容易,让结果在重复元素、并列最优解和输入变化之后仍然可信,才是代码审查的难点。本文实现一个小而完整的序列差异器:输入是两组原始字符串令牌,输出包含保留、删除、插入三类记录,记录可以被独立重放。审查目标不只是一串漂亮的红绿标记,还包括最少编辑数、稳定选择、资源上限,以及调用者能否意外改坏结果。

运行环境为 Node.js v24.19.0。下文恰好九个 JavaScript 示例,每个都包含自己需要的函数和断言,可以独立复制执行,不依赖上一段留下的变量或本地模块。全部采用严格语言模式与 node:assert/strict,并使用 --unhandled-rejections=strict 启动;后一个开关处理未捕获的 Promise 拒绝,与脚本里的严格语言模式是两回事。本算法是同步函数,示例没有把异步等待或定时器混进测试。
一、先区分序列差异和集合差异
假设旧版本依次包含 A、B、A,新版本包含 A、B。按集合求差,两个集合拥有相同成员,看不出任何删除;按位置逐项比较,又容易把一次前置插入误报为整段变化。真正需要保留的是出现次数和相对次序。相同内容重复出现时,每次出现都占据一个独立位置,不能先去重再计算。第一个反例故意展示错误结果,再用人工可核查的三步脚本说明缺失的信息。
示例 1:保存为 01.cjs,单独运行 node --unhandled-rejections=strict 01.cjs。
"use strict";
const assert = require("node:assert/strict");
const before = ["A", "B", "A"];
const after = ["A", "B"];
const wrong = before.filter(x => !new Set(after).has(x));
assert.deepEqual(wrong, []);
assert.notDeepEqual(before, after);
const script = [
{ op: "keep", atA: 0, atB: 0, token: "A" },
{ op: "keep", atA: 1, atB: 1, token: "B" },
{ op: "delete", atA: 2, atB: 2, token: "A" }
];
assert.equal(script.filter(x => x.op !== "keep").length, 1);
console.log("set-difference-loses-duplicates", wrong.length, script.length);实际输出:
set-difference-loses-duplicates 0 3
本设计只让插入和删除计费,每次成本为一;保留成本为零,没有替换指令,也没有移动指令。把一个不同令牌换成另一个,要先删除再插入,成本为二。目标是令牌序列的最短增删脚本,不是允许单位成本替换的 Levenshtein 距离。界面可以把相邻的一删一增绘成一次修改,但这只是展示层分组,不能反过来改变算法的代价模型。
最长公共子序列简称 LCS。它保持原来的先后顺序,却允许跳过中间元素;这与必须连续的公共子串不同,概念定义可查阅 NIST 的最长公共子序列条目。若源长为 m、目标长为 n,保留了 k 个元素,必然删除 m−k 个并插入 n−k 个,所以编辑数是 m+n−2k。要最少编辑,就要最大化保留数。这一计数推导同时给了我们测试时可以独立检查的关系。
二、把输入契约落实到字符串和数组槽位
这里的一个令牌就是一个完整的原始字符串,既可以是一行代码,也可以是一个词或调用方已经拆好的片段。函数不分词、不修剪空白、不折叠大小写,也不执行 Unicode 规范化。空字符串是合法令牌,空数组才表示没有令牌。两个外观相同的字符串若码元序列不同,就视为不同;孤立代理项也原样接受。换行符是否留在行令牌中、文件末尾有没有换行,必须由上游的令牌化策略明确决定。
ECMAScript 的 String 类型定义以 UTF-16 码元序列描述字符串,严格相等比较规范说明原始字符串比较最终要求长度及各位置码元相同。因此实现使用 ===,不接受 String 包装对象,也不通过 String(value) 偷偷进行类型转换。这里比较的是令牌值;一个包含多个码点的表情令牌仍然只占一个序列位置。
数组必须有连续的自有数据属性。稀疏洞、继承而来的数字属性和访问器槽位会被拒绝;读取描述符再取 value,可以避免调用普通数组的元素 getter。函数复制槽位中的原始字符串,不借用调用者数组,额外的非索引属性不参与算法。这个契约以普通、非代理的数组以及未被改写的内建对象为前提:Proxy 可以拦截 length 或描述符操作,本教程不把输入检查宣传成对恶意对象的安全隔离。
示例 2:保存为 02.cjs,单独运行 node --unhandled-rejections=strict 02.cjs。
"use strict";
const assert = require("node:assert/strict");
function snapshot(input) {
if (!Array.isArray(input)) throw new TypeError("array required");
const n = input.length;
if (n > 255) throw new RangeError("token count");
const copy = [];
let units = 0;
for (let i = 0; i < n; i++) {
const d = Object.getOwnPropertyDescriptor(input, String(i));
if (!d || !Object.hasOwn(d, "value") || typeof d.value !== "string") {
throw new TypeError("own primitive string required");
}
const s = d.value;
if (s.length > 1024 || (units += s.length) > 65536) {
throw new RangeError("string budget");
}
copy.push(s);
}
return copy;
}
let calls = 0;
const accessor = [];
Object.defineProperty(accessor, "0", { get() { calls++; return "A"; } });
for (const bad of ["A", [1], [new String("A")], Array(1), accessor]) {
assert.throws(() => snapshot(bad), TypeError);
}
assert.equal(calls, 0);
const tokens = ["", "é", "e\u0301", "\ud800", "👩💻"];
const saved = snapshot(tokens);
tokens[0] = "changed";
assert.equal(saved[0], "");
assert.notEqual(saved[1], saved[2]);
assert.equal(saved[3].length, 1);
assert.equal(saved.length, 5);
console.log("exact-tokens", saved.length, "getter-calls", calls);实际输出:
exact-tokens 5 getter-calls 0
三、后缀表保存最优长度,路径选择另行规定
令 table[i,j] 表示源序列从 i 开始、目标从 j 开始的两个后缀的 LCS 长度。任意一边耗尽时,剩余公共长度为零;因此需要多出一行和一列零边界。若当前位置令牌相同,保留这一对,再加右下后缀的最优值;否则在跳过源令牌与跳过目标令牌两种可能中取较大值。从右下往左上填充,读取的依赖已经计算完成。
相等时匹配当前两个首元素是安全的:总能选到一个包含这对首元素的最优公共子序列,而不降低长度。不同的时候则没有这条捷径,必须比较两个后缀。表格本身只保存长度,不会决定相同最优长度的两条路该选哪条。下面的 A、B 与 B、A 正好制造平局,两种方向都能保留一个令牌,因而最优数值不足以唯一确定脚本。
示例 3:保存为 03.cjs,单独运行 node --unhandled-rejections=strict 03.cjs。
"use strict";
const assert = require("node:assert/strict");
const a = ["A", "B"], b = ["B", "A"];
const w = b.length + 1;
const t = new Uint16Array((a.length + 1) * w);
const at = (i, j) => t[i * w + j];
for (let i = a.length - 1; i >= 0; i--) {
for (let j = b.length - 1; j >= 0; j--) {
t[i * w + j] = a[i] === b[j]
? 1 + at(i + 1, j + 1)
: Math.max(at(i + 1, j), at(i, j + 1));
}
}
assert.equal(t[0], 1);
assert.equal(at(1, 0), at(0, 1));
assert.deepEqual([...t], [1, 1, 0, 1, 0, 0, 0, 0, 0]);
console.log("suffix-table", JSON.stringify([...t]), "tie=delete");实际输出:
suffix-table [1,1,0,1,0,0,0,0,0] tie=delete
为了让同一输入在重复运行、快照测试和代码评审中保持一致,规定如下:当前令牌相等就立即 keep;不等时选择能留下更长公共后缀的方向;两方向同长时优先 delete;一边耗尽就顺序处理另一边。删除优先只适用于不相等时的并列选择,并不意味着看见重复令牌就尽量删除。它也不保证文字 diff 的分块最符合人的阅读习惯,只保证该契约下的确定性。
四、实现可以重放的三类操作
每条记录保存 op、atA、atB、token 四个字段。atA 是执行该操作之前已经消耗的源令牌数;atB 是已经生成的目标令牌数。keep 同时推进两个游标,delete 只推进源游标,insert 只推进目标游标。这是双游标的流式坐标,不是对不断被 splice 修改的数组使用同一个下标。记录同时带值,可以在重放时核对被消耗的源令牌,避免把一份脚本静默用到另一个版本。
下面给出完整生成器。先完成两边快照和预算验证,再分配动态规划表。Uint16Array 每个格子占两个字节,值域足以容纳本契约最大公共长度。生成路径从左上走到右下,任何一步都至少推进一个游标,因此必然结束。结果外壳、操作数组、每个操作对象分别冻结;仅冻结最外层对象是不够的,因为调用方仍可能改写内层字段。
示例 4:保存为 04.cjs,单独运行 node --unhandled-rejections=strict 04.cjs。
"use strict";
const assert = require("node:assert/strict");
function snapshot(input) {
if (!Array.isArray(input)) throw new TypeError("array required");
const n = input.length;
if (n > 255) throw new RangeError("token count");
const copy = [];
let units = 0;
for (let i = 0; i < n; i++) {
const d = Object.getOwnPropertyDescriptor(input, String(i));
if (!d || !Object.hasOwn(d, "value") || typeof d.value !== "string") {
throw new TypeError("own primitive string required");
}
const s = d.value;
if (s.length > 1024 || (units += s.length) > 65536) {
throw new RangeError("string budget");
}
copy.push(s);
}
return copy;
}
function diff(left, right) {
const a = snapshot(left), b = snapshot(right);
const m = a.length, n = b.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 16384) throw new RangeError("cell budget");
const table = new Uint16Array(cells);
const at = (i, j) => table[i * width + j];
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
table[i * width + j] = a[i] === b[j]
? 1 + at(i + 1, j + 1)
: Math.max(at(i + 1, j), at(i, j + 1));
}
}
const steps = [];
let i = 0, j = 0;
const add = (op, token) => steps.push(Object.freeze({
op, atA: i, atB: j, token
}));
while (i < m || j < n) {
if (i < m && j < n && a[i] === b[j]) {
add("keep", a[i]); i++; j++;
} else if (i < m && (j === n || at(i + 1, j) >= at(i, j + 1))) {
add("delete", a[i]); i++;
} else {
add("insert", b[j]); j++;
}
}
return Object.freeze({
lcs: table[0], edits: m + n - 2 * table[0],
steps: Object.freeze(steps)
});
}
const result = diff(["A", "B"], ["B", "A"]);
assert.equal(result.lcs, 1);
assert.equal(result.edits, 2);
assert.deepEqual(result.steps, [
{ op: "delete", atA: 0, atB: 0, token: "A" },
{ op: "keep", atA: 1, atB: 0, token: "B" },
{ op: "insert", atA: 2, atB: 1, token: "A" }
]);
console.log(JSON.stringify(result));实际输出:
{"lcs":1,"edits":2,"steps":[{"op":"delete","atA":0,"atB":0,"token":"A"},{"op":"keep","atA":1,"atB":0,"token":"B"},{"op":"insert","atA":2,"atB":1,"token":"A"}]}在这个例子里,首步删除源 A,接着保留 B,最后插入目标 A。第三步的 atA 为二,因为源已经耗尽;atB 为一,因为目前只生成了 B。这些数字描述执行前的状态,不能把 atA 当成目标插入位置。lcs 是保留数,edits 是非 keep 操作数,steps 的长度则同时包含保留步骤。三者用途不同,日志或监控里应明确字段含义,避免把完整脚本长度误报成修改次数。
五、重放必须验证消费状态,不能只过滤插入和保留
最短性与可执行性是两条独立的正确性要求。只计算出正确编辑数,无法保证坐标没写反;只重放出正确目标,也无法证明没有多余删插。重放器按自己的游标解释记录,每步检查操作名、字段、当前坐标以及被消费的源值,最后要求源刚好全部消费。结果在一个新数组内逐步构建,失败时抛错,原始源数组始终不变。
这个检查器也设置步数和目标预算,避免有人提供一个很长的伪脚本绕开生成器限制。它拒绝槽位或必需字段的 getter,但与生成器一样不支持恶意 Proxy;额外字段被忽略。它只验证结构和重放一致性,不把脚本当作有签名的证据,也不会证明脚本最优。攻击者若提供另一份结构合法、插入值不同的脚本,依然能生成另一目标;若业务需要校验指定目标,还必须把重放结果与该目标比较。
示例 5:保存为 05.cjs,单独运行 node --unhandled-rejections=strict 05.cjs。
"use strict";
const assert = require("node:assert/strict");
function snapshot(input) {
if (!Array.isArray(input)) throw new TypeError("array required");
const n = input.length;
if (n > 255) throw new RangeError("token count");
const copy = [];
let units = 0;
for (let i = 0; i < n; i++) {
const d = Object.getOwnPropertyDescriptor(input, String(i));
if (!d || !Object.hasOwn(d, "value") || typeof d.value !== "string") {
throw new TypeError("own primitive string required");
}
const s = d.value;
if (s.length > 1024 || (units += s.length) > 65536) {
throw new RangeError("string budget");
}
copy.push(s);
}
return copy;
}
function replay(source, steps) {
const a = snapshot(source);
if (!Array.isArray(steps)) throw new TypeError("script array required");
if (steps.length > 510) throw new RangeError("step budget");
const out = [];
let i = 0, units = 0;
for (let k = 0; k < steps.length; k++) {
const d = Object.getOwnPropertyDescriptor(steps, String(k));
if (!d || !Object.hasOwn(d, "value") ||
d.value === null || typeof d.value !== "object") {
throw new TypeError("step record required");
}
const read = key => {
const p = Object.getOwnPropertyDescriptor(d.value, key);
if (!p || !Object.hasOwn(p, "value")) throw new TypeError("data field required");
return p.value;
};
const op = read("op"), x = read("atA"), y = read("atB"), token = read("token");
if (!["keep", "delete", "insert"].includes(op) ||
!Number.isInteger(x) || !Number.isInteger(y) ||
x !== i || y !== out.length || typeof token !== "string") {
throw new TypeError("invalid operation");
}
if (token.length > 1024) throw new RangeError("token budget");
if (op !== "insert") {
if (i === a.length || a[i] !== token) throw new Error("source mismatch");
i++;
}
if (op !== "delete") {
if (out.length === 255 || (units += token.length) > 65536) {
throw new RangeError("target budget");
}
out.push(token);
}
}
if (i !== a.length) throw new Error("unconsumed source");
return Object.freeze(out);
}
const source = ["A", "B"];
const steps = [
{ op: "delete", atA: 0, atB: 0, token: "A" },
{ op: "keep", atA: 1, atB: 0, token: "B" },
{ op: "insert", atA: 2, atB: 1, token: "A" }
];
assert.deepEqual(replay(source, steps), ["B", "A"]);
assert.throws(() => replay(source, steps.slice(1)), /invalid operation/);
assert.throws(() => replay(["X", "B"], steps), /source mismatch/);
assert.throws(() => replay(source, steps.slice(0, 1)), /unconsumed/);
const tampered = steps.map(x => ({ ...x }));
tampered[2].op = "replace";
assert.throws(() => replay(source, tampered), /invalid operation/);
assert.deepEqual(source, ["A", "B"]);
console.log("replay", JSON.stringify(replay(source, steps)), "four-corruptions-rejected");实际输出:
replay ["B","A"] four-corruptions-rejected
删除第一步后直接从第二步开始,会首先触发游标不匹配;换一个源版本,会触发源值不匹配;只运行第一步,会留下未消费的源;伪造 replace 操作则不在允许的指令集合里。断言验证的是预期失败,而不是仅观察程序是否打印了错误。对于外部持久化脚本,保存原始源版本标识和算法契约版本有助于排查错误,但版本标识的认证、存储权限与并发控制属于应用层的另一项工作。
六、所有权与空输入同样需要测试
原始字符串不可变,所以复制数组槽位后不需要再复制字符串的内部字符。调用者之后重新赋值输入数组元素,不应影响已经生成的操作;两个调用得到的结果对象也应互不相同,即使内容完全相等。另一方面,冻结不会自动递归处理嵌套结构,详见 Object.freeze 的规范算法。本实现逐层冻结自己创建的可变容器,且操作字段中不保存可变业务对象。
冻结不是访问控制,也不提供文件版本的真实性保证。本教程要解决的是同进程调用方误改共享数据的问题。严格语言模式使修改冻结属性的行为明确抛出异常,因此测试能够用 TypeError 验证拒绝效果。空输入也要走正式路径:两个空数组得到零编辑和空脚本;一个空令牌对另一个空令牌则必须保留一次,不能被基于真值的分支误删。
示例 6:保存为 06.cjs,单独运行 node --unhandled-rejections=strict 06.cjs。
"use strict";
const assert = require("node:assert/strict");
function snapshot(input) {
if (!Array.isArray(input)) throw new TypeError("array required");
const n = input.length;
if (n > 255) throw new RangeError("token count");
const copy = [];
let units = 0;
for (let i = 0; i < n; i++) {
const d = Object.getOwnPropertyDescriptor(input, String(i));
if (!d || !Object.hasOwn(d, "value") || typeof d.value !== "string") {
throw new TypeError("own primitive string required");
}
const s = d.value;
if (s.length > 1024 || (units += s.length) > 65536) {
throw new RangeError("string budget");
}
copy.push(s);
}
return copy;
}
function diff(left, right) {
const a = snapshot(left), b = snapshot(right);
const m = a.length, n = b.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 16384) throw new RangeError("cell budget");
const table = new Uint16Array(cells);
const at = (i, j) => table[i * width + j];
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
table[i * width + j] = a[i] === b[j]
? 1 + at(i + 1, j + 1)
: Math.max(at(i + 1, j), at(i, j + 1));
}
}
const steps = [];
let i = 0, j = 0;
const add = (op, token) => steps.push(Object.freeze({
op, atA: i, atB: j, token
}));
while (i < m || j < n) {
if (i < m && j < n && a[i] === b[j]) {
add("keep", a[i]); i++; j++;
} else if (i < m && (j === n || at(i + 1, j) >= at(i, j + 1))) {
add("delete", a[i]); i++;
} else {
add("insert", b[j]); j++;
}
}
return Object.freeze({
lcs: table[0], edits: m + n - 2 * table[0],
steps: Object.freeze(steps)
});
}
function replay(source, steps) {
const a = snapshot(source);
if (!Array.isArray(steps)) throw new TypeError("script array required");
if (steps.length > 510) throw new RangeError("step budget");
const out = [];
let i = 0, units = 0;
for (let k = 0; k < steps.length; k++) {
const d = Object.getOwnPropertyDescriptor(steps, String(k));
if (!d || !Object.hasOwn(d, "value") ||
d.value === null || typeof d.value !== "object") {
throw new TypeError("step record required");
}
const read = key => {
const p = Object.getOwnPropertyDescriptor(d.value, key);
if (!p || !Object.hasOwn(p, "value")) throw new TypeError("data field required");
return p.value;
};
const op = read("op"), x = read("atA"), y = read("atB"), token = read("token");
if (!["keep", "delete", "insert"].includes(op) ||
!Number.isInteger(x) || !Number.isInteger(y) ||
x !== i || y !== out.length || typeof token !== "string") {
throw new TypeError("invalid operation");
}
if (token.length > 1024) throw new RangeError("token budget");
if (op !== "insert") {
if (i === a.length || a[i] !== token) throw new Error("source mismatch");
i++;
}
if (op !== "delete") {
if (out.length === 255 || (units += token.length) > 65536) {
throw new RangeError("target budget");
}
out.push(token);
}
}
if (i !== a.length) throw new Error("unconsumed source");
return Object.freeze(out);
}
const a = ["旧", "共同"], b = ["共同", "新"];
const result = diff(a, b);
const oldSource = a.slice();
a[0] = "later"; b[1] = "later";
assert.deepEqual(replay(oldSource, result.steps), ["共同", "新"]);
assert.throws(() => { result.steps[0].token = "bad"; }, TypeError);
assert.throws(() => result.steps.push({}), TypeError);
assert.throws(() => { result.edits = 99; }, TypeError);
const again = diff(oldSource, ["共同", "新"]);
assert.notEqual(result, again);
assert.notEqual(result.steps, again.steps);
assert.deepEqual(result, again);
assert.deepEqual(diff([], []).steps, []);
assert.deepEqual(diff([""], [""]).steps.map(x => x.op), ["keep"]);
console.log("ownership-and-empty-cases-pass");实际输出:
ownership-and-empty-cases-pass
七、预算是接口的一部分,不是分配失败后的补救
每边最多二百五十五个令牌,每个令牌最多一千零二十四个 UTF-16 码元,每边所有令牌合计最多六万五千五百三十六码元。矩阵最多一万六千三百八十四个格子,含零边界;这些限制都在相应大表分配之前检查。两个一百二十七长度的序列刚好需要一百二十八乘一百二十八个格子,可以通过;任意一边增加一个令牌,就越过这个边界。限制不是可配置选项,免去了选项对象和预算互相覆盖的额外语义。
矩阵的元素存储最多三万二千七百六十八字节,但这不是整个函数的堆内存承诺:还存在字符串的引擎表示、快照数组、操作对象及运行时开销。循环最多执行 m×n 次比较;若把原始字符串比较按最长令牌长度 L 保守计费,工作量可表述为 O(mn(1+L)+m+n),不能无条件宣称字符串相等判断恒为常数时间。矩阵空间为 O(mn),快照和脚本为 O(m+n);本实现没有异步让出执行权,所以它适合有明确规模上限的同步计算。
边界测试要同时包含恰好等于限制和刚好多一单位的情况,且分开测试矩阵、令牌数、单令牌长度和总码元数。否则某一项先抛错,可能掩盖另一项根本没有验证的缺陷。下面对单边空序列执行长令牌和总量测试,故意避开矩阵上限的干扰。类型错误使用 TypeError,合法类型但超出预算使用 RangeError,错误文本帮助定位,不被当作版本稳定的公共枚举。
示例 7:保存为 07.cjs,单独运行 node --unhandled-rejections=strict 07.cjs。
"use strict";
const assert = require("node:assert/strict");
function snapshot(input) {
if (!Array.isArray(input)) throw new TypeError("array required");
const n = input.length;
if (n > 255) throw new RangeError("token count");
const copy = [];
let units = 0;
for (let i = 0; i < n; i++) {
const d = Object.getOwnPropertyDescriptor(input, String(i));
if (!d || !Object.hasOwn(d, "value") || typeof d.value !== "string") {
throw new TypeError("own primitive string required");
}
const s = d.value;
if (s.length > 1024 || (units += s.length) > 65536) {
throw new RangeError("string budget");
}
copy.push(s);
}
return copy;
}
function diff(left, right) {
const a = snapshot(left), b = snapshot(right);
const m = a.length, n = b.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 16384) throw new RangeError("cell budget");
const table = new Uint16Array(cells);
const at = (i, j) => table[i * width + j];
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
table[i * width + j] = a[i] === b[j]
? 1 + at(i + 1, j + 1)
: Math.max(at(i + 1, j), at(i, j + 1));
}
}
const steps = [];
let i = 0, j = 0;
const add = (op, token) => steps.push(Object.freeze({
op, atA: i, atB: j, token
}));
while (i < m || j < n) {
if (i < m && j < n && a[i] === b[j]) {
add("keep", a[i]); i++; j++;
} else if (i < m && (j === n || at(i + 1, j) >= at(i, j + 1))) {
add("delete", a[i]); i++;
} else {
add("insert", b[j]); j++;
}
}
return Object.freeze({
lcs: table[0], edits: m + n - 2 * table[0],
steps: Object.freeze(steps)
});
}
const rows = Array(127).fill("x");
assert.equal(diff(rows, rows).lcs, 127); // 128 * 128 = 16384
assert.throws(() => diff(Array(128).fill("x"), rows), /cell budget/);
assert.equal(diff(Array(255).fill("x"), []).edits, 255);
assert.throws(() => diff(Array(256).fill("x"), []), /token count/);
assert.equal(diff(["x".repeat(1024)], []).edits, 1);
assert.throws(() => diff(["x".repeat(1025)], []), /string budget/);
const full = Array(64).fill("x".repeat(1024));
assert.equal(diff(full, []).edits, 64); // 65536 UTF-16 code units
assert.throws(() => diff([...full, "x"], []), /string budget/);
console.log("resource-boundaries-pass", 16384, 32768);实际输出:
resource-boundaries-pass 16384 32768
八、用不同思路构造独立穷举预言机
AI 很容易生成另一份动态规划作为测试,然后把原实现同样的边界错误复制一遍。这里换一种非常慢但容易检查的方法:枚举源序列的所有子序列,再用单向扫描判断它是否也是目标的子序列,记录能够匹配的最大长度。这个预言机不建立动态规划表、不使用原来的递推式,也不引用原生成器返回的 lcs。它与被测实现共享字符串相等规则,因为这是规格本身,而不是待验证的算法步骤。
测试空间采用两个令牌组成的所有长度零到五的序列,共六十三种;两两配对是三千九百六十九组。重复令牌、空序列、完全不相交与多条最优路径都会出现。每组分别检查最优长度、最少编辑数、实际重放目标、keep 计数以及重复调用的稳定性。穷举的是这个有限空间,不能据此宣称已经覆盖任意长度输入;其价值在于边界组合齐全、失败案例可重现,而且预言机足够独立。
示例 8:保存为 08.cjs,单独运行 node --unhandled-rejections=strict 08.cjs。
"use strict";
const assert = require("node:assert/strict");
function snapshot(input) {
if (!Array.isArray(input)) throw new TypeError("array required");
const n = input.length;
if (n > 255) throw new RangeError("token count");
const copy = [];
let units = 0;
for (let i = 0; i < n; i++) {
const d = Object.getOwnPropertyDescriptor(input, String(i));
if (!d || !Object.hasOwn(d, "value") || typeof d.value !== "string") {
throw new TypeError("own primitive string required");
}
const s = d.value;
if (s.length > 1024 || (units += s.length) > 65536) {
throw new RangeError("string budget");
}
copy.push(s);
}
return copy;
}
function diff(left, right) {
const a = snapshot(left), b = snapshot(right);
const m = a.length, n = b.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 16384) throw new RangeError("cell budget");
const table = new Uint16Array(cells);
const at = (i, j) => table[i * width + j];
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
table[i * width + j] = a[i] === b[j]
? 1 + at(i + 1, j + 1)
: Math.max(at(i + 1, j), at(i, j + 1));
}
}
const steps = [];
let i = 0, j = 0;
const add = (op, token) => steps.push(Object.freeze({
op, atA: i, atB: j, token
}));
while (i < m || j < n) {
if (i < m && j < n && a[i] === b[j]) {
add("keep", a[i]); i++; j++;
} else if (i < m && (j === n || at(i + 1, j) >= at(i, j + 1))) {
add("delete", a[i]); i++;
} else {
add("insert", b[j]); j++;
}
}
return Object.freeze({
lcs: table[0], edits: m + n - 2 * table[0],
steps: Object.freeze(steps)
});
}
function replay(source, steps) {
const a = snapshot(source);
if (!Array.isArray(steps)) throw new TypeError("script array required");
if (steps.length > 510) throw new RangeError("step budget");
const out = [];
let i = 0, units = 0;
for (let k = 0; k < steps.length; k++) {
const d = Object.getOwnPropertyDescriptor(steps, String(k));
if (!d || !Object.hasOwn(d, "value") ||
d.value === null || typeof d.value !== "object") {
throw new TypeError("step record required");
}
const read = key => {
const p = Object.getOwnPropertyDescriptor(d.value, key);
if (!p || !Object.hasOwn(p, "value")) throw new TypeError("data field required");
return p.value;
};
const op = read("op"), x = read("atA"), y = read("atB"), token = read("token");
if (!["keep", "delete", "insert"].includes(op) ||
!Number.isInteger(x) || !Number.isInteger(y) ||
x !== i || y !== out.length || typeof token !== "string") {
throw new TypeError("invalid operation");
}
if (token.length > 1024) throw new RangeError("token budget");
if (op !== "insert") {
if (i === a.length || a[i] !== token) throw new Error("source mismatch");
i++;
}
if (op !== "delete") {
if (out.length === 255 || (units += token.length) > 65536) {
throw new RangeError("target budget");
}
out.push(token);
}
}
if (i !== a.length) throw new Error("unconsumed source");
return Object.freeze(out);
}
function bruteLcs(a, b) {
let best = 0;
for (let mask = 0; mask < 2 ** a.length; mask++) {
const candidate = a.filter((_, i) => (mask & (1 << i)) !== 0);
let k = 0;
for (const token of b) {
if (k < candidate.length && candidate[k] === token) k++;
}
if (k === candidate.length) best = Math.max(best, k);
}
return best;
}
function words(max) {
const all = [[]];
let level = [[]];
for (let n = 1; n <= max; n++) {
level = level.flatMap(x => [x.concat("A"), x.concat("B")]);
all.push(...level);
}
return all;
}
const all = words(5);
let pairs = 0;
for (const a of all) for (const b of all) {
const result = diff(a, b), expected = bruteLcs(a, b);
assert.equal(result.lcs, expected);
assert.equal(result.edits, a.length + b.length - 2 * expected);
assert.deepEqual(replay(a, result.steps), b);
assert.equal(result.steps.filter(x => x.op === "keep").length, expected);
assert.equal(result.steps.filter(x => x.op !== "keep").length, result.edits);
assert.deepEqual(diff(a, b), result);
pairs++;
}
assert.equal(pairs, 3969);
console.log("exhaustive-pairs", pairs);实际输出:
exhaustive-pairs 3969
位掩码预言机刻意只用于很短的测试序列。JavaScript 的位运算会转换为三十二位整数,这里的最大长度只有五,因此移位安全;不要把它直接推广到产品上限二百五十五,也不要为了统一架构把它和动态规划包装成同一个内部助手。测试代码应保留不同的推理路线。至于确定性平局,长度预言机不会给出唯一规范脚本,因此还需要前文明确写出的操作顺序断言来约束选择。
九、补上性质测试,说明算法承诺的边界
小规模穷举擅长找组合错误,固定种子的性质测试则可以加入更丰富的令牌内容。下面包含空字符串、组合形式不同的重音字符、孤立代理项、多个码点组成的表情和含空码元的字符串。除了重放,还验证前后方向编辑数相同、与自身比较编辑数为零、两边增加同一个新前缀后编辑数不变。随机生成器是确定性的整数递推,失败可依靠相同种子复现,不依赖时间或外部服务。
这些性质约束数值和语义,不要求反向 diff 的操作数组等于正向数组倒序。删除优先是有方向性的规则,交换两边以后重新作出选择完全合理。同样,添加公共前缀后旧脚本中的游标会整体平移,所以比较的是代价、保留数以及第一个 keep,而不是原样比较整个对象。把数学不变量和展示形式分开,有助于避免写出错误测试,把正确实现也拒绝掉。
示例 9:保存为 09.cjs,单独运行 node --unhandled-rejections=strict 09.cjs。
"use strict";
const assert = require("node:assert/strict");
function snapshot(input) {
if (!Array.isArray(input)) throw new TypeError("array required");
const n = input.length;
if (n > 255) throw new RangeError("token count");
const copy = [];
let units = 0;
for (let i = 0; i < n; i++) {
const d = Object.getOwnPropertyDescriptor(input, String(i));
if (!d || !Object.hasOwn(d, "value") || typeof d.value !== "string") {
throw new TypeError("own primitive string required");
}
const s = d.value;
if (s.length > 1024 || (units += s.length) > 65536) {
throw new RangeError("string budget");
}
copy.push(s);
}
return copy;
}
function diff(left, right) {
const a = snapshot(left), b = snapshot(right);
const m = a.length, n = b.length, width = n + 1;
const cells = (m + 1) * width;
if (cells > 16384) throw new RangeError("cell budget");
const table = new Uint16Array(cells);
const at = (i, j) => table[i * width + j];
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
table[i * width + j] = a[i] === b[j]
? 1 + at(i + 1, j + 1)
: Math.max(at(i + 1, j), at(i, j + 1));
}
}
const steps = [];
let i = 0, j = 0;
const add = (op, token) => steps.push(Object.freeze({
op, atA: i, atB: j, token
}));
while (i < m || j < n) {
if (i < m && j < n && a[i] === b[j]) {
add("keep", a[i]); i++; j++;
} else if (i < m && (j === n || at(i + 1, j) >= at(i, j + 1))) {
add("delete", a[i]); i++;
} else {
add("insert", b[j]); j++;
}
}
return Object.freeze({
lcs: table[0], edits: m + n - 2 * table[0],
steps: Object.freeze(steps)
});
}
function replay(source, steps) {
const a = snapshot(source);
if (!Array.isArray(steps)) throw new TypeError("script array required");
if (steps.length > 510) throw new RangeError("step budget");
const out = [];
let i = 0, units = 0;
for (let k = 0; k < steps.length; k++) {
const d = Object.getOwnPropertyDescriptor(steps, String(k));
if (!d || !Object.hasOwn(d, "value") ||
d.value === null || typeof d.value !== "object") {
throw new TypeError("step record required");
}
const read = key => {
const p = Object.getOwnPropertyDescriptor(d.value, key);
if (!p || !Object.hasOwn(p, "value")) throw new TypeError("data field required");
return p.value;
};
const op = read("op"), x = read("atA"), y = read("atB"), token = read("token");
if (!["keep", "delete", "insert"].includes(op) ||
!Number.isInteger(x) || !Number.isInteger(y) ||
x !== i || y !== out.length || typeof token !== "string") {
throw new TypeError("invalid operation");
}
if (token.length > 1024) throw new RangeError("token budget");
if (op !== "insert") {
if (i === a.length || a[i] !== token) throw new Error("source mismatch");
i++;
}
if (op !== "delete") {
if (out.length === 255 || (units += token.length) > 65536) {
throw new RangeError("target budget");
}
out.push(token);
}
}
if (i !== a.length) throw new Error("unconsumed source");
return Object.freeze(out);
}
let seed = 20261019;
const next = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0);
const alphabet = ["", "A", "é", "e\u0301", "\ud800", "👩💻", "A\0B"];
const make = () => Array.from({ length: next() % 13 }, () => alphabet[next() % alphabet.length]);
for (let k = 0; k < 1000; k++) {
const a = make(), b = make(), r = diff(a, b), back = diff(b, a);
assert.deepEqual(replay(a, r.steps), b);
assert.equal(r.edits, back.edits);
assert.equal(diff(a, a).edits, 0);
const prefixed = diff(["sentinel", ...a], ["sentinel", ...b]);
assert.equal(prefixed.edits, r.edits);
assert.equal(prefixed.lcs, r.lcs + 1);
assert.equal(prefixed.steps[0].op, "keep");
}
assert.equal(diff(["é"], ["e\u0301"]).edits, 2);
assert.equal(diff(["\ud800"], ["\ud800"]).edits, 0);
assert.deepEqual(diff(["A", "A"], ["A"]).steps.map(x => x.op), ["keep", "delete"]);
console.log("seeded-properties", 1000, "exact-unicode-and-ties-pass");实际输出:
seeded-properties 1000 exact-unicode-and-ties-pass
把审查问题交给 AI,也把验收标准留在自己手里
提交审查时,可以要求 AI 先逐项回答:令牌相等是什么意思,是否会调用用户 getter,什么时候分配矩阵,哪个平局分支决定输出,操作坐标属于哪一种状态,失败后是否改变输入,以及预言机是否复用了待测递推。随后要求它给出能击穿错误版本的具体反例。相比笼统地要求检查代码,这些问题会迫使审查围绕可观察契约展开,也便于人工核对其推理有没有偷偷更换题目。
如果将来要扩大规模,不能只调高常量而保留当前说明。更省空间的 LCS 重建方式、面向小差异的算法或用于人类阅读的分块策略,都可能值得单独评估;但任何替代实现仍需遵守相同令牌边界、所有权和脚本解释,或者明确发布新的契约。尤其不要在优化时偷偷加入规范化、替换成本或基于内容哈希的未经验证相等判断,这些变化都会改变允许保留的元素集合。
本文的完成标准是九段代码在指定运行参数下全部通过,并且每个结论都有独立可检查的落点:长度靠穷举预言机,脚本靠重放,选择靠明确平局样例,边界靠恰好通过与恰好失败的成对测试。这样的差异器虽然刻意限制规模,却能解释自己为什么接受一个输入、为什么选择这条路径,以及调用方可以安全依赖哪些行为。AI 生成代码真正需要补齐的,往往正是这些容易被一段简短实现省略的约定。
参考资料与核验范围
资料于 2026 年 10 月 19 日核验。NIST 条目用于区分公共子序列与公共子串;ECMAScript 规范用于确认原始字符串、严格相等和冻结语义;预算、平局规则、错误划分及脚本字段是本文自行制定并测试的接口契约,不是语言标准强制规定。

