审查 AI 写的 LRU 缓存:用九组 Node.js 测试核对 Map 的顺序与边界

10-19 5阅读

让 AI 写一个基于 Map 的 LRU 缓存,通常很快就能得到一个像样的类:读取时返回值,写入时检查容量,满了就删掉第一个键。真正容易漏掉的部分却不是语法,而是“最近使用”到底由哪些操作更新,以及测试有没有把这些区别看见。一个只验证取值结果的测试集,可能让实际上按写入顺序淘汰的实现顺利过关。

本文把 AI 生成的实现视为待验收候选,给出一份可执行的审查合同,再用九个独立脚本检查它。下面的类是按合同整理的参考实现;文中的错误模式是审查时应主动构造的反例,不代表对某个模型、某次生成结果或线上事故的统计结论。重点不是让 AI 再说一遍“已经处理边界”,而是要求它交出足以推翻自己答案的证据。

审查 AI 写的 LRU 缓存:用九组 Node.js 测试核对 Map 的顺序与边界
AI 生成的概念配图,表现有限容量、访问次序与审查过程;不是实现结构图。

先写合同:什么算使用,什么只算观察

本文约定顺序始终从最久未使用到最近使用。get 命中会把对应条目移到末尾;get 未命中返回 undefined,且不改变顺序。has 只报告键是否存在,peek 只读取值,二者都不刷新使用次序。set 无论插入还是替换,都把键放到最新位置;只有完成这次写入后超过容量,才淘汰最旧条目。这是本文选择的 API 合同,并不是所有名为 LRU 的库必须采用的接口约定。

容量表示条目数,必须显式传入非负安全整数。零容量合法,含义是关闭存储;负零也按零处理。非数字抛 TypeError,不合法的数字抛 RangeError。不接受字符串数字、自动截断或把无限大当成默认值。容量在构造后不开放修改。keys 和 entries 返回最旧到最新的数组快照;delete 返回是否删除成功,clear 清空并返回 undefined,set 返回当前实例以支持链式调用。

使用 Map 有一个必须补上的语义差异:原生 set 替换已有键时只更新值,不把位置移到末尾;原生 get 也不会维护 LRU 次序。因此参考实现用删除后重插来表达“触碰”。相关行为可直接核对 ECMAScript 的 Map.prototype.set 算法。不要把底层容器的插入顺序,直接当成业务已经得到的访问顺序。

下面恰好九段 JavaScript,每段包含完整相同的类、断言和确定的输出,分别存成对应的 .mjs 文件即可独立执行,不需要先运行上一段,也不依赖第三方包。每段标题下给出运行命令;本文实测环境是 Node.js v24.19.0。显式启用 --unhandled-rejections=strict,让未处理的 Promise 拒绝按未捕获异常处理,选项含义见 Node.js 命令行文档。本组没有故意制造未处理拒绝,更没有用这个选项来冒充并发正确性测试。

审查顺序也有讲究:先确定单个操作,再检查组合轨迹,最后使用独立数据结构交叉对照。调试输出统一比较数组,而不是只比较两个 Map;Node.js assert 文档说明,Map 的键在深比较中按无序方式处理。LRU 恰恰依赖次序,选错断言对象会让测试遗漏最核心的错误。

测试一:命中必须改变下一次淘汰对象

第一个反例要尽量短。依次放入 a、b、c,读取 a 后再放入 d,应该淘汰 b。如果最终删掉了 a,就说明所谓的 LRU 仍然停留在原来的插入顺序。这里不仅断言 get 返回 1,还立刻检查 b、c、a 的中间状态;这样可以在错误发生的第一步定位问题,而不是只在最后看到某个值丢失。

未命中的读取也必须检查。某些候选实现会无条件删除并写回取出的值,导致一个不存在的键被补成 undefined,甚至挤走真正缓存的数据。参考实现先用 has 判断存在性,命中后才执行删除与重插。测试故意把未命中放在有效读取之后,以证明空读没有把刚建立的次序再次打乱。

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

import assert from "node:assert/strict";

class LRUCache {
  #limit;
  #map = new Map();
  constructor(limit) {
    if (typeof limit !== "number") throw new TypeError("number required");
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError("nonnegative safe integer required");
    }
    this.#limit = limit;
  }
  get size() { return this.#map.size; }
  has(key) { return this.#map.has(key); }
  peek(key) { return this.#map.get(key); }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    if (this.#limit === 0) return this;
    this.#map.set(key, value);
    if (this.#map.size > this.#limit) {
      this.#map.delete(this.#map.keys().next().value);
    }
    return this;
  }
  delete(key) { return this.#map.delete(key); }
  clear() { this.#map.clear(); }
  keys() { return [...this.#map.keys()]; }
  entries() { return [...this.#map.entries()]; }
}

const c = new LRUCache(3);
c.set("a", 1).set("b", 2).set("c", 3);
assert.equal(c.get("a"), 1);
assert.deepEqual(c.keys(), ["b", "c", "a"]);
assert.equal(c.get("missing"), undefined);
assert.deepEqual(c.keys(), ["b", "c", "a"]);
c.set("d", 4);
assert.deepEqual(c.entries(), [["c", 3], ["a", 1], ["d", 4]]);
assert.equal(c.has("b"), false);
console.log("01 OK: get touches only on hit");

实际输出:

01 OK: get touches only on hit

测试二:观察接口不该偷偷改变热度

监控代码可能频繁调用 has 查看数据是否缓存,调试面板也可能通过 peek 展示内容。如果这两个方法通过调用 get 偷懒实现,观察者就会改变被观察对象的淘汰行为。同一份业务代码,打开诊断面板后命中率可能变得不一样,问题也更难复现。

因此这一段让 a 连续被 has 与 peek 观察,然后插入 c。a 仍然应该是最旧条目并被淘汰。这里没有规定所有项目都必须采用不触碰的 has,而是把团队已经选定的语义变成测试。若业务想让某类存在性检查刷新热度,最好另起明确的方法或显式调用 get,避免一个看似无害的查询产生隐藏写入。

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

import assert from "node:assert/strict";

class LRUCache {
  #limit;
  #map = new Map();
  constructor(limit) {
    if (typeof limit !== "number") throw new TypeError("number required");
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError("nonnegative safe integer required");
    }
    this.#limit = limit;
  }
  get size() { return this.#map.size; }
  has(key) { return this.#map.has(key); }
  peek(key) { return this.#map.get(key); }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    if (this.#limit === 0) return this;
    this.#map.set(key, value);
    if (this.#map.size > this.#limit) {
      this.#map.delete(this.#map.keys().next().value);
    }
    return this;
  }
  delete(key) { return this.#map.delete(key); }
  clear() { this.#map.clear(); }
  keys() { return [...this.#map.keys()]; }
  entries() { return [...this.#map.entries()]; }
}

const c = new LRUCache(2);
c.set("a", 1).set("b", 2);
assert.equal(c.has("a"), true);
assert.equal(c.peek("a"), 1);
assert.equal(c.has("missing"), false);
assert.equal(c.peek("missing"), undefined);
assert.deepEqual(c.keys(), ["a", "b"]);
c.set("c", 3);
assert.equal(c.has("a"), false);
assert.deepEqual(c.entries(), [["b", 2], ["c", 3]]);
console.log("02 OK: has and peek never touch");

实际输出:

02 OK: has and peek never touch

测试三:undefined 是合法值,不是缺席证明

Map 既允许保存 undefined,也用 undefined 表示 get 未命中。因此单看返回值无法区分两种情况。Map.prototype.get 的规范把未找到时的返回值写得很清楚;应用层需要存在性时,应使用 has,而不能靠真值判断,也不能随意规定 undefined 不可缓存。

这个测试先保存 undefined,再读取它并验证顺序确实更新,随后用一次淘汰检验它仍被视为有效条目。额外遍历 false、零、空字符串、null 和 NaN,是为了排除 if (value) 这一类常见捷径。Object.is 用于检查取回的值,其中 NaN 不能靠普通相等判断。存在性和取值必须是两项独立断言,任何一项都不能替代另一项。

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

import assert from "node:assert/strict";

class LRUCache {
  #limit;
  #map = new Map();
  constructor(limit) {
    if (typeof limit !== "number") throw new TypeError("number required");
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError("nonnegative safe integer required");
    }
    this.#limit = limit;
  }
  get size() { return this.#map.size; }
  has(key) { return this.#map.has(key); }
  peek(key) { return this.#map.get(key); }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    if (this.#limit === 0) return this;
    this.#map.set(key, value);
    if (this.#map.size > this.#limit) {
      this.#map.delete(this.#map.keys().next().value);
    }
    return this;
  }
  delete(key) { return this.#map.delete(key); }
  clear() { this.#map.clear(); }
  keys() { return [...this.#map.keys()]; }
  entries() { return [...this.#map.entries()]; }
}

const c = new LRUCache(2);
c.set("u", undefined).set("b", 2);
assert.equal(c.has("u"), true);
assert.equal(c.peek("u"), undefined);
assert.equal(c.get("u"), undefined);
assert.deepEqual(c.keys(), ["b", "u"]);
c.set("x", 3);
assert.equal(c.has("u"), true);
assert.equal(c.has("b"), false);
assert.equal(c.has("missing"), false);
for (const value of [false, 0, "", null, NaN]) {
  const d = new LRUCache(2);
  d.set("v", value).set("other", 1);
  assert.ok(Object.is(d.get("v"), value));
  assert.deepEqual(d.keys(), ["other", "v"]);
}
console.log("03 OK: presence is independent of value");

实际输出:

03 OK: presence is independent of value

测试四:替换不是新增,零容量也要有定义

容量已满时,先看到 size 达到上限就立刻淘汰,再判断这次是否替换,会多删一个无辜条目。正确的顺序是移除同键旧记录、写入新值、最后判断是否超限。因为容量固定、每次只写入一个条目,并且操作前不超过上限,这里最多需要淘汰一个;这个结论不自动适用于未来的批量写入或缩容接口。

替换也算一次使用,所以 b 的值变成 20 时必须移动到末尾。测试同时覆盖容量一的连续替换与新键插入,避免只在较大容量下看起来正常。零容量直接不保存,set 仍返回实例;这让调用方可以通过配置关掉缓存,而不用分叉所有业务调用。零容量的含义需要在文档中写清楚,不能让 AI 自行猜成无限容量。

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

import assert from "node:assert/strict";

class LRUCache {
  #limit;
  #map = new Map();
  constructor(limit) {
    if (typeof limit !== "number") throw new TypeError("number required");
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError("nonnegative safe integer required");
    }
    this.#limit = limit;
  }
  get size() { return this.#map.size; }
  has(key) { return this.#map.has(key); }
  peek(key) { return this.#map.get(key); }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    if (this.#limit === 0) return this;
    this.#map.set(key, value);
    if (this.#map.size > this.#limit) {
      this.#map.delete(this.#map.keys().next().value);
    }
    return this;
  }
  delete(key) { return this.#map.delete(key); }
  clear() { this.#map.clear(); }
  keys() { return [...this.#map.keys()]; }
  entries() { return [...this.#map.entries()]; }
}

const c = new LRUCache(3);
c.set("a", 1).set("b", 2).set("c", 3);
assert.equal(c.set("b", 20), c);
assert.equal(c.size, 3);
assert.deepEqual(c.entries(), [["a", 1], ["c", 3], ["b", 20]]);
c.set("d", 4);
assert.deepEqual(c.keys(), ["c", "b", "d"]);
const one = new LRUCache(1);
one.set("a", 1).set("a", 2);
assert.deepEqual(one.entries(), [["a", 2]]);
one.set("b", 3);
assert.deepEqual(one.entries(), [["b", 3]]);
const zero = new LRUCache(0);
assert.equal(zero.set("a", 1).set(undefined, undefined), zero);
assert.equal(zero.size, 0);
assert.deepEqual(zero.keys(), []);
console.log("04 OK: replacement, capacity one and zero");

实际输出:

04 OK: replacement, capacity one and zero

测试五:把非法容量挡在对象创建时

容量属于不变量的入口。只检查小于零会漏掉 NaN;只检查有限值会放过小数;隐式数字转换则会让字符串、布尔值、空数组参与配置。对于一个想长期维护的小工具,显式失败通常比悄悄修正更容易排查。测试区分参数类型错误和数字范围错误,也把未传参数列入了拒绝清单。

非负安全整数是本文的可解释取值范围,ECMAScript 的 Number.isSafeInteger 算法给出了类型、整数性和安全范围的检查方式。接受 MAX_SAFE_INTEGER 只表示参数校验通过,绝不等于承诺现实机器装得下这么多条目;测试仅插入一个值,没有进行巨量分配。系统仍应根据真实内存预算给出更小的业务上限。

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

import assert from "node:assert/strict";

class LRUCache {
  #limit;
  #map = new Map();
  constructor(limit) {
    if (typeof limit !== "number") throw new TypeError("number required");
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError("nonnegative safe integer required");
    }
    this.#limit = limit;
  }
  get size() { return this.#map.size; }
  has(key) { return this.#map.has(key); }
  peek(key) { return this.#map.get(key); }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    if (this.#limit === 0) return this;
    this.#map.set(key, value);
    if (this.#map.size > this.#limit) {
      this.#map.delete(this.#map.keys().next().value);
    }
    return this;
  }
  delete(key) { return this.#map.delete(key); }
  clear() { this.#map.clear(); }
  keys() { return [...this.#map.keys()]; }
  entries() { return [...this.#map.entries()]; }
}

for (const limit of [undefined, null, "2", true, 2n, {}, [], Symbol("n")]) {
  assert.throws(() => new LRUCache(limit), TypeError);
}
for (const limit of [-1, 0.5, NaN, Infinity, -Infinity, 2 ** 53]) {
  assert.throws(() => new LRUCache(limit), RangeError);
}
for (const limit of [0, -0, 1, 2, Number.MAX_SAFE_INTEGER]) {
  const c = new LRUCache(limit);
  assert.equal(c.size, 0);
  c.set("a", 1);
  assert.equal(c.size, limit === 0 ? 0 : 1);
}
console.log("05 OK: explicit capacity validation");

实际输出:

05 OK: explicit capacity validation

测试六:键相等规则必须和 Map 一致

本文的键合同采用 SameValueZero 语义:NaN 与自身匹配,正零和负零表示同一个键,数字 1 与字符串 1 区分。对象键按引用身份区分,而不是按字段内容判断;两个内容相同的对象仍是两个键,同描述的两个 Symbol 也不同。可对照 ECMAScript 的 SameValueZero 定义。这里完全委托 Map 管理键,不先序列化,也不先拼接成字符串。

这个约定关系到缓存是否会串数据。JSON 字符串化不是通用的键规范化方案,它还会引入循环引用、字段序列化顺序和不可序列化值等另一组问题。如果业务需要结构相等,应单独设计稳定的业务键,并把碰撞责任写在接口边界,而不是藏在缓存内部。

最后特意把 undefined 当键淘汰一次。拿到 keys().next().value 后,用“值是否为 undefined”判断迭代器是否为空,会误伤这个合法键。参考实现只在 size 已大于合法容量时取最旧键,此时容器必非空,所以无需那个错误的哨兵判断。

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

import assert from "node:assert/strict";

class LRUCache {
  #limit;
  #map = new Map();
  constructor(limit) {
    if (typeof limit !== "number") throw new TypeError("number required");
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError("nonnegative safe integer required");
    }
    this.#limit = limit;
  }
  get size() { return this.#map.size; }
  has(key) { return this.#map.has(key); }
  peek(key) { return this.#map.get(key); }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    if (this.#limit === 0) return this;
    this.#map.set(key, value);
    if (this.#map.size > this.#limit) {
      this.#map.delete(this.#map.keys().next().value);
    }
    return this;
  }
  delete(key) { return this.#map.delete(key); }
  clear() { this.#map.clear(); }
  keys() { return [...this.#map.keys()]; }
  entries() { return [...this.#map.entries()]; }
}

const c = new LRUCache(12);
c.set(NaN, "first").set(Number("bad"), "second");
assert.equal(c.size, 1);
assert.equal(c.get(NaN), "second");
c.set(-0, "minus").set(+0, "plus");
assert.equal(c.size, 2);
assert.equal(c.get(-0), "plus");
const a = { id: 1 };
const b = { id: 1 };
const s1 = Symbol("id");
const s2 = Symbol("id");
c.set(a, "A").set(b, "B").set(s1, "S1").set(s2, "S2");
c.set(1, "number").set("1", "string");
assert.equal(c.size, 8);
assert.equal(c.get(a), "A");
assert.equal(c.get(b), "B");
assert.equal(c.has({ id: 1 }), false);
assert.equal(c.get(s1), "S1");
assert.equal(c.get(s2), "S2");
assert.equal(c.get(1), "number");
assert.equal(c.get("1"), "string");
const d = new LRUCache(1);
d.set(undefined, "old").set("new", 2);
assert.equal(d.has(undefined), false);
assert.deepEqual(d.keys(), ["new"]);
console.log("06 OK: SameValueZero and identity keys");

实际输出:

06 OK: SameValueZero and identity keys

测试七:用完整轨迹检查淘汰,不只看最终容量

一个实现始终满足 size 不超过容量,仍然可能每次都删错对象。轨迹测试把插入、读取、观察、替换、删除和清空连起来,并在每一步保留预期顺序。对审查者来说,这串变化就是可读的状态机:哪个动作改变次序,哪个动作保留次序,应该一眼能对得上。

删除不存在的键不能改变任何状态,删除存在的键不能扰动剩余项的相对顺序。clear 后再次插入应得到干净的新状态。这里不使用 wall-clock 时间来判断谁更“最近”,因为同一进程内的顺序合同已经足够;引入时间戳反而会增加同毫秒并列和时钟来源之类无关问题。若后续扩展了回调或异步装载,必须重新审查操作中途是否会暴露未完成状态。

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

import assert from "node:assert/strict";

class LRUCache {
  #limit;
  #map = new Map();
  constructor(limit) {
    if (typeof limit !== "number") throw new TypeError("number required");
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError("nonnegative safe integer required");
    }
    this.#limit = limit;
  }
  get size() { return this.#map.size; }
  has(key) { return this.#map.has(key); }
  peek(key) { return this.#map.get(key); }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    if (this.#limit === 0) return this;
    this.#map.set(key, value);
    if (this.#map.size > this.#limit) {
      this.#map.delete(this.#map.keys().next().value);
    }
    return this;
  }
  delete(key) { return this.#map.delete(key); }
  clear() { this.#map.clear(); }
  keys() { return [...this.#map.keys()]; }
  entries() { return [...this.#map.entries()]; }
}

const c = new LRUCache(3);
const states = [];
const check = expected => {
  assert.deepEqual(c.keys(), expected);
  assert.ok(c.size <= 3);
  states.push(c.keys().join(","));
};
c.set("a", 1).set("b", 2).set("c", 3); check(["a", "b", "c"]);
c.get("a"); check(["b", "c", "a"]);
c.set("d", 4); check(["c", "a", "d"]);
c.peek("c"); c.has("c"); check(["c", "a", "d"]);
c.set("a", 10); check(["c", "d", "a"]);
c.set("e", 5); check(["d", "a", "e"]);
assert.equal(c.delete("a"), true); check(["d", "e"]);
assert.equal(c.delete("missing"), false); check(["d", "e"]);
c.set("f", 6); check(["d", "e", "f"]);
assert.equal(c.clear(), undefined); check([]);
c.set("g", 7); check(["g"]);
assert.equal(c.size, 1);
console.log("07 OK: " + states.join(" -> "));

实际输出:

07 OK: a,b,c -> b,c,a -> c,a,d -> c,a,d -> c,d,a -> d,a,e -> d,e -> d,e -> d,e,f ->  -> g

测试八:快照可以稳定遍历,但并不深度复制值

把内部 Map 的 keys 迭代器直接返回,表面上省了一次数组分配,却同时把实时变化语义交给调用方。边遍历边 get 时,删除再重插可能把已经访问的键追加到迭代尾部,造成反复访问。ECMAScript 的 CreateMapIterator 算法说明了迭代恢复后继续观察条目列表的方式。下面的原生 Map 演示只手动取六次,既呈现重复访问,也避免真的让测试挂在无限循环里。

我们的 keys 和 entries 则在调用时复制顺序。修改返回数组或二元组的键槽,不会重命名或插入缓存条目;遍历这个数组时再触碰缓存,也不会改变这一轮要访问的键列表。不过值和对象键仍是原引用,修改对象的 count 会被缓存中的同一个对象看到。这是浅快照,不是事务快照、深复制或不可变数据结构。对外承诺必须停在实际实现的边界上。

这种安全性有成本:生成快照需要与当前条目数成正比的遍历和额外空间。因此它适合调试、导出和有限规模的观察,不应把它包装成零成本接口。若性能需要实时迭代,就应另设计带明显名称的 API,并明确禁止或定义遍历中的修改,而不是随手替换返回类型。

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

import assert from "node:assert/strict";

class LRUCache {
  #limit;
  #map = new Map();
  constructor(limit) {
    if (typeof limit !== "number") throw new TypeError("number required");
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError("nonnegative safe integer required");
    }
    this.#limit = limit;
  }
  get size() { return this.#map.size; }
  has(key) { return this.#map.has(key); }
  peek(key) { return this.#map.get(key); }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    if (this.#limit === 0) return this;
    this.#map.set(key, value);
    if (this.#map.size > this.#limit) {
      this.#map.delete(this.#map.keys().next().value);
    }
    return this;
  }
  delete(key) { return this.#map.delete(key); }
  clear() { this.#map.clear(); }
  keys() { return [...this.#map.keys()]; }
  entries() { return [...this.#map.entries()]; }
}

const c = new LRUCache(2);
const value = { count: 1 };
c.set("a", value).set("b", 2);
const keys = c.keys();
const entries = c.entries();
c.get("a");
assert.deepEqual(keys, ["a", "b"]);
assert.deepEqual(c.keys(), ["b", "a"]);
keys.push("fake");
entries[0][0] = "renamed";
assert.equal(c.has("fake"), false);
assert.equal(c.has("renamed"), false);
entries[0][1].count = 9;
assert.equal(c.peek("a").count, 9);
const seen = [];
for (const key of c.keys()) { seen.push(key); c.get(key); }
assert.deepEqual(seen, ["b", "a"]);
assert.deepEqual(c.keys(), ["b", "a"]);
const live = new Map([["a", 1], ["b", 2]]);
const iterator = live.keys();
const repeated = [];
for (let i = 0; i < 6; i++) {
  const step = iterator.next();
  assert.equal(step.done, false);
  repeated.push(step.value);
  const v = live.get(step.value);
  live.delete(step.value);
  live.set(step.value, v);
}
assert.deepEqual(repeated, ["a", "b", "a", "b", "a", "b"]);
console.log("08 OK: detached order, shared values, live revisits");

实际输出:

08 OK: detached order, shared values, live revisits

测试九:让另一种数据结构检查长操作序列

前八段是可读的边界反例,第九段补充确定性长序列。参考模型使用数组查找和移动,而被测实现使用 Map;两者共享业务合同,但不共享内部容器和触碰逻辑。固定种子的伪随机数让失败能够复现,四种容量总共执行六千步,每一步都比较返回值、顺序、值身份和容量上限。

模型刻意实现 SameValueZero,并将零键归一化。比较键时使用合同规定的相等规则,比较值时使用 Object.is,避免深比较把两个内容相同、身份不同的对象误认为同一个引用。这个模型规模小、查找慢,但适合做测试裁判;不要因为它更容易理解,就顺便把它宣传成大容量生产实现。

最后还检查 Promise 作为普通值保存时的身份:得到的仍是原 Promise,完成以后也不会自动变成它的结果。这只能证明容器没有替换值,不能证明它提供单飞去重、失败自动移除或取消能力。固定序列和九个脚本也不构成形式化证明;它们是在已定义合同下提供可复查的回归证据,实际业务仍需要根据真实输入补充测试。

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

import assert from "node:assert/strict";

class LRUCache {
  #limit;
  #map = new Map();
  constructor(limit) {
    if (typeof limit !== "number") throw new TypeError("number required");
    if (!Number.isSafeInteger(limit) || limit < 0) {
      throw new RangeError("nonnegative safe integer required");
    }
    this.#limit = limit;
  }
  get size() { return this.#map.size; }
  has(key) { return this.#map.has(key); }
  peek(key) { return this.#map.get(key); }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    if (this.#limit === 0) return this;
    this.#map.set(key, value);
    if (this.#map.size > this.#limit) {
      this.#map.delete(this.#map.keys().next().value);
    }
    return this;
  }
  delete(key) { return this.#map.delete(key); }
  clear() { this.#map.clear(); }
  keys() { return [...this.#map.keys()]; }
  entries() { return [...this.#map.entries()]; }
}

const equalKey = (a, b) => a === b || (a !== a && b !== b);
class Model {
  constructor(limit) { this.limit = limit; this.rows = []; }
  index(key) { return this.rows.findIndex(([k]) => equalKey(k, key)); }
  has(key) { return this.index(key) >= 0; }
  peek(key) { return this.rows[this.index(key)]?.[1]; }
  get(key) {
    const i = this.index(key);
    if (i < 0) return undefined;
    const [row] = this.rows.splice(i, 1);
    this.rows.push(row);
    return row[1];
  }
  set(key, value) {
    this.delete(key);
    if (this.limit === 0) return this;
    this.rows.push([key === 0 ? 0 : key, value]);
    if (this.rows.length > this.limit) this.rows.shift();
    return this;
  }
  delete(key) {
    const i = this.index(key);
    if (i < 0) return false;
    this.rows.splice(i, 1);
    return true;
  }
  clear() { this.rows = []; }
}
let seed = 0x12345678;
const random = () => {
  seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5;
  return seed >>> 0;
};
const objectA = { id: 1 }, objectB = { id: 1 };
const keys = ["a", "b", "c", undefined, NaN, -0, 0, 1, "1", objectA, objectB];
const values = [undefined, false, 0, "", null, NaN, { shared: true }];
const ops = ["set", "set", "get", "has", "peek", "delete", "clear"];
let steps = 0;
for (const limit of [0, 1, 2, 5]) {
  const c = new LRUCache(limit), model = new Model(limit);
  for (let i = 0; i < 1500; i++) {
    const op = ops[random() % ops.length];
    const key = keys[random() % keys.length];
    const value = values[random() % values.length];
    const got = c[op](key, value), expected = model[op](key, value);
    if (op === "set") assert.equal(got, c);
    else assert.ok(Object.is(got, expected));
    const actual = c.entries();
    assert.equal(actual.length, model.rows.length);
    for (let j = 0; j < actual.length; j++) {
      assert.ok(equalKey(actual[j][0], model.rows[j][0]));
      assert.ok(Object.is(actual[j][1], model.rows[j][1]));
    }
    assert.ok(c.size <= limit);
    steps++;
  }
}
const p = Promise.resolve("done");
const c = new LRUCache(1);
c.set("job", p);
assert.equal(c.get("job"), p);
assert.equal(await p, "done");
assert.equal(c.peek("job"), p);
console.log("09 OK: " + steps + " model steps; Promise identity retained");

实际输出:

09 OK: 6000 model steps; Promise identity retained

通过九组测试之后,哪些承诺仍然不能写

有界条目数不等于有界字节数。一个条目可能引用很大的对象图,外部也可能继续持有被淘汰的对象,删除缓存引用并不意味着内存立刻释放。本文没有大小估算、权重计算或内存测量,因此不能据此给出进程内存峰值保证。类似地,Map 通常适合这种轻量实现,但 ECMAScript 对 Map 的复杂度要求是平均访问时间次线性,不能把语言规范改写成所有操作在所有引擎上都具有严格常数时间保证。

本文没有 TTL,也没有读取时检查过期时间。只要没有发生淘汰或显式删除,一个冷条目可以一直存在。要加过期策略,必须另外决定过期项何时删除、peek 是否应过滤、过期判定能否触碰顺序,以及计时器如何清理。LRU 解决的是容量压力下谁先离开,TTL 解决的是数据什么时候失效,两者可以组合,但不能互相代替。

本文也没有异步装载器和持久化。两个调用方同时未命中后,各自发起请求,是业务层完全可能出现的行为;把 Promise 放进去并不会自动建立请求去重或失败恢复协议。慢请求回来时是否覆盖较新的结果、淘汰是否取消请求、拒绝后是否保留失败 Promise,都需要新的合同和测试。进程退出后这份数据消失,也没有跨进程共享、磁盘恢复或分布式一致性可言。

给 AI 的下一轮任务,应当可以被反驳

比起要求“再优化一下并确保没有问题”,更有效的审查任务是指定不变量和反例。例如要求它解释为什么替换现有键不会多淘汰一个条目,为什么 undefined 命中后仍更新顺序,再让它写出一个能击穿错误版本的最短测试。若它提出优化,先保留这些回归脚本,再讨论在什么输入规模和运行环境下值得测量收益。

验收时可以把证据分成三层:接口合同是否清楚,独立脚本是否真的执行,叙述是否超出了代码能力。模型写出漂亮注释,不是第一层的替代;输出一行 OK,也不能替代足够敏感的断言;跑过测试,更不能自动把同步内存容器升级为完整缓存系统。将每一条宣传语追溯到一段实现或一项测试,是人审 AI 代码时最值得保留的习惯。

这份参考实现刻意保持小而明确。真正需要按权重驱逐、过期清理、批量操作或装载去重时,应把新增需求视为新的设计问题,评估成熟库并核对其现行文档,再为选定合同补测试。AI 可以帮助枚举边界、生成反例和解释失败;最终接受的是可运行、可核对、范围明确的证据,而不是一句“支持 LRU”。

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