AI 代码审查实战:用稳定索引最小堆实现可更新、可取消的同步调度队列

10-19 5阅读

让 AI 写一个优先队列,得到能按顺序输出任务的演示并不困难。真正容易漏掉的是:任务已经排进堆以后,能否修改它的优先级?取消中间某个任务时,别的任务会不会被误删?调用方保留了一张旧凭据,队列位置又被新任务占用,旧凭据是否还能生效?这篇教程把审查焦点放在这些状态变化上,逐步实现一个稳定、可索引、可任意删除的最小堆。

这里的调度只有同步含义:数据结构决定下一项是谁,外层循环负责调用它。我们不讨论并发额度、Promise 生命周期、超时、事件循环公平性或运行中任务的中止。数值越小越先出队;优先级相同就按最初入队次序排列;修改优先级不会重新获得排队年龄;取消或出队都会永久终结本次句柄的有效期。这些约定需要先写下来,随后才有判断 AI 代码是否正确的依据。

AI 代码审查实战:用稳定索引最小堆实现可更新、可取消的同步调度队列
AI 生成的概念插画:节点会移动,身份令牌保持不变;画面用于表达索引与句柄的关系,并非严格的堆结构示意图。

全文正好九个可独立运行的例子,每段都完整保存为对应的 01.mjs 至 09.mjs。第二段起会重复同一份类定义,目的是让读者复制任何一段后都能直接验证,不必寻找前文隐藏依赖。每段运行命令都是 node --unhandled-rejections=strict 文件名,下面给出精确标准输出;代码只依赖 Node 内置断言模块。测试记录中的本机 Node 版本为 v24.19.0,所有段落的退出码均为零且标准错误为空。Node 的模块文档说明了 .mjs 入口,命令行文档说明了拒绝处理选项。这里的 strict 参数处理未捕获的 Promise 拒绝,与 JavaScript 语言严格模式不是一回事;本文实现本身没有异步操作。

01.先把稳定性写成可比较的键

审查时首先检查比较规则,而不是盯着上浮循环。每个节点拥有两个排序键:有限的 Number 优先级,以及只在入队时分配的 BigInt 序号。先比较优先级,仅在相等时比较序号。序号不代表业务编号,也不代表当前数组下标;它记录的是这个具体入队实例的先后。

只使用优先级比较,会让等优先级节点在交换时失去稳定次序。用普通 Number 不停加一,则会在安全整数范围之外失去相邻整数的区分能力。下面刻意从大整数附近开始,以极少的数据重现区别。ECMAScript 对 BigInt 的定义支持任意位宽整数及精确整数运算,但这并不意味着实际机器拥有无限内存。比较函数返回布尔值;给数组排序时再转换为负一、零或一,不把 BigInt 差值交给排序比较器。

保存为 01.mjs,运行 node --unhandled-rejections=strict 01.mjs。

import assert from "node:assert/strict";
const before = (a, b) => a.p < b.p || (a.p === b.p && a.seq < b.seq);
const start = 9007199254740992n;
const rows = [
  { name: "A", p: 5, seq: start },
  { name: "B", p: 5, seq: start + 1n },
  { name: "C", p: -1, seq: start + 2n }
];
rows.sort((a, b) => before(a, b) ? -1 : before(b, a) ? 1 : 0);
assert.deepEqual(rows.map(x => x.name), ["C", "A", "B"]);
assert.equal(9007199254740992 + 1, 9007199254740992);
assert.notEqual(start + 1n, start);
console.log(rows.map(x => x.name).join(","));
console.log(String(start + 1n));

精确输出:

C,A,B
9007199254740993

这个例子只隔离排序约定。后面的堆不会依靠 Array.sort 维持运行状态,也不会把序号转换回 Number。我们保留有限小数和负数作为合法优先级,同时将正零与负零视为同一个优先级等级。

02.最小闭环:入队、观察与稳定出队

完整实现有两份必须同步变化的状态:数组保存堆节点,Map 保存句柄到当前下标的映射。句柄由每次新建的 Symbol 充当,外部只能原样传回,不能把它当作位置使用。节点中的业务载荷、优先级、序号和句柄都存在私有数组里,避免调用方直接改坏排序键。peek 返回一个新的包装对象,pop 和 cancel 也返回包含 value、priority 的结果。

最值得审查的是交换函数。只交换数组元素还不够,交换后两个句柄的映射都必须更新。以零开始的数组中,父下标为向下取整的 (i − 1) / 2,左右孩子分别为 2i + 1 和 2i + 2。代码使用普通算术,避免把数组下标悄悄转换为有符号三十二位整数。向下调整时先选更小的孩子,再决定是否交换,不能发现左孩子合适就忽略右孩子。

保存为 02.mjs,运行 node --unhandled-rejections=strict 02.mjs。

import assert from "node:assert/strict";
class StableHeap {
  #a = []; #pos = new Map(); #next;
  constructor(sequenceStart = 0n) {
    if (typeof sequenceStart !== "bigint" || sequenceStart < 0n)
      throw new TypeError("sequenceStart must be nonnegative bigint");
    this.#next = sequenceStart;
  }
  get size() { return this.#a.length; }
  has(handle) { return this.#pos.has(handle); }
  #priority(p) {
    if (typeof p !== "number" || !Number.isFinite(p))
      throw new TypeError("priority must be finite number");
  }
  #less(x, y) {
    return x.p < y.p || (x.p === y.p && x.seq < y.seq);
  }
  #index(handle) {
    const i = this.#pos.get(handle);
    if (i === undefined) throw new Error("invalid or stale handle");
    return i;
  }
  #swap(i, j) {
    [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]];
    this.#pos.set(this.#a[i].h, i);
    this.#pos.set(this.#a[j].h, j);
  }
  #up(i) {
    while (i > 0) {
      const p = Math.floor((i - 1) / 2);
      if (!this.#less(this.#a[i], this.#a[p])) break;
      this.#swap(i, p); i = p;
    }
  }
  #down(i) {
    for (;;) {
      let c = 2 * i + 1;
      if (c >= this.size) return;
      if (c + 1 < this.size && this.#less(this.#a[c + 1], this.#a[c])) c++;
      if (!this.#less(this.#a[c], this.#a[i])) return;
      this.#swap(i, c); i = c;
    }
  }
  #repair(i) {
    if (i > 0 && this.#less(this.#a[i], this.#a[Math.floor((i - 1) / 2)]))
      this.#up(i);
    else this.#down(i);
  }
  #view(n) { return n === undefined ? undefined : { value: n.value, priority: n.p }; }
  push(value, priority) {
    this.#priority(priority);
    const h = Symbol("entry");
    const node = { h, value, p: priority, seq: this.#next++ };
    this.#pos.set(h, this.size); this.#a.push(node);
    this.#up(this.size - 1);
    return h;
  }
  peek() { return this.#view(this.#a[0]); }
  updatePriority(handle, priority) {
    const i = this.#index(handle);
    this.#priority(priority);
    this.#a[i].p = priority; this.#repair(i);
  }
  #remove(i) {
    const removed = this.#a[i], last = this.#a.pop();
    this.#pos.delete(removed.h);
    if (i < this.size) {
      this.#a[i] = last; this.#pos.set(last.h, i); this.#repair(i);
    }
    return this.#view(removed);
  }
  cancel(handle) { return this.#remove(this.#index(handle)); }
  pop() { return this.size === 0 ? undefined : this.#remove(0); }
  assertValid() {
    if (this.size !== this.#pos.size) throw new Error("size mismatch");
    const seen = new Set();
    for (let i = 0; i < this.size; i++) {
      const n = this.#a[i];
      if (this.#pos.get(n.h) !== i) throw new Error("index mismatch");
      if (typeof n.seq !== "bigint" || n.seq < 0n || n.seq >= this.#next || seen.has(n.seq))
        throw new Error("sequence mismatch");
      seen.add(n.seq);
      if (i && this.#less(n, this.#a[Math.floor((i - 1) / 2)]))
        throw new Error("heap order mismatch");
    }
    return true;
  }
}

const q = new StableHeap();
const a = q.push("A", 2), b = q.push("B", 1), c = q.push("C", 2);
assert.deepEqual(q.peek(), { value: "B", priority: 1 });
assert.equal(q.size, 3);
q.assertValid();
const order = [q.pop().value, q.pop().value, q.pop().value];
assert.deepEqual(order, ["B", "A", "C"]);
assert.equal(q.pop(), undefined);
assert.equal(q.has(a) || q.has(b) || q.has(c), false);
q.assertValid();
console.log(order.join(","));
console.log(`size=${q.size}; empty=${q.peek() === undefined}`);

精确输出:

B,A,C
size=0; empty=true

观察最小值不会移除节点,空队列的 peek 和 pop 返回 undefined。真实载荷即使就是 undefined,也会装在结果对象里,因此可以与空队列区分。辅助检查方法不会在每次操作中自动执行,测试时显式调用即可。

03.更新优先级时,原来的排队年龄不变

修改键值需要先定位,再修复顺序。先用句柄查 Map 得到下标,然后验证新优先级,最后修改节点。新键比父节点更小时向上走,否则向下走。这个选择建立在修改前堆序成立、且只改变一个节点排序键的前提上;如果整个堆已经坏掉,局部修复不能替代全面检查。

这里尤其要阻止 AI 把 updatePriority 写成先删除、再重新 push。那样虽然最终优先级可能正确,却会换掉句柄,或者改变同级任务的年龄。示例让 C 先升到队首,再回到原等级,随后让 B 也进入相同等级,最终顺序仍然是最初入队的 A、B、C。优先级没变的更新也合法,不必偷偷赋予新序号。

保存为 03.mjs,运行 node --unhandled-rejections=strict 03.mjs。

import assert from "node:assert/strict";
class StableHeap {
  #a = []; #pos = new Map(); #next;
  constructor(sequenceStart = 0n) {
    if (typeof sequenceStart !== "bigint" || sequenceStart < 0n)
      throw new TypeError("sequenceStart must be nonnegative bigint");
    this.#next = sequenceStart;
  }
  get size() { return this.#a.length; }
  has(handle) { return this.#pos.has(handle); }
  #priority(p) {
    if (typeof p !== "number" || !Number.isFinite(p))
      throw new TypeError("priority must be finite number");
  }
  #less(x, y) {
    return x.p < y.p || (x.p === y.p && x.seq < y.seq);
  }
  #index(handle) {
    const i = this.#pos.get(handle);
    if (i === undefined) throw new Error("invalid or stale handle");
    return i;
  }
  #swap(i, j) {
    [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]];
    this.#pos.set(this.#a[i].h, i);
    this.#pos.set(this.#a[j].h, j);
  }
  #up(i) {
    while (i > 0) {
      const p = Math.floor((i - 1) / 2);
      if (!this.#less(this.#a[i], this.#a[p])) break;
      this.#swap(i, p); i = p;
    }
  }
  #down(i) {
    for (;;) {
      let c = 2 * i + 1;
      if (c >= this.size) return;
      if (c + 1 < this.size && this.#less(this.#a[c + 1], this.#a[c])) c++;
      if (!this.#less(this.#a[c], this.#a[i])) return;
      this.#swap(i, c); i = c;
    }
  }
  #repair(i) {
    if (i > 0 && this.#less(this.#a[i], this.#a[Math.floor((i - 1) / 2)]))
      this.#up(i);
    else this.#down(i);
  }
  #view(n) { return n === undefined ? undefined : { value: n.value, priority: n.p }; }
  push(value, priority) {
    this.#priority(priority);
    const h = Symbol("entry");
    const node = { h, value, p: priority, seq: this.#next++ };
    this.#pos.set(h, this.size); this.#a.push(node);
    this.#up(this.size - 1);
    return h;
  }
  peek() { return this.#view(this.#a[0]); }
  updatePriority(handle, priority) {
    const i = this.#index(handle);
    this.#priority(priority);
    this.#a[i].p = priority; this.#repair(i);
  }
  #remove(i) {
    const removed = this.#a[i], last = this.#a.pop();
    this.#pos.delete(removed.h);
    if (i < this.size) {
      this.#a[i] = last; this.#pos.set(last.h, i); this.#repair(i);
    }
    return this.#view(removed);
  }
  cancel(handle) { return this.#remove(this.#index(handle)); }
  pop() { return this.size === 0 ? undefined : this.#remove(0); }
  assertValid() {
    if (this.size !== this.#pos.size) throw new Error("size mismatch");
    const seen = new Set();
    for (let i = 0; i < this.size; i++) {
      const n = this.#a[i];
      if (this.#pos.get(n.h) !== i) throw new Error("index mismatch");
      if (typeof n.seq !== "bigint" || n.seq < 0n || n.seq >= this.#next || seen.has(n.seq))
        throw new Error("sequence mismatch");
      seen.add(n.seq);
      if (i && this.#less(n, this.#a[Math.floor((i - 1) / 2)]))
        throw new Error("heap order mismatch");
    }
    return true;
  }
}

const q = new StableHeap();
const a = q.push("A", 5), b = q.push("B", 1), c = q.push("C", 5);
q.updatePriority(c, 0); q.assertValid();
assert.equal(q.peek().value, "C");
q.updatePriority(c, 5); q.assertValid();
q.updatePriority(b, 5); q.assertValid();
q.updatePriority(a, 5); q.assertValid();
const order = [q.pop().value, q.pop().value, q.pop().value];
assert.deepEqual(order, ["A", "B", "C"]);
console.log(order.join(","));

精确输出:

A,B,C

这项约定适用于希望保留原始等待次序的队列。如果产品要求修改后重新排队,就应提供名字与语义都不同的操作,明确废弃旧句柄并返回新句柄,避免把两种行为塞进同一个含糊接口。

04.任意删除:补洞之后可能向上,也可能向下

任意删除不能使用数组中间的 splice 后就结束。后续元素的下标都会移动,而且层次关系也可能全部变化。索引堆的做法是:记住要删的节点,取走尾节点,删除旧句柄映射;如果被删位置仍在有效范围内,就用尾节点补洞,更新它的新位置,再修复堆序。

补洞之后只会向下的实现是不完整的。尾节点原本属于另一个父节点,它来到新位置时可能比新父节点更小。下面第一组专门迫使补洞节点向上走,第二组迫使它向下走,第三组删除尾部,最后再删除唯一节点。删除尾部和唯一节点时没有洞需要补,必须避免把已弹出的节点重新写回数组。这些定向样例比单纯反复 pop 更容易暴露错误分支。

保存为 04.mjs,运行 node --unhandled-rejections=strict 04.mjs。

import assert from "node:assert/strict";
class StableHeap {
  #a = []; #pos = new Map(); #next;
  constructor(sequenceStart = 0n) {
    if (typeof sequenceStart !== "bigint" || sequenceStart < 0n)
      throw new TypeError("sequenceStart must be nonnegative bigint");
    this.#next = sequenceStart;
  }
  get size() { return this.#a.length; }
  has(handle) { return this.#pos.has(handle); }
  #priority(p) {
    if (typeof p !== "number" || !Number.isFinite(p))
      throw new TypeError("priority must be finite number");
  }
  #less(x, y) {
    return x.p < y.p || (x.p === y.p && x.seq < y.seq);
  }
  #index(handle) {
    const i = this.#pos.get(handle);
    if (i === undefined) throw new Error("invalid or stale handle");
    return i;
  }
  #swap(i, j) {
    [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]];
    this.#pos.set(this.#a[i].h, i);
    this.#pos.set(this.#a[j].h, j);
  }
  #up(i) {
    while (i > 0) {
      const p = Math.floor((i - 1) / 2);
      if (!this.#less(this.#a[i], this.#a[p])) break;
      this.#swap(i, p); i = p;
    }
  }
  #down(i) {
    for (;;) {
      let c = 2 * i + 1;
      if (c >= this.size) return;
      if (c + 1 < this.size && this.#less(this.#a[c + 1], this.#a[c])) c++;
      if (!this.#less(this.#a[c], this.#a[i])) return;
      this.#swap(i, c); i = c;
    }
  }
  #repair(i) {
    if (i > 0 && this.#less(this.#a[i], this.#a[Math.floor((i - 1) / 2)]))
      this.#up(i);
    else this.#down(i);
  }
  #view(n) { return n === undefined ? undefined : { value: n.value, priority: n.p }; }
  push(value, priority) {
    this.#priority(priority);
    const h = Symbol("entry");
    const node = { h, value, p: priority, seq: this.#next++ };
    this.#pos.set(h, this.size); this.#a.push(node);
    this.#up(this.size - 1);
    return h;
  }
  peek() { return this.#view(this.#a[0]); }
  updatePriority(handle, priority) {
    const i = this.#index(handle);
    this.#priority(priority);
    this.#a[i].p = priority; this.#repair(i);
  }
  #remove(i) {
    const removed = this.#a[i], last = this.#a.pop();
    this.#pos.delete(removed.h);
    if (i < this.size) {
      this.#a[i] = last; this.#pos.set(last.h, i); this.#repair(i);
    }
    return this.#view(removed);
  }
  cancel(handle) { return this.#remove(this.#index(handle)); }
  pop() { return this.size === 0 ? undefined : this.#remove(0); }
  assertValid() {
    if (this.size !== this.#pos.size) throw new Error("size mismatch");
    const seen = new Set();
    for (let i = 0; i < this.size; i++) {
      const n = this.#a[i];
      if (this.#pos.get(n.h) !== i) throw new Error("index mismatch");
      if (typeof n.seq !== "bigint" || n.seq < 0n || n.seq >= this.#next || seen.has(n.seq))
        throw new Error("sequence mismatch");
      seen.add(n.seq);
      if (i && this.#less(n, this.#a[Math.floor((i - 1) / 2)]))
        throw new Error("heap order mismatch");
    }
    return true;
  }
}

function run(priorities, removed) {
  const q = new StableHeap();
  const handles = priorities.map(p => q.push(p, p));
  assert.equal(q.cancel(handles[priorities.indexOf(removed)]).value, removed);
  q.assertValid();
  const out = [];
  while (q.size) { out.push(q.pop().value); q.assertValid(); }
  assert.deepEqual(out, priorities.filter(p => p !== removed).sort((a, b) => a - b));
  return out.join(",");
}
console.log("up=" + run([1, 5, 2, 9, 10, 3, 4], 10));
console.log("down=" + run([1, 2, 3, 4, 5, 6, 7], 2));
console.log("tail=" + run([1, 2, 3], 3));
const q = new StableHeap();
q.cancel(q.push("only", 0)); q.assertValid();
console.log(`single=${q.size}`);

精确输出:

up=1,2,3,4,5,9
down=1,3,4,5,6,7
tail=1,2
single=0

本实现把 pop 和 cancel 汇入同一个移除过程,减少两套收尾逻辑产生分歧的机会。返回业务结果之前,句柄已经从映射中消失;队列不会留下等待未来清理的取消标记。

05.句柄是一次生命周期的凭据

句柄要表达一次入队实例,而不是一个可循环利用的整数槽位。否则调用方握着下标二,旧任务离开以后,新任务恰好占据下标二,旧取消请求就会删掉新任务。这是身份与位置混为一谈造成的错误。本实现每次 push 都创建新 Symbol,而且每个队列只接受自己当前 Map 中存在的句柄,因此重复业务标识、相同的 Symbol 描述文字、其他队列的句柄都不能冒充本次实例。ECMAScript 的 Symbol 构造规则会创建新的符号值;这里不用会按名称复用符号的 Symbol.for。

无效和过期句柄在 cancel、updatePriority 中统一抛错,has 则返回 false。这里没有让重复取消悄悄成功,因为审查教程希望调用错误尽早显现。调用方如果需要宽松取消,可以先询问 has;本文没有线程共享和跨调用并发语义,不能把这套同步用法直接当作跨线程原子检查。句柄只是进程内接口凭据,不是可跨网络传输的安全认证令牌,也不承诺可以序列化后恢复。

保存为 05.mjs,运行 node --unhandled-rejections=strict 05.mjs。

import assert from "node:assert/strict";
class StableHeap {
  #a = []; #pos = new Map(); #next;
  constructor(sequenceStart = 0n) {
    if (typeof sequenceStart !== "bigint" || sequenceStart < 0n)
      throw new TypeError("sequenceStart must be nonnegative bigint");
    this.#next = sequenceStart;
  }
  get size() { return this.#a.length; }
  has(handle) { return this.#pos.has(handle); }
  #priority(p) {
    if (typeof p !== "number" || !Number.isFinite(p))
      throw new TypeError("priority must be finite number");
  }
  #less(x, y) {
    return x.p < y.p || (x.p === y.p && x.seq < y.seq);
  }
  #index(handle) {
    const i = this.#pos.get(handle);
    if (i === undefined) throw new Error("invalid or stale handle");
    return i;
  }
  #swap(i, j) {
    [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]];
    this.#pos.set(this.#a[i].h, i);
    this.#pos.set(this.#a[j].h, j);
  }
  #up(i) {
    while (i > 0) {
      const p = Math.floor((i - 1) / 2);
      if (!this.#less(this.#a[i], this.#a[p])) break;
      this.#swap(i, p); i = p;
    }
  }
  #down(i) {
    for (;;) {
      let c = 2 * i + 1;
      if (c >= this.size) return;
      if (c + 1 < this.size && this.#less(this.#a[c + 1], this.#a[c])) c++;
      if (!this.#less(this.#a[c], this.#a[i])) return;
      this.#swap(i, c); i = c;
    }
  }
  #repair(i) {
    if (i > 0 && this.#less(this.#a[i], this.#a[Math.floor((i - 1) / 2)]))
      this.#up(i);
    else this.#down(i);
  }
  #view(n) { return n === undefined ? undefined : { value: n.value, priority: n.p }; }
  push(value, priority) {
    this.#priority(priority);
    const h = Symbol("entry");
    const node = { h, value, p: priority, seq: this.#next++ };
    this.#pos.set(h, this.size); this.#a.push(node);
    this.#up(this.size - 1);
    return h;
  }
  peek() { return this.#view(this.#a[0]); }
  updatePriority(handle, priority) {
    const i = this.#index(handle);
    this.#priority(priority);
    this.#a[i].p = priority; this.#repair(i);
  }
  #remove(i) {
    const removed = this.#a[i], last = this.#a.pop();
    this.#pos.delete(removed.h);
    if (i < this.size) {
      this.#a[i] = last; this.#pos.set(last.h, i); this.#repair(i);
    }
    return this.#view(removed);
  }
  cancel(handle) { return this.#remove(this.#index(handle)); }
  pop() { return this.size === 0 ? undefined : this.#remove(0); }
  assertValid() {
    if (this.size !== this.#pos.size) throw new Error("size mismatch");
    const seen = new Set();
    for (let i = 0; i < this.size; i++) {
      const n = this.#a[i];
      if (this.#pos.get(n.h) !== i) throw new Error("index mismatch");
      if (typeof n.seq !== "bigint" || n.seq < 0n || n.seq >= this.#next || seen.has(n.seq))
        throw new Error("sequence mismatch");
      seen.add(n.seq);
      if (i && this.#less(n, this.#a[Math.floor((i - 1) / 2)]))
        throw new Error("heap order mismatch");
    }
    return true;
  }
}

const q = new StableHeap(), other = new StableHeap();
const old = q.push("same-id", 2), foreign = other.push("foreign", 0);
q.cancel(old);
const fresh = q.push("same-id", 2);
assert.notEqual(old, fresh);
let rejected = 0;
for (const handle of [old, foreign, Symbol("entry"), 0, undefined]) {
  assert.equal(q.has(handle), false);
  assert.throws(() => q.cancel(handle), /invalid or stale handle/); rejected++;
  assert.throws(() => q.updatePriority(handle, -1), /invalid or stale handle/); rejected++;
}
assert.equal(q.has(fresh), true);
q.pop();
assert.throws(() => q.updatePriority(fresh, 1), /invalid or stale handle/);
q.assertValid(); other.assertValid();
console.log(`rejected=${rejected + 1}; other=${other.size}; local=${q.size}`);

精确输出:

rejected=11; other=1; local=0

测试不仅检查旧句柄被拒绝,还检查外来句柄所属的队列完全没有受到影响。出队后的句柄与取消后的句柄具有相同终态,业务标识再次入队也不会使旧句柄复活。

06.数值边界、失败原子性与载荷隔离

比较关系成立的前提是输入集合受控。NaN 不能参与这里的有序关系;字符串、BigInt 优先级和 null 也不做隐式转换。我们只接受有限 Number,因此无穷大被主动拒绝。验证放在修改之前,常规参数错误不会先污染堆再报错。更新时先验证句柄,再验证优先级,因此两者同时错误时,报错顺序也是确定的。

第二个边界是所有权。peek 返回的包装对象可以被调用方修改,但修改包装的 priority 不会触及内部优先级。value 若为对象,仍然是共享引用,本文没有深拷贝或深冻结业务数据;修改 value 的内容会被其他持有者看见,却不会改变独立保存的排序键。第三个边界是序号:构造参数只用于测试从高位整数开始的情况,实际使用默认零即可;它不是恢复快照的接口,不能借它复活句柄。

保存为 06.mjs,运行 node --unhandled-rejections=strict 06.mjs。

import assert from "node:assert/strict";
class StableHeap {
  #a = []; #pos = new Map(); #next;
  constructor(sequenceStart = 0n) {
    if (typeof sequenceStart !== "bigint" || sequenceStart < 0n)
      throw new TypeError("sequenceStart must be nonnegative bigint");
    this.#next = sequenceStart;
  }
  get size() { return this.#a.length; }
  has(handle) { return this.#pos.has(handle); }
  #priority(p) {
    if (typeof p !== "number" || !Number.isFinite(p))
      throw new TypeError("priority must be finite number");
  }
  #less(x, y) {
    return x.p < y.p || (x.p === y.p && x.seq < y.seq);
  }
  #index(handle) {
    const i = this.#pos.get(handle);
    if (i === undefined) throw new Error("invalid or stale handle");
    return i;
  }
  #swap(i, j) {
    [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]];
    this.#pos.set(this.#a[i].h, i);
    this.#pos.set(this.#a[j].h, j);
  }
  #up(i) {
    while (i > 0) {
      const p = Math.floor((i - 1) / 2);
      if (!this.#less(this.#a[i], this.#a[p])) break;
      this.#swap(i, p); i = p;
    }
  }
  #down(i) {
    for (;;) {
      let c = 2 * i + 1;
      if (c >= this.size) return;
      if (c + 1 < this.size && this.#less(this.#a[c + 1], this.#a[c])) c++;
      if (!this.#less(this.#a[c], this.#a[i])) return;
      this.#swap(i, c); i = c;
    }
  }
  #repair(i) {
    if (i > 0 && this.#less(this.#a[i], this.#a[Math.floor((i - 1) / 2)]))
      this.#up(i);
    else this.#down(i);
  }
  #view(n) { return n === undefined ? undefined : { value: n.value, priority: n.p }; }
  push(value, priority) {
    this.#priority(priority);
    const h = Symbol("entry");
    const node = { h, value, p: priority, seq: this.#next++ };
    this.#pos.set(h, this.size); this.#a.push(node);
    this.#up(this.size - 1);
    return h;
  }
  peek() { return this.#view(this.#a[0]); }
  updatePriority(handle, priority) {
    const i = this.#index(handle);
    this.#priority(priority);
    this.#a[i].p = priority; this.#repair(i);
  }
  #remove(i) {
    const removed = this.#a[i], last = this.#a.pop();
    this.#pos.delete(removed.h);
    if (i < this.size) {
      this.#a[i] = last; this.#pos.set(last.h, i); this.#repair(i);
    }
    return this.#view(removed);
  }
  cancel(handle) { return this.#remove(this.#index(handle)); }
  pop() { return this.size === 0 ? undefined : this.#remove(0); }
  assertValid() {
    if (this.size !== this.#pos.size) throw new Error("size mismatch");
    const seen = new Set();
    for (let i = 0; i < this.size; i++) {
      const n = this.#a[i];
      if (this.#pos.get(n.h) !== i) throw new Error("index mismatch");
      if (typeof n.seq !== "bigint" || n.seq < 0n || n.seq >= this.#next || seen.has(n.seq))
        throw new Error("sequence mismatch");
      seen.add(n.seq);
      if (i && this.#less(n, this.#a[Math.floor((i - 1) / 2)]))
        throw new Error("heap order mismatch");
    }
    return true;
  }
}

const q = new StableHeap(9007199254740992n);
const h = q.push({ name: "payload", priority: 999 }, -0);
const view = q.peek(); view.priority = -999;
assert.equal(Object.is(q.peek().priority, -0), true);
let invalid = 0;
for (const p of [NaN, Infinity, -Infinity, "2", 2n, null]) {
  assert.throws(() => q.push("bad", p), TypeError);
  assert.throws(() => q.updatePriority(h, p), TypeError);
  assert.equal(q.size, 1); assert.equal(Object.is(q.peek().priority, -0), true);
  q.assertValid(); invalid++;
}
q.push(undefined, 0);
q.push("fraction", -0.5);
assert.equal(q.pop().value, "fraction");
assert.equal(q.pop().value.name, "payload");
assert.deepEqual(q.pop(), { value: undefined, priority: 0 });
assert.equal(q.pop(), undefined);
q.assertValid();
assert.throws(() => new StableHeap(1), TypeError);
assert.throws(() => new StableHeap(-1n), TypeError);
console.log(`invalid=${invalid}; stable-zero=true; wrapped-undefined=true`);

精确输出:

invalid=6; stable-zero=true; wrapped-undefined=true

这里所说失败前不改状态,限于普通参数验证错误,不是对内存耗尽等运行时故障作事务承诺。测试同时覆盖非法输入、负数、小数、正负零同级以及 undefined 载荷,避免一个漂亮的字符串演示掩盖接口空洞。

07.把索引关系变成每步都能执行的断言

审查索引结构时,输出顺序正确只是必要条件。一个已经损坏的反向索引,可能在下一次按句柄更新时才表现为误操作。因此 assertValid 每次遍历都检查三个层面:数组长度等于映射条数;每个节点的句柄映射回它所在的下标;孩子不比父节点更小。它还检查序号类型、非负性、唯一性,以及序号必须小于下一个待分配值。

映射大小一致,再加上每个数组节点都能正确反查,足以排除遗漏映射和多余映射。这不是单独检查 Map.size 就能替代的。示例先逆序插入制造连续上浮,然后修改一半节点,再取消另一半,最后全部取出。每个状态转换后立即检查,失败位置会比最终顺序断言更靠近根因。序号不会因为节点移动、删除或更新而重新编号。

保存为 07.mjs,运行 node --unhandled-rejections=strict 07.mjs。

import assert from "node:assert/strict";
class StableHeap {
  #a = []; #pos = new Map(); #next;
  constructor(sequenceStart = 0n) {
    if (typeof sequenceStart !== "bigint" || sequenceStart < 0n)
      throw new TypeError("sequenceStart must be nonnegative bigint");
    this.#next = sequenceStart;
  }
  get size() { return this.#a.length; }
  has(handle) { return this.#pos.has(handle); }
  #priority(p) {
    if (typeof p !== "number" || !Number.isFinite(p))
      throw new TypeError("priority must be finite number");
  }
  #less(x, y) {
    return x.p < y.p || (x.p === y.p && x.seq < y.seq);
  }
  #index(handle) {
    const i = this.#pos.get(handle);
    if (i === undefined) throw new Error("invalid or stale handle");
    return i;
  }
  #swap(i, j) {
    [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]];
    this.#pos.set(this.#a[i].h, i);
    this.#pos.set(this.#a[j].h, j);
  }
  #up(i) {
    while (i > 0) {
      const p = Math.floor((i - 1) / 2);
      if (!this.#less(this.#a[i], this.#a[p])) break;
      this.#swap(i, p); i = p;
    }
  }
  #down(i) {
    for (;;) {
      let c = 2 * i + 1;
      if (c >= this.size) return;
      if (c + 1 < this.size && this.#less(this.#a[c + 1], this.#a[c])) c++;
      if (!this.#less(this.#a[c], this.#a[i])) return;
      this.#swap(i, c); i = c;
    }
  }
  #repair(i) {
    if (i > 0 && this.#less(this.#a[i], this.#a[Math.floor((i - 1) / 2)]))
      this.#up(i);
    else this.#down(i);
  }
  #view(n) { return n === undefined ? undefined : { value: n.value, priority: n.p }; }
  push(value, priority) {
    this.#priority(priority);
    const h = Symbol("entry");
    const node = { h, value, p: priority, seq: this.#next++ };
    this.#pos.set(h, this.size); this.#a.push(node);
    this.#up(this.size - 1);
    return h;
  }
  peek() { return this.#view(this.#a[0]); }
  updatePriority(handle, priority) {
    const i = this.#index(handle);
    this.#priority(priority);
    this.#a[i].p = priority; this.#repair(i);
  }
  #remove(i) {
    const removed = this.#a[i], last = this.#a.pop();
    this.#pos.delete(removed.h);
    if (i < this.size) {
      this.#a[i] = last; this.#pos.set(last.h, i); this.#repair(i);
    }
    return this.#view(removed);
  }
  cancel(handle) { return this.#remove(this.#index(handle)); }
  pop() { return this.size === 0 ? undefined : this.#remove(0); }
  assertValid() {
    if (this.size !== this.#pos.size) throw new Error("size mismatch");
    const seen = new Set();
    for (let i = 0; i < this.size; i++) {
      const n = this.#a[i];
      if (this.#pos.get(n.h) !== i) throw new Error("index mismatch");
      if (typeof n.seq !== "bigint" || n.seq < 0n || n.seq >= this.#next || seen.has(n.seq))
        throw new Error("sequence mismatch");
      seen.add(n.seq);
      if (i && this.#less(n, this.#a[Math.floor((i - 1) / 2)]))
        throw new Error("heap order mismatch");
    }
    return true;
  }
}

const q = new StableHeap();
const handles = [];
let checks = 0;
const check = () => { q.assertValid(); checks++; };
for (let i = 0; i < 64; i++) { handles.push(q.push(i, 63 - i)); check(); }
for (let i = 0; i < 64; i += 2) { q.updatePriority(handles[i], i % 5); check(); }
for (let i = 1; i < 64; i += 2) { q.cancel(handles[i]); check(); }
const out = [];
while (q.size) { out.push(q.pop()); check(); }
const expected = Array.from({ length: 32 }, (_, i) => 2 * i)
  .sort((a, b) => a % 5 - b % 5 || a - b);
assert.deepEqual(out.map(x => x.value), expected);
assert.equal(handles.every(h => !q.has(h)), true);
console.log(`checks=${checks}; drained=${out.length}; all-stale=true`);

精确输出:

checks=160; drained=32; all-stale=true

检查器需要遍历整个堆,还使用临时集合检查序号,因此它属于测试工具。若把它无条件放进生产的每一次 push,原本的对数级堆调整就会被线性扫描覆盖。审查报告必须把诊断成本和正常操作成本分开说明。

08.用独立排序数组做可复现的差分测试

定向测试证明我们想到了几个坏路径,差分测试则用大量组合寻找没有想到的路径。参考模型选择普通数组:更新时修改记录,取消时过滤记录,观察和出队时复制并排序。它故意不使用堆,也不维护下标映射,避免把被测实现的核心错误再次抄进答案模型。参考记录保存独立的原始序号,排序比较器单独书写,结果按业务编号和优先级逐步比较。

伪随机数发生器使用固定种子,便于复现;每次选操作、记录和优先级都会推进状态。取值通过归一化缩放产生,不直接用线性同余状态的低位选操作。四种操作的抽样次数都要超过三百,避免所谓两千次测试实际只覆盖少数分支。队列为空时会回退到插入,这也是测试协议的一部分。每一步还核对所有历史句柄的有效状态,最后按参考顺序排空,确认没有幽灵节点。

保存为 08.mjs,运行 node --unhandled-rejections=strict 08.mjs。

import assert from "node:assert/strict";
class StableHeap {
  #a = []; #pos = new Map(); #next;
  constructor(sequenceStart = 0n) {
    if (typeof sequenceStart !== "bigint" || sequenceStart < 0n)
      throw new TypeError("sequenceStart must be nonnegative bigint");
    this.#next = sequenceStart;
  }
  get size() { return this.#a.length; }
  has(handle) { return this.#pos.has(handle); }
  #priority(p) {
    if (typeof p !== "number" || !Number.isFinite(p))
      throw new TypeError("priority must be finite number");
  }
  #less(x, y) {
    return x.p < y.p || (x.p === y.p && x.seq < y.seq);
  }
  #index(handle) {
    const i = this.#pos.get(handle);
    if (i === undefined) throw new Error("invalid or stale handle");
    return i;
  }
  #swap(i, j) {
    [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]];
    this.#pos.set(this.#a[i].h, i);
    this.#pos.set(this.#a[j].h, j);
  }
  #up(i) {
    while (i > 0) {
      const p = Math.floor((i - 1) / 2);
      if (!this.#less(this.#a[i], this.#a[p])) break;
      this.#swap(i, p); i = p;
    }
  }
  #down(i) {
    for (;;) {
      let c = 2 * i + 1;
      if (c >= this.size) return;
      if (c + 1 < this.size && this.#less(this.#a[c + 1], this.#a[c])) c++;
      if (!this.#less(this.#a[c], this.#a[i])) return;
      this.#swap(i, c); i = c;
    }
  }
  #repair(i) {
    if (i > 0 && this.#less(this.#a[i], this.#a[Math.floor((i - 1) / 2)]))
      this.#up(i);
    else this.#down(i);
  }
  #view(n) { return n === undefined ? undefined : { value: n.value, priority: n.p }; }
  push(value, priority) {
    this.#priority(priority);
    const h = Symbol("entry");
    const node = { h, value, p: priority, seq: this.#next++ };
    this.#pos.set(h, this.size); this.#a.push(node);
    this.#up(this.size - 1);
    return h;
  }
  peek() { return this.#view(this.#a[0]); }
  updatePriority(handle, priority) {
    const i = this.#index(handle);
    this.#priority(priority);
    this.#a[i].p = priority; this.#repair(i);
  }
  #remove(i) {
    const removed = this.#a[i], last = this.#a.pop();
    this.#pos.delete(removed.h);
    if (i < this.size) {
      this.#a[i] = last; this.#pos.set(last.h, i); this.#repair(i);
    }
    return this.#view(removed);
  }
  cancel(handle) { return this.#remove(this.#index(handle)); }
  pop() { return this.size === 0 ? undefined : this.#remove(0); }
  assertValid() {
    if (this.size !== this.#pos.size) throw new Error("size mismatch");
    const seen = new Set();
    for (let i = 0; i < this.size; i++) {
      const n = this.#a[i];
      if (this.#pos.get(n.h) !== i) throw new Error("index mismatch");
      if (typeof n.seq !== "bigint" || n.seq < 0n || n.seq >= this.#next || seen.has(n.seq))
        throw new Error("sequence mismatch");
      seen.add(n.seq);
      if (i && this.#less(n, this.#a[Math.floor((i - 1) / 2)]))
        throw new Error("heap order mismatch");
    }
    return true;
  }
}

const q = new StableHeap(9007199254740992n);
let rows = [], seq = 9007199254740992n, state = 123456789;
const all = [];
const random = n => {
  state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
  return Math.floor(state / 4294967296 * n);
};
const sorted = () => [...rows].sort((a, b) => {
  if (a.p !== b.p) return a.p < b.p ? -1 : 1;
  return a.seq < b.seq ? -1 : a.seq > b.seq ? 1 : 0;
});
const view = row => row && ({ value: row.id, priority: row.p });
let nextId = 0;
const counts = [0, 0, 0, 0];
for (let step = 0; step < 2000; step++) {
  const operation = random(4);
  counts[operation]++;
  if (!rows.length || operation === 0) {
    const id = nextId++, p = random(11) - 5, h = q.push(id, p);
    rows.push({ id, p, h, seq: seq++ }); all.push(h);
  } else if (operation === 1) {
    const row = rows[random(rows.length)], p = random(11) - 5;
    q.updatePriority(row.h, p); row.p = p;
  } else if (operation === 2) {
    const row = rows[random(rows.length)];
    assert.deepEqual(q.cancel(row.h), view(row));
    rows = rows.filter(x => x !== row);
    assert.throws(() => q.cancel(row.h), /invalid or stale handle/);
  } else {
    const row = sorted()[0];
    assert.deepEqual(q.pop(), view(row));
    rows = rows.filter(x => x !== row);
    assert.equal(q.has(row.h), false);
  }
  q.assertValid();
  assert.equal(q.size, rows.length);
  assert.deepEqual(q.peek(), view(sorted()[0]));
  const active = new Set(rows.map(x => x.h));
  for (const h of all) assert.equal(q.has(h), active.has(h));
}
assert.equal(counts.every(n => n > 300), true);
for (const row of sorted()) { assert.deepEqual(q.pop(), view(row)); q.assertValid(); }
assert.equal(q.size, 0);
assert.equal(all.every(h => !q.has(h)), true);
console.log("seed=123456789; operations=2000; differential=PASS");

精确输出:

seed=123456789; operations=2000; differential=PASS

参考排序遵循相同的产品契约,所以差分测试不能证明契约本身满足业务;有限随机测试也不能证明所有输入都正确。它应与前面的特定分支样例、内部不变量和人工推理组合使用。这里没有用测试耗时推断算法复杂度,也没有把伪随机发生器宣传为安全随机源。

09.接到同步分发器:先出队,再调用业务代码

最后把结构接到一个小型同步分发循环。关键顺序是先 pop,再调用业务函数:任务开始执行时,其句柄已经过期,队列结构也已恢复一致。即使业务函数抛错,外层捕获后仍然可以取下一个任务;业务函数在执行过程中插入新任务,也会在下一轮重新参与优先级比较。示例把 B 提前,让它抛错,再由 A 动态插入 C,输出顺序可以直接验证。

cancel 只删除仍在队列里的记录,不会撤回已出队函数产生的副作用,也不能中止正在执行的同步代码。这个循环同样没有时间片和工作量上限:若任务不断添加任务,它可以长时间占用线程。若业务需要异步等待、并发控制或真正的中止信号,应在上层另设协议,不能把一个正确的堆误当成完整运行时调度系统。

保存为 09.mjs,运行 node --unhandled-rejections=strict 09.mjs。

import assert from "node:assert/strict";
class StableHeap {
  #a = []; #pos = new Map(); #next;
  constructor(sequenceStart = 0n) {
    if (typeof sequenceStart !== "bigint" || sequenceStart < 0n)
      throw new TypeError("sequenceStart must be nonnegative bigint");
    this.#next = sequenceStart;
  }
  get size() { return this.#a.length; }
  has(handle) { return this.#pos.has(handle); }
  #priority(p) {
    if (typeof p !== "number" || !Number.isFinite(p))
      throw new TypeError("priority must be finite number");
  }
  #less(x, y) {
    return x.p < y.p || (x.p === y.p && x.seq < y.seq);
  }
  #index(handle) {
    const i = this.#pos.get(handle);
    if (i === undefined) throw new Error("invalid or stale handle");
    return i;
  }
  #swap(i, j) {
    [this.#a[i], this.#a[j]] = [this.#a[j], this.#a[i]];
    this.#pos.set(this.#a[i].h, i);
    this.#pos.set(this.#a[j].h, j);
  }
  #up(i) {
    while (i > 0) {
      const p = Math.floor((i - 1) / 2);
      if (!this.#less(this.#a[i], this.#a[p])) break;
      this.#swap(i, p); i = p;
    }
  }
  #down(i) {
    for (;;) {
      let c = 2 * i + 1;
      if (c >= this.size) return;
      if (c + 1 < this.size && this.#less(this.#a[c + 1], this.#a[c])) c++;
      if (!this.#less(this.#a[c], this.#a[i])) return;
      this.#swap(i, c); i = c;
    }
  }
  #repair(i) {
    if (i > 0 && this.#less(this.#a[i], this.#a[Math.floor((i - 1) / 2)]))
      this.#up(i);
    else this.#down(i);
  }
  #view(n) { return n === undefined ? undefined : { value: n.value, priority: n.p }; }
  push(value, priority) {
    this.#priority(priority);
    const h = Symbol("entry");
    const node = { h, value, p: priority, seq: this.#next++ };
    this.#pos.set(h, this.size); this.#a.push(node);
    this.#up(this.size - 1);
    return h;
  }
  peek() { return this.#view(this.#a[0]); }
  updatePriority(handle, priority) {
    const i = this.#index(handle);
    this.#priority(priority);
    this.#a[i].p = priority; this.#repair(i);
  }
  #remove(i) {
    const removed = this.#a[i], last = this.#a.pop();
    this.#pos.delete(removed.h);
    if (i < this.size) {
      this.#a[i] = last; this.#pos.set(last.h, i); this.#repair(i);
    }
    return this.#view(removed);
  }
  cancel(handle) { return this.#remove(this.#index(handle)); }
  pop() { return this.size === 0 ? undefined : this.#remove(0); }
  assertValid() {
    if (this.size !== this.#pos.size) throw new Error("size mismatch");
    const seen = new Set();
    for (let i = 0; i < this.size; i++) {
      const n = this.#a[i];
      if (this.#pos.get(n.h) !== i) throw new Error("index mismatch");
      if (typeof n.seq !== "bigint" || n.seq < 0n || n.seq >= this.#next || seen.has(n.seq))
        throw new Error("sequence mismatch");
      seen.add(n.seq);
      if (i && this.#less(n, this.#a[Math.floor((i - 1) / 2)]))
        throw new Error("heap order mismatch");
    }
    return true;
  }
}

const q = new StableHeap();
const log = [];
const canceled = q.push(() => log.push("never"), 3);
q.cancel(canceled);
let current;
current = q.push(() => {
  assert.equal(q.has(current), false);
  log.push("A");
  q.push(() => log.push("C"), 0);
}, 2);
const b = q.push(() => { log.push("B"); throw new Error("job failed"); }, 5);
q.updatePriority(b, 1);
while (q.size) {
  const job = q.pop();
  try { job.value(); } catch (error) { log.push("caught:" + error.message); }
  q.assertValid();
}
assert.deepEqual(log, ["B", "caught:job failed", "A", "C"]);
console.log(log.join(" | "));
console.log(`remaining=${q.size}`);

精确输出:

B | caught:job failed | A | C
remaining=0

到这一步,AI 审查的问题已经变得具体:身份会不会随位置变动?删除后索引是否同步?更新是否保留年龄?错误是否发生在状态改变之前?旧句柄何时失效?这些问题都有可执行证据,而不只是对一段代码风格的印象。

复杂度与上线前的审查清单

按数组访问和比较为常数的常用模型,入队、更新、任意删除和弹出最小项都只修复一条树路径,堆调整需要 O(log n) 次比较与交换;观察最小项只看根。索引查询依赖 Map。常见实现中可以按平均常数级查找讨论整体预期性能,但 ECMAScript 对 Map 的规定只要求平均次线性访问,不能宣称语言规范保证每次查找都严格 O(1)。数组扩容、垃圾回收和大整数位数增长也不在简单单位成本模型的保证之内。BigInt 解决序号精度,序号位数会随累计入队次数增长,不能据此承诺无限运行资源。

堆和索引只保留活动节点,按记录数量计占 O(n) 空间;已删除节点不会被内部历史列表保留。外部仍保留的载荷和句柄由外部负责释放。测试中的历史句柄数组专门为了检查过期行为,不属于生产数据结构。若业务持续插入而不消费,任何堆都会增长,是否需要容量限制与背压应在接入层明确决定。

合并 AI 生成代码前,建议逐条确认:比较键没有精度丢失;每次交换更新两端索引;移除区分尾部与补洞;补洞允许双方向修复;更新不刷新序号;过期和跨队列句柄被拒绝;对外不暴露内部节点;空结果和空载荷可区分;随机测试可以复现且检查内部不变量。若修改任一接口约定,应同时调整参考模型和定向断言,而不是只修到某一张截图看起来正确。

核验资料

本文代码和测试为独立编写;以下一手资料用于核对数据结构背景与语言行为,访问日期为 2026 年 10 月 19 日。

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