AI 代码审查实战:用 JavaScript 实现并验证 Count-Min Sketch
如果让 AI 写一个流式热点计数器,它很可能交出一段几十行的 Count-Min Sketch。代码看起来简单:哈希几次、增加桶值、查询取最小值。真正值得代码审查的部分,却是计数是否精确、碰撞是否承认、分片能否合并,以及理论保证究竟依赖什么。本文用九个可独立运行的 Node.js 示例,把这些问题逐项变成可复核的断言。
本文只实现插入式、非负 BigInt 权重的点查询。它估计某个已知键的累计频次,不保存完整键集合,也不提供删除接口、去重、自动发现 Top-K 或精确账务能力。需要精确扣费、库存扣减或安全封禁时,不能把这里的估计直接当作最终事实。AI 可以帮助生成候选实现和边界测试,最终接受什么误差、使用什么哈希、怎样处理重复事件,仍然必须写进接口契约。

先写审查任务,再让 AI 写实现
给 AI 的任务应该明确:实现增量非负的频次草图,计数全程使用 BigInt,拒绝负增量和隐式类型转换;列出哈希及编码契约;合并必须校验配置并返回新对象;给出独立 Map 裁判和确定性的失败反例。要求模型把已通过测试的事实、需要数学假设的结论、没有实现的能力分开陈述。这样评审的对象是一份可验证的接口,而不是一段听上去很像论文的说明。
运行方式:把任意一个示例的全部代码保存为 example.cjs,在支持 BigInt 和私有类字段的 Node.js 中执行 node example.cjs。本文所有展示输出均来自 Node.js v24.19.0 的实际运行;每段代码只依赖内置断言模块,不读取网络、随机数、其他示例或第三方包。
示例一:先建立不使用哈希的精确裁判
让 AI 直接补全数据结构,最容易漏掉的是输入语义。这里先写一份完全独立的 Map 计数器:键只能是字符串,增量只能是非负 BigInt,零增量允许通过。每个键的真实频次是增量之和,总量 N 是所有增量之和,不是不同键的数量,也不一定等于事件条数。后面的草图必须接受同一条事件流,再与这份裁判比较。
中文键、空字符串和看起来相同的 Unicode 文本也需要约定。本文按 JavaScript 字符串的 UTF-16 码元序列区分键,不自动做大小写折叠或 Unicode 规范化。示例中的两种 é 是不同的键;如果业务需要合并,必须在所有生产者进入草图前采用同一规则,不能某个分片单独处理。
"use strict";
const assert = require("node:assert/strict");
function exactAdd(map, key, delta) {
if (typeof key !== "string" || typeof delta !== "bigint" || delta < 0n)
throw new TypeError("invalid event");
map.set(key, (map.get(key) ?? 0n) + delta);
}
const events = [["接口", 3n], ["接口", 2n], ["", 0n],
["é", 1n], ["e\u0301", 4n]];
const oracle = new Map();
for (const [key, delta] of events) exactAdd(oracle, key, delta);
const total = [...oracle.values()].reduce((a, b) => a + b, 0n);
assert.equal(oracle.get("接口"), 5n);
assert.equal(oracle.size, 4);
assert.equal(total, 10n);
assert.throws(() => exactAdd(oracle, "接口", -1n), TypeError);
console.log("exact 接口 =", String(oracle.get("接口")));
console.log("keys =", oracle.size, "total =", String(total));运行输出:
exact 接口 = 5 keys = 4 total = 10
示例二:计数器溢出会直接破坏不低估性质
审查一个概率算法,不能只审查概率公式。Number 超过安全整数范围后无法逐个表示整数;Uint32Array 会按固定位宽回绕;BigUint64Array 虽然元素是 BigInt,仍然只有六十四位。只要计数器回绕,草图就可能低于真实频次,原本最可靠的单侧性质也随之消失。
因此本文用普通数组保存 BigInt,索引、行数和哈希的三十二位运算仍然使用 Number。哈希中有意截断与计数中禁止截断是两个不同决定。不要先把巨大十进制输入解析成 Number,再转 BigInt,那一步已经丢掉的信息不会恢复。以下实验给出可复现的边界,而不是声称每个小计数都会出现精度问题。
"use strict";
const assert = require("node:assert/strict");
const unsafe = Number.MAX_SAFE_INTEGER + 1;
assert.equal(unsafe + 1, unsafe);
const u32 = new Uint32Array([0xffffffff]);
u32[0] += 1;
const u64 = new BigUint64Array([(1n << 64n) - 1n]);
u64[0] += 1n;
const wide = [(1n << 64n) - 1n];
wide[0] += 1n;
assert.equal(u32[0], 0);
assert.equal(u64[0], 0n);
assert.equal(wide[0], 1n << 64n);
console.log("Number loses +1 =", unsafe + 1 === unsafe);
console.log("Uint32 =", u32[0], "BigUint64 =", String(u64[0]));
console.log("plain BigInt =", String(wide[0]));运行输出:
Number loses +1 = true Uint32 = 0 BigUint64 = 0 plain BigInt = 18446744073709551616
示例三:二维数组的行必须真的是不同对象
AI 经常给出很简洁的 Array(depth).fill(Array(width).fill(0n))。问题不在 BigInt 是不是可变对象,而在外层 fill 把同一个行数组的引用填进了所有位置。一次行更新会污染其他行;即便所有断言恰好没有低估,实际语义也已经不是每行各记一次。
这个缺陷适合用一个极小反例隔离,不要让它混在几千条随机输入中。正确构造每一行后,还要检查零增量、空草图查询以及对外暴露数组的方式。本文的快照会复制外层和每个内层数组,调用者修改快照不会悄悄改写计数状态。
"use strict";
const assert = require("node:assert/strict");
const bad = Array(2).fill(Array(3).fill(0n));
bad[0][1] += 5n;
assert.equal(bad[1][1], 5n);
const good = Array.from({ length: 2 }, () => Array(3).fill(0n));
good[0][1] += 5n;
assert.equal(good[1][1], 0n);
assert.notEqual(good[0], good[1]);
console.log("aliased second row =", String(bad[1][1]));
console.log("independent second row =", String(good[1][1]));运行输出:
aliased second row = 5 independent second row = 0
示例四:可审查的插入式 Count-Min Sketch 实现
现在再看完整实现。一次 add 在每行的一个哈希位置增加同样的 delta,estimate 读取这些位置中的最小值。碰撞只会增加非负的额外贡献,所以即使哈希分布很差,正确实现也不会低估。最小值能够避开某些行中的污染,却不能保证总有一行完全没有污染。
这里特意使用固定、带行种子的 FNV 风格三十二位哈希,方便读者复现;按 UTF-16 小端字节顺序逐个混入码元。不同种子不等于已经证明行间独立,这个工程哈希也没有在本文中证明满足通用哈希族的碰撞上界。因此类名代表计数与取最小值的结构,不能直接把论文的失败概率贴到这份实现上。
宽度、行数和总桶数有明确上限,防止配置错误触发意外的大分配;这些是教学实现的资源护栏,不是算法定理。私有字段避免调用者直接塞入负数。测试先用单键巨大频次排除碰撞干扰,再确认构造器复制种子、快照复制行。后续需要 CMS 的示例会重复完整核心,存成单独的 .cjs 文件即可运行,不依赖前一个示例的变量。
"use strict";
const assert = require("node:assert/strict");
const HASH = "fnv1a32-utf16le-v1";
function hash(key, seed, width) {
let h = (2166136261 ^ seed) >>> 0;
for (let i = 0; i < key.length; i++) {
const u = key.charCodeAt(i);
h = Math.imul(h ^ (u & 255), 16777619) >>> 0;
h = Math.imul(h ^ (u >>> 8), 16777619) >>> 0;
}
return h % width;
}
class CMS {
#width; #seeds; #rows; #total = 0n;
constructor(width, seeds) {
if (!Number.isSafeInteger(width) || width < 1 || width > 65536)
throw new RangeError("width");
if (!Array.isArray(seeds) || seeds.length < 1 || seeds.length > 16 ||
width * seeds.length > 262144)
throw new RangeError("rows");
for (const x of seeds)
if (!Number.isInteger(x) || x < 0 || x > 0xffffffff)
throw new RangeError("seed");
if (new Set(seeds).size !== seeds.length)
throw new RangeError("duplicate seed");
this.#width = width;
this.#seeds = [...seeds];
this.#rows = seeds.map(() => Array(width).fill(0n));
}
#positions(key) {
if (typeof key !== "string") throw new TypeError("string key required");
return this.#seeds.map(s => hash(key, s, this.#width));
}
add(key, delta = 1n) {
if (typeof delta !== "bigint" || delta < 0n)
throw new TypeError("nonnegative BigInt required");
const positions = this.#positions(key);
for (let r = 0; r < positions.length; r++)
this.#rows[r][positions[r]] += delta;
this.#total += delta;
return this;
}
estimate(key) {
const positions = this.#positions(key);
let result = this.#rows[0][positions[0]];
for (let r = 1; r < positions.length; r++) {
const value = this.#rows[r][positions[r]];
if (value < result) result = value;
}
return result;
}
get total() { return this.#total; }
snapshot() {
return { version: 1, hash: HASH, width: this.#width,
seeds: [...this.#seeds], total: this.#total,
rows: this.#rows.map(row => [...row]) };
}
merge(other) {
if (!(other instanceof CMS) || this.#width !== other.#width ||
this.#seeds.length !== other.#seeds.length ||
this.#seeds.some((s, r) => s !== other.#seeds[r]))
throw new TypeError("incompatible sketch");
const out = new CMS(this.#width, this.#seeds);
for (let r = 0; r < this.#rows.length; r++)
for (let c = 0; c < this.#width; c++)
out.#rows[r][c] = this.#rows[r][c] + other.#rows[r][c];
out.#total = this.#total + other.#total;
return out;
}
}
const seeds = [1, 7, 19];
const sketch = new CMS(17, seeds);
assert.equal(sketch.estimate("empty"), 0n);
seeds[0] = 99;
const large = 9007199254740993n;
sketch.add("接口", large).add("接口", 2n).add("接口", 0n);
assert.equal(sketch.estimate("接口"), large + 2n);
assert.equal(sketch.total, large + 2n);
const copy = sketch.snapshot();
copy.rows[0].fill(0n);
assert.equal(sketch.estimate("接口"), large + 2n);
assert.equal(sketch.snapshot().seeds[0], 1);
console.log("estimate =", String(sketch.estimate("接口")));
console.log("snapshot isolated = true");运行输出:
estimate = 9007199254740995 snapshot isolated = true
示例五:故意制造碰撞,再用精确 Map 对照
不能只用没有碰撞的小例子宣布正确。宽度取一时,所有键都会落进每行唯一的桶;未出现的键也能得到正估计。这个反例提醒调用方,estimate 的返回值不是数据库中的真实行数,正值也不是成员存在的证据。它只能作为近似频次,用来筛选需要进一步精查的对象。
第二段把三十个键挤进两列,逐条生成加权事件,同时更新独立的 Map。对所有已出现键检查估计不低于真实频次,检查每行桶之和等于总量,并确认测试确实观察到至少一次高估。这里裁判没有复用 hash、estimate 或草图计数逻辑。通过这些不变量是实现正确性的证据,有限样本的误差比例仍不能替代对哈希族的数学证明。
"use strict";
const assert = require("node:assert/strict");
const HASH = "fnv1a32-utf16le-v1";
function hash(key, seed, width) {
let h = (2166136261 ^ seed) >>> 0;
for (let i = 0; i < key.length; i++) {
const u = key.charCodeAt(i);
h = Math.imul(h ^ (u & 255), 16777619) >>> 0;
h = Math.imul(h ^ (u >>> 8), 16777619) >>> 0;
}
return h % width;
}
class CMS {
#width; #seeds; #rows; #total = 0n;
constructor(width, seeds) {
if (!Number.isSafeInteger(width) || width < 1 || width > 65536)
throw new RangeError("width");
if (!Array.isArray(seeds) || seeds.length < 1 || seeds.length > 16 ||
width * seeds.length > 262144)
throw new RangeError("rows");
for (const x of seeds)
if (!Number.isInteger(x) || x < 0 || x > 0xffffffff)
throw new RangeError("seed");
if (new Set(seeds).size !== seeds.length)
throw new RangeError("duplicate seed");
this.#width = width;
this.#seeds = [...seeds];
this.#rows = seeds.map(() => Array(width).fill(0n));
}
#positions(key) {
if (typeof key !== "string") throw new TypeError("string key required");
return this.#seeds.map(s => hash(key, s, this.#width));
}
add(key, delta = 1n) {
if (typeof delta !== "bigint" || delta < 0n)
throw new TypeError("nonnegative BigInt required");
const positions = this.#positions(key);
for (let r = 0; r < positions.length; r++)
this.#rows[r][positions[r]] += delta;
this.#total += delta;
return this;
}
estimate(key) {
const positions = this.#positions(key);
let result = this.#rows[0][positions[0]];
for (let r = 1; r < positions.length; r++) {
const value = this.#rows[r][positions[r]];
if (value < result) result = value;
}
return result;
}
get total() { return this.#total; }
snapshot() {
return { version: 1, hash: HASH, width: this.#width,
seeds: [...this.#seeds], total: this.#total,
rows: this.#rows.map(row => [...row]) };
}
merge(other) {
if (!(other instanceof CMS) || this.#width !== other.#width ||
this.#seeds.length !== other.#seeds.length ||
this.#seeds.some((s, r) => s !== other.#seeds[r]))
throw new TypeError("incompatible sketch");
const out = new CMS(this.#width, this.#seeds);
for (let r = 0; r < this.#rows.length; r++)
for (let c = 0; c < this.#width; c++)
out.#rows[r][c] = this.#rows[r][c] + other.#rows[r][c];
out.#total = this.#total + other.#total;
return out;
}
}
const forced = new CMS(1, [1, 7, 19]);
forced.add("hot", 7n);
const absentTruth = new Map([["hot", 7n]]).get("absent") ?? 0n;
assert.equal(absentTruth, 0n);
assert.equal(forced.estimate("absent"), 7n);
const sketch = new CMS(2, [1, 7, 19]);
const oracle = new Map();
let total = 0n;
for (let i = 0; i < 200; i++) {
const key = "item-" + (i % 30), delta = BigInt(i % 5 + 1);
oracle.set(key, (oracle.get(key) ?? 0n) + delta);
total += delta;
sketch.add(key, delta);
}
let overestimates = 0;
for (const [key, truth] of oracle) {
const estimate = sketch.estimate(key);
assert(estimate >= truth);
if (estimate > truth) overestimates++;
}
for (const row of sketch.snapshot().rows)
assert.equal(row.reduce((a, b) => a + b, 0n), total);
assert(overestimates > 0);
assert.equal(sketch.total, total);
console.log("absent exact = 0 estimate =", String(forced.estimate("absent")));
console.log("checked keys =", oracle.size, "overestimates =", overestimates);
console.log("total =", String(total));运行输出:
absent exact = 0 estimate = 7 checked keys = 30 overestimates = 30 total = 600
示例六:合并的是同一坐标系中的桶,不是查询结果
线性累加是这类草图适合分片处理的原因。只要宽度、深度、哈希算法、键编码和每行种子及顺序完全一致,就可以逐桶相加,结果等于把两个输入流依次交给同一草图。本文所有实例来自同一固定版本的类,因此算法和编码在进程内一致;跨语言或跨版本传输必须把版本标识也纳入检查。
不要用 estimateA(key) 加 estimateB(key) 代替真正合并,两个最小值可能来自不同的行。也不要把 merge 当成集合并集:相同事件出现在两个分片会被算两次,同一个草图与自己合并也会把所有计数翻倍。下面既比较全部桶,也比较总量,并验证输入草图没有被修改;精确 Map 对合并后的键频次再做一层独立检查。
"use strict";
const assert = require("node:assert/strict");
const HASH = "fnv1a32-utf16le-v1";
function hash(key, seed, width) {
let h = (2166136261 ^ seed) >>> 0;
for (let i = 0; i < key.length; i++) {
const u = key.charCodeAt(i);
h = Math.imul(h ^ (u & 255), 16777619) >>> 0;
h = Math.imul(h ^ (u >>> 8), 16777619) >>> 0;
}
return h % width;
}
class CMS {
#width; #seeds; #rows; #total = 0n;
constructor(width, seeds) {
if (!Number.isSafeInteger(width) || width < 1 || width > 65536)
throw new RangeError("width");
if (!Array.isArray(seeds) || seeds.length < 1 || seeds.length > 16 ||
width * seeds.length > 262144)
throw new RangeError("rows");
for (const x of seeds)
if (!Number.isInteger(x) || x < 0 || x > 0xffffffff)
throw new RangeError("seed");
if (new Set(seeds).size !== seeds.length)
throw new RangeError("duplicate seed");
this.#width = width;
this.#seeds = [...seeds];
this.#rows = seeds.map(() => Array(width).fill(0n));
}
#positions(key) {
if (typeof key !== "string") throw new TypeError("string key required");
return this.#seeds.map(s => hash(key, s, this.#width));
}
add(key, delta = 1n) {
if (typeof delta !== "bigint" || delta < 0n)
throw new TypeError("nonnegative BigInt required");
const positions = this.#positions(key);
for (let r = 0; r < positions.length; r++)
this.#rows[r][positions[r]] += delta;
this.#total += delta;
return this;
}
estimate(key) {
const positions = this.#positions(key);
let result = this.#rows[0][positions[0]];
for (let r = 1; r < positions.length; r++) {
const value = this.#rows[r][positions[r]];
if (value < result) result = value;
}
return result;
}
get total() { return this.#total; }
snapshot() {
return { version: 1, hash: HASH, width: this.#width,
seeds: [...this.#seeds], total: this.#total,
rows: this.#rows.map(row => [...row]) };
}
merge(other) {
if (!(other instanceof CMS) || this.#width !== other.#width ||
this.#seeds.length !== other.#seeds.length ||
this.#seeds.some((s, r) => s !== other.#seeds[r]))
throw new TypeError("incompatible sketch");
const out = new CMS(this.#width, this.#seeds);
for (let r = 0; r < this.#rows.length; r++)
for (let c = 0; c < this.#width; c++)
out.#rows[r][c] = this.#rows[r][c] + other.#rows[r][c];
out.#total = this.#total + other.#total;
return out;
}
}
const events = [["a", 3n], ["b", 8n], ["a", 2n], ["c", 5n], ["d", 1n]];
const left = new CMS(17, [1, 7, 19]);
const right = new CMS(17, [1, 7, 19]);
const all = new CMS(17, [1, 7, 19]);
const oracle = new Map();
events.forEach(([key, delta], i) => {
(i % 2 ? right : left).add(key, delta);
all.add(key, delta);
oracle.set(key, (oracle.get(key) ?? 0n) + delta);
});
const beforeLeft = left.snapshot(), beforeRight = right.snapshot();
const combined = left.merge(right);
assert.deepEqual(combined.snapshot(), all.snapshot());
assert.deepEqual(left.snapshot(), beforeLeft);
assert.deepEqual(right.snapshot(), beforeRight);
assert.deepEqual(right.merge(left).snapshot(), combined.snapshot());
for (const [key, truth] of oracle) assert(combined.estimate(key) >= truth);
const doubled = combined.merge(combined);
assert.equal(doubled.total, 2n * combined.total);
assert.equal(doubled.estimate("a"), 2n * combined.estimate("a"));
console.log("merged equals sequential = true");
console.log("total =", String(combined.total), "self-merge total =", String(doubled.total));运行输出:
merged equals sequential = true total = 19 self-merge total = 38
示例七:不兼容合并和非法更新必须在改写之前失败
只比较二维数组尺寸不足以确认兼容。两份草图行数相同、宽度相同,种子顺序不同,桶的含义就已经改变。把它们强行相加,虽然每行总量仍然正常,查询语义却错了。这说明总和不变量很有用,但无法单独证明所有行为正确。
此处把宽度、种子、顺序、深度四种不兼容情形逐一测试,再尝试负数、Number、字符串增量和非字符串键。拒绝之后比较完整快照,确保普通参数校验失败没有部分更新。资源耗尽或进程崩溃不属于这个原子性承诺;真正的多进程服务还需要自己的事务、锁或消息消费机制,单个 JavaScript 类不能替代这些设施。
"use strict";
const assert = require("node:assert/strict");
const HASH = "fnv1a32-utf16le-v1";
function hash(key, seed, width) {
let h = (2166136261 ^ seed) >>> 0;
for (let i = 0; i < key.length; i++) {
const u = key.charCodeAt(i);
h = Math.imul(h ^ (u & 255), 16777619) >>> 0;
h = Math.imul(h ^ (u >>> 8), 16777619) >>> 0;
}
return h % width;
}
class CMS {
#width; #seeds; #rows; #total = 0n;
constructor(width, seeds) {
if (!Number.isSafeInteger(width) || width < 1 || width > 65536)
throw new RangeError("width");
if (!Array.isArray(seeds) || seeds.length < 1 || seeds.length > 16 ||
width * seeds.length > 262144)
throw new RangeError("rows");
for (const x of seeds)
if (!Number.isInteger(x) || x < 0 || x > 0xffffffff)
throw new RangeError("seed");
if (new Set(seeds).size !== seeds.length)
throw new RangeError("duplicate seed");
this.#width = width;
this.#seeds = [...seeds];
this.#rows = seeds.map(() => Array(width).fill(0n));
}
#positions(key) {
if (typeof key !== "string") throw new TypeError("string key required");
return this.#seeds.map(s => hash(key, s, this.#width));
}
add(key, delta = 1n) {
if (typeof delta !== "bigint" || delta < 0n)
throw new TypeError("nonnegative BigInt required");
const positions = this.#positions(key);
for (let r = 0; r < positions.length; r++)
this.#rows[r][positions[r]] += delta;
this.#total += delta;
return this;
}
estimate(key) {
const positions = this.#positions(key);
let result = this.#rows[0][positions[0]];
for (let r = 1; r < positions.length; r++) {
const value = this.#rows[r][positions[r]];
if (value < result) result = value;
}
return result;
}
get total() { return this.#total; }
snapshot() {
return { version: 1, hash: HASH, width: this.#width,
seeds: [...this.#seeds], total: this.#total,
rows: this.#rows.map(row => [...row]) };
}
merge(other) {
if (!(other instanceof CMS) || this.#width !== other.#width ||
this.#seeds.length !== other.#seeds.length ||
this.#seeds.some((s, r) => s !== other.#seeds[r]))
throw new TypeError("incompatible sketch");
const out = new CMS(this.#width, this.#seeds);
for (let r = 0; r < this.#rows.length; r++)
for (let c = 0; c < this.#width; c++)
out.#rows[r][c] = this.#rows[r][c] + other.#rows[r][c];
out.#total = this.#total + other.#total;
return out;
}
}
const sketch = new CMS(8, [1, 7, 19]).add("x", 9n);
const before = sketch.snapshot();
const incompatible = [new CMS(9, [1, 7, 19]), new CMS(8, [1, 7, 20]),
new CMS(8, [7, 1, 19]), new CMS(8, [1, 7])];
for (const other of incompatible) {
assert.throws(() => sketch.merge(other), /incompatible sketch/);
assert.deepEqual(sketch.snapshot(), before);
}
for (const delta of [-1n, 1, "1", null]) {
assert.throws(() => sketch.add("x", delta), TypeError);
assert.deepEqual(sketch.snapshot(), before);
}
assert.throws(() => sketch.add(123, 1n), TypeError);
assert.throws(() => sketch.estimate({}), TypeError);
assert.deepEqual(sketch.snapshot(), before);
assert.throws(() => new CMS(0, [1]), RangeError);
assert.throws(() => new CMS(8, [1, 1]), RangeError);
console.log("incompatible merges rejected =", incompatible.length);
console.log("invalid inputs leave state unchanged = true");运行输出:
incompatible merges rejected = 4 invalid inputs leave state unchanged = true
示例八:持久化必须保住整数和协议身份
直接 JSON.stringify 含 BigInt 的对象,在没有自定义转换逻辑时会抛出 TypeError。为了让结果可以进入日志或持久化协议,下面只在明确的 total 和 rows 字段中使用十进制字符串,并保留版本、哈希标识、宽度及种子。没有把所有看似数字的字符串一律转回整数,避免误伤键名或版本描述。
解码器只接收本示例的受限快照协议:先限制文本长度和形状,再检查种子、桶值的十进制语法、位数和每行总量。它返回用于校验的普通快照对象,不冒充已恢复的可变 CMS 实例。这些检查能发现格式错误和部分损坏,不能证明外部文件记录的事件真实,也不是数字签名或访问控制。生产系统仍需明确可信来源、版本迁移和完整性保护。
"use strict";
const assert = require("node:assert/strict");
const HASH = "fnv1a32-utf16le-v1";
function hash(key, seed, width) {
let h = (2166136261 ^ seed) >>> 0;
for (let i = 0; i < key.length; i++) {
const u = key.charCodeAt(i);
h = Math.imul(h ^ (u & 255), 16777619) >>> 0;
h = Math.imul(h ^ (u >>> 8), 16777619) >>> 0;
}
return h % width;
}
class CMS {
#width; #seeds; #rows; #total = 0n;
constructor(width, seeds) {
if (!Number.isSafeInteger(width) || width < 1 || width > 65536)
throw new RangeError("width");
if (!Array.isArray(seeds) || seeds.length < 1 || seeds.length > 16 ||
width * seeds.length > 262144)
throw new RangeError("rows");
for (const x of seeds)
if (!Number.isInteger(x) || x < 0 || x > 0xffffffff)
throw new RangeError("seed");
if (new Set(seeds).size !== seeds.length)
throw new RangeError("duplicate seed");
this.#width = width;
this.#seeds = [...seeds];
this.#rows = seeds.map(() => Array(width).fill(0n));
}
#positions(key) {
if (typeof key !== "string") throw new TypeError("string key required");
return this.#seeds.map(s => hash(key, s, this.#width));
}
add(key, delta = 1n) {
if (typeof delta !== "bigint" || delta < 0n)
throw new TypeError("nonnegative BigInt required");
const positions = this.#positions(key);
for (let r = 0; r < positions.length; r++)
this.#rows[r][positions[r]] += delta;
this.#total += delta;
return this;
}
estimate(key) {
const positions = this.#positions(key);
let result = this.#rows[0][positions[0]];
for (let r = 1; r < positions.length; r++) {
const value = this.#rows[r][positions[r]];
if (value < result) result = value;
}
return result;
}
get total() { return this.#total; }
snapshot() {
return { version: 1, hash: HASH, width: this.#width,
seeds: [...this.#seeds], total: this.#total,
rows: this.#rows.map(row => [...row]) };
}
merge(other) {
if (!(other instanceof CMS) || this.#width !== other.#width ||
this.#seeds.length !== other.#seeds.length ||
this.#seeds.some((s, r) => s !== other.#seeds[r]))
throw new TypeError("incompatible sketch");
const out = new CMS(this.#width, this.#seeds);
for (let r = 0; r < this.#rows.length; r++)
for (let c = 0; c < this.#width; c++)
out.#rows[r][c] = this.#rows[r][c] + other.#rows[r][c];
out.#total = this.#total + other.#total;
return out;
}
}
function encode(sketch) {
const s = sketch.snapshot();
return JSON.stringify({ ...s, total: String(s.total),
rows: s.rows.map(row => row.map(String)) });
}
function decode(text) {
if (typeof text !== "string" || text.length > 2000000)
throw new TypeError("wire size");
const x = JSON.parse(text);
if (!x || x.version !== 1 || x.hash !== HASH)
throw new TypeError("wire version");
new CMS(x.width, x.seeds); // 复用配置校验,不恢复内部状态
if (!Array.isArray(x.rows) || x.rows.length !== x.seeds.length ||
x.rows.some(row => !Array.isArray(row) || row.length !== x.width))
throw new TypeError("wire shape");
function integer(v) {
if (typeof v !== "string" || v.length > 1000 || !/^(0|[1-9][0-9]*)$/.test(v))
throw new TypeError("wire integer");
return BigInt(v);
}
const total = integer(x.total);
const rows = x.rows.map(row => row.map(integer));
for (const row of rows)
if (row.reduce((a, b) => a + b, 0n) !== total)
throw new TypeError("wire sum");
return { version: 1, hash: HASH, width: x.width,
seeds: [...x.seeds], total, rows };
}
const sketch = new CMS(4, [1, 7]).add("接口", 9007199254740993n);
assert.throws(() => JSON.stringify(sketch.snapshot()), TypeError);
const wire = encode(sketch);
assert.deepEqual(decode(wire), sketch.snapshot());
const bad = JSON.parse(wire);
bad.rows[0][0] = "-1";
assert.throws(() => decode(JSON.stringify(bad)), /wire integer/);
const wrongVersion = JSON.parse(wire);
wrongVersion.hash = "other-v2";
assert.throws(() => decode(JSON.stringify(wrongVersion)), /wire version/);
console.log("round trip total =", String(decode(wire).total));
console.log("bad count and hash version rejected = true");运行输出:
round trip total = 9007199254740993 bad count and hash version rejected = true
示例九:把误差预算算清楚,但不要伪造概率证明
论文中常用的参数选择是宽度 w 向上取整 e/ε,深度 d 向上取整 ln(1/δ)。在固定的非负频次向量、固定查询键,以及满足碰撞界且各行独立抽取的随机哈希前提下,估计不低于真实值;以至少 1−δ 的概率,高估量不超过 εN。概率来自哈希的随机选择,不是每次查询重新抽一次彩票。原论文第四节的非负情形给出了这一结论。
注意这是相对于总量 N 的加性误差,而不是每个键都具有百分之一的相对误差。一个只出现一次的冷门键,在大流量中仍可能被严重高估。许多事先固定的查询若要联合保证,需要分配失败预算,例如对 Q 个查询使用每项 δ总/Q;不能直接宣称所有键、所有时刻、针对已公开种子自适应挑选的输入都自动享有同一保证。
本节只演示参数和大整数误差预算的计算。前面固定种子的工程哈希没有满足理论假设的证明,所以这段输出不是给那个类颁发的概率证书。要对外承诺概率界,应替换成已分析的哈希族,说明键域和映射方式,独立抽取各行函数,并审查取模是否改变碰撞上界。随机跑一百万条样本依然不能补上这些条件。
"use strict";
const assert = require("node:assert/strict");
const epsilon = 0.01, delta = 0.001;
const width = Math.ceil(Math.E / epsilon);
const depth = Math.ceil(Math.log(1 / delta));
assert.equal(width, 272);
assert.equal(depth, 7);
const total = 900719925474099300n;
// epsilon 的数学目标为精确的 1/100;整数误差上限向上取整。
const roundedBudget = (total + 99n) / 100n;
assert.equal(roundedBudget, 9007199254740993n);
console.log("theoretical width =", width, "depth =", depth);
console.log("ceil(N / 100) =", String(roundedBudget));
console.log("hash assumptions verified by this program = false");运行输出:
theoretical width = 272 depth = 7 ceil(N / 100) = 9007199254740993 hash assumptions verified by this program = false
把合格的实现与合格的使用场景一起验收
一次更新和查询会访问 d 行,但本实现还要为每一行扫描键的 UTF-16 码元,所以哈希开销随键长增长。普通 BigInt 计数器不会按固定位宽回绕,却会随数值变大消耗更多内存和计算时间;固定桶数不等于固定字节数。合并需要遍历全部桶,并且本实现为结果分配新数组。评估吞吐量时应使用实际键长、权重分布、草图尺寸和运行时版本,不能把抽象模型中的常数时间直接当成基准结果。
工程验收还应说明消费语义。消息重试会重复加数,合并重放也会重复加数;需要恰好一次统计时,去重或幂等控制属于上游协议。时间窗口可以通过分别维护窗口草图并丢弃过期窗口实现,但本文没有实现窗口管理;不要为了方便直接开放负增量。若业务确实要求删除,应重新定义数据模型和不变量,再选择相应算法与测试,不能仅仅放宽这里的参数检查。
最后可以把审查结论压缩成五个问题:真实计数由谁提供?所有更新是否满足非负契约?哈希和编码是否完全一致?每个合并是否重复计入数据?概率界的假设是否已证明?前四项能用很多确定性实验有效发现错误,第五项必须读懂数学条件。让 AI 逐项给证据,比让它再写一遍“高性能、低内存、准确可靠”更有价值。
参考资料
Cormode 与 Muthukrishnan 的原论文书目信息;原论文全文,第三节结构、第四节非负点查询及条件。
ECMAScript 数值类型,Number 与 BigInt 的表示和算术语义。
ECMAScript BigInt.asUintN,固定位宽取模语义;TypedArray 数值写入,类型宽度影响底层存储。
ECMAScript JSON 属性序列化,未转换 BigInt 的异常行为。

