AI 代码审查实战:用九个可运行实验验收流式 KMP 字节匹配器

10-19 5阅读

让 AI 写一个查找函数,常常几秒就能得到看似完整的答案。真正难验收的版本是:数据分多次到达,模式可能跨过分块边界,还要保留重叠命中,并返回整条字节流中的位置。一次普通字符串搜索成功,不能证明这些承诺都成立。本文把 AI 代码审查变成九个可重现的实验,每个实验都给出完整程序、断言和精确输出。

场景是一个只做精确字节匹配的扫描器:例如在日志归档或二进制数据中找固定标记。它不会解释消息语法,也不承担文本规范化、压缩解码或协议校验。输入字节为 0 到 255,输出是所有命中的起始字节偏移。重复、相交的命中都保留;空模式在构造时明确拒绝。先把这份契约写下来,再请 AI 解释实现中的每个状态变量,能避免把默认行为误当成业务要求。

AI 代码审查实战:用九个可运行实验验收流式 KMP 字节匹配器
AI 生成概念图:审查者追踪跨分块延续的匹配状态。图中连线表达概念,不是前缀表或运行轨迹的精确示意。

本文在 Node.js v24.19.0 下验证。把任意一段代码单独保存为对应的 .mjs 文件,再用 node --unhandled-rejections=strict 文件名.mjs 运行。九段代码互不依赖,后面的例子有意重复核心实现,方便直接复制复现。没有第三方依赖,输出中每一个值都由程序产生。严格未处理拒绝模式用于固定运行约定;这里的匹配器本身是同步 API。

先定验收边界,再讨论复杂度

匹配器只有 open、finished、failed 三种状态。push 同步消费一个分块,返回本次完成的命中;finish 表示不会再有输入,返回下一字节的全局位置;fail 用一个 Error 记录上游失败。正常结束后重复 finish 返回同一个位置,任何新的 push 都报错。失败后不再恢复,push 和 finish 都抛出最初保存的错误对象。末尾只有模式前半段是正常的未命中,不是损坏数据。

为让所有权和并发边界清楚,示例只接受同一 realm 中正常使用的 Uint8Array,包括符合这些条件的 Node.js Buffer。底层必须是未分离、固定长度、非共享的 ArrayBuffer。跨 realm 对象、代理、恶意重写属性或被篡改的内建方法不属于支持范围;SharedArrayBuffer 与可调整长度缓冲区明确拒绝。不要把这个教学实现当作隔离不可信 JavaScript 对象的安全沙箱。

NIST 的 KMP 条目将它概括为由模式构建状态机,再顺序消费待搜索数据。本文采用前缀表的实现形式:预处理长度为 m 的模式需要 O(m) 时间和空间,消费总计 n 个字节需要 O(n) 时间。输出 k 个命中仍需要 O(k) 工作;本实现每个 push 返回数组,所以额外峰值空间还包括当前分块的命中数量。大量单字节命中时,不能把总内存简单宣传为常数。

一、前缀表不是背公式,而是失配时的可复用证据

前缀表 pi[i] 记录模式从开头到 i 这一段中,最长的、同时也是后缀的真前缀长度。真前缀不能等于整段本身。例如 ababaca 的第五个位置之前已经出现重复结构;遇到 c 时,连续的候选边界都不适配,状态才退回零。这里保存的是长度,不是字符下标,这个差别正是 AI 容易混淆的地方。

审查 while 循环时可以问:为什么回退到 pi[j - 1] 后,还要拿同一个新字节继续比较?答案是前面失败的只是更长候选,较短的前缀仍可能成立。把 while 改成一次 if,会漏掉需要多次回退的情况;把 j 减一则丢失预处理带来的效率保证。这个例子固定一张易于人工核对的表,为后面所有状态转移建立共同语义。

独立文件:01_prefix.mjs

import assert from "node:assert/strict";
function prefixTable(p) {
  const pi = new Array(p.length).fill(0);
  for (let i = 1, j = 0; i < p.length; i++) {
    while (j > 0 && p[i] !== p[j]) j = pi[j - 1];
    if (p[i] === p[j]) j++;
    pi[i] = j;
  }
  return pi;
}
const p = new TextEncoder().encode("ababaca");
const table = prefixTable(p);
assert.deepEqual(table, [0, 0, 1, 2, 3, 0, 1]);
console.log(JSON.stringify(table));

精确输出:

[0,0,1,2,3,0,1]

二、先写慢而直白的参考答案

为了审查 AI 生成的快速实现,需要一份思路独立的裁判。暴力版本从每一个可能的起点逐字节比较,不使用前缀表,不复用失败状态,也不调用被测匹配器。它在小数据上较慢,却容易看懂。命中后外层起点仍然只加一,因此天然保留重叠结果。若裁判也采用同一套 KMP 回退逻辑,两份代码可能共享同一个错误。

这里既测 ASCII 的 ababa,也测包含零字节和 255 的数组。后者提醒我们,接口并不需要把二进制输入转成字符串。空模式被显式拒绝,避免在零字节、分块边缘和结束位置处产生难以协调的空匹配规则。请 AI 给出空模式处理建议时,要审查建议是否符合自己的契约,而不是照搬某个字符串库的约定。

独立文件:02_reference.mjs

import assert from "node:assert/strict";
function brute(text, pattern) {
  if (pattern.length === 0) throw new RangeError("empty pattern");
  const result = [];
  for (let i = 0; i + pattern.length <= text.length; i++) {
    let j = 0;
    while (j < pattern.length && text[i + j] === pattern[j]) j++;
    if (j === pattern.length) result.push(i);
  }
  return result;
}
const b = s => new TextEncoder().encode(s);
const overlap = brute(b("ababa"), b("aba"));
const binary = brute(Uint8Array.of(0, 255, 0, 255), Uint8Array.of(0, 255));
assert.deepEqual(overlap, [0, 2]);
assert.deepEqual(binary, [0, 2]);
assert.throws(() => brute(b("x"), new Uint8Array()), /empty pattern/);
console.log("overlap=" + JSON.stringify(overlap));
console.log("binary=" + JSON.stringify(binary));

精确输出:

overlap=[0,2]
binary=[0,2]

三、流式实现只保留必要的匹配状态

完整实现的 q 表示已消费输入的末尾,与模式真前缀匹配的最长长度。它跨 push 保存,分块结束时不会清零。offset 是下一字节的全局位置,默认从零开始。每次命中后先记录起点,再把 q 回退到模式最后一个位置的前缀表值,让重叠候选继续存活。空分块既不推进位置,也不破坏 q。

注意构造函数复制模式;分块在同步调用中被借用,调用结束后不保留引用。push 先验证参数和位置上限,再使用局部 q 处理,最后提交新状态。这使正常可捕获的处理错误不会留下已经推进一半的 offset。这里没有用户回调,也没有异步暂停点,避免在读取分块过程中引入重入。bytes 中直接调用内建 values 是为了验证已分离的缓冲区,而不是靠长度为零猜测输入是否合法。

示例把 ababa 拆成 ab、空分块和 aba。第二次输入为空时不能误认为流已经结束;只有显式 finish 才关闭对象。最后一个分块完成两个命中,它们的起点仍然是整条流的位置。审查结果时不仅看命中数量,还要核对每次 push 分别返回了什么。

独立文件:03_stream.mjs

import assert from "node:assert/strict";
function bytes(value) {
  if (!(value instanceof Uint8Array)) throw new TypeError("Uint8Array required");
  if (!(value.buffer instanceof ArrayBuffer) || value.buffer.resizable) {
    throw new TypeError("fixed non-shared buffer required");
  }
  Uint8Array.prototype.values.call(value);
  return value;
}
function prefixTable(p) {
  const pi = new Array(p.length).fill(0);
  for (let i = 1, j = 0; i < p.length; i++) {
    while (j > 0 && p[i] !== p[j]) j = pi[j - 1];
    if (p[i] === p[j]) j++;
    pi[i] = j;
  }
  return pi;
}
class KmpStream {
  #p; #pi; #q = 0; #offset; #state = "open"; #error;
  constructor(pattern, baseOffset = 0) {
    this.#p = new Uint8Array(bytes(pattern));
    if (this.#p.length === 0) throw new RangeError("empty pattern");
    if (!Number.isSafeInteger(baseOffset) || baseOffset < 0) {
      throw new RangeError("invalid base offset");
    }
    this.#pi = prefixTable(this.#p);
    this.#offset = baseOffset;
  }
  get state() { return this.#state; }
  get offset() { return this.#offset; }
  #open() {
    if (this.#state === "failed") throw this.#error;
    if (this.#state === "finished") throw new Error("finished");
  }
  push(input) {
    this.#open();
    try {
      const chunk = bytes(input);
      if (chunk.length > Number.MAX_SAFE_INTEGER - this.#offset) {
        throw new RangeError("offset overflow");
      }
      let q = this.#q;
      const hits = [], m = this.#p.length;
      for (let i = 0; i < chunk.length; i++) {
        while (q > 0 && chunk[i] !== this.#p[q]) q = this.#pi[q - 1];
        if (chunk[i] === this.#p[q]) q++;
        if (q === m) {
          hits.push(this.#offset + i - (m - 1));
          q = this.#pi[m - 1];
        }
      }
      this.#q = q;
      this.#offset += chunk.length;
      return hits;
    } catch (error) {
      this.#state = "failed";
      this.#error = error;
      throw error;
    }
  }
  finish() {
    if (this.#state === "failed") throw this.#error;
    this.#state = "finished";
    return this.#offset;
  }
  fail(error = new Error("aborted")) {
    this.#open();
    if (!(error instanceof Error)) throw new TypeError("Error required");
    this.#state = "failed";
    this.#error = error;
  }
}
const b = s => new TextEncoder().encode(s);
const matcher = new KmpStream(b("aba"));
const batches = ["ab", "", "aba"].map(s => matcher.push(b(s)));
assert.deepEqual(batches, [[], [], [0, 2]]);
assert.equal(matcher.finish(), 5);
console.log(JSON.stringify(batches));
console.log("end=" + matcher.offset + ", state=" + matcher.state);

精确输出:

[[],[],[0,2]]
end=5, state=finished

四、重叠命中与字节坐标必须一起验证

连续五个 a 中查找 aaa,正确起点为零、一、二。若 AI 在命中后把 q 设为零,通常只能留下第一个结果;如果直接从匹配末尾继续寻找下一段,也会形成同样的漏报。本例故意每次只送一个字节,让每一次状态延续都显露出来。完成命中时回退到最长真前后缀,是保留相交候选的关键。

另一个常见错误是把字节坐标写成字符坐标。示例中的两个中字在 UTF-8 下各占三个字节,所以命中起点是零和三。匹配器既不识别 Unicode 码点,也不判断字形、大小写或规范化等价性。若业务希望返回用户看到的字符位置,需要额外维护字节与文本索引的映射,不能对这里的偏移直接做字符切片。

独立文件:04_overlap.mjs

import assert from "node:assert/strict";
function bytes(value) {
  if (!(value instanceof Uint8Array)) throw new TypeError("Uint8Array required");
  if (!(value.buffer instanceof ArrayBuffer) || value.buffer.resizable) {
    throw new TypeError("fixed non-shared buffer required");
  }
  Uint8Array.prototype.values.call(value);
  return value;
}
function prefixTable(p) {
  const pi = new Array(p.length).fill(0);
  for (let i = 1, j = 0; i < p.length; i++) {
    while (j > 0 && p[i] !== p[j]) j = pi[j - 1];
    if (p[i] === p[j]) j++;
    pi[i] = j;
  }
  return pi;
}
class KmpStream {
  #p; #pi; #q = 0; #offset; #state = "open"; #error;
  constructor(pattern, baseOffset = 0) {
    this.#p = new Uint8Array(bytes(pattern));
    if (this.#p.length === 0) throw new RangeError("empty pattern");
    if (!Number.isSafeInteger(baseOffset) || baseOffset < 0) {
      throw new RangeError("invalid base offset");
    }
    this.#pi = prefixTable(this.#p);
    this.#offset = baseOffset;
  }
  get state() { return this.#state; }
  get offset() { return this.#offset; }
  #open() {
    if (this.#state === "failed") throw this.#error;
    if (this.#state === "finished") throw new Error("finished");
  }
  push(input) {
    this.#open();
    try {
      const chunk = bytes(input);
      if (chunk.length > Number.MAX_SAFE_INTEGER - this.#offset) {
        throw new RangeError("offset overflow");
      }
      let q = this.#q;
      const hits = [], m = this.#p.length;
      for (let i = 0; i < chunk.length; i++) {
        while (q > 0 && chunk[i] !== this.#p[q]) q = this.#pi[q - 1];
        if (chunk[i] === this.#p[q]) q++;
        if (q === m) {
          hits.push(this.#offset + i - (m - 1));
          q = this.#pi[m - 1];
        }
      }
      this.#q = q;
      this.#offset += chunk.length;
      return hits;
    } catch (error) {
      this.#state = "failed";
      this.#error = error;
      throw error;
    }
  }
  finish() {
    if (this.#state === "failed") throw this.#error;
    this.#state = "finished";
    return this.#offset;
  }
  fail(error = new Error("aborted")) {
    this.#open();
    if (!(error instanceof Error)) throw new TypeError("Error required");
    this.#state = "failed";
    this.#error = error;
  }
}
const b = s => new TextEncoder().encode(s);
const matcher = new KmpStream(b("aaa"));
const hits = [];
for (const char of "aaaaa") hits.push(...matcher.push(b(char)));
assert.deepEqual(hits, [0, 1, 2]);
assert.equal(matcher.finish(), 5);
const utf8 = new KmpStream(b("中"));
const offsets = utf8.push(b("中中"));
assert.deepEqual(offsets, [0, 3]);
console.log("overlap=" + JSON.stringify(hits));
console.log("utf8-byte-offsets=" + JSON.stringify(offsets));

精确输出:

overlap=[0,1,2]
utf8-byte-offsets=[0,3]

五、枚举分块方式,检验边界是否改变结果

流式算法的核心性质是:同一字节序列以任何方式切分,按顺序送入后,合并的命中列表都应与整段搜索一致。长度七的输入有六个内部间隙,每个间隙选择切或不切,恰好得到六十四种非空分块划分。我们全部枚举,并在每个分块后额外插入空分块,检查空输入是否错误地清掉状态。

枚举范围是这条短输入的全部划分,不是对所有长度的数学穷举。空分块的无限种重复插入也没有逐一枚举,不过实现的空循环不改变状态,可以直接解释任意次插入为何等价。测试与推理各有职责:测试抓住具体回归,状态不变量支撑一般结论。示例用到位运算只是为了枚举六个切点,绝不把这类三十二位技巧用来累计全局偏移。

独立文件:05_partitions.mjs

import assert from "node:assert/strict";
function bytes(value) {
  if (!(value instanceof Uint8Array)) throw new TypeError("Uint8Array required");
  if (!(value.buffer instanceof ArrayBuffer) || value.buffer.resizable) {
    throw new TypeError("fixed non-shared buffer required");
  }
  Uint8Array.prototype.values.call(value);
  return value;
}
function prefixTable(p) {
  const pi = new Array(p.length).fill(0);
  for (let i = 1, j = 0; i < p.length; i++) {
    while (j > 0 && p[i] !== p[j]) j = pi[j - 1];
    if (p[i] === p[j]) j++;
    pi[i] = j;
  }
  return pi;
}
class KmpStream {
  #p; #pi; #q = 0; #offset; #state = "open"; #error;
  constructor(pattern, baseOffset = 0) {
    this.#p = new Uint8Array(bytes(pattern));
    if (this.#p.length === 0) throw new RangeError("empty pattern");
    if (!Number.isSafeInteger(baseOffset) || baseOffset < 0) {
      throw new RangeError("invalid base offset");
    }
    this.#pi = prefixTable(this.#p);
    this.#offset = baseOffset;
  }
  get state() { return this.#state; }
  get offset() { return this.#offset; }
  #open() {
    if (this.#state === "failed") throw this.#error;
    if (this.#state === "finished") throw new Error("finished");
  }
  push(input) {
    this.#open();
    try {
      const chunk = bytes(input);
      if (chunk.length > Number.MAX_SAFE_INTEGER - this.#offset) {
        throw new RangeError("offset overflow");
      }
      let q = this.#q;
      const hits = [], m = this.#p.length;
      for (let i = 0; i < chunk.length; i++) {
        while (q > 0 && chunk[i] !== this.#p[q]) q = this.#pi[q - 1];
        if (chunk[i] === this.#p[q]) q++;
        if (q === m) {
          hits.push(this.#offset + i - (m - 1));
          q = this.#pi[m - 1];
        }
      }
      this.#q = q;
      this.#offset += chunk.length;
      return hits;
    } catch (error) {
      this.#state = "failed";
      this.#error = error;
      throw error;
    }
  }
  finish() {
    if (this.#state === "failed") throw this.#error;
    this.#state = "finished";
    return this.#offset;
  }
  fail(error = new Error("aborted")) {
    this.#open();
    if (!(error instanceof Error)) throw new TypeError("Error required");
    this.#state = "failed";
    this.#error = error;
  }
}
function brute(text, pattern) {
  if (pattern.length === 0) throw new RangeError("empty pattern");
  const result = [];
  for (let i = 0; i + pattern.length <= text.length; i++) {
    let j = 0;
    while (j < pattern.length && text[i + j] === pattern[j]) j++;
    if (j === pattern.length) result.push(i);
  }
  return result;
}
const b = s => new TextEncoder().encode(s);
const text = b("abababa"), pattern = b("aba");
const expected = brute(text, pattern);
let checked = 0;
for (let mask = 0; mask < 2 ** (text.length - 1); mask++) {
  const matcher = new KmpStream(pattern), hits = [];
  let start = 0;
  for (let end = 1; end <= text.length; end++) {
    if (end === text.length || (mask & (1 << (end - 1)))) {
      hits.push(...matcher.push(text.subarray(start, end)));
      hits.push(...matcher.push(new Uint8Array()));
      start = end;
    }
  }
  assert.deepEqual(hits, expected);
  assert.equal(matcher.finish(), text.length);
  checked++;
}
console.log("partitions=" + checked + ", hits=" + JSON.stringify(expected));

精确输出:

partitions=64, hits=[0,2,4]

六、输入所有权决定状态会不会被外部改坏

保存调用者传来的模式引用,往往是功能测试难以发现的隐患。调用者之后复用缓冲区,模式内容已经变了,前缀表却仍对应旧数据,搜索结果自然失去依据。构造时用 new Uint8Array 复制传入视图中的字节,让模式与前缀表共同成为内部快照。不要仅从 pattern.buffer 建一个视图,那既可能共享存储,也可能无意包含视图范围外的字节。

分块采用不同策略:同步读取完便不再保留它,因此 push 返回后可以安全修改或回收这个分块。匹配进度已经浓缩在 q 中,不需要保留历史尾部字节。本例还故意传入有非零 byteOffset 的 subarray,确认只扫描当前视图,再篡改返回的命中数组,确认调用者拿到的是独立结果。ECMAScript 的 TypedArray 构造规则可以用来核对复制语义,而不要仅凭函数名猜测。

独立文件:06_ownership.mjs

import assert from "node:assert/strict";
function bytes(value) {
  if (!(value instanceof Uint8Array)) throw new TypeError("Uint8Array required");
  if (!(value.buffer instanceof ArrayBuffer) || value.buffer.resizable) {
    throw new TypeError("fixed non-shared buffer required");
  }
  Uint8Array.prototype.values.call(value);
  return value;
}
function prefixTable(p) {
  const pi = new Array(p.length).fill(0);
  for (let i = 1, j = 0; i < p.length; i++) {
    while (j > 0 && p[i] !== p[j]) j = pi[j - 1];
    if (p[i] === p[j]) j++;
    pi[i] = j;
  }
  return pi;
}
class KmpStream {
  #p; #pi; #q = 0; #offset; #state = "open"; #error;
  constructor(pattern, baseOffset = 0) {
    this.#p = new Uint8Array(bytes(pattern));
    if (this.#p.length === 0) throw new RangeError("empty pattern");
    if (!Number.isSafeInteger(baseOffset) || baseOffset < 0) {
      throw new RangeError("invalid base offset");
    }
    this.#pi = prefixTable(this.#p);
    this.#offset = baseOffset;
  }
  get state() { return this.#state; }
  get offset() { return this.#offset; }
  #open() {
    if (this.#state === "failed") throw this.#error;
    if (this.#state === "finished") throw new Error("finished");
  }
  push(input) {
    this.#open();
    try {
      const chunk = bytes(input);
      if (chunk.length > Number.MAX_SAFE_INTEGER - this.#offset) {
        throw new RangeError("offset overflow");
      }
      let q = this.#q;
      const hits = [], m = this.#p.length;
      for (let i = 0; i < chunk.length; i++) {
        while (q > 0 && chunk[i] !== this.#p[q]) q = this.#pi[q - 1];
        if (chunk[i] === this.#p[q]) q++;
        if (q === m) {
          hits.push(this.#offset + i - (m - 1));
          q = this.#pi[m - 1];
        }
      }
      this.#q = q;
      this.#offset += chunk.length;
      return hits;
    } catch (error) {
      this.#state = "failed";
      this.#error = error;
      throw error;
    }
  }
  finish() {
    if (this.#state === "failed") throw this.#error;
    this.#state = "finished";
    return this.#offset;
  }
  fail(error = new Error("aborted")) {
    this.#open();
    if (!(error instanceof Error)) throw new TypeError("Error required");
    this.#state = "failed";
    this.#error = error;
  }
}
const pattern = Uint8Array.of(1, 2, 1);
const matcher = new KmpStream(pattern);
pattern.fill(9);
const backing = Uint8Array.of(7, 1, 2, 7);
const chunk = backing.subarray(1, 3);
assert.deepEqual(matcher.push(chunk), []);
chunk.fill(8);
const first = matcher.push(Uint8Array.of(1));
assert.deepEqual(first, [0]);
first[0] = 999;
const next = matcher.push(Uint8Array.of(2, 1));
assert.deepEqual(next, [2]);
assert.equal(matcher.finish(), 5);
console.log("pattern-copied=true, chunk-retained=false");
console.log("next=" + JSON.stringify(next));

精确输出:

pattern-copied=true, chunk-retained=false
next=[2]

七、全局偏移要在加法之前检查

Number 能表示很大的数,但不是每一个很大的整数都能准确区分。这里用 Number.isSafeInteger 检查起始位置,再要求分块长度不超过最大安全整数减去当前 offset。先比较剩余空间,避免先执行不安全的加法。ECMAScript 对安全整数的定义明确给出了这一边界。

baseOffset 只是为当前输入片段指定全局坐标起点,不会重建起点之前的匹配状态。因此本例可以从接近上限的位置开始测试,不需要真的读取海量数据,也不能宣称它能发现跨越片段起点的旧匹配。offset 使用右侧开区间终点,允许到达最大安全整数;此时仍可接受空分块,无法再接受任何非空分块。最后可处理的字节位置因此是最大安全整数减一。

溢出会把实例置为 failed,并保留原 offset,后续 finish 抛出同一个错误对象。断言同时验证数值、状态和错误身份,防止 AI 用一个新错误掩盖最初原因。若确实需要超出这个范围,应设计完整的 BigInt 坐标接口及其序列化约定,不能只在某一个加法表达式里临时换类型。

独立文件:07_offsets.mjs

import assert from "node:assert/strict";
function bytes(value) {
  if (!(value instanceof Uint8Array)) throw new TypeError("Uint8Array required");
  if (!(value.buffer instanceof ArrayBuffer) || value.buffer.resizable) {
    throw new TypeError("fixed non-shared buffer required");
  }
  Uint8Array.prototype.values.call(value);
  return value;
}
function prefixTable(p) {
  const pi = new Array(p.length).fill(0);
  for (let i = 1, j = 0; i < p.length; i++) {
    while (j > 0 && p[i] !== p[j]) j = pi[j - 1];
    if (p[i] === p[j]) j++;
    pi[i] = j;
  }
  return pi;
}
class KmpStream {
  #p; #pi; #q = 0; #offset; #state = "open"; #error;
  constructor(pattern, baseOffset = 0) {
    this.#p = new Uint8Array(bytes(pattern));
    if (this.#p.length === 0) throw new RangeError("empty pattern");
    if (!Number.isSafeInteger(baseOffset) || baseOffset < 0) {
      throw new RangeError("invalid base offset");
    }
    this.#pi = prefixTable(this.#p);
    this.#offset = baseOffset;
  }
  get state() { return this.#state; }
  get offset() { return this.#offset; }
  #open() {
    if (this.#state === "failed") throw this.#error;
    if (this.#state === "finished") throw new Error("finished");
  }
  push(input) {
    this.#open();
    try {
      const chunk = bytes(input);
      if (chunk.length > Number.MAX_SAFE_INTEGER - this.#offset) {
        throw new RangeError("offset overflow");
      }
      let q = this.#q;
      const hits = [], m = this.#p.length;
      for (let i = 0; i < chunk.length; i++) {
        while (q > 0 && chunk[i] !== this.#p[q]) q = this.#pi[q - 1];
        if (chunk[i] === this.#p[q]) q++;
        if (q === m) {
          hits.push(this.#offset + i - (m - 1));
          q = this.#pi[m - 1];
        }
      }
      this.#q = q;
      this.#offset += chunk.length;
      return hits;
    } catch (error) {
      this.#state = "failed";
      this.#error = error;
      throw error;
    }
  }
  finish() {
    if (this.#state === "failed") throw this.#error;
    this.#state = "finished";
    return this.#offset;
  }
  fail(error = new Error("aborted")) {
    this.#open();
    if (!(error instanceof Error)) throw new TypeError("Error required");
    this.#state = "failed";
    this.#error = error;
  }
}
const max = Number.MAX_SAFE_INTEGER;
const matcher = new KmpStream(Uint8Array.of(7), max - 2);
const hits = matcher.push(Uint8Array.of(7, 7));
assert.deepEqual(hits, [max - 2, max - 1]);
assert.deepEqual(matcher.push(new Uint8Array()), []);
let overflow;
try { matcher.push(Uint8Array.of(7)); } catch (error) { overflow = error; }
assert.equal(overflow?.message, "offset overflow");
assert.equal(matcher.offset, max);
assert.equal(matcher.state, "failed");
assert.throws(() => matcher.finish(), error => error === overflow);
for (const value of [-1, 0.5, NaN, Infinity, max + 1]) {
  assert.throws(() => new KmpStream(Uint8Array.of(7), value), RangeError);
}
const atomic = new KmpStream(Uint8Array.of(7), max - 2);
assert.throws(() => atomic.push(Uint8Array.of(7, 7, 7)), /offset overflow/);
assert.equal(atomic.offset, max - 2);
assert.equal(atomic.state, "failed");
console.log("hits=" + JSON.stringify(hits));
console.log("offset=" + matcher.offset + ", state=" + matcher.state);

精确输出:

hits=[9007199254740989,9007199254740990]
offset=9007199254740991, state=failed

八、完成与失败是两条不同的终止路径

finish 不会把不完整前缀补成一个命中,也不会把正常未命中升级为异常。它只宣告输入结束,重复调用保持相同结果。finished 后连空分块也不允许再提交,这样调用方无法偷偷重启旧实例。相反,上游读取失败时调用 fail,必须保留原始 Error;之后的 push 和 finish 都沿用它,便于上层识别根因。

本例分别覆盖正常结束、人工中止、数组误传、空模式、共享缓冲区、可调整长度缓冲区和已分离缓冲区。非法 push 会使实例失败,不允许调用者把已经出错的流当作连续输入继续扫描。fail 参数不是 Error 时会抛 TypeError,但对象保持 open,这是参数使用错误的约定;已经终止后调用 fail 则直接拒绝。生产接入时应明确由谁捕获上游异常、何时调用 fail,以及已经返回的命中是否需要业务层撤销。

TypedArray 的 values 验证规则与ArrayBuffer 的 resizable 定义是输入检查的依据。拒绝共享和可调整存储是本文自行选择的简化契约,并非 JavaScript 或 KMP 天生禁止它们。

独立文件:08_lifecycle.mjs

import assert from "node:assert/strict";
function bytes(value) {
  if (!(value instanceof Uint8Array)) throw new TypeError("Uint8Array required");
  if (!(value.buffer instanceof ArrayBuffer) || value.buffer.resizable) {
    throw new TypeError("fixed non-shared buffer required");
  }
  Uint8Array.prototype.values.call(value);
  return value;
}
function prefixTable(p) {
  const pi = new Array(p.length).fill(0);
  for (let i = 1, j = 0; i < p.length; i++) {
    while (j > 0 && p[i] !== p[j]) j = pi[j - 1];
    if (p[i] === p[j]) j++;
    pi[i] = j;
  }
  return pi;
}
class KmpStream {
  #p; #pi; #q = 0; #offset; #state = "open"; #error;
  constructor(pattern, baseOffset = 0) {
    this.#p = new Uint8Array(bytes(pattern));
    if (this.#p.length === 0) throw new RangeError("empty pattern");
    if (!Number.isSafeInteger(baseOffset) || baseOffset < 0) {
      throw new RangeError("invalid base offset");
    }
    this.#pi = prefixTable(this.#p);
    this.#offset = baseOffset;
  }
  get state() { return this.#state; }
  get offset() { return this.#offset; }
  #open() {
    if (this.#state === "failed") throw this.#error;
    if (this.#state === "finished") throw new Error("finished");
  }
  push(input) {
    this.#open();
    try {
      const chunk = bytes(input);
      if (chunk.length > Number.MAX_SAFE_INTEGER - this.#offset) {
        throw new RangeError("offset overflow");
      }
      let q = this.#q;
      const hits = [], m = this.#p.length;
      for (let i = 0; i < chunk.length; i++) {
        while (q > 0 && chunk[i] !== this.#p[q]) q = this.#pi[q - 1];
        if (chunk[i] === this.#p[q]) q++;
        if (q === m) {
          hits.push(this.#offset + i - (m - 1));
          q = this.#pi[m - 1];
        }
      }
      this.#q = q;
      this.#offset += chunk.length;
      return hits;
    } catch (error) {
      this.#state = "failed";
      this.#error = error;
      throw error;
    }
  }
  finish() {
    if (this.#state === "failed") throw this.#error;
    this.#state = "finished";
    return this.#offset;
  }
  fail(error = new Error("aborted")) {
    this.#open();
    if (!(error instanceof Error)) throw new TypeError("Error required");
    this.#state = "failed";
    this.#error = error;
  }
}
const pattern = Uint8Array.of(1, 2, 3);
const done = new KmpStream(pattern);
assert.deepEqual(done.push(Uint8Array.of(1, 2)), []);
assert.equal(done.finish(), 2);
assert.equal(done.finish(), 2);
assert.throws(() => done.push(new Uint8Array()), /finished/);
assert.throws(() => done.fail(new Error("late")), /finished/);
const wrongFail = new KmpStream(pattern);
assert.throws(() => wrongFail.fail("not an Error"), TypeError);
assert.equal(wrongFail.state, "open");
const stopped = new KmpStream(pattern), reason = new Error("source failed");
stopped.fail(reason);
assert.throws(() => stopped.push(Uint8Array.of(1)), e => e === reason);
assert.throws(() => stopped.finish(), e => e === reason);
const bad = new KmpStream(pattern);
assert.throws(() => bad.push([1, 2]), TypeError);
assert.equal(bad.state, "failed");
assert.equal(bad.offset, 0);
assert.throws(() => new KmpStream(new Uint8Array()), /empty pattern/);
const shared = new Uint8Array(new SharedArrayBuffer(1));
const resizable = new Uint8Array(new ArrayBuffer(1, { maxByteLength: 2 }));
const detached = new Uint8Array(1);
structuredClone(detached.buffer, { transfer: [detached.buffer] });
for (const value of [shared, resizable, detached]) {
  assert.throws(() => new KmpStream(value), TypeError);
  const fresh = new KmpStream(pattern);
  assert.throws(() => fresh.push(value), TypeError);
  assert.equal(fresh.state, "failed");
}
console.log("finish-idempotent=true, partial-tail-is-not-a-hit=true");
console.log("fail-sticky=true, invalid-inputs-rejected=true");

精确输出:

finish-idempotent=true, partial-tail-is-not-a-hit=true
fail-sticky=true, invalid-inputs-rejected=true

九、固定种子的差分实验,让失败能够复现

最后把优化实现和暴力裁判放到同一组生成输入上。固定种子使每次运行能重现同样的案例顺序;短字母表更容易产生重复前后缀和重叠命中,完整字节表补充非文本数据。模式长度有时超过输入,输入也可能为空,分块长度则独立变化。所有结果用深度相等比较,既检查位置,也检查顺序与是否重复报告。

伪随机生成器使用位运算保持可复现的三十二位状态,这是测试数据生成器的局部选择,与被测实现的全局坐标完全分开。这里的一千二百个案例没有性能排名意义,也不是密码学随机实验。若某次断言失败,先保存输入、模式、切点和案例编号,再缩小反例;不要让 AI 只改到当前报错消失,随后重新执行前面全部确定性实验。

复杂度的理由来自不变量而非计时:每消费一个新字节,匹配长度最多增加一;回退只缩短已经建立的候选,因此跨整个扫描过程可摊还为线性工作。分块不会重新预处理模式,也不会重复扫描旧文本。另一方面,本实现为命中数组分配的内存随结果增长;需要持续处理高密度命中时,应另行设计有界输出协议,并重新审查背压、回调异常和重入。

独立文件:09_differential.mjs

import assert from "node:assert/strict";
function bytes(value) {
  if (!(value instanceof Uint8Array)) throw new TypeError("Uint8Array required");
  if (!(value.buffer instanceof ArrayBuffer) || value.buffer.resizable) {
    throw new TypeError("fixed non-shared buffer required");
  }
  Uint8Array.prototype.values.call(value);
  return value;
}
function prefixTable(p) {
  const pi = new Array(p.length).fill(0);
  for (let i = 1, j = 0; i < p.length; i++) {
    while (j > 0 && p[i] !== p[j]) j = pi[j - 1];
    if (p[i] === p[j]) j++;
    pi[i] = j;
  }
  return pi;
}
class KmpStream {
  #p; #pi; #q = 0; #offset; #state = "open"; #error;
  constructor(pattern, baseOffset = 0) {
    this.#p = new Uint8Array(bytes(pattern));
    if (this.#p.length === 0) throw new RangeError("empty pattern");
    if (!Number.isSafeInteger(baseOffset) || baseOffset < 0) {
      throw new RangeError("invalid base offset");
    }
    this.#pi = prefixTable(this.#p);
    this.#offset = baseOffset;
  }
  get state() { return this.#state; }
  get offset() { return this.#offset; }
  #open() {
    if (this.#state === "failed") throw this.#error;
    if (this.#state === "finished") throw new Error("finished");
  }
  push(input) {
    this.#open();
    try {
      const chunk = bytes(input);
      if (chunk.length > Number.MAX_SAFE_INTEGER - this.#offset) {
        throw new RangeError("offset overflow");
      }
      let q = this.#q;
      const hits = [], m = this.#p.length;
      for (let i = 0; i < chunk.length; i++) {
        while (q > 0 && chunk[i] !== this.#p[q]) q = this.#pi[q - 1];
        if (chunk[i] === this.#p[q]) q++;
        if (q === m) {
          hits.push(this.#offset + i - (m - 1));
          q = this.#pi[m - 1];
        }
      }
      this.#q = q;
      this.#offset += chunk.length;
      return hits;
    } catch (error) {
      this.#state = "failed";
      this.#error = error;
      throw error;
    }
  }
  finish() {
    if (this.#state === "failed") throw this.#error;
    this.#state = "finished";
    return this.#offset;
  }
  fail(error = new Error("aborted")) {
    this.#open();
    if (!(error instanceof Error)) throw new TypeError("Error required");
    this.#state = "failed";
    this.#error = error;
  }
}
function brute(text, pattern) {
  if (pattern.length === 0) throw new RangeError("empty pattern");
  const result = [];
  for (let i = 0; i + pattern.length <= text.length; i++) {
    let j = 0;
    while (j < pattern.length && text[i + j] === pattern[j]) j++;
    if (j === pattern.length) result.push(i);
  }
  return result;
}
let seed = 0x12345678;
function random(n) {
  seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5;
  return (seed >>> 0) % n;
}
for (let test = 0; test < 1200; test++) {
  const alphabet = test % 2 === 0 ? 3 : 256;
  const text = Uint8Array.from({ length: random(50) }, () => random(alphabet));
  const pattern = Uint8Array.from({ length: 1 + random(9) }, () => random(alphabet));
  const expected = brute(text, pattern), matcher = new KmpStream(pattern);
  const actual = [];
  let offset = 0;
  assert.deepEqual(matcher.push(new Uint8Array()), []);
  while (offset < text.length) {
    const end = Math.min(text.length, offset + 1 + random(8));
    actual.push(...matcher.push(text.subarray(offset, end)));
    if (random(3) === 0) assert.deepEqual(matcher.push(new Uint8Array()), []);
    offset = end;
  }
  assert.equal(matcher.finish(), text.length);
  assert.deepEqual(actual, expected, "case=" + test);
}
console.log("seed=0x12345678, differential-cases=1200, all-pass=true");

精确输出:

seed=0x12345678, differential-cases=1200, all-pass=true

交给 AI 的最终验收问题

代码审查到这里,可以要求 AI 对照实验逐条回答:前缀表存的是长度还是位置?分块边界为何不改变 q?命中后为何保留最长真前后缀?所有输出为何始终是字节坐标?调用者修改模式、分块或结果时,哪些对象拥有自己的数据?偏移溢出发生在消费之前还是之后?正常结束与失败分别允许哪些后续调用?每个答案都应指向具体实现和断言,而不是只说使用了经典算法。

这套代码的价值不是替代成熟检索库,而是给 AI 生成的流式实现建立一份可执行的验收合同。需要多模式匹配、忽略大小写、并行消费或异步输出时,合同本身已经改变,应增加相应的参考模型与边界实验。先把正确性边界讲清楚,再讨论缓存、批处理和速度,才能让优化有一个稳定的落脚点。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。