AI 代码审查:JavaScript Lossy Counting 的桶边界与误差保证

10-20 4阅读

让 AI 写一个流式高频项统计器并不难,难的是让它准确解释自己什么时候会忘记一个键,以及忘记之后还能保证什么。Lossy Counting 很适合拿来做代码审查练习:核心更新只有几行,正确性却同时依赖桶编号、清理顺序、两个方向相反的等号,以及对估计误差的准确理解。一次最终输出看起来合理,不能说明实现符合这些条件。

本文处理持续到来的单个字符串事件,例如错误类型、接口名称或日志模板。流只增加事件,不支持撤销;每次插入的权重为一。我们希望在不保存所有历史键计数的情况下,找出达到给定支持度的候选,并为返回的低估计数提供确定的加性误差界。全文提供九个可独立运行的 Node.js 示例,每个代码块都包含自己的依赖定义,输出均由实际执行得到。

AI 代码审查:JavaScript Lossy Counting 的桶边界与误差保证
AI概念图。透明分桶与流动方块仅用于表达按阶段清理低频条目的直觉,不是实际执行轨迹或性能测试结果。

先审查机制,不要把不同算法拼成一个名字

Lossy Counting 的来源是 Gurmeet Singh Manku 与 Rajeev Motwani 在 VLDB 2002 发表的 Approximate Frequency Counts over Data Streams,第 4.2 节。这里沿用单项流版本:按固定条数分桶,在桶边界进行删除;每个活跃条目保存计数与历史误差上界。本文的 JavaScript 实现、反例和逐前缀测试均围绕这一规则构造。

如果此前接触过 Space-Saving、Misra–Gries 或 Count-Min Sketch,最容易犯的错误是套用熟悉的更新动作。Lossy Counting 的这份实现没有满表替换最小计数,没有遇到新键时将全体计数抵消,也没有把键映射到共享的哈希计数阵列。它保存真实的候选键,随着已经完成的桶数提高删除门槛。审阅代码时应首先确认这条机制,随后才讨论接口和性能。

将已处理事件数记作 N,桶宽记作 w,要求 w 为不小于二的整数。非空前缀当前桶号是 b=ceil(N/w)。真实频次记作 F(x),条目的存活期计数记作 c(x),其允许遗忘的历史上界记作 delta(x)。这三个数量不能混用:c 是下界,c+delta 是上界,delta 既不是额外发生的事件,也不是概率误差。

示例一:先把桶编号写对

流中的桶是按事件条数划分的,不是定时器窗口。宽度为四时,第一到第四条属于第一桶,第五条才进入第二桶。下面把零长度单独表示为零号状态;正式插入使用已经加一的 N。整数除法作用于非负 BigInt,向零截断正好等于向下取整。

function bucketOf(n, width) {
  if (typeof n !== "bigint" || n < 0n ||
      typeof width !== "bigint" || width < 2n) {
    throw new RangeError("invalid n or width");
  }
  return (n + width - 1n) / width;
}
for (const n of [0n, 1n, 4n, 5n, 8n, 9n]) {
  console.log(`N=${n}, bucket=${bucketOf(n, 4n)}`);
}

运行输出:

N=0, bucket=0
N=1, bucket=1
N=4, bucket=1
N=5, bucket=2
N=8, bucket=2
N=9, bucket=3

审查 AI 输出时,看到 Math.floor(N / width) 就不能直接通过。它在完整桶末尾可能碰巧正确,却会把下一桶开头算错;把 N 加一放在最后也可能将错误转移到插入时的 delta。编号、计数与清理必须共用同一个已处理前缀定义。

示例二:等号决定第一次清理

每个条目记录 count 与 delta,下面的输出用 count/delta 表示。已有条目只增加 count;缺失条目以 count=1、delta=b−1 插入。处理完一条事件后,如果桶刚好填满,就删除 count+delta≤b 的条目。这个教学核心只接受示例中已给定的合法参数,完整校验在示例四。

function makeCounter(width) {
  let n = 0n;
  const table = new Map();
  return {
    add(key) {
      n += 1n;
      const b = (n + width - 1n) / width;
      const r = table.get(key);
      if (r) r.count += 1n;
      else table.set(key, { count: 1n, delta: b - 1n });
      if (n % width === 0n) {
        for (const [k, v] of table) {
          if (v.count + v.delta <= b) table.delete(k);
        }
      }
    },
    get n() { return n; },
    rows() { return [...table].map(([k, v]) => `${k}:${v.count}/${v.delta}`).join(",") || "-"; },
    get(key) { return table.get(key); }
  };
}
const lc = makeCounter(4n);
for (const key of "abac") {
  lc.add(key);
  console.log(`N=${lc.n} ${lc.rows()}`);
}

运行输出:

N=1 a:1/0
N=2 a:1/0,b:1/0
N=3 a:2/0,b:1/0
N=4 a:2/0

第四条之后,b 与 c 的 count+delta 都等于一,因此消失;a 的计数为二,所以保留。清理并不把所有 count 减一,也不因为表满而替换最小槽位。代码在边界先计入当前事件再清理,若调换顺序,恰好跨过删除门槛的键可能被错误忘记。

示例三:条目回来以后,不能假装从未丢过历史

这里第一桶四个不同键全部被清理,随后 a 连续到来四次。表中的 count 只精确记录本次条目存活以来的出现次数,不一定是整个流的真实频次。delta 是被忘记历史的上界,而不是必须发生的误差。

function makeCounter(width) {
  let n = 0n;
  const table = new Map();
  return {
    add(key) {
      n += 1n;
      const b = (n + width - 1n) / width;
      const r = table.get(key);
      if (r) r.count += 1n;
      else table.set(key, { count: 1n, delta: b - 1n });
      if (n % width === 0n) {
        for (const [k, v] of table) {
          if (v.count + v.delta <= b) table.delete(k);
        }
      }
    },
    get n() { return n; },
    rows() { return [...table].map(([k, v]) => `${k}:${v.count}/${v.delta}`).join(",") || "-"; },
    get(key) { return table.get(key); }
  };
}
const lc = makeCounter(4n);
const exact = new Map();
for (const key of "abcdaaaa") {
  exact.set(key, (exact.get(key) ?? 0n) + 1n);
  lc.add(key);
}
const r = lc.get("a");
console.log(`N=${lc.n}, table=${lc.rows()}`);
console.log(`a lower=${r.count}, upper=${r.count + r.delta}, exact=${exact.get("a")}`);
console.log(`missing b lower=0, upper=${lc.n / 4n}, exact=${exact.get("b")}`);

运行输出:

N=8, table=a:4/1
a lower=4, upper=5, exact=5
missing b lower=0, upper=2, exact=1

此时 a 的真实频次为五,估计值为四,上界为五。没有条目的 b 也不是从未出现过,返回零只是它的下界。把缺失键的上界统一设为 floor(N/w) 是安全且可计算的选择;这个上界可能很松,调用者不能把区间宽度解释成标准差或置信水平。

示例四:给 AI 生成的实现补上明确契约

下面是可直接保存运行的完整版本。为了把讨论集中在算法上,键限定为字符串,每次 add 恰好插入一次;总长度、条目计数、桶宽与误差都使用 BigInt。内部状态采用私有字段,entries 返回拷贝,调用方不能通过改快照破坏不变量。查询使用有理数 p/q,避免浮点阈值在等号附近漂移。

class LossyCounting {
  #width;
  #n = 0n;
  #table = new Map();

  constructor(width) {
    if (typeof width !== "bigint" || width < 2n) {
      throw new RangeError("width must be a BigInt >= 2");
    }
    this.#width = width;
  }
  get n() { return this.#n; }
  get width() { return this.#width; }
  get size() { return this.#table.size; }

  add(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    this.#n += 1n;
    const bucket = (this.#n + this.#width - 1n) / this.#width;
    const row = this.#table.get(key);
    if (row) row.count += 1n;
    else this.#table.set(key, { count: 1n, delta: bucket - 1n });
    if (this.#n % this.#width === 0n) {
      for (const [item, r] of this.#table) {
        if (r.count + r.delta <= bucket) this.#table.delete(item);
      }
    }
    return this;
  }

  entries() {
    return [...this.#table].map(([key, r]) => ({ key, ...r }))
      .sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
  }

  bounds(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    const r = this.#table.get(key);
    return r ? { lower: r.count, upper: r.count + r.delta }
      : { lower: 0n, upper: this.#n / this.#width };
  }

  query(p, q) {
    if (typeof p !== "bigint" || typeof q !== "bigint" ||
        p <= 0n || q <= 0n || p > q || p * this.#width <= q) {
      throw new RangeError("support must satisfy 1/width < p/q <= 1");
    }
    if (this.#n === 0n) return [];
    const cutoff = this.#n * (p * this.#width - q);
    return this.entries().filter(r => r.count * q * this.#width >= cutoff);
  }
}
const lc = new LossyCounting(4n);
for (const key of "aaaabbcd") lc.add(key);
console.log(`N=${lc.n}, size=${lc.size}`);
console.log(lc.entries().map(r => `${r.key}:${r.count}+${r.delta}`).join(","));
console.log(lc.query(1n, 2n).map(r => r.key).join(","));
const copy = lc.entries();
copy[0].count = 999n;
console.log(`internal a=${lc.bounds("a").lower}`);

运行输出:

N=8, size=2
a:4+0,b:2+1
a,b
internal a=4

该接口刻意没有提供负权更新、任意权重批量插入或可写的 N。把大量重复事件一次性加到 count 上,会跳过中途桶边界,不能未经证明就视为等价优化。也不应强行把 Map 截短到 w 个条目;这里的宽度是误差参数,不是容量参数。

把误差声明拆成可以逐条证明的不变量

下面的结论都指一次 add 完整结束后的状态,包含该次必要的清理。初始时 N=0,表为空,所有键的真实频次均为零。对 N>0,我们要维持两组条件:表内键满足 c≤F≤c+delta;表外键满足 F≤floor(N/w)。此外,表内 delta 不超过 ceil(N/w)−1。它们一起描述了保存与遗忘这两种状态,不依赖输入随机性。

证明从一次插入开始。若键已经在表中,真实频次和 c 同时加一,delta 不动,原来的上下界继续成立。若键不在表中,插入之前只处理了 N−1 条事件;由表外不变量,它过去最多出现 floor((N−1)/w) 次。这个数恰好等于 ceil(N/w)−1,也就是 b−1。因此新条目设置 c=1、delta=b−1,足以覆盖全部可能遗忘的历史,同时下界不会超过真实频次。

再看边界删除。当 N 是 w 的整数倍,b=N/w。被删除条目满足 c+delta≤b,而删除前已有 F≤c+delta,所以删除后 F≤b=floor(N/w),正好接上表外不变量。没有到桶边界时,表外键若未到来,其真实频次不增加,floor(N/w) 也不会减少,因此仍然安全。这个归纳同时说明:清理应当发生在本条事件更新之后,且删除条件包括等号。

对表内键,delta 是插入时的桶号减一,之后保持不变;当前桶号只增不减,所以 delta≤ceil(N/w)−1≤floor(N/w)。于是无论键在不在表中,只要定义 estimate(x) 为表内的 c、表外的零,就有 0≤F(x)−estimate(x)≤floor(N/w)≤N/w。这里最后的误差是加性的,以整个前缀长度为尺度,不是以该键频次为尺度的相对误差。

等号不能改成严格小于。宽度四时输入四个不同键,第一桶清理后表为空,每个键真实频次为一、估计为零,误差恰好等于 N/w。另一方面,表内上界 c+delta 往往比统一的 c+floor(N/w) 更紧,接口因此保留了条目自己的 delta。这个额外字段的意义是保住历史上界,不是把估计值抬高。

若业务给出允许误差率 epsilon,且 0<epsilon<1,选择 w=ceil(1/epsilon) 可得 1/w≤epsilon,因此上述误差还满足 F−estimate≤epsilon·N。实现直接接收整数桶宽,避免将浮点倒数的舍入误差藏在构造器里。精确的有理数换算见示例七。BigInt 负责整数算术准确,摘要仍会有意忘掉部分历史;这两种不同层面的精确性应分别说明。

示例五:阈值查询必须保留灰区

选用 w=4,内部误差率为 1/4;支持度取 1/2。查询的筛选线是 count≥(1/2−1/4)N,而不是 count≥N/2。N=8 时该线恰好是二,b 的计数等于筛选线,因此必须包含在结果里。下面保留完整类,整段可以独立运行。

class LossyCounting {
  #width;
  #n = 0n;
  #table = new Map();

  constructor(width) {
    if (typeof width !== "bigint" || width < 2n) {
      throw new RangeError("width must be a BigInt >= 2");
    }
    this.#width = width;
  }
  get n() { return this.#n; }
  get width() { return this.#width; }
  get size() { return this.#table.size; }

  add(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    this.#n += 1n;
    const bucket = (this.#n + this.#width - 1n) / this.#width;
    const row = this.#table.get(key);
    if (row) row.count += 1n;
    else this.#table.set(key, { count: 1n, delta: bucket - 1n });
    if (this.#n % this.#width === 0n) {
      for (const [item, r] of this.#table) {
        if (r.count + r.delta <= bucket) this.#table.delete(item);
      }
    }
    return this;
  }

  entries() {
    return [...this.#table].map(([key, r]) => ({ key, ...r }))
      .sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
  }

  bounds(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    const r = this.#table.get(key);
    return r ? { lower: r.count, upper: r.count + r.delta }
      : { lower: 0n, upper: this.#n / this.#width };
  }

  query(p, q) {
    if (typeof p !== "bigint" || typeof q !== "bigint" ||
        p <= 0n || q <= 0n || p > q || p * this.#width <= q) {
      throw new RangeError("support must satisfy 1/width < p/q <= 1");
    }
    if (this.#n === 0n) return [];
    const cutoff = this.#n * (p * this.#width - q);
    return this.entries().filter(r => r.count * q * this.#width >= cutoff);
  }
}
const lc = new LossyCounting(4n);
const exact = new Map();
for (const key of "aaaabbcd") {
  lc.add(key);
  exact.set(key, (exact.get(key) ?? 0n) + 1n);
}
console.log("cutoff=2, true-heavy threshold=4");
for (const r of lc.query(1n, 2n)) {
  console.log(`${r.key}: estimate=${r.count}, exact=${exact.get(r.key)}`);
}
console.log(`empty=${new LossyCounting(4n).query(1n, 2n).length}`);

运行输出:

cutoff=2, true-heavy threshold=4
a: estimate=4, exact=4
b: estimate=2, exact=2
empty=0

a 确实达到支持度;b 没有达到,却处于允许返回的灰区。算法保证不漏掉足够频繁的键,不承诺输出集合与精确 GROUP BY 完全一致。这个保证针对 N>0;空流定义为返回空数组,不能宣称它枚举了整个无限键空间里所有频次大于等于零的键。

查询保证为什么需要两个阈值

设支持度 s=p/q,要求 1/w<s≤1,并且 N>0。正式查询筛选 c≥(s−1/w)N。若某键真实频次 F≥sN,由于 sN>N/w,它不可能处于表外;又因为 c≥F−N/w≥(s−1/w)N,所以一定被返回。这就给出了目标阈值处不漏报的证明,包含 F=sN 的等号情形。

反过来,返回键满足 F≥c≥(s−1/w)N,因此真实频次严格低于下方阈值的键不会被返回。介于两个阈值之间的键则可能返回,也可能不返回。灰区是接口明确允许的结果范围,并不是实现不稳定。在代码中,将筛选式乘以正整数 q·w,得到 c·q·w≥N·(p·w−q),整个判断只需 BigInt 的乘法与比较,无需小数除法。

要求 s>1/w 也有具体理由:当 s=1/w 时,第一桶全是不同键的例子中,每个键都达到目标,却已经被清理。若调用者要求更低支持度,就必须选择更大的桶宽后重新处理完整流,或者改用能满足新契约的数据结构。已丢弃的信息不能通过改一个查询参数重新出现。

示例六:用反例拆穿看起来更严格的过滤

AI 经常把更高的筛选阈值解释成更可靠,实际却会破坏召回保证。以下仍使用 a 曾在第一桶被遗忘的输入,真实频次五,支持度为 5/8,恰好达到目标。我们同时计算错误过滤与正式查询。

class LossyCounting {
  #width;
  #n = 0n;
  #table = new Map();

  constructor(width) {
    if (typeof width !== "bigint" || width < 2n) {
      throw new RangeError("width must be a BigInt >= 2");
    }
    this.#width = width;
  }
  get n() { return this.#n; }
  get width() { return this.#width; }
  get size() { return this.#table.size; }

  add(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    this.#n += 1n;
    const bucket = (this.#n + this.#width - 1n) / this.#width;
    const row = this.#table.get(key);
    if (row) row.count += 1n;
    else this.#table.set(key, { count: 1n, delta: bucket - 1n });
    if (this.#n % this.#width === 0n) {
      for (const [item, r] of this.#table) {
        if (r.count + r.delta <= bucket) this.#table.delete(item);
      }
    }
    return this;
  }

  entries() {
    return [...this.#table].map(([key, r]) => ({ key, ...r }))
      .sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
  }

  bounds(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    const r = this.#table.get(key);
    return r ? { lower: r.count, upper: r.count + r.delta }
      : { lower: 0n, upper: this.#n / this.#width };
  }

  query(p, q) {
    if (typeof p !== "bigint" || typeof q !== "bigint" ||
        p <= 0n || q <= 0n || p > q || p * this.#width <= q) {
      throw new RangeError("support must satisfy 1/width < p/q <= 1");
    }
    if (this.#n === 0n) return [];
    const cutoff = this.#n * (p * this.#width - q);
    return this.entries().filter(r => r.count * q * this.#width >= cutoff);
  }
}
const lc = new LossyCounting(4n);
for (const key of "abcdaaaa") lc.add(key);
const wrong = lc.entries().filter(r => r.count * 8n >= lc.n * 5n);
const correct = lc.query(5n, 8n);
console.log("exact a=5, stored a=4, N=8");
console.log(`wrong=${wrong.map(r => r.key).join(",") || "-"}`);
console.log(`correct=${correct.map(r => r.key).join(",") || "-"}`);

运行输出:

exact a=5, stored a=4, N=8
wrong=-
correct=a

反例也提醒我们,不要把该结构当成可精确排序的排行榜。两个键的真实频次可能落在重叠区间里,仅凭 count 的大小不能证明真实先后次序。需要精确结果时,可以保存原始数据或在候选集上进行第二遍精确复核;只有候选摘要本身,无法还原已经丢失的历史。

示例七:参数边界也属于正确性

本例验证非法操作不会偷偷增加流长度,并演示如何以有理数 epsilon=a/b 精确计算 ceil(b/a)。不能先用 Number 算一个过大的整数再交给 BigInt;精度丢失发生在转换之前。最后的巨大桶号测试只验证算术,不冒充真的处理过九千万亿次事件。

class LossyCounting {
  #width;
  #n = 0n;
  #table = new Map();

  constructor(width) {
    if (typeof width !== "bigint" || width < 2n) {
      throw new RangeError("width must be a BigInt >= 2");
    }
    this.#width = width;
  }
  get n() { return this.#n; }
  get width() { return this.#width; }
  get size() { return this.#table.size; }

  add(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    this.#n += 1n;
    const bucket = (this.#n + this.#width - 1n) / this.#width;
    const row = this.#table.get(key);
    if (row) row.count += 1n;
    else this.#table.set(key, { count: 1n, delta: bucket - 1n });
    if (this.#n % this.#width === 0n) {
      for (const [item, r] of this.#table) {
        if (r.count + r.delta <= bucket) this.#table.delete(item);
      }
    }
    return this;
  }

  entries() {
    return [...this.#table].map(([key, r]) => ({ key, ...r }))
      .sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
  }

  bounds(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    const r = this.#table.get(key);
    return r ? { lower: r.count, upper: r.count + r.delta }
      : { lower: 0n, upper: this.#n / this.#width };
  }

  query(p, q) {
    if (typeof p !== "bigint" || typeof q !== "bigint" ||
        p <= 0n || q <= 0n || p > q || p * this.#width <= q) {
      throw new RangeError("support must satisfy 1/width < p/q <= 1");
    }
    if (this.#n === 0n) return [];
    const cutoff = this.#n * (p * this.#width - q);
    return this.entries().filter(r => r.count * q * this.#width >= cutoff);
  }
}
function widthFor(a, b) {
  if (typeof a !== "bigint" || typeof b !== "bigint" ||
      a <= 0n || b <= a) throw new RangeError("need 0 < a/b < 1");
  return (b + a - 1n) / a;
}
const lc = new LossyCounting(4n);
for (const operation of [
  () => new LossyCounting(4),
  () => lc.add(7),
  () => lc.query(1n, 4n)
]) {
  try { operation(); } catch (e) { console.log(e.name); }
}
console.log(`N after errors=${lc.n}`);
console.log(`epsilon=3/10 -> width=${widthFor(3n, 10n)}`);
const n = 9007199254740993n;
console.log(`large bucket=${(n + 3n) / 4n}`);
console.log(`Number loses one=${BigInt(Number(n)) === n - 1n}`);

运行输出:

RangeError
TypeError
RangeError
N after errors=0
epsilon=3/10 -> width=4
large bucket=2251799813685249
Number loses one=true

epsilon=3/10 得到宽度四,所以实际使用的误差率是 1/4,严格不大于用户要求的 3/10。查询条件要求 p/q>1/w,支持度低于或等于误差率时,未保存的键也可能达到目标,当前候选表接口无法提供同样的完整性承诺。生产入口应先解析十进制或有理数字符串,再进入整数算法。

示例八:桶宽不是固定内存槽位数

宽度四并不意味着最多保存四个键。前一桶留下的条目与新一桶尚未清理的条目可以同时存在;直到边界到达,统一删除才发生。下面在第七条时记录状态,再观察第八条后的变化。

class LossyCounting {
  #width;
  #n = 0n;
  #table = new Map();

  constructor(width) {
    if (typeof width !== "bigint" || width < 2n) {
      throw new RangeError("width must be a BigInt >= 2");
    }
    this.#width = width;
  }
  get n() { return this.#n; }
  get width() { return this.#width; }
  get size() { return this.#table.size; }

  add(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    this.#n += 1n;
    const bucket = (this.#n + this.#width - 1n) / this.#width;
    const row = this.#table.get(key);
    if (row) row.count += 1n;
    else this.#table.set(key, { count: 1n, delta: bucket - 1n });
    if (this.#n % this.#width === 0n) {
      for (const [item, r] of this.#table) {
        if (r.count + r.delta <= bucket) this.#table.delete(item);
      }
    }
    return this;
  }

  entries() {
    return [...this.#table].map(([key, r]) => ({ key, ...r }))
      .sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
  }

  bounds(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    const r = this.#table.get(key);
    return r ? { lower: r.count, upper: r.count + r.delta }
      : { lower: 0n, upper: this.#n / this.#width };
  }

  query(p, q) {
    if (typeof p !== "bigint" || typeof q !== "bigint" ||
        p <= 0n || q <= 0n || p > q || p * this.#width <= q) {
      throw new RangeError("support must satisfy 1/width < p/q <= 1");
    }
    if (this.#n === 0n) return [];
    const cutoff = this.#n * (p * this.#width - q);
    return this.entries().filter(r => r.count * q * this.#width >= cutoff);
  }
}
const lc = new LossyCounting(4n);
for (const key of "aabbcdef") {
  lc.add(key);
  if (lc.n === 7n || lc.n === 8n) {
    console.log(`N=${lc.n}, size=${lc.size}, keys=${lc.entries().map(r => r.key).join(",") || "-"}`);
  }
}

运行输出:

N=7, size=5, keys=a,b,c,d,e
N=8, size=0, keys=-

第七条时表里有五个键,已经超过桶宽;第八条后全部清理则是合法结果,因为此时没有键的真实频次超过二。算法空间随输入分布与桶龄变化。工程上应监控条目数以及边界扫描耗时,不能将桶宽直接写入固定内存预算,也不能把每次 add 都描述成最坏情况常数时间。

示例九:对所有短流的每个前缀做精确对照

只测一条最终输出容易漏掉边界前后的错误。下面穷举三种键组成的所有长度不超过八的序列,对每一个前缀都重放独立的 BigInt 精确计数,同时测试一个从未出现的键。它检查区间、全局加性误差、删除后条件与多个有理支持度查询,并使用断言直接中止错误实现。

class LossyCounting {
  #width;
  #n = 0n;
  #table = new Map();

  constructor(width) {
    if (typeof width !== "bigint" || width < 2n) {
      throw new RangeError("width must be a BigInt >= 2");
    }
    this.#width = width;
  }
  get n() { return this.#n; }
  get width() { return this.#width; }
  get size() { return this.#table.size; }

  add(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    this.#n += 1n;
    const bucket = (this.#n + this.#width - 1n) / this.#width;
    const row = this.#table.get(key);
    if (row) row.count += 1n;
    else this.#table.set(key, { count: 1n, delta: bucket - 1n });
    if (this.#n % this.#width === 0n) {
      for (const [item, r] of this.#table) {
        if (r.count + r.delta <= bucket) this.#table.delete(item);
      }
    }
    return this;
  }

  entries() {
    return [...this.#table].map(([key, r]) => ({ key, ...r }))
      .sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
  }

  bounds(key) {
    if (typeof key !== "string") {
      throw new TypeError("key must be a string");
    }
    const r = this.#table.get(key);
    return r ? { lower: r.count, upper: r.count + r.delta }
      : { lower: 0n, upper: this.#n / this.#width };
  }

  query(p, q) {
    if (typeof p !== "bigint" || typeof q !== "bigint" ||
        p <= 0n || q <= 0n || p > q || p * this.#width <= q) {
      throw new RangeError("support must satisfy 1/width < p/q <= 1");
    }
    if (this.#n === 0n) return [];
    const cutoff = this.#n * (p * this.#width - q);
    return this.entries().filter(r => r.count * q * this.#width >= cutoff);
  }
}
const assert = require("node:assert/strict");
const alphabet = ["a", "b", "c"];
let states = 0;
let boundaries = 0;
let queries = 0;
function visit(word, width) {
  const lc = new LossyCounting(width);
  const exact = new Map();
  for (const key of word) {
    lc.add(key);
    exact.set(key, (exact.get(key) ?? 0n) + 1n);
  }
  states += 1;
  if (lc.n > 0n && lc.n % width === 0n) boundaries += 1;
  const rows = lc.entries();
  const table = new Map(rows.map(r => [r.key, r]));
  for (const key of [...alphabet, "never-seen"]) {
    const f = exact.get(key) ?? 0n;
    const r = table.get(key);
    const { lower, upper } = lc.bounds(key);
    assert(lower <= f && f <= upper);
    assert(f - lower <= lc.n / width);
    if (r) {
      assert(r.count <= f && f <= r.count + r.delta);
      assert(r.delta <= (lc.n + width - 1n) / width - 1n);
      if (lc.n % width === 0n) assert(r.count + r.delta > lc.n / width);
    } else {
      assert(f <= lc.n / width);
    }
  }
  for (let q = 1n; q <= 6n; q += 1n) {
    for (let p = 1n; p <= q; p += 1n) {
      if (p * width <= q) continue;
      const out = new Set(lc.query(p, q).map(r => r.key));
      queries += 1;
      if (lc.n === 0n) { assert.equal(out.size, 0); continue; }
      for (const key of [...alphabet, "never-seen"]) {
        const f = exact.get(key) ?? 0n;
        if (f * q >= p * lc.n) assert(out.has(key));
        if (out.has(key)) assert(f * q * width >= lc.n * (p * width - q));
      }
    }
  }
  if (word.length < 8) {
    for (const key of alphabet) visit(word + key, width);
  }
}
for (const width of [2n, 3n, 4n, 5n, 6n]) visit("", width);
console.log(`states=${states}, boundaries=${boundaries}, queries=${queries}`);
console.log("all invariants passed");

运行输出:

states=49205, boundaries=15750, queries=836485
all invariants passed

这是有限状态空间的穷举测试,不是对无限流的数学证明。它的作用是把证明中的每条不变量变成可执行检查,尤其针对 count+delta=b、N 能整除 w、重新插入以及查询恰好等于阈值的时刻。若以后改写为批处理、分片合并或滑动窗口,既要重新证明,也要扩展测试模型,不能沿用当前结论当作免检证明。

从演示到生产,还要补齐哪些边界

在这份实现中,普通更新只做一次候选表查找与整数运算;桶边界要扫描当前全部条目。entries 会复制并排序,query 为了稳定输出也沿用了这一排序,因此查询不能被描述成常数时间。若只需无序候选,可单独实现不排序的只读遍历;如果关心尾延迟,应记录边界扫描时间。BigInt 运算成本也会随整数位数增长,不能把它的数值范围与恒定机器字长混为一谈。

空间结论同样需要措辞谨慎。原论文给出随桶数呈对数增长的最坏情况条目界;在本文整数宽度记法下,可用 O(w·(1+log(1+N/w))) 表达一个包含早期前缀的渐近上界。这是条目数量级,不包含字符串内容、Map 与对象开销,也不是永远保持固定 w 个计数器的承诺。不同事件分布可能得到完全不同的实际常驻条目数。

它统计的是从启动开始的整个前缀,不能直接回答最近五分钟的高频项。按时间过期、支持删除、跨分片合并和以权重跨桶,都改变了证明依赖的事件顺序或质量尺度。实现里若要增加这些功能,应明确新的摘要语义并给出新的证明。尤其不能将两个摘要的 c 与 delta 逐键相加后,就继续声称等价于按原始顺序处理所有事件。

字符串键还需要由业务确定规范化规则。空字符串在本接口中是合法键;大小写、前后空格和 Unicode 规范形式不同的字符串也会分别统计。若上游希望把它们视为同一个事件类型,应在进入摘要之前完成一致的规范化。这样做改变的是输入键定义,而不是计数器偷偷替用户猜测语义。涉及持久化时,应显式将 BigInt 转换成十进制字符串并在读取时校验,不能把 JSON 的默认行为当作可用的状态格式。

审查清单:让 AI 交付证据,而不只是解释

第一,问清输入是单位插入流还是带删除、权重、窗口的另一种问题;第二,逐一检查 N、b、delta 的更新时间;第三,核实删除包含等号而查询也包含等号;第四,要求写出表外键的界,不要只盯着还在 Map 里的条目;第五,用能造成重新插入的短反例测试估计下界;第六,把精确计数作为独立 oracle,而不是拿同一个近似公式互相验证。

最后再检查数值类型与输出承诺。本文九段示例均可单独保存为 .cjs 文件后用 Node.js 运行;示例九覆盖 49,205 个前缀状态、15,750 个非空完整桶边界及 836,485 次合法阈值查询。测试结果用于验证这份实现,不替代上面的归纳证明,也不是吞吐率或内存性能基准。可靠的 AI 辅助编程,应让算法规则、代码、反例和不变量对齐,再谈优化。

资料与语义依据

算法原始来源:Manku 与 Motwani,Approximate Frequency Counts over Data Streams,VLDB 2002,第 4.2 节。本文重点复核单项 Lossy Counting 的插入、桶边界删除与频率保证,不讨论论文中的频繁项集扩展。

JavaScript 数值语义:ECMAScript 的 BigInt 类型与运算;Number.MAX_SAFE_INTEGER 的规范定义。计数器和阈值使用 BigInt,避免 Number 超过安全整数范围后无法区分相邻整数。

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