AI 代码审查实战:JavaScript LZ78 字节词典与严格终止对

10-20 4阅读

让 AI 写一个 LZ78 编解码器,最容易得到的是十几行字符串拼接:找到词典中的前缀,输出索引和一个字符,然后把新短语放进词典。困难不在演示正常句子,而在定义最后一个短语恰好已经存在时怎么办、解码器能不能引用尚未建立的词条,以及词典满了以后双方是否仍然同步。本文把这些问题固定成一个可执行的字节接口,再用独立模型审查实现。

这里交付的是 LZ78 风格的二元组表示,不是可直接落盘的压缩位流。每个普通 token 是 [已有词条索引, 新字节],末尾可以有一个 [已有词条索引, null]。JSON 数组中的数字、逗号和括号都占空间;token 数减少不能当作压缩率。若要形成文件格式,还必须另行规定索引位宽、终止标记、块边界、版本和完整性校验,不能把本文输出冒充现成压缩格式。

全文九段代码各自完整,复制到独立的 .cjs 文件后用 Node.js 运行即可,不引用前一段,也不安装第三方包。每段都重复相同的核心实现,便于单独复现。实测环境为 Node.js v24.19.0;输出区展示本次运行的逐字结果。API 接收当前 JavaScript realm 内的 Uint8Array,解码输入按普通数据数组处理,不承诺防御带副作用的 Proxy、访问器、被修改的内建对象或并发写入的共享内存。

AI 代码审查实战:JavaScript LZ78 字节词典与严格终止对
AI概念图:逐步建立的词典与向已有短语回溯的引用。示意构图,不代表真实位流布局。

一、先把词条编号与字节边界写成契约

词典零号项永远是空短语,不能被覆盖。每个普通 token 恰好增加一个非空词条,其编号就是新增前的词典长度;该项由旧短语追加一个字节构成。编码器匹配到已知边时继续向下走,第一次遇到不存在的边才输出,并把当前位置重置到根。这个重置是分词边界,不是清空整个词典。

例子把 ABABAAB 写成明确的 ASCII 字节。前四个词条依次是 A、B、AB、AA,最后剩下的 B 已在词典内,所以输出索引二的终止对。解码器先确认引用已经存在,再允许追加新项;把这两个动作倒过来,会无意接纳自引用。每一次函数调用都从零号根重新开始,调用者不能把另一块数据的索引直接接到当前块后面。

实现保存父索引、末字节和短语长度,不在主词典里复制整段短语。解码分成验证和展开两步:先累计长度并记录要输出的词条,再一次性分配结果缓冲区,沿父链反向填入每个输出片段。父编号严格更小,所以链最终到达零,不需要猜测循环何时结束。

独立示例 01,保存为 01_walkthrough.cjs 后运行 node 01_walkthrough.cjs。

'use strict';
const fail = code => { throw new Error(code); };
const natural = x => Number.isSafeInteger(x) && x >= 0 && !Object.is(x, -0);
function limits({maxBytes = 1048576, maxEntries = 65536, maxTokens = 65536} = {}) {
  if (![maxBytes, maxEntries, maxTokens].every(natural)) fail('LIMIT');
  return {maxBytes, maxEntries, maxTokens};
}
function encode(input, options) {
  const l = limits(options);
  if (!(input instanceof Uint8Array)) fail('INPUT');
  if (input.length > l.maxBytes) fail('BYTES');
  const next = [new Map()], tokens = [];
  let p = 0;
  const emit = t => {
    if (tokens.length >= l.maxTokens) fail('TOKENS');
    tokens.push(t);
  };
  for (const b of input) {
    if (next[p].has(b)) { p = next[p].get(b); continue; }
    if (next.length - 1 >= l.maxEntries) fail('ENTRIES');
    emit([p, b]);
    next[p].set(b, next.length);
    next.push(new Map());
    p = 0;
  }
  if (p !== 0) emit([p, null]);
  return tokens;
}
function decode(tokens, options) {
  const l = limits(options);
  if (!Array.isArray(tokens)) fail('TOKENS_TYPE');
  if (tokens.length > l.maxTokens) fail('TOKENS');
  const parent = [0], tail = [0], size = [0], edges = [new Set()], ids = [];
  let total = 0;
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    if (!Array.isArray(t) || t.length !== 2) fail('PAIR');
    const [p, b] = t;
    if (!natural(p) || p >= parent.length) fail('INDEX');
    let id = p, n = size[p];
    if (b === null) {
      if (p === 0 || i !== tokens.length - 1) fail('TERMINAL');
    } else {
      if (!natural(b) || b > 255) fail('BYTE');
      if (edges[p].has(b)) fail('DUPLICATE');
      if (parent.length - 1 >= l.maxEntries) fail('ENTRIES');
      n++;
    }
    if (n > l.maxBytes - total) fail('BYTES');
    if (b !== null) {
      edges[p].add(b);
      id = parent.length;
      parent.push(p); tail.push(b); size.push(n); edges.push(new Set());
    }
    ids.push(id); total += n;
  }
  const out = new Uint8Array(total);
  let end = 0;
  for (let id of ids) {
    end += size[id];
    let k = end;
    while (id !== 0) { out[--k] = tail[id]; id = parent[id]; }
  }
  return out;
}
const assert = require('node:assert/strict');
const input = Uint8Array.from([65, 66, 65, 66, 65, 65, 66]);
const tokens = encode(input);
assert.deepEqual(tokens, [[0,65],[0,66],[1,66],[1,65],[2,null]]);
assert.deepEqual(decode(tokens), input);
console.log(JSON.stringify(tokens));
console.log(Array.from(decode(tokens)).join(','));

实际输出:

[[0,65],[0,66],[1,66],[1,65],[2,null]]
65,66,65,66,65,65,66

二、终止对只是最后的剩余短语

空输入对应空 token 数组,没有必须追加的结束 token。输入结束时若当前索引为零,说明最后一个普通 token 已完整消费数据,也不追加终止对。只有还持有一个非空、已存在的短语,才输出 [p, null]。因此两个 A 需要终止对,三个 A 恰好形成第二个新词条,反而不需要它。

终止对必须位于整个数组的最后,索引必须大于零,而且不新增词条。null 是接口层的特殊值,与字节零完全不同。不能用零字节表示结束,也不能把 undefined、空字符串或者缺失第二个字段等同于 null。接纳中间的终止对会让一个块出现多个结束位置,接纳零号终止对则会给空输入制造多种表示。

原始论文讨论增量分词及最后一段可能重复已有短语的情况;本文用显式 null 对表示这一工程边界,并非声称复刻论文的二进制编码。论文来源见 Ziv 与 Lempel 1978 年原文,第 533 页。

独立示例 02,保存为 02_terminal.cjs 后运行 node 02_terminal.cjs。

'use strict';
const fail = code => { throw new Error(code); };
const natural = x => Number.isSafeInteger(x) && x >= 0 && !Object.is(x, -0);
function limits({maxBytes = 1048576, maxEntries = 65536, maxTokens = 65536} = {}) {
  if (![maxBytes, maxEntries, maxTokens].every(natural)) fail('LIMIT');
  return {maxBytes, maxEntries, maxTokens};
}
function encode(input, options) {
  const l = limits(options);
  if (!(input instanceof Uint8Array)) fail('INPUT');
  if (input.length > l.maxBytes) fail('BYTES');
  const next = [new Map()], tokens = [];
  let p = 0;
  const emit = t => {
    if (tokens.length >= l.maxTokens) fail('TOKENS');
    tokens.push(t);
  };
  for (const b of input) {
    if (next[p].has(b)) { p = next[p].get(b); continue; }
    if (next.length - 1 >= l.maxEntries) fail('ENTRIES');
    emit([p, b]);
    next[p].set(b, next.length);
    next.push(new Map());
    p = 0;
  }
  if (p !== 0) emit([p, null]);
  return tokens;
}
function decode(tokens, options) {
  const l = limits(options);
  if (!Array.isArray(tokens)) fail('TOKENS_TYPE');
  if (tokens.length > l.maxTokens) fail('TOKENS');
  const parent = [0], tail = [0], size = [0], edges = [new Set()], ids = [];
  let total = 0;
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    if (!Array.isArray(t) || t.length !== 2) fail('PAIR');
    const [p, b] = t;
    if (!natural(p) || p >= parent.length) fail('INDEX');
    let id = p, n = size[p];
    if (b === null) {
      if (p === 0 || i !== tokens.length - 1) fail('TERMINAL');
    } else {
      if (!natural(b) || b > 255) fail('BYTE');
      if (edges[p].has(b)) fail('DUPLICATE');
      if (parent.length - 1 >= l.maxEntries) fail('ENTRIES');
      n++;
    }
    if (n > l.maxBytes - total) fail('BYTES');
    if (b !== null) {
      edges[p].add(b);
      id = parent.length;
      parent.push(p); tail.push(b); size.push(n); edges.push(new Set());
    }
    ids.push(id); total += n;
  }
  const out = new Uint8Array(total);
  let end = 0;
  for (let id of ids) {
    end += size[id];
    let k = end;
    while (id !== 0) { out[--k] = tail[id]; id = parent[id]; }
  }
  return out;
}
const assert = require('node:assert/strict');
for (const n of [0, 1, 2, 3, 4, 6]) {
  const a = new Uint8Array(n).fill(65);
  const ts = encode(a);
  assert.deepEqual(decode(ts), a);
  console.log(n + ': ' + JSON.stringify(ts));
}
assert.throws(() => decode([[0,null]]), /TERMINAL/);
assert.throws(() => decode([[0,65],[1,null],[0,66]]), /TERMINAL/);

实际输出:

0: []
1: [[0,65]]
2: [[0,65],[1,null]]
3: [[0,65],[1,65]]
4: [[0,65],[1,65],[1,null]]
6: [[0,65],[1,65],[2,65]]

三、字节接口不偷偷替你处理文本

字节域是零到二百五十五,所有值都必须能够原样往返,包含零、高位字节和并非有效 UTF-8 的序列。把输入先转换成 JavaScript 字符串,会把问题换成码元、码点或字符编码问题;这样的实现即使能还原英文句子,也没有证明能还原任意二进制内容。

示例先覆盖完整的二百五十六值字母表,再测试混合零和高位字节。中文及表情示例由调用方用 UTF-8 编成字节,往返后才解码回文字;词典不理解中文,也不承担 Unicode 规范化。类型化数组的转换本来就可能进行数值归一,故这里拒绝普通数组,避免在编解码入口默默把越界值折回。参见 ECMAScript 类型化数组规范。

这也界定了验证时机:若调用者已经执行 Uint8Array.from([256]),得到的就是字节零,编码器不可能恢复此前的错误意图。边界验证应在不可信数字转换成字节之前完成。解码 token 中的字节则仍是普通数字,所以代码能明确拒绝二百五十六。

独立示例 03,保存为 03_bytes.cjs 后运行 node 03_bytes.cjs。

'use strict';
const fail = code => { throw new Error(code); };
const natural = x => Number.isSafeInteger(x) && x >= 0 && !Object.is(x, -0);
function limits({maxBytes = 1048576, maxEntries = 65536, maxTokens = 65536} = {}) {
  if (![maxBytes, maxEntries, maxTokens].every(natural)) fail('LIMIT');
  return {maxBytes, maxEntries, maxTokens};
}
function encode(input, options) {
  const l = limits(options);
  if (!(input instanceof Uint8Array)) fail('INPUT');
  if (input.length > l.maxBytes) fail('BYTES');
  const next = [new Map()], tokens = [];
  let p = 0;
  const emit = t => {
    if (tokens.length >= l.maxTokens) fail('TOKENS');
    tokens.push(t);
  };
  for (const b of input) {
    if (next[p].has(b)) { p = next[p].get(b); continue; }
    if (next.length - 1 >= l.maxEntries) fail('ENTRIES');
    emit([p, b]);
    next[p].set(b, next.length);
    next.push(new Map());
    p = 0;
  }
  if (p !== 0) emit([p, null]);
  return tokens;
}
function decode(tokens, options) {
  const l = limits(options);
  if (!Array.isArray(tokens)) fail('TOKENS_TYPE');
  if (tokens.length > l.maxTokens) fail('TOKENS');
  const parent = [0], tail = [0], size = [0], edges = [new Set()], ids = [];
  let total = 0;
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    if (!Array.isArray(t) || t.length !== 2) fail('PAIR');
    const [p, b] = t;
    if (!natural(p) || p >= parent.length) fail('INDEX');
    let id = p, n = size[p];
    if (b === null) {
      if (p === 0 || i !== tokens.length - 1) fail('TERMINAL');
    } else {
      if (!natural(b) || b > 255) fail('BYTE');
      if (edges[p].has(b)) fail('DUPLICATE');
      if (parent.length - 1 >= l.maxEntries) fail('ENTRIES');
      n++;
    }
    if (n > l.maxBytes - total) fail('BYTES');
    if (b !== null) {
      edges[p].add(b);
      id = parent.length;
      parent.push(p); tail.push(b); size.push(n); edges.push(new Set());
    }
    ids.push(id); total += n;
  }
  const out = new Uint8Array(total);
  let end = 0;
  for (let id of ids) {
    end += size[id];
    let k = end;
    while (id !== 0) { out[--k] = tail[id]; id = parent[id]; }
  }
  return out;
}
const assert = require('node:assert/strict');
const alphabet = Uint8Array.from({length:256}, (_, i) => i);
const binary = Uint8Array.from([0,255,0,128,255,0]);
const text = Uint8Array.from(Buffer.from('字典🙂', 'utf8'));
for (const a of [alphabet, binary, text]) assert.deepEqual(decode(encode(a)), a);
assert.throws(() => encode([256]), /INPUT/);
assert.throws(() => decode([[0,256]]), /BYTE/);
console.log('alphabet=' + alphabet.length + ', all bytes preserved');
console.log('binary=' + Array.from(decode(encode(binary))).join(','));
console.log('utf8=' + Buffer.from(decode(encode(text))).toString('utf8'));
console.log('plain array and byte 256 rejected');

实际输出:

alphabet=256, all bytes preserved
binary=0,255,0,128,255,0
utf8=字典🙂
plain array and byte 256 rejected

四、能展开不等于规范:重复边也必须拒绝

索引检查不能只看它是不是整数。它还必须非负、可安全表示,并且严格小于当前词典长度。负零虽然在很多比较中等于零,本文仍拒绝它,避免同一个逻辑值出现不必要的表示分歧。字符串数字、分数、非数和无穷值同样不做隐式转换。安全整数的语言语义可查 Number.isSafeInteger 规范。

重复普通对是更隐蔽的错误。[[0,65],[0,65]] 可以展开成 AA,却不可能由本文编码器生成,因为第二个 A 已在词典中,正确形式应使用终止对。解码器用每个父词条的字节集合拒绝重复边;这保证新增短语此前不存在,而不仅仅是输出内容看起来合理。

有些其他字典算法允许特殊的尚未定义索引,但那不是本接口的规则。审查 AI 生成代码时,不能把不同算法里的例外搬过来兜底。本例还把短对、额外字段和外层空洞列成明确错误,避免解构赋值产生 undefined 后继续运行。错误字符串只是本文稳定的测试接口,不是行业标准。

独立示例 04,保存为 04_malformed.cjs 后运行 node 04_malformed.cjs。

'use strict';
const fail = code => { throw new Error(code); };
const natural = x => Number.isSafeInteger(x) && x >= 0 && !Object.is(x, -0);
function limits({maxBytes = 1048576, maxEntries = 65536, maxTokens = 65536} = {}) {
  if (![maxBytes, maxEntries, maxTokens].every(natural)) fail('LIMIT');
  return {maxBytes, maxEntries, maxTokens};
}
function encode(input, options) {
  const l = limits(options);
  if (!(input instanceof Uint8Array)) fail('INPUT');
  if (input.length > l.maxBytes) fail('BYTES');
  const next = [new Map()], tokens = [];
  let p = 0;
  const emit = t => {
    if (tokens.length >= l.maxTokens) fail('TOKENS');
    tokens.push(t);
  };
  for (const b of input) {
    if (next[p].has(b)) { p = next[p].get(b); continue; }
    if (next.length - 1 >= l.maxEntries) fail('ENTRIES');
    emit([p, b]);
    next[p].set(b, next.length);
    next.push(new Map());
    p = 0;
  }
  if (p !== 0) emit([p, null]);
  return tokens;
}
function decode(tokens, options) {
  const l = limits(options);
  if (!Array.isArray(tokens)) fail('TOKENS_TYPE');
  if (tokens.length > l.maxTokens) fail('TOKENS');
  const parent = [0], tail = [0], size = [0], edges = [new Set()], ids = [];
  let total = 0;
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    if (!Array.isArray(t) || t.length !== 2) fail('PAIR');
    const [p, b] = t;
    if (!natural(p) || p >= parent.length) fail('INDEX');
    let id = p, n = size[p];
    if (b === null) {
      if (p === 0 || i !== tokens.length - 1) fail('TERMINAL');
    } else {
      if (!natural(b) || b > 255) fail('BYTE');
      if (edges[p].has(b)) fail('DUPLICATE');
      if (parent.length - 1 >= l.maxEntries) fail('ENTRIES');
      n++;
    }
    if (n > l.maxBytes - total) fail('BYTES');
    if (b !== null) {
      edges[p].add(b);
      id = parent.length;
      parent.push(p); tail.push(b); size.push(n); edges.push(new Set());
    }
    ids.push(id); total += n;
  }
  const out = new Uint8Array(total);
  let end = 0;
  for (let id of ids) {
    end += size[id];
    let k = end;
    while (id !== 0) { out[--k] = tail[id]; id = parent[id]; }
  }
  return out;
}
const assert = require('node:assert/strict');
const bad = [
  ['forward', [[1,65]], 'INDEX'],
  ['out-of-range', [[0,65],[2,66]], 'INDEX'],
  ['fraction', [[0.5,65]], 'INDEX'],
  ['negative-zero', [[-0,65]], 'INDEX'],
  ['string-index', [['0',65]], 'INDEX'],
  ['nan-byte', [[0,NaN]], 'BYTE'],
  ['negative-byte', [[0,-1]], 'BYTE'],
  ['short-pair', [[0]], 'PAIR'],
  ['extra-field', [[0,65,99]], 'PAIR'],
  ['hole', new Array(1), 'PAIR'],
  ['duplicate', [[0,65],[0,65]], 'DUPLICATE'],
  ['empty-terminal', [[0,null]], 'TERMINAL'],
  ['middle-terminal', [[0,65],[1,null],[0,66]], 'TERMINAL']
];
for (const [name, ts, code] of bad) {
  assert.throws(() => decode(ts), e => e.message === code);
  console.log(name + '=' + code);
}

实际输出:

forward=INDEX
out-of-range=INDEX
fraction=INDEX
negative-zero=INDEX
string-index=INDEX
nan-byte=BYTE
negative-byte=BYTE
short-pair=PAIR
extra-field=PAIR
hole=PAIR
duplicate=DUPLICATE
empty-terminal=TERMINAL
middle-terminal=TERMINAL

五、预算是拒绝条件,不是悄悄换一套词典

默认最多一 MiB 输入或输出、六万五千五百三十六个非空词条,以及同样数量的 token。零号根不占词条预算,终止对占 token 预算但不占新增词条预算。三个数都是非负安全整数,零预算可接受空数据。示例同时测试恰好到达边界和少一个单位的拒绝结果,避免只测远超限制的情况。

超过词典限制时,编码与解码都抛错,不冻结词典、不循环覆盖旧项,也不自动重置。若将来引入重置 token,就要重新定义它如何影响编号、末尾短语和规范性。把重置当作一个内部优化,会使编码器输出的索引在解码端指向不同短语,这是格式层面的破坏。

解码器先检查新增长度是否大于剩余输出预算,再分配结果;因此短 token 流也不能绕过展开上限。限制只约束本实现处理的条目和字节,不包含输入 JSON 解析器、对象开销或宿主内存分配失败。上游仍应限制请求体大小,并按实际服务内存配置预算;允许很大的安全整数不代表宿主能分配相应数组。

独立示例 05,保存为 05_budgets.cjs 后运行 node 05_budgets.cjs。

'use strict';
const fail = code => { throw new Error(code); };
const natural = x => Number.isSafeInteger(x) && x >= 0 && !Object.is(x, -0);
function limits({maxBytes = 1048576, maxEntries = 65536, maxTokens = 65536} = {}) {
  if (![maxBytes, maxEntries, maxTokens].every(natural)) fail('LIMIT');
  return {maxBytes, maxEntries, maxTokens};
}
function encode(input, options) {
  const l = limits(options);
  if (!(input instanceof Uint8Array)) fail('INPUT');
  if (input.length > l.maxBytes) fail('BYTES');
  const next = [new Map()], tokens = [];
  let p = 0;
  const emit = t => {
    if (tokens.length >= l.maxTokens) fail('TOKENS');
    tokens.push(t);
  };
  for (const b of input) {
    if (next[p].has(b)) { p = next[p].get(b); continue; }
    if (next.length - 1 >= l.maxEntries) fail('ENTRIES');
    emit([p, b]);
    next[p].set(b, next.length);
    next.push(new Map());
    p = 0;
  }
  if (p !== 0) emit([p, null]);
  return tokens;
}
function decode(tokens, options) {
  const l = limits(options);
  if (!Array.isArray(tokens)) fail('TOKENS_TYPE');
  if (tokens.length > l.maxTokens) fail('TOKENS');
  const parent = [0], tail = [0], size = [0], edges = [new Set()], ids = [];
  let total = 0;
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    if (!Array.isArray(t) || t.length !== 2) fail('PAIR');
    const [p, b] = t;
    if (!natural(p) || p >= parent.length) fail('INDEX');
    let id = p, n = size[p];
    if (b === null) {
      if (p === 0 || i !== tokens.length - 1) fail('TERMINAL');
    } else {
      if (!natural(b) || b > 255) fail('BYTE');
      if (edges[p].has(b)) fail('DUPLICATE');
      if (parent.length - 1 >= l.maxEntries) fail('ENTRIES');
      n++;
    }
    if (n > l.maxBytes - total) fail('BYTES');
    if (b !== null) {
      edges[p].add(b);
      id = parent.length;
      parent.push(p); tail.push(b); size.push(n); edges.push(new Set());
    }
    ids.push(id); total += n;
  }
  const out = new Uint8Array(total);
  let end = 0;
  for (let id of ids) {
    end += size[id];
    let k = end;
    while (id !== 0) { out[--k] = tail[id]; id = parent[id]; }
  }
  return out;
}
const assert = require('node:assert/strict');
const a = Uint8Array.from([65,65,65,65]);
const ts = [[0,65],[1,65],[1,null]];
const exact = {maxBytes:4, maxEntries:2, maxTokens:3};
assert.deepEqual(encode(a, exact), ts);
assert.deepEqual(decode(ts, exact), a);
for (const [key, value, code] of [
  ['maxBytes',3,'BYTES'], ['maxEntries',1,'ENTRIES'], ['maxTokens',2,'TOKENS']
]) {
  const l = {...exact, [key]:value};
  assert.throws(() => encode(a,l), e => e.message === code);
  assert.throws(() => decode(ts,l), e => e.message === code);
  console.log(key + '=' + code);
}
assert.deepEqual(decode([], {maxBytes:0,maxEntries:0,maxTokens:0}), new Uint8Array());
for (const x of [-1,-0,0.5,NaN,Infinity,'4',Number.MAX_SAFE_INTEGER+1])
  assert.throws(() => decode([], {maxBytes:x}), /LIMIT/);
console.log('exact boundary, zero budget and invalid limits passed');

实际输出:

maxBytes=BYTES
maxEntries=ENTRIES
maxTokens=TOKENS
exact boundary, zero budget and invalid limits passed

六、用另一个算法写法审查自己的算法

仅验证 decode(encode(x)) 等于 x 不足以证明实现正确:两个函数可能共享同一个错误约定。这里的 oracle 保存完整短语数组,每一步扫描所有词条选最长匹配;它不复用主实现的转移 Map、父链或长度表。独立解码模型也直接复制短语并拼接,通过完整短语内容判断重复。

穷举分两层进行。第一层覆盖完整字节字母表中长度零到二的全部六万五千七百九十三个输入,确保每种字节及相邻组合都被触及。第二层使用包含零和二百五十五的三值字母表,覆盖长度零到九的两万九千五百二十四个输入,深入检查词条复用与末尾残留。两层有重叠,报告计数是测试执行次数而非去重样本数。

每个输入同时核对 token 的逐项一致、主解码往返、独立解码往返以及再次编码不变。有限穷举不是对任意长度的形式证明,但它比挑几个自然语言句子更容易覆盖短小、反直觉的边界。独立性也要落到数据结构和决策过程上,换几个变量名不算第二个模型。

独立示例 06,保存为 06_oracles.cjs 后运行 node 06_oracles.cjs。

'use strict';
const fail = code => { throw new Error(code); };
const natural = x => Number.isSafeInteger(x) && x >= 0 && !Object.is(x, -0);
function limits({maxBytes = 1048576, maxEntries = 65536, maxTokens = 65536} = {}) {
  if (![maxBytes, maxEntries, maxTokens].every(natural)) fail('LIMIT');
  return {maxBytes, maxEntries, maxTokens};
}
function encode(input, options) {
  const l = limits(options);
  if (!(input instanceof Uint8Array)) fail('INPUT');
  if (input.length > l.maxBytes) fail('BYTES');
  const next = [new Map()], tokens = [];
  let p = 0;
  const emit = t => {
    if (tokens.length >= l.maxTokens) fail('TOKENS');
    tokens.push(t);
  };
  for (const b of input) {
    if (next[p].has(b)) { p = next[p].get(b); continue; }
    if (next.length - 1 >= l.maxEntries) fail('ENTRIES');
    emit([p, b]);
    next[p].set(b, next.length);
    next.push(new Map());
    p = 0;
  }
  if (p !== 0) emit([p, null]);
  return tokens;
}
function decode(tokens, options) {
  const l = limits(options);
  if (!Array.isArray(tokens)) fail('TOKENS_TYPE');
  if (tokens.length > l.maxTokens) fail('TOKENS');
  const parent = [0], tail = [0], size = [0], edges = [new Set()], ids = [];
  let total = 0;
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    if (!Array.isArray(t) || t.length !== 2) fail('PAIR');
    const [p, b] = t;
    if (!natural(p) || p >= parent.length) fail('INDEX');
    let id = p, n = size[p];
    if (b === null) {
      if (p === 0 || i !== tokens.length - 1) fail('TERMINAL');
    } else {
      if (!natural(b) || b > 255) fail('BYTE');
      if (edges[p].has(b)) fail('DUPLICATE');
      if (parent.length - 1 >= l.maxEntries) fail('ENTRIES');
      n++;
    }
    if (n > l.maxBytes - total) fail('BYTES');
    if (b !== null) {
      edges[p].add(b);
      id = parent.length;
      parent.push(p); tail.push(b); size.push(n); edges.push(new Set());
    }
    ids.push(id); total += n;
  }
  const out = new Uint8Array(total);
  let end = 0;
  for (let id of ids) {
    end += size[id];
    let k = end;
    while (id !== 0) { out[--k] = tail[id]; id = parent[id]; }
  }
  return out;
}
const assert = require('node:assert/strict');
function oracleEncode(a) {
  const d = [[]], out = [];
  let pos = 0;
  while (pos < a.length) {
    let best = 0;
    for (let j = 1; j < d.length; j++) {
      const w = d[j];
      if (w.length > d[best].length && pos + w.length <= a.length &&
          w.every((b, k) => b === a[pos + k])) best = j;
    }
    const n = d[best].length;
    if (pos + n === a.length) { out.push([best, null]); break; }
    const b = a[pos + n];
    out.push([best, b]); d.push(d[best].concat(b)); pos += n + 1;
  }
  return out;
}
function oracleDecode(ts) {
  const d = [[]], out = [], seen = new Set();
  for (let i = 0; i < ts.length; i++) {
    const [p, b] = ts[i];
    assert.ok(Number.isSafeInteger(p) && p >= 0 && p < d.length);
    let w = d[p].slice();
    if (b === null) {
      assert.ok(p > 0 && i === ts.length - 1);
    } else {
      assert.ok(Number.isInteger(b) && b >= 0 && b <= 255);
      w.push(b);
      const key = JSON.stringify(w);
      assert.ok(!seen.has(key)); seen.add(key); d.push(w);
    }
    out.push(...w);
  }
  return out;
}

let count = 0;
function check(a) {
  const expected = oracleEncode(a), actual = encode(Uint8Array.from(a));
  assert.deepEqual(actual, expected);
  assert.deepEqual(Array.from(decode(actual)), a);
  assert.deepEqual(oracleDecode(actual), a);
  assert.deepEqual(encode(decode(actual)), actual);
  count++;
}
check([]);
for (let a = 0; a < 256; a++) {
  check([a]);
  for (let b = 0; b < 256; b++) check([a,b]);
}
const full = count;
function visit(a) {
  check(a);
  if (a.length < 9) for (const b of [0,1,255]) visit(a.concat(b));
}
visit([]);
console.log('full byte alphabet, lengths 0..2: ' + full);
console.log('alphabet 0,1,255, lengths 0..9: ' + (count-full));
console.log('oracle and roundtrip checks: ' + count);

实际输出:

full byte alphabet, lengths 0..2: 65793
alphabet 0,1,255, lengths 0..9: 29524
oracle and roundtrip checks: 95317

七、反向穷举 token 空间,检查拒绝集合

正确输入覆盖充分,仍可能漏掉解码器对错误输入的宽容。这个示例反过来枚举长度零到四的 token 数组,每个索引取零到三,第二字段取零、二百五十五或 null,共两万二千六百二十一个候选。它不是拿主解码器自身的规则当预期,而是先用独立编码器生成合法集合。

为什么合法集合只需枚举长度到十的二进制字节串?四个普通 token 的短语长度最多依次是一、二、三、四,总输出最多十;若最后一个是终止对,上界更小。因此候选域内每一种有效输出都已包含在预先建立的集合里。这是有边界的穷举证明,不是在无限输入空间上取样。

结果中只有二百三十九个候选被接受,其余全部拒绝。对每个接受项,再核对独立短语解码以及重新编码后的逐项一致。此处枚举只包含两种普通字节,第四节额外承担类型错误、额外字段、负零和越界数字等结构性测试,二者互补。

独立示例 07,保存为 07_token_space.cjs 后运行 node 07_token_space.cjs。

'use strict';
const fail = code => { throw new Error(code); };
const natural = x => Number.isSafeInteger(x) && x >= 0 && !Object.is(x, -0);
function limits({maxBytes = 1048576, maxEntries = 65536, maxTokens = 65536} = {}) {
  if (![maxBytes, maxEntries, maxTokens].every(natural)) fail('LIMIT');
  return {maxBytes, maxEntries, maxTokens};
}
function encode(input, options) {
  const l = limits(options);
  if (!(input instanceof Uint8Array)) fail('INPUT');
  if (input.length > l.maxBytes) fail('BYTES');
  const next = [new Map()], tokens = [];
  let p = 0;
  const emit = t => {
    if (tokens.length >= l.maxTokens) fail('TOKENS');
    tokens.push(t);
  };
  for (const b of input) {
    if (next[p].has(b)) { p = next[p].get(b); continue; }
    if (next.length - 1 >= l.maxEntries) fail('ENTRIES');
    emit([p, b]);
    next[p].set(b, next.length);
    next.push(new Map());
    p = 0;
  }
  if (p !== 0) emit([p, null]);
  return tokens;
}
function decode(tokens, options) {
  const l = limits(options);
  if (!Array.isArray(tokens)) fail('TOKENS_TYPE');
  if (tokens.length > l.maxTokens) fail('TOKENS');
  const parent = [0], tail = [0], size = [0], edges = [new Set()], ids = [];
  let total = 0;
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    if (!Array.isArray(t) || t.length !== 2) fail('PAIR');
    const [p, b] = t;
    if (!natural(p) || p >= parent.length) fail('INDEX');
    let id = p, n = size[p];
    if (b === null) {
      if (p === 0 || i !== tokens.length - 1) fail('TERMINAL');
    } else {
      if (!natural(b) || b > 255) fail('BYTE');
      if (edges[p].has(b)) fail('DUPLICATE');
      if (parent.length - 1 >= l.maxEntries) fail('ENTRIES');
      n++;
    }
    if (n > l.maxBytes - total) fail('BYTES');
    if (b !== null) {
      edges[p].add(b);
      id = parent.length;
      parent.push(p); tail.push(b); size.push(n); edges.push(new Set());
    }
    ids.push(id); total += n;
  }
  const out = new Uint8Array(total);
  let end = 0;
  for (let id of ids) {
    end += size[id];
    let k = end;
    while (id !== 0) { out[--k] = tail[id]; id = parent[id]; }
  }
  return out;
}
const assert = require('node:assert/strict');
function oracleEncode(a) {
  const d = [[]], out = [];
  let pos = 0;
  while (pos < a.length) {
    let best = 0;
    for (let j = 1; j < d.length; j++) {
      const w = d[j];
      if (w.length > d[best].length && pos + w.length <= a.length &&
          w.every((b, k) => b === a[pos + k])) best = j;
    }
    const n = d[best].length;
    if (pos + n === a.length) { out.push([best, null]); break; }
    const b = a[pos + n];
    out.push([best, b]); d.push(d[best].concat(b)); pos += n + 1;
  }
  return out;
}
function oracleDecode(ts) {
  const d = [[]], out = [], seen = new Set();
  for (let i = 0; i < ts.length; i++) {
    const [p, b] = ts[i];
    assert.ok(Number.isSafeInteger(p) && p >= 0 && p < d.length);
    let w = d[p].slice();
    if (b === null) {
      assert.ok(p > 0 && i === ts.length - 1);
    } else {
      assert.ok(Number.isInteger(b) && b >= 0 && b <= 255);
      w.push(b);
      const key = JSON.stringify(w);
      assert.ok(!seen.has(key)); seen.add(key); d.push(w);
    }
    out.push(...w);
  }
  return out;
}

const canonical = new Map();
function words(a) {
  const ts = oracleEncode(a);
  if (ts.length <= 4) canonical.set(JSON.stringify(ts), a);
  if (a.length < 10) for (const b of [0,255]) words(a.concat(b));
}
words([]);
let checked = 0, accepted = 0;
function visit(ts) {
  const key = JSON.stringify(ts), want = canonical.get(key);
  let got, error;
  try { got = Array.from(decode(ts)); } catch (e) { error = e; }
  if (want === undefined) assert.ok(error, key);
  else {
    assert.ifError(error); assert.deepEqual(got, want);
    assert.deepEqual(oracleDecode(ts), want);
    assert.deepEqual(encode(Uint8Array.from(got)), ts);
    accepted++;
  }
  checked++;
  if (ts.length < 4) for (let p = 0; p < 4; p++)
    for (const b of [0,255,null]) visit(ts.concat([[p,b]]));
}
visit([]);
console.log('candidate token arrays=' + checked);
console.log('accepted canonical arrays=' + accepted);
console.log('rejected=' + (checked-accepted));

实际输出:

candidate token arrays=22621
accepted canonical arrays=239
rejected=22382

八、固定随机种子,验证所有权和确定性

随机测试覆盖更长的组合,但必须固定种子,才能把失败复现成同一串字节。五百个案例交替使用二值、十七值和完整字节域,长度小于四百;它们继续与朴素词典模型逐项对照,而不是只检查输出长度。随机生成器只服务测试,不是安全随机源。

代码还保存输入和 token 的快照,证明本次调用没有改写它们;随后修改解码结果,再核对原输入不变。新返回的字节缓冲区不应与源输入共享可变存储,否则调用者处理输出时会破坏下一次测试。确定性要求相同字节在同样预算下产生同样的对序列,而不是依赖跨调用遗留的全局词典。

独立示例 08,保存为 08_random.cjs 后运行 node 08_random.cjs。

'use strict';
const fail = code => { throw new Error(code); };
const natural = x => Number.isSafeInteger(x) && x >= 0 && !Object.is(x, -0);
function limits({maxBytes = 1048576, maxEntries = 65536, maxTokens = 65536} = {}) {
  if (![maxBytes, maxEntries, maxTokens].every(natural)) fail('LIMIT');
  return {maxBytes, maxEntries, maxTokens};
}
function encode(input, options) {
  const l = limits(options);
  if (!(input instanceof Uint8Array)) fail('INPUT');
  if (input.length > l.maxBytes) fail('BYTES');
  const next = [new Map()], tokens = [];
  let p = 0;
  const emit = t => {
    if (tokens.length >= l.maxTokens) fail('TOKENS');
    tokens.push(t);
  };
  for (const b of input) {
    if (next[p].has(b)) { p = next[p].get(b); continue; }
    if (next.length - 1 >= l.maxEntries) fail('ENTRIES');
    emit([p, b]);
    next[p].set(b, next.length);
    next.push(new Map());
    p = 0;
  }
  if (p !== 0) emit([p, null]);
  return tokens;
}
function decode(tokens, options) {
  const l = limits(options);
  if (!Array.isArray(tokens)) fail('TOKENS_TYPE');
  if (tokens.length > l.maxTokens) fail('TOKENS');
  const parent = [0], tail = [0], size = [0], edges = [new Set()], ids = [];
  let total = 0;
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    if (!Array.isArray(t) || t.length !== 2) fail('PAIR');
    const [p, b] = t;
    if (!natural(p) || p >= parent.length) fail('INDEX');
    let id = p, n = size[p];
    if (b === null) {
      if (p === 0 || i !== tokens.length - 1) fail('TERMINAL');
    } else {
      if (!natural(b) || b > 255) fail('BYTE');
      if (edges[p].has(b)) fail('DUPLICATE');
      if (parent.length - 1 >= l.maxEntries) fail('ENTRIES');
      n++;
    }
    if (n > l.maxBytes - total) fail('BYTES');
    if (b !== null) {
      edges[p].add(b);
      id = parent.length;
      parent.push(p); tail.push(b); size.push(n); edges.push(new Set());
    }
    ids.push(id); total += n;
  }
  const out = new Uint8Array(total);
  let end = 0;
  for (let id of ids) {
    end += size[id];
    let k = end;
    while (id !== 0) { out[--k] = tail[id]; id = parent[id]; }
  }
  return out;
}
const assert = require('node:assert/strict');
function oracleEncode(a) {
  const d = [[]], out = [];
  let pos = 0;
  while (pos < a.length) {
    let best = 0;
    for (let j = 1; j < d.length; j++) {
      const w = d[j];
      if (w.length > d[best].length && pos + w.length <= a.length &&
          w.every((b, k) => b === a[pos + k])) best = j;
    }
    const n = d[best].length;
    if (pos + n === a.length) { out.push([best, null]); break; }
    const b = a[pos + n];
    out.push([best, b]); d.push(d[best].concat(b)); pos += n + 1;
  }
  return out;
}
function oracleDecode(ts) {
  const d = [[]], out = [], seen = new Set();
  for (let i = 0; i < ts.length; i++) {
    const [p, b] = ts[i];
    assert.ok(Number.isSafeInteger(p) && p >= 0 && p < d.length);
    let w = d[p].slice();
    if (b === null) {
      assert.ok(p > 0 && i === ts.length - 1);
    } else {
      assert.ok(Number.isInteger(b) && b >= 0 && b <= 255);
      w.push(b);
      const key = JSON.stringify(w);
      assert.ok(!seen.has(key)); seen.add(key); d.push(w);
    }
    out.push(...w);
  }
  return out;
}

let state = 0x12345678, count = 0;
function rand() {
  state = (Math.imul(state,1664525) + 1013904223) >>> 0;
  return state;
}
for (let test = 0; test < 500; test++) {
  const n = rand() % 400, width = [2,17,256][test % 3];
  const a = Uint8Array.from({length:n}, () => (rand() >>> 16) % width);
  const before = a.slice(), ts = encode(a), snapshot = JSON.stringify(ts);
  assert.deepEqual(ts, oracleEncode(Array.from(a)));
  const out = decode(ts);
  assert.deepEqual(out,a); assert.deepEqual(a,before);
  assert.equal(JSON.stringify(ts),snapshot);
  assert.deepEqual(oracleDecode(ts),Array.from(a));
  if (out.length) out[0] ^= 255;
  assert.deepEqual(a,before);
  count++;
}
console.log('seed=0x12345678, cases=' + count);
console.log('oracle, input immutability and fresh output passed');

实际输出:

seed=0x12345678, cases=500
oracle, input immutability and fresh output passed

九、长重复串揭示词典增长与输出膨胀

最后一个示例把两万个相同字节编码成二百个 token,同时构造两百个普通对逐层引用前项的链,展开为两万零一百个字节。后者的长度是前两百个正整数之和,说明 token 个数不能代替输出预算。本文只报告数量关系,绝不据此给出压缩百分比,因为尚未定义每个 token 的实际位数。

在常见哈希实现假设下,编码对每个输入字节做常数次查表,解码对每个输出字节做一次父链展开;主结构规模与词条、token 和输出字节数相应增长。语言规范对 Map 只要求平均次线性访问,并不承诺最坏情况常数时间,因此这里不把工程估计写成语言保证。参见 ECMAScript Map 对象规范。

可接受 token 必须保持词典前缀封闭:新项来自旧项追加一字节,且新增边此前不存在。于是其每个真前缀都已知,而完整新短语未知,编码器必定在同一位置输出同一对。最后的已知短语只允许作为终止对出现。这给出规范性的归纳理由:在资源预算容许的范围内,接受的 token 再解码、再编码后不变。测试检验实现是否遵守这个理由。

独立示例 09,保存为 09_lifecycle.cjs 后运行 node 09_lifecycle.cjs。

'use strict';
const fail = code => { throw new Error(code); };
const natural = x => Number.isSafeInteger(x) && x >= 0 && !Object.is(x, -0);
function limits({maxBytes = 1048576, maxEntries = 65536, maxTokens = 65536} = {}) {
  if (![maxBytes, maxEntries, maxTokens].every(natural)) fail('LIMIT');
  return {maxBytes, maxEntries, maxTokens};
}
function encode(input, options) {
  const l = limits(options);
  if (!(input instanceof Uint8Array)) fail('INPUT');
  if (input.length > l.maxBytes) fail('BYTES');
  const next = [new Map()], tokens = [];
  let p = 0;
  const emit = t => {
    if (tokens.length >= l.maxTokens) fail('TOKENS');
    tokens.push(t);
  };
  for (const b of input) {
    if (next[p].has(b)) { p = next[p].get(b); continue; }
    if (next.length - 1 >= l.maxEntries) fail('ENTRIES');
    emit([p, b]);
    next[p].set(b, next.length);
    next.push(new Map());
    p = 0;
  }
  if (p !== 0) emit([p, null]);
  return tokens;
}
function decode(tokens, options) {
  const l = limits(options);
  if (!Array.isArray(tokens)) fail('TOKENS_TYPE');
  if (tokens.length > l.maxTokens) fail('TOKENS');
  const parent = [0], tail = [0], size = [0], edges = [new Set()], ids = [];
  let total = 0;
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    if (!Array.isArray(t) || t.length !== 2) fail('PAIR');
    const [p, b] = t;
    if (!natural(p) || p >= parent.length) fail('INDEX');
    let id = p, n = size[p];
    if (b === null) {
      if (p === 0 || i !== tokens.length - 1) fail('TERMINAL');
    } else {
      if (!natural(b) || b > 255) fail('BYTE');
      if (edges[p].has(b)) fail('DUPLICATE');
      if (parent.length - 1 >= l.maxEntries) fail('ENTRIES');
      n++;
    }
    if (n > l.maxBytes - total) fail('BYTES');
    if (b !== null) {
      edges[p].add(b);
      id = parent.length;
      parent.push(p); tail.push(b); size.push(n); edges.push(new Set());
    }
    ids.push(id); total += n;
  }
  const out = new Uint8Array(total);
  let end = 0;
  for (let id of ids) {
    end += size[id];
    let k = end;
    while (id !== 0) { out[--k] = tail[id]; id = parent[id]; }
  }
  return out;
}
const assert = require('node:assert/strict');
const a = new Uint8Array(20000).fill(7);
const ts = encode(a);
assert.deepEqual(decode(ts), a);
const first = encode(Uint8Array.from([7,7]));
assert.deepEqual(first, [[0,7],[1,null]]);
assert.deepEqual(encode(Uint8Array.from([7,7])), first);
assert.throws(() => decode([[0,7],[0,7]]), /DUPLICATE/);
const chain = Array.from({length:200}, (_, i) => [i,7]);
assert.equal(decode(chain).length, 20100);
assert.throws(() => decode(chain,{maxBytes:20000}), /BYTES/);
assert.throws(() => decode(chain,{maxEntries:199}), /ENTRIES/);
console.log('repeated bytes=' + a.length + ', tokens=' + ts.length);
console.log('fresh calls restart the dictionary');
console.log('200-token chain expands to 20100 bytes; budgets enforced');

实际输出:

repeated bytes=20000, tokens=200
fresh calls restart the dictionary
200-token chain expands to 20100 bytes; budgets enforced

结语:先证明双方在同一本词典上工作

审查结论应当落在可复核的契约上:普通对只引用已有词条,新增短语唯一;终止对只负责最后的已知剩余部分;每次调用独立建表;预算不足明确失败。不要以一个成功的英文往返替代全字节测试,也不要把能够展开的任意对序列当作规范 LZ78 表示。

这里的断言使用 Node.js 官方 strict assert 接口。所有例子均可独立运行,输出没有时间戳或随机浮动字段。需要扩展成流式协议时,先补齐块长度、截断检测、重置规则与位布局,再谈真实压缩效率;那些是新的协议设计,不能靠给当前二元组数组改一个名字完成。

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