AI 代码审查实战:用 JavaScript 实现 Misra-Gries 流式频繁项算法
让 AI 写一个从海量日志里找高频键的函数,得到一段几十行 JavaScript 并不难。难的是看清它承诺了什么:保存的是候选还是精确频数,超过阈值是否包含等号,第二次扫描是否真的读到了同一批数据。本篇围绕 Misra-Gries 算法,用九段可以独立执行的 Node.js 示例,把这些审查点变成可运行的断言。

Misra 与 Gries 在 1982 年的原论文 Finding Repeated Elements 中讨论寻找出现次数超过 n/k 的值,并采用候选与核验的思路。下面是面向只追加字符串流的教学实现,代码、反例与测试由本文重新组织,不是对论文伪代码的逐行转录。
与基于随机哈希桶的 Count-Min Sketch 相比,Misra-Gries 直接保留少量真实键,通过确定性抵消给出候选覆盖保证。这里没有概率参数,也没有把桶碰撞造成的高估当作答案。Count-Min 的点查询估计与 Misra-Gries 的候选枚举解决的是不同接口问题,不能只因二者都节省计数空间就互相替换。
运行方式:把任意一段 JavaScript 保存成单独的 .cjs 文件,再用 node 执行。九段都包含各自依赖的定义,无需复制其他段落,不安装第三方包。文中输出由 Node.js 24.19.0 实际执行得到;普通文本输出不是另一段需要运行的代码。
示例一:先用精确 Map 定义问题
审查 AI 生成的算法,第一步不是盯着循环,而是把输入输出写成可反驳的契约。输入是只追加、每条记录权重为一的字符串序列;长度为 n,参数 k 是至少为二的安全整数。目标是找出真实频数严格大于 n/k 的所有键,并返回它们的真实次数。重复事件每出现一次就加一,算法不会按事件标识自动去重。
下面的 Map 预言机保存全部不同键,所以不适合用来证明内存优势,却适合在小数据上定义正确答案。这里采用整数交叉相乘,避免把阈值先四舍五入,也避免 Number 乘积超出安全整数后出现边界误判。返回值按字符串比较排序,结果不依赖 Map 插入顺序。
"use strict";
const assert = require("node:assert/strict");
function oracle(xs, k) {
const counts = new Map();
for (const x of xs) counts.set(x, (counts.get(x) || 0) + 1);
return [...counts].filter(([, f]) => BigInt(f) * BigInt(k) > BigInt(xs.length))
.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
}
const xs = ["A", "B", "C", "A", "A", "B"];
assert.deepEqual(oracle(xs, 3), [["A", 3]]);
assert.deepEqual(oracle(["A", "B", "C"], 3), []);
assert.deepEqual(oracle([], 3), []);
console.log(JSON.stringify(oracle(xs, 3)));
console.log("equal-to-threshold excluded; empty stream OK");实际输出:
[["A",3]] equal-to-threshold excluded; empty stream OK
示例二:最多保留 k−1 个候选计数器
第一遍只有三种互斥分支:已存在的键加一;未存在且有空位时插入一;否则让现有的全部计数器减一,归零就删除。第三种分支里的新键本身也被抵消,所以本轮结束后不能把它补插进去。把第三个分支写成先全减、再插入新键,是看起来合理却破坏证明的常见 AI 错误。
示例采用私有字段,避免调用方直接把候选表改成负数或塞进额外键。读取计数器返回副本,既便于调试,又不把可变内部状态泄露出去。参数非法、键不是字符串、流长度即将超出安全整数时都在修改状态之前报错。这里主动收窄输入域,不把对象转成同一个字符串,也不把数字和字符串混为一谈。
"use strict";
const assert = require("node:assert/strict");
class MisraGries {
#k; #c = new Map(); #n = 0; #d = 0;
constructor(k) {
if (!Number.isSafeInteger(k) || k < 2) {
throw new RangeError("k must be a safe integer >= 2");
}
this.#k = k;
}
get k() { return this.#k; }
get n() { return this.#n; }
get d() { return this.#d; }
counters() { return new Map(this.#c); }
add(x) {
if (typeof x !== "string") throw new TypeError("string key required");
if (this.#n === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
this.#n++;
if (this.#c.has(x)) this.#c.set(x, this.#c.get(x) + 1);
else if (this.#c.size < this.#k - 1) this.#c.set(x, 1);
else {
this.#d++;
for (const [key, count] of this.#c) {
if (count === 1) this.#c.delete(key);
else this.#c.set(key, count - 1);
}
}
return this;
}
}
const ordered = rows => rows.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
const over = (f, n, k) => BigInt(f) * BigInt(k) > BigInt(n);
const s = new MisraGries(3);
for (const x of ["A", "B", "C", "A", "A", "B"]) s.add(x);
assert.equal(s.counters().size, 2);
assert.deepEqual(ordered([...s.counters()]), [["A", 2], ["B", 1]]);
console.log(JSON.stringify({n: s.n, d: s.d, candidates: ordered([...s.counters()])}));
const copy = s.counters(); copy.clear();
assert.equal(s.counters().size, 2);
console.log("snapshot cannot mutate internal counters");实际输出:
{"n":6,"d":1,"candidates":[["A",2],["B",1]]}
snapshot cannot mutate internal counters输出里 A 的残余计数是二,真实次数却是三;B 的残余计数是一,真实次数是二。候选计数器没有记录全部历史,它记录的是抵消之后还留下多少份。这个区别决定了后续不能直接对残余计数进行业务阈值过滤。
示例三:把抵消证明写成前缀不变量
设已经发生 D 次全体减一,某个键 x 的真实频数为 f(x),残余计数为 c(x),不在表里就把 c(x) 定义为零。每次抵消发生时,表中恰好有 k−1 个不同键,而到达的新键不在表里,因此这一次可以解释为删除一组 k 个互不相同的元素。它们是真实输入的不同出现次数,任何一次出现不会被删两次。
由此得到三个同时成立的不变量:候选数量不超过 k−1;残余计数总和等于 n−kD;每个键满足 c(x) ≤ f(x) ≤ c(x)+D。最后一个不等式的原因是,每组互异元素至多删掉一个 x。总和非负又说明 D ≤ floor(n/k)。如果 f(x) 严格大于 n/k,便不可能被最多 D 轮抵消删干净,因而一定留在候选表中。
这是确定性结论,对任何输入排列都成立,不需要独立哈希函数、不需要随机种子,也没有失败概率。相同多重集合换一种排列,残余候选可能变化,但真正超过阈值的键仍然都会留下。下面对每个前缀独立核对真值,避免只检查最终状态而漏掉中途违反约束的实现。
"use strict";
const assert = require("node:assert/strict");
class MisraGries {
#k; #c = new Map(); #n = 0; #d = 0;
constructor(k) {
if (!Number.isSafeInteger(k) || k < 2) {
throw new RangeError("k must be a safe integer >= 2");
}
this.#k = k;
}
get k() { return this.#k; }
get n() { return this.#n; }
get d() { return this.#d; }
counters() { return new Map(this.#c); }
add(x) {
if (typeof x !== "string") throw new TypeError("string key required");
if (this.#n === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
this.#n++;
if (this.#c.has(x)) this.#c.set(x, this.#c.get(x) + 1);
else if (this.#c.size < this.#k - 1) this.#c.set(x, 1);
else {
this.#d++;
for (const [key, count] of this.#c) {
if (count === 1) this.#c.delete(key);
else this.#c.set(key, count - 1);
}
}
return this;
}
}
const ordered = rows => rows.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
const over = (f, n, k) => BigInt(f) * BigInt(k) > BigInt(n);
const s = new MisraGries(3), truth = new Map();
const xs = ["A", "B", "C", "A", "A", "B", "D", "E"];
for (const x of xs) {
truth.set(x, (truth.get(x) || 0) + 1); s.add(x);
const c = s.counters();
const mass = [...c.values()].reduce((a, b) => a + b, 0);
assert.equal(mass, s.n - s.k * s.d);
assert(c.size <= s.k - 1);
for (const [key, f] of truth) {
const residual = c.get(key) || 0;
assert(residual <= f && f <= residual + s.d);
if (over(f, s.n, s.k)) assert(c.has(key));
}
console.log(`${s.n}: mass=${mass}, cancellations=${s.d}, keys=${c.size}`);
}实际输出:
1: mass=1, cancellations=0, keys=1 2: mass=2, cancellations=0, keys=2 3: mass=0, cancellations=1, keys=0 4: mass=1, cancellations=1, keys=1 5: mass=2, cancellations=1, keys=1 6: mass=3, cancellations=1, keys=2 7: mass=1, cancellations=2, keys=1 8: mass=2, cancellations=2, keys=2
示例四:第二遍只精确统计候选键
第一遍提供的是覆盖保证:所有真正的频繁项都在候选集合里,但集合也可能包含普通项。精确回答需要重读同一个数据快照,把候选计数全部清零,再按原始记录重新计数。第二遍只为这些候选建表,因此额外键数量仍然与 k 成正比。
注意第二遍不能从残余值继续累加,那会把没有抵消掉的出现次数重复计算。也不能只重读第一遍结束之后的新事件,否则统计窗口已经变了。代码把数据来源设计成工厂,每次调用得到可遍历的数据;两遍长度不一致就报错。长度相同只是必要条件,不能证明内容相同,快照一致性仍由调用方负责。
四个不同键的例子尤其适合审查:k 为三时,最后留下 D 这个候选,但它只出现一次,不超过四除以三的阈值。第二遍会正确返回空集合。候选不等于答案,候选表里的键也不能直接拿去做告警名单。
"use strict";
const assert = require("node:assert/strict");
class MisraGries {
#k; #c = new Map(); #n = 0; #d = 0;
constructor(k) {
if (!Number.isSafeInteger(k) || k < 2) {
throw new RangeError("k must be a safe integer >= 2");
}
this.#k = k;
}
get k() { return this.#k; }
get n() { return this.#n; }
get d() { return this.#d; }
counters() { return new Map(this.#c); }
add(x) {
if (typeof x !== "string") throw new TypeError("string key required");
if (this.#n === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
this.#n++;
if (this.#c.has(x)) this.#c.set(x, this.#c.get(x) + 1);
else if (this.#c.size < this.#k - 1) this.#c.set(x, 1);
else {
this.#d++;
for (const [key, count] of this.#c) {
if (count === 1) this.#c.delete(key);
else this.#c.set(key, count - 1);
}
}
return this;
}
}
const ordered = rows => rows.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
const over = (f, n, k) => BigInt(f) * BigInt(k) > BigInt(n);
function frequent(makeSource, k) {
if (typeof makeSource !== "function") throw new TypeError("source factory required");
const s = new MisraGries(k);
for (const x of makeSource()) s.add(x);
const exact = new Map([...s.counters().keys()].map(x => [x, 0]));
let replayN = 0;
for (const x of makeSource()) {
if (typeof x !== "string") throw new TypeError("string key required");
if (replayN === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
replayN++;
if (exact.has(x)) exact.set(x, exact.get(x) + 1);
}
if (replayN !== s.n) throw new Error("replay length mismatch");
return ordered([...exact].filter(([, f]) => over(f, s.n, k)));
}
const xs = Object.freeze(["A", "B", "C", "A", "A", "B"]);
assert.deepEqual(frequent(() => xs, 3), [["A", 3]]);
assert.deepEqual(frequent(() => ["A", "B", "C", "D"], 3), []);
console.log(JSON.stringify(frequent(() => xs, 3)));
console.log("false-positive candidate removed by exact replay");实际输出:
[["A",3]] false-positive candidate removed by exact replay
示例五:严格大于不能偷偷改成大于等于
当 n 能被 k 整除时,恰好等于 n/k 的键可以全部消失。三个不同键各出现一次,就是最短的边界反例:严格版本应返回空集合,而大于等于版本应返回三个键,已经超过两个候选位的容量。因此不能只改最后一个比较运算符,就宣称算法支持包含边界的查询。
如果业务要求频数至少为某个固定整数,需要重新推导候选覆盖条件,使候选阶段的严格阈值低于目标下界;第二遍再执行业务谓词。本文固定讨论严格大于 n/k,不把两种契约混用。并列频数同样不需要特殊淘汰规则:两个键都严格越线就都返回,所谓频繁项也不等价于固定数量的 Top-K 排行榜。
k 大于 n 并不违反契约,这时尚未出现足够多的不同键触发抵消,所有出现过的键都超过小于一的阈值。空流的答案则是空集合。实际服务还应按照可接受的资源预算限制 k,不能因为数学允许巨大参数,就把它直接交给不受信任的请求。
"use strict";
const assert = require("node:assert/strict");
class MisraGries {
#k; #c = new Map(); #n = 0; #d = 0;
constructor(k) {
if (!Number.isSafeInteger(k) || k < 2) {
throw new RangeError("k must be a safe integer >= 2");
}
this.#k = k;
}
get k() { return this.#k; }
get n() { return this.#n; }
get d() { return this.#d; }
counters() { return new Map(this.#c); }
add(x) {
if (typeof x !== "string") throw new TypeError("string key required");
if (this.#n === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
this.#n++;
if (this.#c.has(x)) this.#c.set(x, this.#c.get(x) + 1);
else if (this.#c.size < this.#k - 1) this.#c.set(x, 1);
else {
this.#d++;
for (const [key, count] of this.#c) {
if (count === 1) this.#c.delete(key);
else this.#c.set(key, count - 1);
}
}
return this;
}
}
const ordered = rows => rows.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
const over = (f, n, k) => BigInt(f) * BigInt(k) > BigInt(n);
function frequent(makeSource, k) {
if (typeof makeSource !== "function") throw new TypeError("source factory required");
const s = new MisraGries(k);
for (const x of makeSource()) s.add(x);
const exact = new Map([...s.counters().keys()].map(x => [x, 0]));
let replayN = 0;
for (const x of makeSource()) {
if (typeof x !== "string") throw new TypeError("string key required");
if (replayN === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
replayN++;
if (exact.has(x)) exact.set(x, exact.get(x) + 1);
}
if (replayN !== s.n) throw new Error("replay length mismatch");
return ordered([...exact].filter(([, f]) => over(f, s.n, k)));
}
const boundary = ["A", "B", "C"];
const s = new MisraGries(3);
for (const x of boundary) s.add(x);
assert.equal(s.counters().size, 0);
assert.deepEqual(frequent(() => boundary, 3), []);
const inclusive = [...new Set(boundary)].filter(x =>
BigInt(boundary.filter(y => y === x).length) * 3n >= BigInt(boundary.length));
assert.deepEqual(inclusive, ["A", "B", "C"]);
assert.deepEqual(frequent(() => ["A", "A", "B", "B", "C"], 3), [["A", 2], ["B", 2]]);
assert.deepEqual(frequent(() => ["Z"], 8), [["Z", 1]]);
assert.deepEqual(frequent(() => [], 2), []);
for (const k of [0, 1, -1, 2.5, NaN, Infinity, "3"]) {
assert.throws(() => new MisraGries(k), RangeError);
}
console.log("strict=[]; inclusive=[A,B,C]; candidate capacity=2");
console.log("ties, k>n, empty stream, invalid k: PASS");实际输出:
strict=[]; inclusive=[A,B,C]; candidate capacity=2 ties, k>n, empty stream, invalid k: PASS
示例六:Unicode、特殊键与重复事件
JavaScript 的字符串比较不会自动做 Unicode 规范化。看起来一样的重音字符,可能是单个码点,也可能是字母加组合标记;它们默认是不同键。是否合并必须由产品语义决定,若选择 NFC,就要让两遍在同一个位置应用同一项转换。不能第一遍用原始串、第二遍用规范化串,否则候选匹配会悄悄丢失。
采用 Map 可以正常保存 __proto__、constructor 和表情符号,不会把用户键误当作普通对象的继承属性。本文把一个字符串当作一条记录,不按 UTF-16 单元拆字符;如果要分析文本词频,分词器是前置处理,不能把它的语言规则误算成 Misra-Gries 的能力。
消息队列重投同一条事件时,三次输入就是三次计数。业务若要求去重,必须在输入层基于稳定事件标识处理,并说明去重状态占用的额外空间。算法的有限候选表并没有附赠一个无限大小的去重集合。
"use strict";
const assert = require("node:assert/strict");
class MisraGries {
#k; #c = new Map(); #n = 0; #d = 0;
constructor(k) {
if (!Number.isSafeInteger(k) || k < 2) {
throw new RangeError("k must be a safe integer >= 2");
}
this.#k = k;
}
get k() { return this.#k; }
get n() { return this.#n; }
get d() { return this.#d; }
counters() { return new Map(this.#c); }
add(x) {
if (typeof x !== "string") throw new TypeError("string key required");
if (this.#n === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
this.#n++;
if (this.#c.has(x)) this.#c.set(x, this.#c.get(x) + 1);
else if (this.#c.size < this.#k - 1) this.#c.set(x, 1);
else {
this.#d++;
for (const [key, count] of this.#c) {
if (count === 1) this.#c.delete(key);
else this.#c.set(key, count - 1);
}
}
return this;
}
}
const ordered = rows => rows.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
const over = (f, n, k) => BigInt(f) * BigInt(k) > BigInt(n);
function frequent(makeSource, k) {
if (typeof makeSource !== "function") throw new TypeError("source factory required");
const s = new MisraGries(k);
for (const x of makeSource()) s.add(x);
const exact = new Map([...s.counters().keys()].map(x => [x, 0]));
let replayN = 0;
for (const x of makeSource()) {
if (typeof x !== "string") throw new TypeError("string key required");
if (replayN === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
replayN++;
if (exact.has(x)) exact.set(x, exact.get(x) + 1);
}
if (replayN !== s.n) throw new Error("replay length mismatch");
return ordered([...exact].filter(([, f]) => over(f, s.n, k)));
}
const raw = ["é", "e\u0301", "é", "e\u0301", "茶"];
assert.deepEqual(frequent(() => raw, 3), [["e\u0301", 2], ["é", 2]]);
const normalized = raw.map(x => x.normalize("NFC"));
assert.deepEqual(frequent(() => normalized, 3), [["é", 4]]);
const special = ["__proto__", "constructor", "__proto__", "🦊", "🦊"];
assert.deepEqual(frequent(() => special, 3), [["__proto__", 2], ["🦊", 2]]);
assert.deepEqual(frequent(() => ["event-7", "event-7", "event-7"], 2), [["event-7", 3]]);
const s = new MisraGries(2);
for (const x of [7, null, {}, ["A"]]) assert.throws(() => s.add(x), TypeError);
assert.equal(s.n, 0);
console.log("raw=" + JSON.stringify(frequent(() => raw, 3)));
console.log("NFC=" + JSON.stringify(frequent(() => normalized, 3)));
console.log("special=" + JSON.stringify(frequent(() => special, 3)));
console.log("duplicate events count separately; invalid input unchanged");实际输出:
raw=[["é",2],["é",2]] NFC=[["é",4]] special=[["__proto__",2],["🦊",2]] duplicate events count separately; invalid input unchanged
示例七:流可遍历,不代表能够重放
单个生成器对象通常只能消费一次。把已耗尽的对象再交给第二遍,不会神奇地回到开头。正确方式是传入能重新打开同一快照的工厂,例如固定版本的对象存储文件、数据库一致性快照,或者示例中的不可变数组。仅仅把读取动作封装成函数,并没有自动获得快照隔离。
最后一个反例故意返回相同长度、不同内容的第二遍。函数不会报警,却给出了不代表第一遍数据的结果,这正是长度校验能力的边界。生产实现应绑定快照标识、版本号和读取区间;若必须比较摘要,需要明确摘要碰撞与存储一致性的假设,不能把普通哈希相等宣传为数学证明。
真正无法重放的单遍流,只能输出候选及残余下界、D 导出的上界,或者在额外架构里保留可核验的数据。对于某个候选,如果残余下界已经严格越线,可以确认它是频繁项;但其余候选不能据此简单判为否,更不能承诺所有真实次数都已恢复。
"use strict";
const assert = require("node:assert/strict");
class MisraGries {
#k; #c = new Map(); #n = 0; #d = 0;
constructor(k) {
if (!Number.isSafeInteger(k) || k < 2) {
throw new RangeError("k must be a safe integer >= 2");
}
this.#k = k;
}
get k() { return this.#k; }
get n() { return this.#n; }
get d() { return this.#d; }
counters() { return new Map(this.#c); }
add(x) {
if (typeof x !== "string") throw new TypeError("string key required");
if (this.#n === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
this.#n++;
if (this.#c.has(x)) this.#c.set(x, this.#c.get(x) + 1);
else if (this.#c.size < this.#k - 1) this.#c.set(x, 1);
else {
this.#d++;
for (const [key, count] of this.#c) {
if (count === 1) this.#c.delete(key);
else this.#c.set(key, count - 1);
}
}
return this;
}
}
const ordered = rows => rows.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
const over = (f, n, k) => BigInt(f) * BigInt(k) > BigInt(n);
function frequent(makeSource, k) {
if (typeof makeSource !== "function") throw new TypeError("source factory required");
const s = new MisraGries(k);
for (const x of makeSource()) s.add(x);
const exact = new Map([...s.counters().keys()].map(x => [x, 0]));
let replayN = 0;
for (const x of makeSource()) {
if (typeof x !== "string") throw new TypeError("string key required");
if (replayN === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
replayN++;
if (exact.has(x)) exact.set(x, exact.get(x) + 1);
}
if (replayN !== s.n) throw new Error("replay length mismatch");
return ordered([...exact].filter(([, f]) => over(f, s.n, k)));
}
function* source() { yield* ["茶", "茶", "水"]; }
assert.deepEqual(frequent(source, 2), [["茶", 2]]);
const spent = source();
assert.throws(() => frequent(() => spent, 2), /replay length mismatch/);
let calls = 0;
assert.throws(() => frequent(() => ++calls === 1 ? ["A"] : [], 2), /replay length mismatch/);
console.log(JSON.stringify(frequent(source, 2)));
console.log("exhausted generator and shortened replay rejected");
let changedCalls = 0;
const misleading = frequent(() => ++changedCalls === 1 ? ["A", "A", "B"] : ["B", "B", "A"], 2);
assert.deepEqual(misleading, []);
console.log("same-length changed source=" + JSON.stringify(misleading));实际输出:
[["茶",2]] exhausted generator and shortened replay rejected same-length changed source=[]
示例八:穷举所有短流,并验证每个前缀
只测一个多数元素样例,无法区分正确实现和凑巧通过的实现。这个穷举程序生成三种键、长度零至八的全部序列,分别测试三个 k,并在每个前缀上维护一个与算法独立的精确 Map。它同时检查容量、正整数计数、抵消质量守恒、逐键误差上下界、真正频繁项覆盖,以及两遍最终结果与预言机完全相等。
测试中的精确 Map、前缀数组与反复重放是验证设施,不属于生产算法的常驻空间。重复覆盖某些前缀是有意的,便于让每条完整输入独立运行;输出中的前缀数是检查次数,而不是互不重复的前缀数量。穷举只能覆盖这个有限输入域,完整正确性仍依赖前面的抵消证明,二者提供不同层面的保障。
"use strict";
const assert = require("node:assert/strict");
class MisraGries {
#k; #c = new Map(); #n = 0; #d = 0;
constructor(k) {
if (!Number.isSafeInteger(k) || k < 2) {
throw new RangeError("k must be a safe integer >= 2");
}
this.#k = k;
}
get k() { return this.#k; }
get n() { return this.#n; }
get d() { return this.#d; }
counters() { return new Map(this.#c); }
add(x) {
if (typeof x !== "string") throw new TypeError("string key required");
if (this.#n === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
this.#n++;
if (this.#c.has(x)) this.#c.set(x, this.#c.get(x) + 1);
else if (this.#c.size < this.#k - 1) this.#c.set(x, 1);
else {
this.#d++;
for (const [key, count] of this.#c) {
if (count === 1) this.#c.delete(key);
else this.#c.set(key, count - 1);
}
}
return this;
}
}
const ordered = rows => rows.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
const over = (f, n, k) => BigInt(f) * BigInt(k) > BigInt(n);
function frequent(makeSource, k) {
if (typeof makeSource !== "function") throw new TypeError("source factory required");
const s = new MisraGries(k);
for (const x of makeSource()) s.add(x);
const exact = new Map([...s.counters().keys()].map(x => [x, 0]));
let replayN = 0;
for (const x of makeSource()) {
if (typeof x !== "string") throw new TypeError("string key required");
if (replayN === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
replayN++;
if (exact.has(x)) exact.set(x, exact.get(x) + 1);
}
if (replayN !== s.n) throw new Error("replay length mismatch");
return ordered([...exact].filter(([, f]) => over(f, s.n, k)));
}
let streams = 0, prefixes = 0;
const alphabet = ["A", "B", "C"];
function check(xs, k) {
const s = new MisraGries(k), truth = new Map();
function inspect() {
prefixes++;
const c = s.counters();
assert(c.size <= k - 1);
assert([...c.values()].every(v => Number.isSafeInteger(v) && v > 0));
const mass = [...c.values()].reduce((a, b) => a + b, 0);
assert.equal(mass, s.n - k * s.d);
assert(s.d <= Math.floor(s.n / k));
for (const [x, f] of truth) {
const r = c.get(x) || 0;
assert(r <= f && f <= r + s.d);
if (over(f, s.n, k)) assert(c.has(x));
}
for (const x of c.keys()) assert(truth.has(x));
const prefix = xs.slice(0, s.n);
const expected = ordered([...truth].filter(([, f]) => over(f, s.n, k)));
assert.deepEqual(frequent(() => prefix, k), expected);
}
inspect();
for (const x of xs) { truth.set(x, (truth.get(x) || 0) + 1); s.add(x); inspect(); }
}
function enumerate(xs, remaining) {
streams++;
for (const k of [2, 3, 4]) check(xs, k);
if (!remaining) return;
for (const x of alphabet) enumerate([...xs, x], remaining - 1);
}
enumerate([], 8);
console.log(JSON.stringify({streams, prefixes, result: "PASS"}));实际输出:
{"streams":9841,"prefixes":250959,"result":"PASS"}示例九:用反例卡住 AI 最容易写错的三处
审查时最好把反例加入回归测试,而不是只写一句请注意边界。第一个反例证明,按残余计数筛选会漏掉 A;第二个反例证明,全体减一后补插当前键会破坏质量守恒;第三个反例证明,候选随顺序变化不等于算法不确定,也不等于验证后的答案不稳定。
还要看复杂度陈述是否准确。一次全减可能扫描 k−1 个计数器,因此单条更新最坏要处理与 k 成正比的条目。但 D 次全减总共访问 D(k−1) 个条目,而 kD 不超过 n;假设 Map 基本操作的平均成本为常数,整遍的表操作总成本是线性的,不必粗暴估成每条都全减的 n 乘 k。ECMAScript 规范只要求 Map 平均访问次线性,不能把具体引擎的平均常数性能说成规范给出的严格最坏保证。此外,末尾按键排序要另计成本;在通常的比较排序模型下是 O(r log r),其中 r 为输出键数。长字符串比较与 BigInt 运算的位成本,也不包含在上述表操作次数里。
空间方面,两个阶段最多保存与 k 成正比的键和计数器;键本身可以很长,计数器的位数也随 n 增长,因此这是条目数量级,不是字节数永远固定。读取完整数组、每步输出快照、保存调试轨迹,都会额外花空间。本文这些小样例为了可复现而使用数组,部署时应把它们换成真正分批读取的固定快照。
"use strict";
const assert = require("node:assert/strict");
class MisraGries {
#k; #c = new Map(); #n = 0; #d = 0;
constructor(k) {
if (!Number.isSafeInteger(k) || k < 2) {
throw new RangeError("k must be a safe integer >= 2");
}
this.#k = k;
}
get k() { return this.#k; }
get n() { return this.#n; }
get d() { return this.#d; }
counters() { return new Map(this.#c); }
add(x) {
if (typeof x !== "string") throw new TypeError("string key required");
if (this.#n === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
this.#n++;
if (this.#c.has(x)) this.#c.set(x, this.#c.get(x) + 1);
else if (this.#c.size < this.#k - 1) this.#c.set(x, 1);
else {
this.#d++;
for (const [key, count] of this.#c) {
if (count === 1) this.#c.delete(key);
else this.#c.set(key, count - 1);
}
}
return this;
}
}
const ordered = rows => rows.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
const over = (f, n, k) => BigInt(f) * BigInt(k) > BigInt(n);
function frequent(makeSource, k) {
if (typeof makeSource !== "function") throw new TypeError("source factory required");
const s = new MisraGries(k);
for (const x of makeSource()) s.add(x);
const exact = new Map([...s.counters().keys()].map(x => [x, 0]));
let replayN = 0;
for (const x of makeSource()) {
if (typeof x !== "string") throw new TypeError("string key required");
if (replayN === Number.MAX_SAFE_INTEGER) throw new RangeError("stream too long");
replayN++;
if (exact.has(x)) exact.set(x, exact.get(x) + 1);
}
if (replayN !== s.n) throw new Error("replay length mismatch");
return ordered([...exact].filter(([, f]) => over(f, s.n, k)));
}
const xs = ["A", "B", "C", "A", "A", "B"], k = 3;
const s = new MisraGries(k); xs.forEach(x => s.add(x));
const wrongResidualFilter = ordered([...s.counters()].filter(([, c]) => over(c, s.n, k)));
assert.deepEqual(wrongResidualFilter, []);
assert.deepEqual(frequent(() => xs, k), [["A", 3]]);
function wrongReinsert(xs, k) {
const c = new Map(); let d = 0;
for (const x of xs) {
if (c.has(x)) c.set(x, c.get(x) + 1);
else if (c.size < k - 1) c.set(x, 1);
else {
d++;
for (const [y, n] of c) n === 1 ? c.delete(y) : c.set(y, n - 1);
c.set(x, 1); // deliberate bug: incoming element was already cancelled
}
}
return {c, d};
}
const broken = wrongReinsert(["A", "B", "C"], 3);
const mass = [...broken.c.values()].reduce((a, b) => a + b, 0);
assert.notEqual(mass, 3 - 3 * broken.d);
const forward = ["A", "B", "C", "D"], backward = [...forward].reverse();
const a = new MisraGries(3), b = new MisraGries(3);
forward.forEach(x => a.add(x)); backward.forEach(x => b.add(x));
assert.notDeepEqual([...a.counters()], [...b.counters()]);
assert.deepEqual(frequent(() => forward, 3), frequent(() => backward, 3));
console.log("residual-count filtering loses A: caught");
console.log("reinsert-after-decrement violates mass invariant: caught");
console.log("candidate order dependence does not change verified answer: PASS");实际输出:
residual-count filtering loses A: caught reinsert-after-decrement violates mass invariant: caught candidate order dependence does not change verified answer: PASS
交付前的审查清单
明确只追加、单位权重、字符串键,以及重复事件是否已经在上游去重。
容量用 k−1,满表且遇到新键时只抵消,不补插;归零立即删除。
把残余计数标为下界,保留 D 并核对每个前缀的质量守恒。
用严格大于判断 n/k,采用精确整数比较,空流、并列、Unicode 都有反例。
第二遍从零统计候选,绑定同一快照;没有重放条件时不声称得到了完整精确结果。
让精确 Map 预言机检查结果,让不变量检查过程,再单独审查资源与输入限制。
这套审查方法的重点,是让每个承诺都有对应证据。有限计数器解决的是候选空间,抵消证明解决的是不漏掉严格频繁项,第二遍解决的是真实次数与误报,快照契约解决的是数据是否仍是同一份。把这四件事分开检查,才能判断一段看起来简洁的 AI 代码是否真的可以投入业务。
原始资料与实现语义
Misra、Gries:Finding Repeated Elements,1982 原论文,阈值问题与候选核验的来源。
Cornell University 原始技术报告档案,作者与报告版本信息。
Cormode、Muthukrishnan:Count-Min Sketch 原始论文,用于区分随机桶摘要与候选抵消接口。
ECMAScript Map Objects 规范,键语义与平均访问复杂度要求。

