审查 AI 写的 TTL 缓存:用可控时钟锁定过期边界的九个测试

10-19 5阅读

让 AI 写一个带有效期的缓存,最容易得到的答案是:保存值,再用定时器删除。代码很短,也能演示成功。但真正进入业务后,我们需要回答的是另一组问题:截止时间恰好到了还能不能读?反复访问会不会延长寿命?缓存了 undefined 算命中吗?进程忙到定时器迟迟没执行,旧值是否仍会被返回?这些问题都不能靠一张成功运行的截图解决。

这次审计把重点放在时间契约。我们用注入式时钟把时间变成普通输入,先写下可观察行为,再让断言检查实现。这里的实现是一份便于审查的教学参考,不声称复现某个模型的真实输出,也不是可直接替代成熟缓存库的完整产品。AI 可以协助生成候选实现、反例和测试,但不能替团队决定什么叫过期。

审查 AI 写的 TTL 缓存:用可控时钟锁定过期边界的九个测试
AI 生成的概念配图:固定截止边界与可控制的时钟。图片用于表达主题,不是测试截图或真实系统界面。

先签订契约,再讨论实现

本例把 TTL 定义为写入时长,单位是毫秒。一次成功写入用同一次时钟采样计算 expiresAt = now + ttl,之后读取不会更新它。活跃区间包含写入时刻,不包含截止时刻:now 小于 expiresAt 才能命中;二者相等就已经过期。这里的绝对截止时间是同一时钟坐标内的固定数值,不是某个日历日期。

  • TTL 必须是有限、非负的 number;允许小数。零表示立即失效,同时移除同名旧项;不接受负数、字符串、NaN 或 Infinity。

  • 时钟必须是同步、无副作用且不重入缓存的方法,返回非负、有限的毫秒数;相邻成功采样可以相等,不能倒退。构造时只检查函数类型,不读时间。

  • lookup 返回带 hit 的结果,get 为便捷读取,has 为有效成员判断。命中 undefined 与缺失必须能区分。

  • 读取只清理被访问的过期项;set、size 和 prune 会扫描清理。size 是当前采样时刻的有效项数,storedSize 是尚存储的项数,包含未清理的过期项。

  • 容量是非负安全整数,默认一千项。清理后仍满则拒绝新增键;允许覆盖已有有效键。这里没有淘汰顺序,也没有最近访问晋升。

默认时钟使用包装函数调用 performance.now()。Node.js 官方文档说明它返回当前进程起点之后的高精度毫秒时间戳,并要求以 performance 对象为接收者调用。High Resolution Time 的时钟定义解释了单调时钟与可能被校正的墙上时钟的区别;这也是本地持续时间判断不直接依赖 Date.now() 的原因。本文不把单调时钟解释为跨进程、跨机器或跨休眠环境统一的持久化时间。

如何运行九个检查

以下恰好九个 JavaScript 示例都可独立保存为 .mjs 文件。每段重复同一份完整 TTLCache,是为了让读者复制任意一段就能运行,不依赖上一段的全局变量或另一个源码文件。保存为 case-01.mjs 至 case-09.mjs 后,分别运行 node --unhandled-rejections=strict case-01.mjs,并按编号更换文件名。本文已在 Node.js v24.19.0 下逐段执行,展示的输出与实际结果一致。

Node.js 的 ESM 文档说明 .mjs 是显式启用模块格式的方式之一;严格未处理拒绝模式的官方说明给出了该命令行选项的行为。这里的用例是同步的,没有等待真实毫秒流逝,也没有用睡眠时间掩盖边界。严格选项用于统一执行基线,不能代替断言,更不能把同步缓存变成异步安全组件。

一、截止时刻必须明确排除

第一个检查只问一件事:存活区间的右端点究竟归谁。把时间从一千推进到一千零九点九九九,再推进到一千零一十,就能直接检查边界。若 AI 把比较符写成严格大于,恰好到期时会多活一次;若使用了整数截断,小数边界又可能被误改。我们不靠操作系统恰好在第十毫秒调度测试,而是让时钟直接返回目标值。

lookup 的时间采样位于查表之前,连缺失查询也遵守同一个时钟契约。返回结果只代表该采样瞬间;方法返回后时间继续前进,并不保证调用者稍后使用数据时还在有效期内。授权、支付或锁租约等强时效业务,不能把这个普通缓存当作最终判定依据。

独立示例 1,文件名 case-01.mjs:

import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";

class TTLCache {
  #entries = new Map();
  #now;
  #last = -Infinity;
  #capacity;

  constructor({ now = () => performance.now(), capacity = 1000 } = {}) {
    if (typeof now !== "function") throw new TypeError("clock must be a function");
    if (!Number.isSafeInteger(capacity) || capacity < 0) {
      throw new RangeError("capacity must be a nonnegative safe integer");
    }
    this.#now = now;
    this.#capacity = capacity;
  }

  #time() {
    const t = this.#now();
    if (typeof t !== "number" || !Number.isFinite(t) || t < 0) {
      throw new TypeError("clock must return finite nonnegative milliseconds");
    }
    if (t < this.#last) throw new RangeError("clock moved backwards");
    this.#last = t;
    return t;
  }

  #pruneAt(t) {
    let removed = 0;
    for (const [key, entry] of this.#entries) {
      if (t >= entry.expiresAt) {
        this.#entries.delete(key);
        removed++;
      }
    }
    return removed;
  }

  set(key, value, ttl) {
    if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl < 0) {
      throw new RangeError("ttl must be finite nonnegative milliseconds");
    }
    const t = this.#time();
    const expiresAt = t + ttl;
    if (!Number.isFinite(expiresAt) || (ttl > 0 && expiresAt <= t)) {
      throw new RangeError("deadline is not representable");
    }
    this.#pruneAt(t);
    if (ttl === 0) {
      this.#entries.delete(key);
      return this;
    }
    if (!this.#entries.has(key) && this.#entries.size >= this.#capacity) {
      throw new RangeError("capacity reached");
    }
    this.#entries.set(key, { value, expiresAt });
    return this;
  }

  lookup(key) {
    const t = this.#time();
    const entry = this.#entries.get(key);
    if (!entry) return { hit: false };
    if (t >= entry.expiresAt) {
      this.#entries.delete(key);
      return { hit: false };
    }
    return { hit: true, value: entry.value };
  }

  get(key) { return this.lookup(key).value; }
  has(key) { return this.lookup(key).hit; }
  prune() { return this.#pruneAt(this.#time()); }
  get size() { this.prune(); return this.#entries.size; }
  get storedSize() { return this.#entries.size; }
}

let t = 1000;
const cache = new TTLCache({ now: () => t });
cache.set("item", "fresh", 10);
assert.deepEqual(cache.lookup("item"), { hit: true, value: "fresh" });
t = 1009.999;
assert.equal(cache.get("item"), "fresh");
t = 1010;
assert.deepEqual(cache.lookup("item"), { hit: false });
assert.equal(cache.storedSize, 0);
console.log("01 deadline boundary passed");

预期输出:

01 deadline boundary passed

二、频繁读取不能悄悄续期

写入后有效二十毫秒,与每次访问后再有效二十毫秒,是两份不同的业务约定。后者叫滑动过期,热门键可能一直存活;前者的热点数据也会按写入时刻失效。审核时必须检查 get、has 和 lookup 的命中分支有没有更新截止时间,不能只搜索 set 中的赋值。

这个用例在截止之前多次查询,最后仍要求第二十毫秒失效。使用同一个假时钟还可以重复读取完全相同的时刻,确认实现没有把单调误解为每次都必须严格递增。我们的代码允许相等采样,判断倒退使用小于,而不是小于等于。若产品以后需要滑动策略,应另改契约和测试,不能顺手在读取路径加一个续期副作用。

独立示例 2,文件名 case-02.mjs:

import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";

class TTLCache {
  #entries = new Map();
  #now;
  #last = -Infinity;
  #capacity;

  constructor({ now = () => performance.now(), capacity = 1000 } = {}) {
    if (typeof now !== "function") throw new TypeError("clock must be a function");
    if (!Number.isSafeInteger(capacity) || capacity < 0) {
      throw new RangeError("capacity must be a nonnegative safe integer");
    }
    this.#now = now;
    this.#capacity = capacity;
  }

  #time() {
    const t = this.#now();
    if (typeof t !== "number" || !Number.isFinite(t) || t < 0) {
      throw new TypeError("clock must return finite nonnegative milliseconds");
    }
    if (t < this.#last) throw new RangeError("clock moved backwards");
    this.#last = t;
    return t;
  }

  #pruneAt(t) {
    let removed = 0;
    for (const [key, entry] of this.#entries) {
      if (t >= entry.expiresAt) {
        this.#entries.delete(key);
        removed++;
      }
    }
    return removed;
  }

  set(key, value, ttl) {
    if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl < 0) {
      throw new RangeError("ttl must be finite nonnegative milliseconds");
    }
    const t = this.#time();
    const expiresAt = t + ttl;
    if (!Number.isFinite(expiresAt) || (ttl > 0 && expiresAt <= t)) {
      throw new RangeError("deadline is not representable");
    }
    this.#pruneAt(t);
    if (ttl === 0) {
      this.#entries.delete(key);
      return this;
    }
    if (!this.#entries.has(key) && this.#entries.size >= this.#capacity) {
      throw new RangeError("capacity reached");
    }
    this.#entries.set(key, { value, expiresAt });
    return this;
  }

  lookup(key) {
    const t = this.#time();
    const entry = this.#entries.get(key);
    if (!entry) return { hit: false };
    if (t >= entry.expiresAt) {
      this.#entries.delete(key);
      return { hit: false };
    }
    return { hit: true, value: entry.value };
  }

  get(key) { return this.lookup(key).value; }
  has(key) { return this.lookup(key).hit; }
  prune() { return this.#pruneAt(this.#time()); }
  get size() { this.prune(); return this.#entries.size; }
  get storedSize() { return this.#entries.size; }
}

let t = 0;
const cache = new TTLCache({ now: () => t });
cache.set("hot", 7, 20);
for (const next of [0, 0, 5, 10, 19]) {
  t = next;
  assert.equal(cache.get("hot"), 7);
  assert.equal(cache.has("hot"), true);
  assert.deepEqual(cache.lookup("hot"), { hit: true, value: 7 });
}
t = 20;
assert.equal(cache.has("hot"), false);
assert.equal(cache.get("hot"), undefined);
console.log("02 reads do not renew passed");

预期输出:

02 reads do not renew passed

三、undefined 是值,缺失是状态

直接用 get(key) !== undefined 判断命中,会把真实缓存的 undefined 当作缺失。ECMAScript 的 Map.get 规范确实规定未找到时返回 undefined,而 Map.has另行表达成员是否存在。本文借鉴这种区分,但加入了过期判断;lookup 让调用者通过一次时钟采样同时拿到状态和值。

内部始终存放包含 value 和 expiresAt 的记录对象,因此对内部 entry 做存在性判断不会误伤用户存入的 false、零或空字符串。代码没有复制对象,返回的仍是同一引用。键也沿用 Map 的语义,两个长得一样的对象不是同一个键。不要把这个内存容器误读成带序列化、不可变快照或深比较能力的数据层。

独立示例 3,文件名 case-03.mjs:

import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";

class TTLCache {
  #entries = new Map();
  #now;
  #last = -Infinity;
  #capacity;

  constructor({ now = () => performance.now(), capacity = 1000 } = {}) {
    if (typeof now !== "function") throw new TypeError("clock must be a function");
    if (!Number.isSafeInteger(capacity) || capacity < 0) {
      throw new RangeError("capacity must be a nonnegative safe integer");
    }
    this.#now = now;
    this.#capacity = capacity;
  }

  #time() {
    const t = this.#now();
    if (typeof t !== "number" || !Number.isFinite(t) || t < 0) {
      throw new TypeError("clock must return finite nonnegative milliseconds");
    }
    if (t < this.#last) throw new RangeError("clock moved backwards");
    this.#last = t;
    return t;
  }

  #pruneAt(t) {
    let removed = 0;
    for (const [key, entry] of this.#entries) {
      if (t >= entry.expiresAt) {
        this.#entries.delete(key);
        removed++;
      }
    }
    return removed;
  }

  set(key, value, ttl) {
    if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl < 0) {
      throw new RangeError("ttl must be finite nonnegative milliseconds");
    }
    const t = this.#time();
    const expiresAt = t + ttl;
    if (!Number.isFinite(expiresAt) || (ttl > 0 && expiresAt <= t)) {
      throw new RangeError("deadline is not representable");
    }
    this.#pruneAt(t);
    if (ttl === 0) {
      this.#entries.delete(key);
      return this;
    }
    if (!this.#entries.has(key) && this.#entries.size >= this.#capacity) {
      throw new RangeError("capacity reached");
    }
    this.#entries.set(key, { value, expiresAt });
    return this;
  }

  lookup(key) {
    const t = this.#time();
    const entry = this.#entries.get(key);
    if (!entry) return { hit: false };
    if (t >= entry.expiresAt) {
      this.#entries.delete(key);
      return { hit: false };
    }
    return { hit: true, value: entry.value };
  }

  get(key) { return this.lookup(key).value; }
  has(key) { return this.lookup(key).hit; }
  prune() { return this.#pruneAt(this.#time()); }
  get size() { this.prune(); return this.#entries.size; }
  get storedSize() { return this.#entries.size; }
}

let t = 0;
const cache = new TTLCache({ now: () => t });
cache.set("undefined", undefined, 10);
assert.equal(cache.get("undefined"), cache.get("missing"));
assert.deepEqual(cache.lookup("undefined"), { hit: true, value: undefined });
assert.deepEqual(cache.lookup("missing"), { hit: false });
assert.equal(cache.has("undefined"), true);
for (const [key, value] of [["null", null], ["false", false], ["zero", 0], ["empty", ""]]) {
  cache.set(key, value, 10);
  assert.deepEqual(cache.lookup(key), { hit: true, value });
}
const key = {};
const value = { count: 1 };
cache.set(key, value, 10);
assert.equal(cache.get(key), value);
assert.equal(cache.has({}), false);
t = 10;
assert.equal(cache.has("undefined"), false);
console.log("03 values and absence passed");

预期输出:

03 values and absence passed

四、零 TTL、非法输入与数值边界

零的含义尤其容易被默认参数写错。若使用 ttl || defaultTTL,零会被替换成默认时长;若只是忽略零写入,同名旧值又会继续存活。本例选择明确的删除语义:零 TTL 不占容量,覆盖旧键时立即让旧值失效。负数与无穷大则直接拒绝,避免默认值和数值转换悄悄制造另一套规则。

只验证 TTL 有限仍不够,两个有限数相加也可能溢出。更隐蔽的是,极大的时钟值加一个很小的正 TTL,浮点结果可能仍等于原值。我们拒绝这两种无法表达正向截止时间的情况。除此之外仍按 JavaScript number 的实际运算结果比较,没有宣称任意精度或真实世界纳秒级准确性。下面还检查错误写入不会覆盖原有值,防止验证顺序改变数据。

独立示例 4,文件名 case-04.mjs:

import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";

class TTLCache {
  #entries = new Map();
  #now;
  #last = -Infinity;
  #capacity;

  constructor({ now = () => performance.now(), capacity = 1000 } = {}) {
    if (typeof now !== "function") throw new TypeError("clock must be a function");
    if (!Number.isSafeInteger(capacity) || capacity < 0) {
      throw new RangeError("capacity must be a nonnegative safe integer");
    }
    this.#now = now;
    this.#capacity = capacity;
  }

  #time() {
    const t = this.#now();
    if (typeof t !== "number" || !Number.isFinite(t) || t < 0) {
      throw new TypeError("clock must return finite nonnegative milliseconds");
    }
    if (t < this.#last) throw new RangeError("clock moved backwards");
    this.#last = t;
    return t;
  }

  #pruneAt(t) {
    let removed = 0;
    for (const [key, entry] of this.#entries) {
      if (t >= entry.expiresAt) {
        this.#entries.delete(key);
        removed++;
      }
    }
    return removed;
  }

  set(key, value, ttl) {
    if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl < 0) {
      throw new RangeError("ttl must be finite nonnegative milliseconds");
    }
    const t = this.#time();
    const expiresAt = t + ttl;
    if (!Number.isFinite(expiresAt) || (ttl > 0 && expiresAt <= t)) {
      throw new RangeError("deadline is not representable");
    }
    this.#pruneAt(t);
    if (ttl === 0) {
      this.#entries.delete(key);
      return this;
    }
    if (!this.#entries.has(key) && this.#entries.size >= this.#capacity) {
      throw new RangeError("capacity reached");
    }
    this.#entries.set(key, { value, expiresAt });
    return this;
  }

  lookup(key) {
    const t = this.#time();
    const entry = this.#entries.get(key);
    if (!entry) return { hit: false };
    if (t >= entry.expiresAt) {
      this.#entries.delete(key);
      return { hit: false };
    }
    return { hit: true, value: entry.value };
  }

  get(key) { return this.lookup(key).value; }
  has(key) { return this.lookup(key).hit; }
  prune() { return this.#pruneAt(this.#time()); }
  get size() { this.prune(); return this.#entries.size; }
  get storedSize() { return this.#entries.size; }
}

let t = 0;
const cache = new TTLCache({ now: () => t });
cache.set("k", "old", 100);
for (const ttl of [-1, NaN, Infinity, -Infinity, "10", null, undefined]) {
  assert.throws(() => cache.set("k", "bad", ttl), RangeError);
  assert.equal(cache.get("k"), "old");
}
assert.equal(cache.set("k", "gone", 0), cache);
assert.equal(cache.has("k"), false);
cache.set("fraction", 1, 0.25);
t = 0.25;
assert.equal(cache.has("fraction"), false);
const huge = new TTLCache({ now: () => Number.MAX_VALUE });
assert.throws(() => huge.set("overflow", 1, Number.MAX_VALUE), RangeError);
assert.throws(() => huge.set("rounded", 1, 1), RangeError);
assert.equal(huge.storedSize, 0);
console.log("04 ttl validation passed");

预期输出:

04 ttl validation passed

五、注入时钟也需要被审计

注入依赖让测试可控,却不会自动保证依赖正确。有人可能传入日期字符串、返回 NaN,或在测试间把全局时间重置为零。如果实现直接拿这些值比较,NaN 会让大小关系全部为假,过期数据就可能永久命中。本文要求时钟返回非负有限数,倒退单独报错,不偷偷钳制到上次时间。

高水位只接受有效的非倒退采样。非法数值和倒退不会降低它;恢复到原高水位或更晚即可继续操作。时钟函数自己抛出的错误原样传播,不能包装成缓存未命中,否则基础设施故障会被伪装成正常业务分支。同步、无副作用和不重入是调用方前提,类型检查无法证明这些性质。本例不接收异步时钟,也不尝试处理恶意回调的任意行为。

独立示例 5,文件名 case-05.mjs:

import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";

class TTLCache {
  #entries = new Map();
  #now;
  #last = -Infinity;
  #capacity;

  constructor({ now = () => performance.now(), capacity = 1000 } = {}) {
    if (typeof now !== "function") throw new TypeError("clock must be a function");
    if (!Number.isSafeInteger(capacity) || capacity < 0) {
      throw new RangeError("capacity must be a nonnegative safe integer");
    }
    this.#now = now;
    this.#capacity = capacity;
  }

  #time() {
    const t = this.#now();
    if (typeof t !== "number" || !Number.isFinite(t) || t < 0) {
      throw new TypeError("clock must return finite nonnegative milliseconds");
    }
    if (t < this.#last) throw new RangeError("clock moved backwards");
    this.#last = t;
    return t;
  }

  #pruneAt(t) {
    let removed = 0;
    for (const [key, entry] of this.#entries) {
      if (t >= entry.expiresAt) {
        this.#entries.delete(key);
        removed++;
      }
    }
    return removed;
  }

  set(key, value, ttl) {
    if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl < 0) {
      throw new RangeError("ttl must be finite nonnegative milliseconds");
    }
    const t = this.#time();
    const expiresAt = t + ttl;
    if (!Number.isFinite(expiresAt) || (ttl > 0 && expiresAt <= t)) {
      throw new RangeError("deadline is not representable");
    }
    this.#pruneAt(t);
    if (ttl === 0) {
      this.#entries.delete(key);
      return this;
    }
    if (!this.#entries.has(key) && this.#entries.size >= this.#capacity) {
      throw new RangeError("capacity reached");
    }
    this.#entries.set(key, { value, expiresAt });
    return this;
  }

  lookup(key) {
    const t = this.#time();
    const entry = this.#entries.get(key);
    if (!entry) return { hit: false };
    if (t >= entry.expiresAt) {
      this.#entries.delete(key);
      return { hit: false };
    }
    return { hit: true, value: entry.value };
  }

  get(key) { return this.lookup(key).value; }
  has(key) { return this.lookup(key).hit; }
  prune() { return this.#pruneAt(this.#time()); }
  get size() { this.prune(); return this.#entries.size; }
  get storedSize() { return this.#entries.size; }
}

assert.throws(() => new TTLCache({ now: 1 }), TypeError);
let t = 10;
const cache = new TTLCache({ now: () => t });
cache.set("k", "stable", 100);
for (const bad of [NaN, Infinity, -Infinity, -1, "10", null, undefined]) {
  t = bad;
  assert.throws(() => cache.lookup("k"), TypeError);
}
t = 9;
assert.throws(() => cache.lookup("k"), RangeError);
t = 10;
assert.equal(cache.get("k"), "stable");
const sentinel = new Error("clock unavailable");
const broken = new TTLCache({ now: () => { throw sentinel; } });
assert.throws(() => broken.lookup("missing"), error => error === sentinel);
assert.equal(broken.storedSize, 0);
console.log("05 clock validation passed");

预期输出:

05 clock validation passed

六、覆盖以本次写入为起点,一次操作只采样一次

覆盖同名键应该从本次写入重新计算截止时间,而不是沿用旧期限,也不是把新 TTL 累加到旧期限。覆盖既可以延长,也可以缩短。下面故意先延长再缩短,并在最终边界上检查失效。这样的反例比只测试一次覆盖更容易识别 AI 误用旧记录的错误。

同样需要钉住采样次数。若 set 清理时采一次时间、写入时又采一次,测试边界会受到时钟回调行为影响。当前设计在公开的时间相关操作中恰好采样一次,再把数值向内部传递;storedSize 不读时钟,非法 TTL 也会在读取时钟前被拒绝。即使写入后来因截止溢出或容量不足失败,已经成功采到的时钟高水位仍会前进。这不是整次操作的事务回滚承诺。

独立示例 6,文件名 case-06.mjs:

import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";

class TTLCache {
  #entries = new Map();
  #now;
  #last = -Infinity;
  #capacity;

  constructor({ now = () => performance.now(), capacity = 1000 } = {}) {
    if (typeof now !== "function") throw new TypeError("clock must be a function");
    if (!Number.isSafeInteger(capacity) || capacity < 0) {
      throw new RangeError("capacity must be a nonnegative safe integer");
    }
    this.#now = now;
    this.#capacity = capacity;
  }

  #time() {
    const t = this.#now();
    if (typeof t !== "number" || !Number.isFinite(t) || t < 0) {
      throw new TypeError("clock must return finite nonnegative milliseconds");
    }
    if (t < this.#last) throw new RangeError("clock moved backwards");
    this.#last = t;
    return t;
  }

  #pruneAt(t) {
    let removed = 0;
    for (const [key, entry] of this.#entries) {
      if (t >= entry.expiresAt) {
        this.#entries.delete(key);
        removed++;
      }
    }
    return removed;
  }

  set(key, value, ttl) {
    if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl < 0) {
      throw new RangeError("ttl must be finite nonnegative milliseconds");
    }
    const t = this.#time();
    const expiresAt = t + ttl;
    if (!Number.isFinite(expiresAt) || (ttl > 0 && expiresAt <= t)) {
      throw new RangeError("deadline is not representable");
    }
    this.#pruneAt(t);
    if (ttl === 0) {
      this.#entries.delete(key);
      return this;
    }
    if (!this.#entries.has(key) && this.#entries.size >= this.#capacity) {
      throw new RangeError("capacity reached");
    }
    this.#entries.set(key, { value, expiresAt });
    return this;
  }

  lookup(key) {
    const t = this.#time();
    const entry = this.#entries.get(key);
    if (!entry) return { hit: false };
    if (t >= entry.expiresAt) {
      this.#entries.delete(key);
      return { hit: false };
    }
    return { hit: true, value: entry.value };
  }

  get(key) { return this.lookup(key).value; }
  has(key) { return this.lookup(key).hit; }
  prune() { return this.#pruneAt(this.#time()); }
  get size() { this.prune(); return this.#entries.size; }
  get storedSize() { return this.#entries.size; }
}

let t = 0;
let calls = 0;
const cache = new TTLCache({ now: () => { calls++; return t; } });
assert.equal(calls, 0);
cache.set("k", "first", 10);
assert.equal(calls, 1);
t = 5;
cache.set("k", "extended", 20);
assert.equal(calls, 2);
t = 10;
assert.equal(cache.get("k"), "extended");
assert.equal(calls, 3);
cache.set("k", "shortened", 2);
assert.equal(calls, 4);
t = 11;
assert.equal(cache.has("k"), true);
assert.equal(calls, 5);
t = 12;
assert.deepEqual(cache.lookup("k"), { hit: false });
assert.equal(calls, 6);
assert.equal(cache.prune(), 0);
assert.equal(calls, 7);
assert.equal(cache.size, 0);
assert.equal(calls, 8);
assert.equal(cache.storedSize, 0);
assert.throws(() => cache.set("k", 1, -1), RangeError);
assert.equal(calls, 8);
console.log("06 overwrite and sampling passed");

预期输出:

06 overwrite and sampling passed

七、逻辑过期与物理清理是两件事

时间前进不会自动执行 JavaScript。没有任何调用时,已过期记录仍可能留在 Map 中;但下次读取它时,必须按当前采样时间拒绝返回旧值。我们为此把 size 与 storedSize 分开:前者先清理并反映有效项数,后者仅用于观察保留的记录数量,不承诺它们仍可用。把两种数字共用一个含糊字段,会让监控和容量判断互相误导。

get 和 has 只清理目标键,避免一次热路径读取扫描整个缓存;读取一个无关键不会顺便清空所有旧项。显式 prune 返回本次移除数量,重复调用可返回零。set、size、prune 都需要遍历存储项,复杂度随数量增长,因此这份代码有意用清晰换取吞吐量。后续若改为堆或分桶清理,必须保留这些可观察语义,再针对负载重新测量。

独立示例 7,文件名 case-07.mjs:

import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";

class TTLCache {
  #entries = new Map();
  #now;
  #last = -Infinity;
  #capacity;

  constructor({ now = () => performance.now(), capacity = 1000 } = {}) {
    if (typeof now !== "function") throw new TypeError("clock must be a function");
    if (!Number.isSafeInteger(capacity) || capacity < 0) {
      throw new RangeError("capacity must be a nonnegative safe integer");
    }
    this.#now = now;
    this.#capacity = capacity;
  }

  #time() {
    const t = this.#now();
    if (typeof t !== "number" || !Number.isFinite(t) || t < 0) {
      throw new TypeError("clock must return finite nonnegative milliseconds");
    }
    if (t < this.#last) throw new RangeError("clock moved backwards");
    this.#last = t;
    return t;
  }

  #pruneAt(t) {
    let removed = 0;
    for (const [key, entry] of this.#entries) {
      if (t >= entry.expiresAt) {
        this.#entries.delete(key);
        removed++;
      }
    }
    return removed;
  }

  set(key, value, ttl) {
    if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl < 0) {
      throw new RangeError("ttl must be finite nonnegative milliseconds");
    }
    const t = this.#time();
    const expiresAt = t + ttl;
    if (!Number.isFinite(expiresAt) || (ttl > 0 && expiresAt <= t)) {
      throw new RangeError("deadline is not representable");
    }
    this.#pruneAt(t);
    if (ttl === 0) {
      this.#entries.delete(key);
      return this;
    }
    if (!this.#entries.has(key) && this.#entries.size >= this.#capacity) {
      throw new RangeError("capacity reached");
    }
    this.#entries.set(key, { value, expiresAt });
    return this;
  }

  lookup(key) {
    const t = this.#time();
    const entry = this.#entries.get(key);
    if (!entry) return { hit: false };
    if (t >= entry.expiresAt) {
      this.#entries.delete(key);
      return { hit: false };
    }
    return { hit: true, value: entry.value };
  }

  get(key) { return this.lookup(key).value; }
  has(key) { return this.lookup(key).hit; }
  prune() { return this.#pruneAt(this.#time()); }
  get size() { this.prune(); return this.#entries.size; }
  get storedSize() { return this.#entries.size; }
}

let t = 0;
const cache = new TTLCache({ now: () => t });
cache.set("a", 1, 5).set("b", 2, 5).set("live", 3, 20);
t = 5;
assert.equal(cache.storedSize, 3);
assert.equal(cache.has("unknown"), false);
assert.equal(cache.storedSize, 3);
assert.equal(cache.has("a"), false);
assert.equal(cache.storedSize, 2);
assert.equal(cache.size, 1);
assert.equal(cache.storedSize, 1);
t = 20;
assert.equal(cache.storedSize, 1);
assert.equal(cache.prune(), 1);
assert.equal(cache.prune(), 0);
assert.equal(cache.size, 0);
console.log("07 lazy pruning and size passed");

预期输出:

07 lazy pruning and size passed

八、容量保护不必偷偷变成 LRU

TTL 回答数据还能用多久,容量回答最多保留多少项,二者相互独立。本例容量满时拒绝新增键,既不删除最早插入项,也不因为刚读过某键就改变优先级。这能让文章聚焦时间语义,同时让调用方清楚知道写入可能失败。上游需要决定捕获错误后是绕过缓存、记录指标还是采取别的策略,不能把容量错误当作数据已经成功缓存。

写入先清理过期项,再判断容量,所以过期数据不会阻挡新键。覆盖已有有效键不增加计数,可以在满容量时进行;容量为零时仍接受零 TTL 的无保留操作。若新增因为容量不足失败,旧的有效项保持原样,不过此前清掉的过期项不会恢复。这里限制的是条目数量,不是堆内存字节;一个巨大对象或仍被外部引用的对象,足以打破任何把条目上限解释成内存硬上限的说法。

独立示例 8,文件名 case-08.mjs:

import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";

class TTLCache {
  #entries = new Map();
  #now;
  #last = -Infinity;
  #capacity;

  constructor({ now = () => performance.now(), capacity = 1000 } = {}) {
    if (typeof now !== "function") throw new TypeError("clock must be a function");
    if (!Number.isSafeInteger(capacity) || capacity < 0) {
      throw new RangeError("capacity must be a nonnegative safe integer");
    }
    this.#now = now;
    this.#capacity = capacity;
  }

  #time() {
    const t = this.#now();
    if (typeof t !== "number" || !Number.isFinite(t) || t < 0) {
      throw new TypeError("clock must return finite nonnegative milliseconds");
    }
    if (t < this.#last) throw new RangeError("clock moved backwards");
    this.#last = t;
    return t;
  }

  #pruneAt(t) {
    let removed = 0;
    for (const [key, entry] of this.#entries) {
      if (t >= entry.expiresAt) {
        this.#entries.delete(key);
        removed++;
      }
    }
    return removed;
  }

  set(key, value, ttl) {
    if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl < 0) {
      throw new RangeError("ttl must be finite nonnegative milliseconds");
    }
    const t = this.#time();
    const expiresAt = t + ttl;
    if (!Number.isFinite(expiresAt) || (ttl > 0 && expiresAt <= t)) {
      throw new RangeError("deadline is not representable");
    }
    this.#pruneAt(t);
    if (ttl === 0) {
      this.#entries.delete(key);
      return this;
    }
    if (!this.#entries.has(key) && this.#entries.size >= this.#capacity) {
      throw new RangeError("capacity reached");
    }
    this.#entries.set(key, { value, expiresAt });
    return this;
  }

  lookup(key) {
    const t = this.#time();
    const entry = this.#entries.get(key);
    if (!entry) return { hit: false };
    if (t >= entry.expiresAt) {
      this.#entries.delete(key);
      return { hit: false };
    }
    return { hit: true, value: entry.value };
  }

  get(key) { return this.lookup(key).value; }
  has(key) { return this.lookup(key).hit; }
  prune() { return this.#pruneAt(this.#time()); }
  get size() { this.prune(); return this.#entries.size; }
  get storedSize() { return this.#entries.size; }
}

let t = 0;
const cache = new TTLCache({ now: () => t, capacity: 2 });
cache.set("a", "A", 100).set("b", "B", 5);
assert.equal(cache.get("a"), "A");
assert.throws(() => cache.set("c", "C", 20), /capacity reached/);
assert.equal(cache.get("b"), "B");
assert.equal(cache.get("a"), "A");
cache.set("a", "A2", 100);
assert.equal(cache.size, 2);
t = 5;
cache.set("c", "C", 20);
assert.equal(cache.has("b"), false);
assert.equal(cache.get("a"), "A2");
assert.equal(cache.get("c"), "C");
assert.equal(cache.size, 2);
const zero = new TTLCache({ now: () => t, capacity: 0 });
assert.throws(() => zero.set("k", 1, 1), /capacity reached/);
zero.set("k", 1, 0);
assert.equal(zero.storedSize, 0);
for (const capacity of [-1, 1.5, NaN, Infinity, "2", 2 ** 53]) {
  assert.throws(() => new TTLCache({ capacity }), RangeError);
}
console.log("08 bounded admission passed");

预期输出:

08 bounded admission passed

九、用可复现操作序列检查组合行为

前八个用例各自锁住一个容易说错的细节,最后再让操作组合起来。参考模型使用普通数组,按当前时间筛出有效记录,容量只有三项;被测实现仍是前面相同的类。固定种子的整数生成器让键、TTL、时间推进和操作类型可重复,失败时可以记录步骤编号,不必追逐偶现的调度问题。这组参数还会触发十一次容量拒绝,代码显式断言该分支确实被走到。

这个模型只比较有效结果和容量策略,不要求两者具有相同的物理清理时机。我们还刻意不在每一步调用 size,避免每次都全量清理而掩盖懒清理路径。五百步是固定的回归样本,不是所有输入的证明;它无法覆盖恶意时钟、全部浮点值、共享内存并发或业务级一致性。先用小而明确的边界用例描述契约,再用组合序列找交互缺陷,比让 AI 无限制堆砌随机断言更容易审查。

独立示例 9,文件名 case-09.mjs:

import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";

class TTLCache {
  #entries = new Map();
  #now;
  #last = -Infinity;
  #capacity;

  constructor({ now = () => performance.now(), capacity = 1000 } = {}) {
    if (typeof now !== "function") throw new TypeError("clock must be a function");
    if (!Number.isSafeInteger(capacity) || capacity < 0) {
      throw new RangeError("capacity must be a nonnegative safe integer");
    }
    this.#now = now;
    this.#capacity = capacity;
  }

  #time() {
    const t = this.#now();
    if (typeof t !== "number" || !Number.isFinite(t) || t < 0) {
      throw new TypeError("clock must return finite nonnegative milliseconds");
    }
    if (t < this.#last) throw new RangeError("clock moved backwards");
    this.#last = t;
    return t;
  }

  #pruneAt(t) {
    let removed = 0;
    for (const [key, entry] of this.#entries) {
      if (t >= entry.expiresAt) {
        this.#entries.delete(key);
        removed++;
      }
    }
    return removed;
  }

  set(key, value, ttl) {
    if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl < 0) {
      throw new RangeError("ttl must be finite nonnegative milliseconds");
    }
    const t = this.#time();
    const expiresAt = t + ttl;
    if (!Number.isFinite(expiresAt) || (ttl > 0 && expiresAt <= t)) {
      throw new RangeError("deadline is not representable");
    }
    this.#pruneAt(t);
    if (ttl === 0) {
      this.#entries.delete(key);
      return this;
    }
    if (!this.#entries.has(key) && this.#entries.size >= this.#capacity) {
      throw new RangeError("capacity reached");
    }
    this.#entries.set(key, { value, expiresAt });
    return this;
  }

  lookup(key) {
    const t = this.#time();
    const entry = this.#entries.get(key);
    if (!entry) return { hit: false };
    if (t >= entry.expiresAt) {
      this.#entries.delete(key);
      return { hit: false };
    }
    return { hit: true, value: entry.value };
  }

  get(key) { return this.lookup(key).value; }
  has(key) { return this.lookup(key).hit; }
  prune() { return this.#pruneAt(this.#time()); }
  get size() { this.prune(); return this.#entries.size; }
  get storedSize() { return this.#entries.size; }
}

let t = 0;
let seed = 0x12345678;
const random = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0);
const cache = new TTLCache({ now: () => t, capacity: 3 });
let model = [];
let rejected = 0;
const lookupModel = key => {
  const entry = model.find(item => item.key === key && t < item.until);
  return entry ? { hit: true, value: entry.value } : { hit: false };
};
for (let step = 0; step < 500; step++) {
  t += (random() >>> 16) % 3;
  const key = `k${(random() >>> 16) % 5}`;
  const operation = (random() >>> 16) % 5;
  if (operation <= 1) {
    const ttl = (random() >>> 16) % 16;
    const value = step % 7 === 0 ? undefined : step;
    model = model.filter(item => t < item.until);
    const exists = model.some(item => item.key === key);
    if (ttl > 0 && !exists && model.length === 3) {
      rejected++;
      assert.throws(() => cache.set(key, value, ttl), /capacity reached/);
    } else {
      cache.set(key, value, ttl);
      model = model.filter(item => item.key !== key);
      if (ttl > 0) model.push({ key, value, until: t + ttl });
    }
  } else if (operation === 2) {
    assert.deepEqual(cache.lookup(key), lookupModel(key), `step ${step}`);
  } else if (operation === 3) {
    assert.equal(cache.has(key), lookupModel(key).hit, `step ${step}`);
  } else {
    const live = model.filter(item => t < item.until).length;
    assert.equal(cache.size, live, `step ${step}`);
  }
  assert.ok(cache.storedSize <= 3, `step ${step}`);
}
assert.equal(rejected, 11);
for (let i = 0; i < 5; i++) {
  assert.deepEqual(cache.lookup(`k${i}`), lookupModel(`k${i}`));
}
t += 20;
assert.equal(cache.size, 0);
console.log("09 deterministic model: 500 steps, 11 rejections passed");

预期输出:

09 deterministic model: 500 steps, 11 rejections passed

审阅 AI 代码时,最后再问四个问题

第一,是否把定时删除当成了有效性保证?Node.js 定时器文档明确指出回调的精确触发时间和顺序没有保证。因此,本例完全不创建定时器,正确性依赖访问时的截止比较。若以后增加后台清理,它也只能帮助回收记录,不能取代读取校验。本实现同样不承诺过期瞬间释放对象内存,删除引用之后何时回收仍不由这个容器控制。

第二,是否把一次进程内的时间坐标写到了磁盘或发送给另一台机器?本例没有持久化接口,缓存随进程结束消失,performance.now() 的截止值也不能直接跨重启恢复。若要支持离线恢复,需要单独定义持久化时间来源、停机期间是否消耗 TTL、时钟校正以及重放规则。不能只把 Map 转成 JSON 就宣布获得可靠持久化。

第三,是否在包装层重新制造了歧义?如果调用方先 has 再 get,两次调用各自采样,时间可能正好跨过截止点。需要状态和值一致时应使用一次 lookup。对于异步加载,过期后的多个并发请求还可能同时回源;本文没有单飞合并、取消、错误缓存或旧值回退协议,也没有为这些机制提供保证。

第四,是否把测试通过误认为业务契约已经正确?我们选择固定有效期、零值删除、拒绝容量溢出和懒清理,是为了让规则可以说明白。别的系统可以选择不同策略,但每一种选择都需要相应测试和调用方处理。最值得交给 AI 的任务,是依据已经确定的规则寻找反例、检查实现和生成可复现用例;最不该外包的决定,是在没有讨论的情况下让它自行发明过期语义。

回看这九个检查,核心没有复杂算法:一次受验证的时间采样,一份固定截止记录,一次明确的命中判断。它们把边界从调度运气中拿出来,变成能执行、能解释、能在改动后重新验证的契约。这样的审计结果,才比一段看似精简的缓存代码更有长期价值。

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