AI 代码审查实战:把 LRU-2 缓存的第二次访问、冷项淘汰与写入语义写清楚

10-19 5阅读

让 AI 写一个缓存,最容易得到的是一张 Map 加上访问后移动键的代码。把需求换成 LRU-K,模型也可能只是多放一个计数器,然后继续按最近一次访问排序。这样的实现即使容量正确、读写都能返回值,仍然可能选错被淘汰者。审查的起点不是类名里有没有 K,而是同一段访问轨迹能否得到唯一且可解释的结果。

本文固定 K=2,实现一个同步、按条目数限制容量的 JavaScript 缓存。关注点只有两次访问历史如何影响保留资格与淘汰顺序,不加入过期时间、异步加载、权重或固定条目。九段代码均可独立保存成 .mjs 文件,在本次实测的 Node.js v24.19.0 中执行。统一运行方式为 node --unhandled-rejections=strict 文件名.mjs;每段都带断言,输出不是凭手工推演填入。

AI 代码审查实战:把 LRU-2 缓存的第二次访问、冷项淘汰与写入语义写清楚
AI 生成的概念配图:单点与双点象征一条或两条访问记录;环形装置只表达顺序,不代表真实时钟或过期机制。此图不是算法结构图。

先把变体说清楚:第二次访问改变资格,不阻止第一次入驻

LRU-K 的原始论文用向后第 K 次访问距离选择替换对象:已有足够历史时,看当前时刻距离倒数第 K 次引用有多远;历史不足时,该距离视为无穷大。论文还讨论了相关引用及非驻留页面的历史保留。本文只借用基础选择原则,明确采用驻留历史版 LRU-2:键被删除或淘汰后,其历史也消失,重新写入从一次访问开始;不实现原论文的完整数据库缓冲管理方案。参见 O’Neil、O’Neil 与 Weikum 的原始论文,重点是第 2 节定义与第 2.1 节的工程条件。

这里的冷项只有一条有效访问记录,热项有两条。冷项优先淘汰,多个冷项之间淘汰唯一那次访问最早的项;全是热项时,淘汰倒数第二次访问最早的项。所谓热,只是历史长度满足二次引用门槛,不是对未来受欢迎程度的保证,也不是累计命中次数排名。第三次及之后的访问会滑动这两条记录,最早的旧记录立即被丢弃。

本实现始终允许新键在正容量缓存中入驻。满容量时先从原有驻留项中选出受害者,再记录新键的第一次访问。因此,全热缓存也必须为新键让出一个位置。把新键先加入候选集、再因为它是冷项而立刻淘汰自己,会变成另一种准入政策;要求访问两次才存值,同样是另一种接口。二者都不能悄悄代替本文的约定。

示例一:最近刚读过的键,仍然可能被 LRU-2 淘汰

先不要写完整类,只让 AI 回答一个最小反例。A 的两次记录是 1 和 6,B 的记录是 2 和 4。若按最后一次访问排序,B 更旧;若按第二近访问排序,A 更旧。一个实现即使维护了两格数组,只要比较的是数组末尾,仍然只是把普通 LRU 换了包装。这个小实验直接锁住算法与普通 LRU 的差别。

import assert from 'node:assert/strict';

const rows = [
  { key: 'A', history: [1n, 6n] },
  { key: 'B', history: [2n, 4n] }
];
const oldest = index => rows.reduce((a, b) =>
  a.history[index] < b.history[index] ? a : b).key;
assert.equal(oldest(1), 'B');
assert.equal(oldest(0), 'A');
console.log('LRU victim: B; LRU-2 victim: A');

运行输出:

LRU victim: B; LRU-2 victim: A

这个反例不说明哪种策略在你的业务里更好。它只说明两个契约不同,并给审查者一个不依赖随机流量的判别证据。我们不从这条轨迹推出命中率、吞吐量或延迟结论;这些需要另行定义工作负载并实测。

示例二:把无穷大距离转成两层确定的比较规则

当冷项存在时,热项根本不进入这一轮的最终竞争。由于 K 固定为二,冷项恰好有一个时间戳,所以以其唯一记录的先后打破无穷大距离之间的平局即可。热项比较倒数第二条记录;当前时刻对所有候选者相同,时间戳越小,向后距离越大,不需要真的存储 Infinity,也不需要把 BigInt 距离转回 Number。

import assert from 'node:assert/strict';

function before(a, b) {
  if (a.length !== b.length) return a.length < b.length;
  return a[0] < b[0];
}
assert.equal(before([9n], [1n, 8n]), true);
assert.equal(before([3n], [9n]), true);
assert.equal(before([1n, 8n], [2n, 7n]), true);
const now = 10n;
assert.equal(now - 1n > now - 2n, true);
console.log('cold first; oldest first reference or second-last reference');

运行输出:

cold first; oldest first reference or second-last reference

生产类使用历史长度和第一格记录完成比较。这个写法只适用于已经维持一格或两格历史的不变量,不能把空数组塞进来,也不能直接推广到任意 K 的冷项规则。每次有效引用拿到独占的递增序号,因此不同驻留键的比较时间戳不会相同。无需借助键的字典序、Map 枚举顺序或对象字符串化来决定胜负。

示例三:逻辑时钟只计算我们承认的引用

Date.now 的用途是读取墙上时间,本文需要的却是操作顺序。两个调用发生在同一毫秒不应该打平,机器时钟调整也不应该让旧项突然变新。我们从 0n 开始,用 BigInt 给成功记录的访问逐一编号。ECMAScript 的 BigInt 定义不把整数限定在固定比特宽度;这能避免把长序列挤进 Number 的安全整数范围。

先固定事件口径:正容量下的新 set 记录一次,已有键的 set 也记录一次,get 命中记录一次。get 未命中、peek、has、update、delete 和 clear 都不增加序号。容量为零的 set 没有接纳条目,也不产生记录。相同的有效操作序列会产生相同历史,测试不需要等待真实时间流逝。

import assert from 'node:assert/strict';

let clock = 9007199254740991n;
const tick = () => ++clock;
const first = tick();
const second = tick();
assert.equal(second - first, 1n);
assert.notEqual(first, second);
assert.equal(Number(first), Number(second));
const trace = [];
let logical = 0n;
for (const operation of ['set', 'peek', 'miss', 'get', 'update']) {
  if (operation === 'set' || operation === 'get') trace.push(++logical);
}
assert.deepEqual(trace, [1n, 2n]);
console.log(first.toString(), second.toString());
console.log('recorded references:', logical.toString());

运行输出:

9007199254740992 9007199254740993
recorded references: 2

BigInt 不是无限资源承诺。序号位数会随运行时间增长,值本身也可能指向很大的对象,因此本文的有界只表示驻留条目数和每项历史记录数量有界,不表示严格的堆内存字节上限。若系统必须限制总内存,应另外设计价值大小、键大小与计数器寿命策略,不能把一个容量参数当成完整资源预算。

示例四:一次给出完整实现,分开 get、peek、update 和 set

下面的类是后续实验共同审查的实现。每段需要它的实验都包含完整定义,不依赖前面运行留下的变量。get 与 peek 返回带 found 的结果对象,让存储 undefined 与真正未命中可以区分。update 只替换已有值,返回是否成功,不插入新键,也不制造一次访问;set 则明确代表写入并记录引用,即使新旧值相同也照常记录。

缓存的 Map 存的是内部条目对象,所以读取到一个真实条目时它总为真值。代码没有用用户值本身的真假判断是否命中,零、空字符串、false 和 undefined 都可作为值。容量在构造时严格检查为非负安全整数,不进行字符串到数字的隐式转换。容量固定不变,省去缩容时一次淘汰多个条目的额外政策。

import assert from 'node:assert/strict';

class LRU2 {
  #limit;
  #clock = 0n;
  #entries = new Map();
  constructor(limit) {
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError('limit must be a nonnegative safe integer');
    }
    this.#limit = limit === 0 ? 0 : limit;
  }
  get size() { return this.#entries.size; }
  get time() { return this.#clock; }
  #touch(entry) {
    const tick = ++this.#clock;
    entry.history = entry.history.length === 1
      ? [entry.history[0], tick]
      : [entry.history[1], tick];
  }
  #victim() {
    let best;
    for (const pair of this.#entries) {
      const h = pair[1].history;
      if (!best || h.length < best[1].history.length ||
          (h.length === best[1].history.length &&
           h[0] < best[1].history[0])) best = pair;
    }
    return best;
  }
  has(key) { return this.#entries.has(key); }
  peek(key) {
    const e = this.#entries.get(key);
    return e ? { found: true, value: e.value } : { found: false };
  }
  get(key) {
    const e = this.#entries.get(key);
    if (!e) return { found: false };
    this.#touch(e);
    return { found: true, value: e.value };
  }
  update(key, value) {
    const e = this.#entries.get(key);
    if (!e) return false;
    e.value = value;
    return true;
  }
  set(key, value) {
    const e = this.#entries.get(key);
    if (e) {
      e.value = value;
      this.#touch(e);
      return { stored: true, evicted: null };
    }
    if (this.#limit === 0) return { stored: false, evicted: null };
    let evicted = null;
    if (this.#entries.size === this.#limit) {
      const [oldKey, old] = this.#victim();
      evicted = { key: oldKey, value: old.value };
      this.#entries.delete(oldKey);
    }
    this.#entries.set(key, { value, history: [++this.#clock] });
    return { stored: true, evicted };
  }
  delete(key) { return this.#entries.delete(key); }
  clear() { this.#entries.clear(); }
  inspect() {
    return [...this.#entries].map(([key, e]) => ({
      key, value: e.value, history: [...e.history]
    }));
  }
}

const c = new LRU2(2);
assert.deepEqual(c.set('a', undefined), { stored: true, evicted: null });
assert.deepEqual(c.peek('a'), { found: true, value: undefined });
assert.deepEqual(c.peek('missing'), { found: false });
assert.equal(c.update('a', 7), true);
assert.equal(c.update('missing', 9), false);
assert.equal(c.has('a'), true);
assert.deepEqual(c.get('missing'), { found: false });
assert.equal(c.time, 1n);
assert.deepEqual(c.get('a'), { found: true, value: 7 });
assert.deepEqual(c.inspect()[0].history, [1n, 2n]);
c.set('a', 8);
assert.deepEqual(c.inspect()[0].history, [2n, 3n]);
assert.equal(c.size, 1);
console.log('get touches; peek and update do not; set touches');

运行输出:

get touches; peek and update do not; set touches

选择受害者时遍历当前驻留项,以清楚展示政策,而不是把它埋进复杂的索引结构。更新已有键不会通过删除再插入来移动 Map 顺序,因为淘汰比较根本不依赖那个顺序。inspect 按 Map 的入驻顺序返回诊断快照,它不是下一轮淘汰队列,不能把第一项直接当成受害者。

代码没有自定义比较器、回调、加载器或清理钩子,因而这些方法不会主动调用用户提供的函数。这里讨论的是正常可执行环境中的状态语义,不承诺在内存分配失败、宿主终止或内建对象被恶意改写时仍具备事务回滚能力。避免加上实现无法兑现的全局安全口号,也是审查 AI 代码的一部分。

示例五:全部为热项时,检查第二近记录而非最后记录

现在把第一节的差别放进真实 API。三个键完成两次引用后,A 是最后刚访问的那个,但它的倒数第二次记录仍然最旧。写入 D 应淘汰 A,而 B、C 的两条历史不变,D 只获得新的一条。断言同时检查受害者、驻留集合与历史,避免某段实现只是偶然返回了正确的键,却损坏了内部状态。

import assert from 'node:assert/strict';

class LRU2 {
  #limit;
  #clock = 0n;
  #entries = new Map();
  constructor(limit) {
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError('limit must be a nonnegative safe integer');
    }
    this.#limit = limit === 0 ? 0 : limit;
  }
  get size() { return this.#entries.size; }
  get time() { return this.#clock; }
  #touch(entry) {
    const tick = ++this.#clock;
    entry.history = entry.history.length === 1
      ? [entry.history[0], tick]
      : [entry.history[1], tick];
  }
  #victim() {
    let best;
    for (const pair of this.#entries) {
      const h = pair[1].history;
      if (!best || h.length < best[1].history.length ||
          (h.length === best[1].history.length &&
           h[0] < best[1].history[0])) best = pair;
    }
    return best;
  }
  has(key) { return this.#entries.has(key); }
  peek(key) {
    const e = this.#entries.get(key);
    return e ? { found: true, value: e.value } : { found: false };
  }
  get(key) {
    const e = this.#entries.get(key);
    if (!e) return { found: false };
    this.#touch(e);
    return { found: true, value: e.value };
  }
  update(key, value) {
    const e = this.#entries.get(key);
    if (!e) return false;
    e.value = value;
    return true;
  }
  set(key, value) {
    const e = this.#entries.get(key);
    if (e) {
      e.value = value;
      this.#touch(e);
      return { stored: true, evicted: null };
    }
    if (this.#limit === 0) return { stored: false, evicted: null };
    let evicted = null;
    if (this.#entries.size === this.#limit) {
      const [oldKey, old] = this.#victim();
      evicted = { key: oldKey, value: old.value };
      this.#entries.delete(oldKey);
    }
    this.#entries.set(key, { value, history: [++this.#clock] });
    return { stored: true, evicted };
  }
  delete(key) { return this.#entries.delete(key); }
  clear() { this.#entries.clear(); }
  inspect() {
    return [...this.#entries].map(([key, e]) => ({
      key, value: e.value, history: [...e.history]
    }));
  }
}

const c = new LRU2(3);
c.set('A', 1); // 1
c.set('B', 2); // 2
c.set('C', 3); // 3
c.get('B');    // 4: B = [2, 4]
c.get('C');    // 5: C = [3, 5]
c.get('A');    // 6: A = [1, 6]
assert.deepEqual(c.set('D', 4).evicted, { key: 'A', value: 1 });
assert.equal(c.has('A'), false);
assert.deepEqual(c.inspect().map(e => e.history), [
  [2n, 4n], [3n, 5n], [7n]
]);
console.log('all hot: evicted A although A was the latest hit');

运行输出:

all hot: evicted A although A was the latest hit

注意热项没有永久保护。每次命中只把上次最新记录移到第一格,再把新序号写进第二格。旧的引用证据随着后续访问不断被替换,而不是越读越积累一笔永不消失的资历。缓存也不计算两次引用之间的间隔来直接排序:本文比较的是当前时刻距第二近引用的距离。把这两种距离混淆,会在访问轨迹变化时得到不同答案。

示例六:冷项优先、全热接纳,以及重新入驻重置历史

第一次轨迹保留一个热项,并连续写入单次访问的冷项。新的冷项会替换旧的冷项,热项因此继续驻留。第二次轨迹从全热集合开始,明确验证新键仍被接纳。随后重新写回曾被淘汰的 A,它不能继承已经删除的历史;此时它只有一个新序号,仍然是冷项。

import assert from 'node:assert/strict';

class LRU2 {
  #limit;
  #clock = 0n;
  #entries = new Map();
  constructor(limit) {
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError('limit must be a nonnegative safe integer');
    }
    this.#limit = limit === 0 ? 0 : limit;
  }
  get size() { return this.#entries.size; }
  get time() { return this.#clock; }
  #touch(entry) {
    const tick = ++this.#clock;
    entry.history = entry.history.length === 1
      ? [entry.history[0], tick]
      : [entry.history[1], tick];
  }
  #victim() {
    let best;
    for (const pair of this.#entries) {
      const h = pair[1].history;
      if (!best || h.length < best[1].history.length ||
          (h.length === best[1].history.length &&
           h[0] < best[1].history[0])) best = pair;
    }
    return best;
  }
  has(key) { return this.#entries.has(key); }
  peek(key) {
    const e = this.#entries.get(key);
    return e ? { found: true, value: e.value } : { found: false };
  }
  get(key) {
    const e = this.#entries.get(key);
    if (!e) return { found: false };
    this.#touch(e);
    return { found: true, value: e.value };
  }
  update(key, value) {
    const e = this.#entries.get(key);
    if (!e) return false;
    e.value = value;
    return true;
  }
  set(key, value) {
    const e = this.#entries.get(key);
    if (e) {
      e.value = value;
      this.#touch(e);
      return { stored: true, evicted: null };
    }
    if (this.#limit === 0) return { stored: false, evicted: null };
    let evicted = null;
    if (this.#entries.size === this.#limit) {
      const [oldKey, old] = this.#victim();
      evicted = { key: oldKey, value: old.value };
      this.#entries.delete(oldKey);
    }
    this.#entries.set(key, { value, history: [++this.#clock] });
    return { stored: true, evicted };
  }
  delete(key) { return this.#entries.delete(key); }
  clear() { this.#entries.clear(); }
  inspect() {
    return [...this.#entries].map(([key, e]) => ({
      key, value: e.value, history: [...e.history]
    }));
  }
}

const c = new LRU2(2);
c.set('hot', 1);
c.get('hot');
c.set('cold', 2);
assert.equal(c.set('new', 3).evicted.key, 'cold');
assert.equal(c.has('hot'), true);
assert.equal(c.set('next', 4).evicted.key, 'new');
const d = new LRU2(2);
d.set('A', 1); d.get('A');
d.set('B', 2); d.get('B');
assert.equal(d.set('C', 3).evicted.key, 'A');
assert.equal(d.has('C'), true);
assert.equal(d.set('A', 10).evicted.key, 'C');
assert.deepEqual(d.inspect().find(e => e.key === 'A').history, [6n]);
console.log('cold entries go first; new entries enter; re-entry is cold');

运行输出:

cold entries go first; new entries enter; re-entry is cold

驻留历史的取舍必须写进文档。若一个键总是在第二次访问前被淘汰,本实现永远看不到它在不同驻留周期之间的重复出现。要识别这种模式,需要额外的非驻留历史表,并单独定义那张表的容量、保留时间或淘汰规则。本文不暗藏一张无限增长的影子表,也不声称它具有原论文完整历史管理的行为。

这里也解释了为什么不采用先插入后裁剪。只把容量最终恢复到上限,不能证明准入过程正确。新键是否参与当次候选、冷项能否立即拒绝自己、受害者返回值对应哪个时刻,都是可观察行为,应该由接口契约决定,再由代码实现。

示例七:内部历史归缓存所有,键和值仍共享引用

一个常见的 AI 修复建议是对所有内容做深拷贝,但那会改变对象键的身份,还会带来新的可克隆类型限制。本文保留 Map 的键语义:对象按身份,NaN 可与 NaN 匹配,正负零视为同一键。对应依据是 ECMAScript 的 Map 与 SameValueZero 约定。不对键做字符串拼接或 JSON 序列化,也不读取对象内部的 id 属性作为替代身份。

缓存拥有内部条目与历史数组。inspect 会复制结果数组、条目外壳和历史数组,调用者修改这些结构不会伪造访问记录。与此同时,键对象和值对象仍是原来的引用;通过 peek、get、inspect 或淘汰结果拿到对象后,修改对象内容会被其他持有者看到。这是有意的浅层边界,不能描述成不可变快照。

import assert from 'node:assert/strict';

class LRU2 {
  #limit;
  #clock = 0n;
  #entries = new Map();
  constructor(limit) {
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError('limit must be a nonnegative safe integer');
    }
    this.#limit = limit === 0 ? 0 : limit;
  }
  get size() { return this.#entries.size; }
  get time() { return this.#clock; }
  #touch(entry) {
    const tick = ++this.#clock;
    entry.history = entry.history.length === 1
      ? [entry.history[0], tick]
      : [entry.history[1], tick];
  }
  #victim() {
    let best;
    for (const pair of this.#entries) {
      const h = pair[1].history;
      if (!best || h.length < best[1].history.length ||
          (h.length === best[1].history.length &&
           h[0] < best[1].history[0])) best = pair;
    }
    return best;
  }
  has(key) { return this.#entries.has(key); }
  peek(key) {
    const e = this.#entries.get(key);
    return e ? { found: true, value: e.value } : { found: false };
  }
  get(key) {
    const e = this.#entries.get(key);
    if (!e) return { found: false };
    this.#touch(e);
    return { found: true, value: e.value };
  }
  update(key, value) {
    const e = this.#entries.get(key);
    if (!e) return false;
    e.value = value;
    return true;
  }
  set(key, value) {
    const e = this.#entries.get(key);
    if (e) {
      e.value = value;
      this.#touch(e);
      return { stored: true, evicted: null };
    }
    if (this.#limit === 0) return { stored: false, evicted: null };
    let evicted = null;
    if (this.#entries.size === this.#limit) {
      const [oldKey, old] = this.#victim();
      evicted = { key: oldKey, value: old.value };
      this.#entries.delete(oldKey);
    }
    this.#entries.set(key, { value, history: [++this.#clock] });
    return { stored: true, evicted };
  }
  delete(key) { return this.#entries.delete(key); }
  clear() { this.#entries.clear(); }
  inspect() {
    return [...this.#entries].map(([key, e]) => ({
      key, value: e.value, history: [...e.history]
    }));
  }
}

const c = new LRU2(6);
const key = { id: 1 };
const value = { count: 1 };
c.set(key, value);
const snapshot = c.inspect();
snapshot[0].history[0] = 999n;
snapshot[0].key = 'different';
snapshot.pop();
assert.deepEqual(c.inspect()[0].history, [1n]);
value.count = 2;
assert.equal(c.peek(key).value.count, 2);
assert.equal(c.has({ id: 1 }), false);
c.peek(key).value.count = 3;
assert.equal(value.count, 3);
c.set(NaN, 'nan');
assert.equal(c.peek(Number('not a number')).value, 'nan');
c.set(-0, 'zero');
assert.equal(c.peek(+0).value, 'zero');
c.set(undefined, undefined);
assert.equal(c.has(undefined), true);
const only = new LRU2(1);
only.set(undefined, value);
assert.deepEqual(only.set('next', 0).evicted, { key: undefined, value });
assert.equal(value.count, 3);
console.log('history is copied; keys and values retain their references');

运行输出:

history is copied; keys and values retain their references

受害者用对象包装返回,未淘汰时用 null 表示,所以 undefined 作为合法键不会与未选择受害者混淆。删除只是让缓存放弃相应引用,不会主动关闭值中的文件句柄、销毁资源或冻结对象。需要资源释放的业务应在外层建立明确的所有权和清理机制;不能因为缓存容量有界就推断所有外部资源都自动释放。

示例八:零容量、删除与清空也是算法契约

边界检查常被推迟到实现完成以后,实际上它们会决定历史的生命期。零容量缓存永不接纳,且不增加时钟;删除已有键返回 true,重复删除返回 false;clear 移除全部驻留历史,但保留时钟。保留时钟意味着诊断时能看到同一实例中前后操作的顺序,而不是在每次清空后重复使用旧序号。

import assert from 'node:assert/strict';

class LRU2 {
  #limit;
  #clock = 0n;
  #entries = new Map();
  constructor(limit) {
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError('limit must be a nonnegative safe integer');
    }
    this.#limit = limit === 0 ? 0 : limit;
  }
  get size() { return this.#entries.size; }
  get time() { return this.#clock; }
  #touch(entry) {
    const tick = ++this.#clock;
    entry.history = entry.history.length === 1
      ? [entry.history[0], tick]
      : [entry.history[1], tick];
  }
  #victim() {
    let best;
    for (const pair of this.#entries) {
      const h = pair[1].history;
      if (!best || h.length < best[1].history.length ||
          (h.length === best[1].history.length &&
           h[0] < best[1].history[0])) best = pair;
    }
    return best;
  }
  has(key) { return this.#entries.has(key); }
  peek(key) {
    const e = this.#entries.get(key);
    return e ? { found: true, value: e.value } : { found: false };
  }
  get(key) {
    const e = this.#entries.get(key);
    if (!e) return { found: false };
    this.#touch(e);
    return { found: true, value: e.value };
  }
  update(key, value) {
    const e = this.#entries.get(key);
    if (!e) return false;
    e.value = value;
    return true;
  }
  set(key, value) {
    const e = this.#entries.get(key);
    if (e) {
      e.value = value;
      this.#touch(e);
      return { stored: true, evicted: null };
    }
    if (this.#limit === 0) return { stored: false, evicted: null };
    let evicted = null;
    if (this.#entries.size === this.#limit) {
      const [oldKey, old] = this.#victim();
      evicted = { key: oldKey, value: old.value };
      this.#entries.delete(oldKey);
    }
    this.#entries.set(key, { value, history: [++this.#clock] });
    return { stored: true, evicted };
  }
  delete(key) { return this.#entries.delete(key); }
  clear() { this.#entries.clear(); }
  inspect() {
    return [...this.#entries].map(([key, e]) => ({
      key, value: e.value, history: [...e.history]
    }));
  }
}

for (const bad of [-1, 1.5, NaN, Infinity, '2', 2n, null, undefined,
                   Number.MAX_SAFE_INTEGER + 1]) {
  assert.throws(() => new LRU2(bad), RangeError);
}
const zero = new LRU2(-0);
assert.deepEqual(zero.set('x', 1), { stored: false, evicted: null });
assert.equal(zero.time, 0n);
assert.equal(zero.size, 0);
const c = new LRU2(1);
c.set('x', 1); c.get('x');
assert.equal(c.delete('x'), true);
assert.equal(c.delete('x'), false);
c.set('x', 2);
assert.deepEqual(c.inspect()[0].history, [3n]);
c.clear();
assert.equal(c.size, 0);
assert.equal(c.time, 3n);
c.set('y', 3);
assert.deepEqual(c.inspect()[0].history, [4n]);
console.log('zero capacity, validation, delete and clear: PASS');

运行输出:

zero capacity, validation, delete and clear: PASS

非法容量统一抛出 RangeError,既拒绝负值、小数与非有限数,也拒绝数字字符串、BigInt、空值和省略参数。这里并不是讨论所有 API 都应该采取这个错误分类,而是要把当前类的行为固定下来。负零按零处理,容量字段不对外暴露可写入口,避免调用者绕过校验修改限制。

删除或清空之后再 set 是全新的驻留周期。这条规则应与淘汰后的重新入驻一致,否则同一个键会因为离开的路径不同而获得不同的历史待遇。测试应同时覆盖这三种离开方式,尤其不要只验证清空后的 size 等于零。

示例九:用完整事件日志模型做差分,而不是复制一份同样的算法

只拿另一份两格数组代码与生产类互相比较,容易让同一个下标错误在两边共同存在。最后的参考模型保存完整引用日志,为每个驻留周期分配独立身份。需要历史时重新从日志提取,热项明确计算当前时刻到倒数第二次记录的距离,然后按距离选择受害者。它与生产类的存储方式和比较写法不同,适合充当小规模测试的可读判定器。

随机序列使用固定种子,覆盖容量零到五,每个容量三十二条轨迹,每条四百步,共七万六千八百次操作。操作混合 set、get、peek、has、update、delete 和 clear,键包含普通字符串、特殊数值、对象与 Symbol。每一步都比较返回值、完整可观察快照和逻辑时钟,同时检查容量与历史单调性。失败后可以用相同种子重放,不需要碰运气复现。

import assert from 'node:assert/strict';

class LRU2 {
  #limit;
  #clock = 0n;
  #entries = new Map();
  constructor(limit) {
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError('limit must be a nonnegative safe integer');
    }
    this.#limit = limit === 0 ? 0 : limit;
  }
  get size() { return this.#entries.size; }
  get time() { return this.#clock; }
  #touch(entry) {
    const tick = ++this.#clock;
    entry.history = entry.history.length === 1
      ? [entry.history[0], tick]
      : [entry.history[1], tick];
  }
  #victim() {
    let best;
    for (const pair of this.#entries) {
      const h = pair[1].history;
      if (!best || h.length < best[1].history.length ||
          (h.length === best[1].history.length &&
           h[0] < best[1].history[0])) best = pair;
    }
    return best;
  }
  has(key) { return this.#entries.has(key); }
  peek(key) {
    const e = this.#entries.get(key);
    return e ? { found: true, value: e.value } : { found: false };
  }
  get(key) {
    const e = this.#entries.get(key);
    if (!e) return { found: false };
    this.#touch(e);
    return { found: true, value: e.value };
  }
  update(key, value) {
    const e = this.#entries.get(key);
    if (!e) return false;
    e.value = value;
    return true;
  }
  set(key, value) {
    const e = this.#entries.get(key);
    if (e) {
      e.value = value;
      this.#touch(e);
      return { stored: true, evicted: null };
    }
    if (this.#limit === 0) return { stored: false, evicted: null };
    let evicted = null;
    if (this.#entries.size === this.#limit) {
      const [oldKey, old] = this.#victim();
      evicted = { key: oldKey, value: old.value };
      this.#entries.delete(oldKey);
    }
    this.#entries.set(key, { value, history: [++this.#clock] });
    return { stored: true, evicted };
  }
  delete(key) { return this.#entries.delete(key); }
  clear() { this.#entries.clear(); }
  inspect() {
    return [...this.#entries].map(([key, e]) => ({
      key, value: e.value, history: [...e.history]
    }));
  }
}

// Independent model: keep full reference logs, not a two-slot history.
class Reference {
  constructor(limit) { this.limit = limit; this.rows = []; this.log = []; this.time = 0n; this.id = 0; }
  equal(a, b) { return a === b || (Number.isNaN(a) && Number.isNaN(b)); }
  find(key) { return this.rows.find(r => this.equal(r.key, key)); }
  history(r) { return this.log.filter(x => x.id === r.id).map(x => x.at); }
  touch(r) { this.log.push({ id: r.id, at: ++this.time }); }
  apply(op, key, value) {
    const r = this.find(key);
    if (op === 'peek' || op === 'get') {
      if (!r) return { found: false };
      if (op === 'get') this.touch(r);
      return { found: true, value: r.value };
    }
    if (op === 'has') return !!r;
    if (op === 'update') { if (!r) return false; r.value = value; return true; }
    if (op === 'delete') { if (!r) return false; this.rows = this.rows.filter(x => x !== r); return true; }
    if (op === 'clear') { this.rows = []; return; }
    if (r) { r.value = value; this.touch(r); return { stored: true, evicted: null }; }
    if (!this.limit) return { stored: false, evicted: null };
    let evicted = null;
    if (this.rows.length === this.limit) {
      const cold = this.rows.filter(x => this.history(x).length < 2);
      const candidates = cold.length ? cold : this.rows;
      const age = x => {
        const h = this.history(x);
        return this.time - h[cold.length ? 0 : h.length - 2];
      };
      const victim = [...candidates].sort((a, b) => age(a) > age(b) ? -1 : 1)[0];
      evicted = { key: victim.key, value: victim.value };
      this.rows = this.rows.filter(x => x !== victim);
    }
    const fresh = { key: key === 0 ? 0 : key, value, id: ++this.id };
    this.rows.push(fresh); this.touch(fresh);
    return { stored: true, evicted };
  }
  inspect() {
    return this.rows.map(r => ({ key: r.key, value: r.value, history: this.history(r).slice(-2) }));
  }
}
const keys = [undefined, null, NaN, -0, 0, 'A', 'B', 'C', {}, Symbol('s')];
const operations = ['set', 'set', 'get', 'peek', 'has', 'update', 'delete', 'clear'];
let checks = 0;
for (let capacity = 0; capacity <= 5; capacity++) {
  for (let seed = 1; seed <= 32; seed++) {
    const c = new LRU2(capacity), ref = new Reference(capacity);
    let state = seed;
    const random = () => (state = (Math.imul(state, 1664525) + 1013904223) >>> 0);
    for (let i = 0; i < 400; i++) {
      const op = operations[(random() >>> 16) % operations.length];
      const key = keys[(random() >>> 16) % keys.length];
      const value = i % 7 ? i : undefined;
      assert.deepEqual(c[op](key, value), ref.apply(op, key, value));
      assert.deepEqual(c.inspect(), ref.inspect());
      assert.equal(c.time, ref.time);
      assert.ok(c.size <= capacity);
      for (const e of c.inspect()) {
        assert.ok(e.history.length === 1 || e.history.length === 2);
        assert.ok(e.history.every(t => t > 0n && t <= c.time));
        if (e.history.length === 2) assert.ok(e.history[0] < e.history[1]);
      }
      checks++;
    }
  }
}
console.log('differential operations:', checks);

运行输出:

differential operations: 76800

参考模型故意保留整个测试过程的日志,它不属于生产缓存,也不承诺生产级空间边界。代码中的 clear 只清空模型驻留项,新的驻留身份让旧事件不会被错误复用。这个设计恰好能检验生产类是否偷偷保留了被删键的历史。固定种子测试不是对无限输入空间的证明,因此前八个针对性反例仍不可省略。

审查结束时,最有价值的交付物不是一句算法已实现,而是一组可以问出唯一答案的问题:哪些操作产生引用,冷项之间如何排序,全热时谁让位,新项能否自我拒绝,清空是否重置时钟,值是否共享引用,非驻留历史是否保留。让 AI 先填写这些答案,再用可重放测试逐项核对,比只要求它优化代码更容易暴露真正的语义偏差。

核对依据与适用范围

算法出处为上述 SIGMOD 原论文;语言行为依据为 ECMAScript 的 Map 与 BigInt 条款。断言使用 Node.js 官方 assert 文档中的严格断言接口。九个示例均在实际 Node.js v24.19.0 进程中通过,不把文档中的其他版本输出当成这里的实测结果。

本文交付的是固定 K=2、固定条目容量、驻留期内历史、共享键值引用的同步实现。它没有时间到期逻辑、后台任务或请求合并,也不把冷与热解释成业务价值等级。若这些条件变化,应重新审查准入与淘汰规则,而不是在当前类里零散加入字段后继续沿用旧测试结论。

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