AI 生成的撤销重做能直接上线吗?用九组状态机测试审查有界历史

10-19 5阅读

AI 很容易写出两个能运行的 undo 和 redo 函数,难的是证明它们在分支、空提交、容量淘汰与异常之后仍然正确。本文从代码评审角度拆解一份有界历史实现,并用九个独立 Node.js 示例建立可执行的验收合同。

AI 生成的撤销重做能直接上线吗?用九组状态机测试审查有界历史
AI 生成概念图:快照、当前状态、被放弃的未来与分组检查点。画面用于解释概念,并非真实软件截图。

一、先审合同,再审两个按钮

审查 AI 辅助生成的撤销重做代码,我通常先把演示页面关掉。按钮变灰、快捷键有反应,只能说明界面接上了函数,不能说明历史是正确的。一份实现即使顺利走完零到一再回到零,也可能在第二次修改、撤销后的新提交,或者容量刚好为一时丢失数据。本文把这种代码当作待验收草稿,用可重复运行的状态机测试讨论它是否满足约定,不给未经验证的生成结果打分。

这次约定很具体:历史是过去、现在、未来三部分;容量计算三部分的快照总数,包含现在;成功的新提交截断未来;内容相等的提交不占位置,也不清空未来;没有可撤销或可重做的状态时返回假值。提交、撤销、重做返回布尔值,读取返回独立副本。异常必须保持整份历史不变,不能只保住眼前的值却偷偷破坏后续重做。

下面九个代码块都可以单独保存为一个 .mjs 文件执行,不需要拼接前文、不安装依赖。运行方式是 node --unhandled-rejections=strict 文件名.mjs;本文实际使用 Node.js v24.19.0 验证。重复列出核心实现,是为了让每个反例都能独立复现。核心采用私有闭包保存快照,接口只给出副本和数量,不把内部数组交出去。示例一首先检查最短闭环及两端边界。

import assert from 'node:assert/strict';
import { isDeepStrictEqual } from 'node:util';

function history(initial, capacity = 8, copy = structuredClone) {
  if (!Number.isSafeInteger(capacity) || capacity < 1) {
    throw new RangeError('capacity must be a positive safe integer');
  }
  // Pure data only. Inspect descriptors instead of running getters.
  function validate(value, seen = new WeakSet()) {
    if (value === null || typeof value === 'string' ||
        typeof value === 'boolean') return;
    if (typeof value === 'number' && Number.isFinite(value)) return;
    if (typeof value !== 'object') throw new TypeError('data only');
    const proto = Object.getPrototypeOf(value);
    if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
      throw new TypeError('plain objects and arrays only');
    }
    if (seen.has(value)) return;
    seen.add(value);
    for (const key of Reflect.ownKeys(value)) {
      if (Array.isArray(value) && key === 'length') continue;
      const d = Object.getOwnPropertyDescriptor(value, key);
      if (typeof key !== 'string' || !d.enumerable || !('value' in d)) {
        throw new TypeError('enumerable data properties only');
      }
      validate(d.value, seen);
    }
  }
  function snapshot(value) { validate(value); return copy(value); }
  let state = { past: [], present: snapshot(initial), future: [] };
  let busy = false;
  function guarded(fn) {
    if (busy) throw new Error('reentrant history access');
    busy = true;
    try { return fn(); } finally { busy = false; }
  }
  const trim = values => capacity === 1 ? [] : values.slice(-(capacity - 1));
  return {
    read: () => guarded(() => snapshot(state.present)),
    info: () => ({ past: state.past.length, future: state.future.length,
      size: state.past.length + 1 + state.future.length }),
    commit: value => guarded(() => {
      const next = snapshot(value);
      if (isDeepStrictEqual(next, state.present)) return false;
      const past = trim([...state.past, state.present]);
      state = { past, present: next, future: [] };
      return true;
    }),
    undo: () => guarded(() => {
      if (!state.past.length) return false;
      const { past, present, future } = state;
      state = { past: past.slice(0, -1), present: past.at(-1),
        future: [present, ...future] };
      return true;
    }),
    redo: () => guarded(() => {
      if (!state.future.length) return false;
      const { past, present, future } = state;
      state = { past: [...past, present], present: future[0],
        future: future.slice(1) };
      return true;
    })
  };
}

const h = history(0, 4);
assert.equal(h.undo(), false);
assert.equal(h.redo(), false);
assert.equal(h.commit(1), true);
assert.equal(h.commit(2), true);
assert.deepEqual(h.info(), { past: 2, future: 0, size: 3 });
assert.equal(h.undo(), true);
assert.equal(h.read(), 1);
assert.equal(h.redo(), true);
assert.equal(h.read(), 2);
assert.equal(h.redo(), false);
console.log('round trip: ok');

运行输出:

round trip: ok

二、不可变快照是一条所有权边界

看到展开运算符或数组切片,不能立刻认定快照已经不可变。它们可能只复制外层容器,内部卡片对象仍被多个版本共享。更隐蔽的泄漏来自读取接口:写入时深拷贝,读取时却直接返回当前对象,调用者下一行修改标题就绕过了提交。测试必须同时覆盖初始输入、后续提交参数、读取结果这三个入口,不能只测试其中一个。

本实现的不可变,是内部快照从不被业务代码继续修改,并不要求调用者拿到一个冻结对象。读取的副本允许修改,修改完成后再提交;内部快照不会因这份副本变化而改变。示例二故意修改三类外部引用,再穿过撤销和重做,检查过去与现在都没被污染。这比只断言两个顶层对象不相等更接近真实风险。

数据范围也要明确:这里只接收空值、字符串、布尔值、有限数值,以及由它们组成的普通对象和数组,允许这种数据图中的循环引用。访问器、符号属性、不可枚举业务属性、函数、日期对象和共享内存不在合同内。空原型对象经原生克隆后按普通对象处理。限制并非 JavaScript 的能力上限,而是这份教程主动收窄的产品边界。

import assert from 'node:assert/strict';
import { isDeepStrictEqual } from 'node:util';

function history(initial, capacity = 8, copy = structuredClone) {
  if (!Number.isSafeInteger(capacity) || capacity < 1) {
    throw new RangeError('capacity must be a positive safe integer');
  }
  // Pure data only. Inspect descriptors instead of running getters.
  function validate(value, seen = new WeakSet()) {
    if (value === null || typeof value === 'string' ||
        typeof value === 'boolean') return;
    if (typeof value === 'number' && Number.isFinite(value)) return;
    if (typeof value !== 'object') throw new TypeError('data only');
    const proto = Object.getPrototypeOf(value);
    if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
      throw new TypeError('plain objects and arrays only');
    }
    if (seen.has(value)) return;
    seen.add(value);
    for (const key of Reflect.ownKeys(value)) {
      if (Array.isArray(value) && key === 'length') continue;
      const d = Object.getOwnPropertyDescriptor(value, key);
      if (typeof key !== 'string' || !d.enumerable || !('value' in d)) {
        throw new TypeError('enumerable data properties only');
      }
      validate(d.value, seen);
    }
  }
  function snapshot(value) { validate(value); return copy(value); }
  let state = { past: [], present: snapshot(initial), future: [] };
  let busy = false;
  function guarded(fn) {
    if (busy) throw new Error('reentrant history access');
    busy = true;
    try { return fn(); } finally { busy = false; }
  }
  const trim = values => capacity === 1 ? [] : values.slice(-(capacity - 1));
  return {
    read: () => guarded(() => snapshot(state.present)),
    info: () => ({ past: state.past.length, future: state.future.length,
      size: state.past.length + 1 + state.future.length }),
    commit: value => guarded(() => {
      const next = snapshot(value);
      if (isDeepStrictEqual(next, state.present)) return false;
      const past = trim([...state.past, state.present]);
      state = { past, present: next, future: [] };
      return true;
    }),
    undo: () => guarded(() => {
      if (!state.past.length) return false;
      const { past, present, future } = state;
      state = { past: past.slice(0, -1), present: past.at(-1),
        future: [present, ...future] };
      return true;
    }),
    redo: () => guarded(() => {
      if (!state.future.length) return false;
      const { past, present, future } = state;
      state = { past: [...past, present], present: future[0],
        future: future.slice(1) };
      return true;
    })
  };
}

const input = { card: { text: 'A' }, tags: ['draft'] };
const h = history(input, 4);
input.card.text = 'outside';
assert.equal(h.read().card.text, 'A');
const next = h.read();
next.card.text = 'B';
assert.equal(h.commit(next), true);
next.tags.push('outside');
const view = h.read();
view.card.text = 'leaked?';
view.tags.length = 0;
assert.deepEqual(h.read(), { card: { text: 'B' }, tags: ['draft'] });
h.undo();
assert.deepEqual(h.read(), { card: { text: 'A' }, tags: ['draft'] });
h.redo();
assert.equal(h.read().card.text, 'B');
console.log('snapshot isolation: ok');

运行输出:

snapshot isolation: ok

三、新分支必须让旧未来失效

最容易漏掉的路径是先连续提交几次,再撤销两次,最后写入一个新值。此时旧未来属于另一条编辑路线,不能再由重做按钮复活。否则用户刚改完的内容可能被一段已经放弃的历史覆盖。这里保留的是线性编辑历史,不是可以切换多条支线的版本管理系统;如果产品需要分支浏览,数据结构与交互合同都应另行设计。

示例三把零、一、二、三回退到一,再提交九。新的过去应保留零和一,未来归零;继续往返,只会沿零、一、九移动。评审时还要看截断发生在什么位置:必须等候选快照准备成功、确认为有效新状态以后再做。先清空未来再尝试复制,失败时就会留下一个看似没改内容、实际已经丢了重做记录的半成品。

import assert from 'node:assert/strict';
import { isDeepStrictEqual } from 'node:util';

function history(initial, capacity = 8, copy = structuredClone) {
  if (!Number.isSafeInteger(capacity) || capacity < 1) {
    throw new RangeError('capacity must be a positive safe integer');
  }
  // Pure data only. Inspect descriptors instead of running getters.
  function validate(value, seen = new WeakSet()) {
    if (value === null || typeof value === 'string' ||
        typeof value === 'boolean') return;
    if (typeof value === 'number' && Number.isFinite(value)) return;
    if (typeof value !== 'object') throw new TypeError('data only');
    const proto = Object.getPrototypeOf(value);
    if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
      throw new TypeError('plain objects and arrays only');
    }
    if (seen.has(value)) return;
    seen.add(value);
    for (const key of Reflect.ownKeys(value)) {
      if (Array.isArray(value) && key === 'length') continue;
      const d = Object.getOwnPropertyDescriptor(value, key);
      if (typeof key !== 'string' || !d.enumerable || !('value' in d)) {
        throw new TypeError('enumerable data properties only');
      }
      validate(d.value, seen);
    }
  }
  function snapshot(value) { validate(value); return copy(value); }
  let state = { past: [], present: snapshot(initial), future: [] };
  let busy = false;
  function guarded(fn) {
    if (busy) throw new Error('reentrant history access');
    busy = true;
    try { return fn(); } finally { busy = false; }
  }
  const trim = values => capacity === 1 ? [] : values.slice(-(capacity - 1));
  return {
    read: () => guarded(() => snapshot(state.present)),
    info: () => ({ past: state.past.length, future: state.future.length,
      size: state.past.length + 1 + state.future.length }),
    commit: value => guarded(() => {
      const next = snapshot(value);
      if (isDeepStrictEqual(next, state.present)) return false;
      const past = trim([...state.past, state.present]);
      state = { past, present: next, future: [] };
      return true;
    }),
    undo: () => guarded(() => {
      if (!state.past.length) return false;
      const { past, present, future } = state;
      state = { past: past.slice(0, -1), present: past.at(-1),
        future: [present, ...future] };
      return true;
    }),
    redo: () => guarded(() => {
      if (!state.future.length) return false;
      const { past, present, future } = state;
      state = { past: [...past, present], present: future[0],
        future: future.slice(1) };
      return true;
    })
  };
}

const h = history(0, 5);
for (const n of [1, 2, 3]) h.commit(n);
h.undo();
h.undo();
assert.equal(h.read(), 1);
assert.deepEqual(h.info(), { past: 1, future: 2, size: 4 });
h.commit(9);
assert.deepEqual(h.info(), { past: 2, future: 0, size: 3 });
assert.equal(h.redo(), false);
h.undo();
assert.equal(h.read(), 1);
h.undo();
assert.equal(h.read(), 0);
h.redo();
h.redo();
assert.equal(h.read(), 9);
console.log('new branch discards old future: ok');

运行输出:

new branch discards old future: ok

四、无变化提交不能吃掉一次撤销

空提交不是无关紧要的性能优化。表单重复保存、自动格式化没有改变结果、拖拽回到原位,都可能触发一次提交请求。若每次请求都追加快照,用户需要按多次撤销才看到变化;若在判等之前先清空未来,撤销后的原样保存还会把重做入口抹掉。因此本实现把内容相等视为真正的无操作,返回假值,过去和未来都保持原样。

这里使用 Node.js 的深严格相等语义,不使用对象引用相等,也不把 JSON 字符串相等当通用判据。示例四特意调换对象属性插入顺序,证明测试针对结构内容,而不是序列化文本。相等规则本身仍是业务决策:负零与正零等边界依照所选比较器处理;循环数据的比较也继承该工具语义。深严格相等不是引用拓扑一致性的证明;若共享子对象的关系本身具有业务含义,必须另行制定比较规则。若领域只关注部分字段,应先明确投影合同,不能临时忽略字段来让测试变绿。

import assert from 'node:assert/strict';
import { isDeepStrictEqual } from 'node:util';

function history(initial, capacity = 8, copy = structuredClone) {
  if (!Number.isSafeInteger(capacity) || capacity < 1) {
    throw new RangeError('capacity must be a positive safe integer');
  }
  // Pure data only. Inspect descriptors instead of running getters.
  function validate(value, seen = new WeakSet()) {
    if (value === null || typeof value === 'string' ||
        typeof value === 'boolean') return;
    if (typeof value === 'number' && Number.isFinite(value)) return;
    if (typeof value !== 'object') throw new TypeError('data only');
    const proto = Object.getPrototypeOf(value);
    if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
      throw new TypeError('plain objects and arrays only');
    }
    if (seen.has(value)) return;
    seen.add(value);
    for (const key of Reflect.ownKeys(value)) {
      if (Array.isArray(value) && key === 'length') continue;
      const d = Object.getOwnPropertyDescriptor(value, key);
      if (typeof key !== 'string' || !d.enumerable || !('value' in d)) {
        throw new TypeError('enumerable data properties only');
      }
      validate(d.value, seen);
    }
  }
  function snapshot(value) { validate(value); return copy(value); }
  let state = { past: [], present: snapshot(initial), future: [] };
  let busy = false;
  function guarded(fn) {
    if (busy) throw new Error('reentrant history access');
    busy = true;
    try { return fn(); } finally { busy = false; }
  }
  const trim = values => capacity === 1 ? [] : values.slice(-(capacity - 1));
  return {
    read: () => guarded(() => snapshot(state.present)),
    info: () => ({ past: state.past.length, future: state.future.length,
      size: state.past.length + 1 + state.future.length }),
    commit: value => guarded(() => {
      const next = snapshot(value);
      if (isDeepStrictEqual(next, state.present)) return false;
      const past = trim([...state.past, state.present]);
      state = { past, present: next, future: [] };
      return true;
    }),
    undo: () => guarded(() => {
      if (!state.past.length) return false;
      const { past, present, future } = state;
      state = { past: past.slice(0, -1), present: past.at(-1),
        future: [present, ...future] };
      return true;
    }),
    redo: () => guarded(() => {
      if (!state.future.length) return false;
      const { past, present, future } = state;
      state = { past: [...past, present], present: future[0],
        future: future.slice(1) };
      return true;
    })
  };
}

const h = history({ x: 0, y: 0 }, 3);
h.commit({ x: 1, y: 2 });
h.undo();
const before = h.info();
assert.equal(h.commit({ y: 0, x: 0 }), false);
assert.deepEqual(h.info(), before);
assert.equal(h.redo(), true);
assert.deepEqual(h.read(), { x: 1, y: 2 });
for (let i = 0; i < 20; i++) assert.equal(h.commit(h.read()), false);
assert.deepEqual(h.info(), { past: 1, future: 0, size: 2 });
h.undo();
assert.deepEqual(h.read(), { x: 0, y: 0 });
console.log('no-op keeps history and redo: ok');

运行输出:

no-op keeps history and redo: ok

五、有界到底限制什么,要把一写进测试

所谓保留三条历史,可能指三次可撤销操作,也可能指包含当前值的三份状态。这两个解释会差一,用户体感和内存预算都会不同。本文选择后者:过去长度加一再加未来长度,始终不超过容量。撤销和重做只移动位置,不额外制造快照;真正提交时才截断未来、追加旧现在,并从最早的过去开始淘汰。

容量为一是很好的审查探针。此时仍然能修改当前值,但没有任何历史可撤销。常见写法用负零进行数组切片,结果却保留了整个数组;核心里的显式分支就是为避免这种边界错误。示例五既检查一,也检查三以及非法容量。已经淘汰的快照不能凭空恢复,历史容量不是审计留存保证,更不是数据库备份。

还有一个不能藏在命名里的成本:数量有界不等于字节有界。一个状态可能包含很大的文本或数组,提交过程还会暂时同时持有输入、候选副本和旧快照。此实现偏重语义清楚,提交还要做验证、克隆、比较与数组复制;大型画布或长文档应另测延迟和峰值内存,必要时改用补丁、结构共享或分层快照,但必须保留同一套状态机合同。

import assert from 'node:assert/strict';
import { isDeepStrictEqual } from 'node:util';

function history(initial, capacity = 8, copy = structuredClone) {
  if (!Number.isSafeInteger(capacity) || capacity < 1) {
    throw new RangeError('capacity must be a positive safe integer');
  }
  // Pure data only. Inspect descriptors instead of running getters.
  function validate(value, seen = new WeakSet()) {
    if (value === null || typeof value === 'string' ||
        typeof value === 'boolean') return;
    if (typeof value === 'number' && Number.isFinite(value)) return;
    if (typeof value !== 'object') throw new TypeError('data only');
    const proto = Object.getPrototypeOf(value);
    if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
      throw new TypeError('plain objects and arrays only');
    }
    if (seen.has(value)) return;
    seen.add(value);
    for (const key of Reflect.ownKeys(value)) {
      if (Array.isArray(value) && key === 'length') continue;
      const d = Object.getOwnPropertyDescriptor(value, key);
      if (typeof key !== 'string' || !d.enumerable || !('value' in d)) {
        throw new TypeError('enumerable data properties only');
      }
      validate(d.value, seen);
    }
  }
  function snapshot(value) { validate(value); return copy(value); }
  let state = { past: [], present: snapshot(initial), future: [] };
  let busy = false;
  function guarded(fn) {
    if (busy) throw new Error('reentrant history access');
    busy = true;
    try { return fn(); } finally { busy = false; }
  }
  const trim = values => capacity === 1 ? [] : values.slice(-(capacity - 1));
  return {
    read: () => guarded(() => snapshot(state.present)),
    info: () => ({ past: state.past.length, future: state.future.length,
      size: state.past.length + 1 + state.future.length }),
    commit: value => guarded(() => {
      const next = snapshot(value);
      if (isDeepStrictEqual(next, state.present)) return false;
      const past = trim([...state.past, state.present]);
      state = { past, present: next, future: [] };
      return true;
    }),
    undo: () => guarded(() => {
      if (!state.past.length) return false;
      const { past, present, future } = state;
      state = { past: past.slice(0, -1), present: past.at(-1),
        future: [present, ...future] };
      return true;
    }),
    redo: () => guarded(() => {
      if (!state.future.length) return false;
      const { past, present, future } = state;
      state = { past: [...past, present], present: future[0],
        future: future.slice(1) };
      return true;
    })
  };
}

for (const bad of [0, -1, 1.5, Infinity, NaN, '3']) {
  assert.throws(() => history(0, bad), RangeError);
}
const one = history(0, 1);
one.commit(1);
one.commit(2);
assert.equal(one.read(), 2);
assert.deepEqual(one.info(), { past: 0, future: 0, size: 1 });
assert.equal(one.undo(), false);
const h = history(0, 3);
for (const n of [1, 2, 3, 4]) h.commit(n);
assert.equal(h.info().size, 3);
h.undo();
h.undo();
assert.equal(h.read(), 2);
assert.equal(h.undo(), false);
assert.deepEqual(h.info(), { past: 0, future: 2, size: 3 });
h.redo();
h.redo();
assert.equal(h.read(), 4);
assert.equal(h.info().size, 3);
console.log('capacity includes present: ok');

运行输出:

capacity includes present: ok

六、事务分组从一个明确的检查点开始

一次用户动作常常改多个字段,例如移动图形同时更新横坐标、纵坐标和选中状态。若每个赋值都提交一次,撤销就会把一个完整动作拆成数个碎片。本例采用显式检查点语义:先读取独立草稿,在草稿上完成所有同步修改与验证,最后只调用一次提交。提交前,历史看不到中间状态;提交后,整组修改占用一个位置。

示例六让三个字段共同前进,也共同后退,并让一次校验异常发生在检查点之前。丢弃草稿就足够了,不需要向历史写入补偿状态。草稿最终回到原值时,提交依然是无操作。这种设计很小,却把分组边界交给了调用者,不依赖模糊的时间窗口猜测哪些输入应该合并。

这里的原子性只覆盖内存历史,不会撤销网络请求、文件写入或第三方副作用。示例没有开放异步事务,也没有声称解决并发草稿冲突。如果读取草稿后跨越异步等待,再覆盖期间已经变化的状态,就需要版本号及比较后提交机制;那是另一份接口合同。在当前同步流程里,保持检查点之前无外部副作用,才有资格说失败可以直接放弃。

import assert from 'node:assert/strict';
import { isDeepStrictEqual } from 'node:util';

function history(initial, capacity = 8, copy = structuredClone) {
  if (!Number.isSafeInteger(capacity) || capacity < 1) {
    throw new RangeError('capacity must be a positive safe integer');
  }
  // Pure data only. Inspect descriptors instead of running getters.
  function validate(value, seen = new WeakSet()) {
    if (value === null || typeof value === 'string' ||
        typeof value === 'boolean') return;
    if (typeof value === 'number' && Number.isFinite(value)) return;
    if (typeof value !== 'object') throw new TypeError('data only');
    const proto = Object.getPrototypeOf(value);
    if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
      throw new TypeError('plain objects and arrays only');
    }
    if (seen.has(value)) return;
    seen.add(value);
    for (const key of Reflect.ownKeys(value)) {
      if (Array.isArray(value) && key === 'length') continue;
      const d = Object.getOwnPropertyDescriptor(value, key);
      if (typeof key !== 'string' || !d.enumerable || !('value' in d)) {
        throw new TypeError('enumerable data properties only');
      }
      validate(d.value, seen);
    }
  }
  function snapshot(value) { validate(value); return copy(value); }
  let state = { past: [], present: snapshot(initial), future: [] };
  let busy = false;
  function guarded(fn) {
    if (busy) throw new Error('reentrant history access');
    busy = true;
    try { return fn(); } finally { busy = false; }
  }
  const trim = values => capacity === 1 ? [] : values.slice(-(capacity - 1));
  return {
    read: () => guarded(() => snapshot(state.present)),
    info: () => ({ past: state.past.length, future: state.future.length,
      size: state.past.length + 1 + state.future.length }),
    commit: value => guarded(() => {
      const next = snapshot(value);
      if (isDeepStrictEqual(next, state.present)) return false;
      const past = trim([...state.past, state.present]);
      state = { past, present: next, future: [] };
      return true;
    }),
    undo: () => guarded(() => {
      if (!state.past.length) return false;
      const { past, present, future } = state;
      state = { past: past.slice(0, -1), present: past.at(-1),
        future: [present, ...future] };
      return true;
    }),
    redo: () => guarded(() => {
      if (!state.future.length) return false;
      const { past, present, future } = state;
      state = { past: [...past, present], present: future[0],
        future: future.slice(1) };
      return true;
    })
  };
}

const h = history({ x: 0, y: 0, selected: false }, 4);
const draft = h.read();
draft.x = 10;
draft.y = 20;
draft.selected = true;
assert.deepEqual(h.read(), { x: 0, y: 0, selected: false });
h.commit(draft);
assert.equal(h.info().past, 1);
h.undo();
assert.deepEqual(h.read(), { x: 0, y: 0, selected: false });
h.redo();
const saved = h.read();
assert.throws(() => {
  const abandoned = h.read();
  abandoned.x = 999;
  throw new Error('validation failed before checkpoint');
}, /validation failed/);
assert.deepEqual(h.read(), saved);
assert.equal(h.info().past, 1);
const reverted = h.read();
reverted.x = 42;
reverted.x = 10;
assert.equal(h.commit(reverted), false);
console.log('one checkpoint, one undo: ok');

运行输出:

one checkpoint, one undo: ok

七、克隆失败必须连未来一起保住

成功路径上先修改数组再复制内容,肉眼通常看不出问题。异常路径却会暴露顺序:验证和克隆都必须发生在发布新历史之前。核心先构建候选快照,再比较内容,再构造新记录,最后用一次赋值替换历史记录。只要前面的步骤抛出异常,旧记录仍然完整。撤销和重做只重排已经受控的内部快照,不会在移动到一半时额外克隆。

示例七提供的是显式故障注入:第三个参数仅用于测试,默认仍是原生 structuredClone;注入器在开关开启时抛出带有 DataCloneError 名称的异常。它并非声称某个合法小对象会自然触发这种错误。测试从仍有未来记录的位置发起失败提交,随后检查数量、当前值和重做结果;还检查读取失败不移动游标,以及故障解除后仍可继续提交。

复制依赖属于受信任的测试接缝,必须同步、正确地返回隔离副本;不能在生产环境随意替换为返回原引用的函数,更不能传入异步函数。如果没有故障注入需求,可以固定使用原生克隆并删除第三个参数。正常业务输入中的函数会先被数据验证拒绝,本例因此另外断言验证失败也不改变历史。失败的具体异常种类可以不同,历史原子性不能不同。

import assert from 'node:assert/strict';
import { isDeepStrictEqual } from 'node:util';

function history(initial, capacity = 8, copy = structuredClone) {
  if (!Number.isSafeInteger(capacity) || capacity < 1) {
    throw new RangeError('capacity must be a positive safe integer');
  }
  // Pure data only. Inspect descriptors instead of running getters.
  function validate(value, seen = new WeakSet()) {
    if (value === null || typeof value === 'string' ||
        typeof value === 'boolean') return;
    if (typeof value === 'number' && Number.isFinite(value)) return;
    if (typeof value !== 'object') throw new TypeError('data only');
    const proto = Object.getPrototypeOf(value);
    if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
      throw new TypeError('plain objects and arrays only');
    }
    if (seen.has(value)) return;
    seen.add(value);
    for (const key of Reflect.ownKeys(value)) {
      if (Array.isArray(value) && key === 'length') continue;
      const d = Object.getOwnPropertyDescriptor(value, key);
      if (typeof key !== 'string' || !d.enumerable || !('value' in d)) {
        throw new TypeError('enumerable data properties only');
      }
      validate(d.value, seen);
    }
  }
  function snapshot(value) { validate(value); return copy(value); }
  let state = { past: [], present: snapshot(initial), future: [] };
  let busy = false;
  function guarded(fn) {
    if (busy) throw new Error('reentrant history access');
    busy = true;
    try { return fn(); } finally { busy = false; }
  }
  const trim = values => capacity === 1 ? [] : values.slice(-(capacity - 1));
  return {
    read: () => guarded(() => snapshot(state.present)),
    info: () => ({ past: state.past.length, future: state.future.length,
      size: state.past.length + 1 + state.future.length }),
    commit: value => guarded(() => {
      const next = snapshot(value);
      if (isDeepStrictEqual(next, state.present)) return false;
      const past = trim([...state.past, state.present]);
      state = { past, present: next, future: [] };
      return true;
    }),
    undo: () => guarded(() => {
      if (!state.past.length) return false;
      const { past, present, future } = state;
      state = { past: past.slice(0, -1), present: past.at(-1),
        future: [present, ...future] };
      return true;
    }),
    redo: () => guarded(() => {
      if (!state.future.length) return false;
      const { past, present, future } = state;
      state = { past: [...past, present], present: future[0],
        future: future.slice(1) };
      return true;
    })
  };
}

let fail = false;
const copy = value => {
  if (fail) throw new DOMException('injected clone failure', 'DataCloneError');
  return structuredClone(value);
};
const h = history(0, 3, copy);
h.commit(1);
h.commit(2);
h.undo();
const before = h.info();
fail = true;
assert.throws(() => h.commit(9), { name: 'DataCloneError' });
assert.deepEqual(h.info(), before);
assert.throws(() => h.read(), { name: 'DataCloneError' });
assert.deepEqual(h.info(), before);
fail = false;
assert.equal(h.read(), 1);
assert.equal(h.redo(), true);
assert.equal(h.read(), 2);
assert.throws(() => h.commit({ callback() {} }), TypeError);
assert.equal(h.read(), 2);
assert.equal(h.commit(3), true);
assert.deepEqual(h.info(), { past: 2, future: 0, size: 3 });
console.log('clone failure leaves history intact: ok');

运行输出:

clone failure leaves history intact: ok

八、拒绝不支持的数据,也要避免二次进入

深拷贝并不自动构成数据安全边界。例如共享内存能够让不同对象观察到同一块可变内容,访问器又可能在读取属性时执行任意逻辑。示例八先通过属性描述符检查数据,不调用访问器,再验证若干不在合同内的类型。对于没有执行成功的提交,外部应该能得到异常,也应该能继续读取原来的历史。这里不试图把代理对象或恶意宿主对象包装成可信数据;那类来源需要更前置的解析和验证。

虽然核心是同步的,注入的测试复制器仍可能回调同一份历史,造成提交期间再次撤销。忙碌标记的作用是拒绝这种重入,且用 finally 保证异常之后解除标记。示例八故意制造重入,再验证正常提交仍能恢复。这个标记不是线程锁,也不会替你处理跨进程一致性;它只把单次同步操作的入口边界讲清楚,避免失败后历史永远处于不可用状态。

import assert from 'node:assert/strict';
import { isDeepStrictEqual } from 'node:util';

function history(initial, capacity = 8, copy = structuredClone) {
  if (!Number.isSafeInteger(capacity) || capacity < 1) {
    throw new RangeError('capacity must be a positive safe integer');
  }
  // Pure data only. Inspect descriptors instead of running getters.
  function validate(value, seen = new WeakSet()) {
    if (value === null || typeof value === 'string' ||
        typeof value === 'boolean') return;
    if (typeof value === 'number' && Number.isFinite(value)) return;
    if (typeof value !== 'object') throw new TypeError('data only');
    const proto = Object.getPrototypeOf(value);
    if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
      throw new TypeError('plain objects and arrays only');
    }
    if (seen.has(value)) return;
    seen.add(value);
    for (const key of Reflect.ownKeys(value)) {
      if (Array.isArray(value) && key === 'length') continue;
      const d = Object.getOwnPropertyDescriptor(value, key);
      if (typeof key !== 'string' || !d.enumerable || !('value' in d)) {
        throw new TypeError('enumerable data properties only');
      }
      validate(d.value, seen);
    }
  }
  function snapshot(value) { validate(value); return copy(value); }
  let state = { past: [], present: snapshot(initial), future: [] };
  let busy = false;
  function guarded(fn) {
    if (busy) throw new Error('reentrant history access');
    busy = true;
    try { return fn(); } finally { busy = false; }
  }
  const trim = values => capacity === 1 ? [] : values.slice(-(capacity - 1));
  return {
    read: () => guarded(() => snapshot(state.present)),
    info: () => ({ past: state.past.length, future: state.future.length,
      size: state.past.length + 1 + state.future.length }),
    commit: value => guarded(() => {
      const next = snapshot(value);
      if (isDeepStrictEqual(next, state.present)) return false;
      const past = trim([...state.past, state.present]);
      state = { past, present: next, future: [] };
      return true;
    }),
    undo: () => guarded(() => {
      if (!state.past.length) return false;
      const { past, present, future } = state;
      state = { past: past.slice(0, -1), present: past.at(-1),
        future: [present, ...future] };
      return true;
    }),
    redo: () => guarded(() => {
      if (!state.future.length) return false;
      const { past, present, future } = state;
      state = { past: [...past, present], present: future[0],
        future: future.slice(1) };
      return true;
    })
  };
}

let getterCalls = 0;
const h = history({ n: 0 });
const accessor = { get n() { getterCalls++; return 1; } };
assert.throws(() => h.commit(accessor), TypeError);
assert.equal(getterCalls, 0);
for (const bad of [new Date(), new Map(), new SharedArrayBuffer(8),
  { n: undefined }, { n: NaN }, { [Symbol('x')]: 1 }]) {
  assert.throws(() => h.commit(bad), TypeError);
}
assert.deepEqual(h.read(), { n: 0 });
assert.equal(h.info().size, 1);
let target;
let attack = false;
const copy = value => {
  if (attack) target.undo();
  return structuredClone(value);
};
target = history(0, 3, copy);
target.commit(1);
const before = target.info();
attack = true;
assert.throws(() => target.commit(2), /reentrant/);
assert.deepEqual(target.info(), before);
attack = false;
assert.equal(target.read(), 1);
assert.equal(target.commit(2), true);
console.log('input boundary and reentrancy: ok');

运行输出:

input boundary and reentrancy: ok

九、用另一种模型审状态机,不复制实现当答案

前八个例子覆盖了人能想到的重要路径,但排列组合很快就超过手写用例。最后用一条状态数组加一个游标写参考模型,与正式实现的过去、现在、未来三个区域形成结构上的差异。伪随机种子固定,五种容量各运行两千四百次操作,每一步同时核对返回值、当前值、两端数量以及总容量,合计一万两千次转换。失败可以定位到具体步数并重放。

这类测试也有边界:随机遍历通过不等于数学证明,参考模型若抄错合同也会一起错。因而容量一、分支截断、空提交与克隆失败仍保留为明确的确定性断言;随机模型负责把它们组合起来,不替代它们。若把代码交回 AI 修改,我会要求保留这组测试,先说明哪条合同需要改变,再讨论实现方案,避免模型仅修改期望值来迎合错误结果。

最终验收的对象应是行为证据,而不是几行看起来优雅的代码。快照所有权、容量定义、检查点边界、失败原子性和分支规则都写清楚以后,AI 可以帮助枚举用例、解释差异或重构实现;人仍要决定这些语义是否符合产品。撤销重做真正值得信任的时刻,是在不顺手的操作顺序与失败路径下,用户仍然找得到自己以为保留着的那份状态。

import assert from 'node:assert/strict';
import { isDeepStrictEqual } from 'node:util';

function history(initial, capacity = 8, copy = structuredClone) {
  if (!Number.isSafeInteger(capacity) || capacity < 1) {
    throw new RangeError('capacity must be a positive safe integer');
  }
  // Pure data only. Inspect descriptors instead of running getters.
  function validate(value, seen = new WeakSet()) {
    if (value === null || typeof value === 'string' ||
        typeof value === 'boolean') return;
    if (typeof value === 'number' && Number.isFinite(value)) return;
    if (typeof value !== 'object') throw new TypeError('data only');
    const proto = Object.getPrototypeOf(value);
    if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
      throw new TypeError('plain objects and arrays only');
    }
    if (seen.has(value)) return;
    seen.add(value);
    for (const key of Reflect.ownKeys(value)) {
      if (Array.isArray(value) && key === 'length') continue;
      const d = Object.getOwnPropertyDescriptor(value, key);
      if (typeof key !== 'string' || !d.enumerable || !('value' in d)) {
        throw new TypeError('enumerable data properties only');
      }
      validate(d.value, seen);
    }
  }
  function snapshot(value) { validate(value); return copy(value); }
  let state = { past: [], present: snapshot(initial), future: [] };
  let busy = false;
  function guarded(fn) {
    if (busy) throw new Error('reentrant history access');
    busy = true;
    try { return fn(); } finally { busy = false; }
  }
  const trim = values => capacity === 1 ? [] : values.slice(-(capacity - 1));
  return {
    read: () => guarded(() => snapshot(state.present)),
    info: () => ({ past: state.past.length, future: state.future.length,
      size: state.past.length + 1 + state.future.length }),
    commit: value => guarded(() => {
      const next = snapshot(value);
      if (isDeepStrictEqual(next, state.present)) return false;
      const past = trim([...state.past, state.present]);
      state = { past, present: next, future: [] };
      return true;
    }),
    undo: () => guarded(() => {
      if (!state.past.length) return false;
      const { past, present, future } = state;
      state = { past: past.slice(0, -1), present: past.at(-1),
        future: [present, ...future] };
      return true;
    }),
    redo: () => guarded(() => {
      if (!state.future.length) return false;
      const { past, present, future } = state;
      state = { past: [...past, present], present: future[0],
        future: future.slice(1) };
      return true;
    })
  };
}

let seed = 20261018;
let transitions = 0;
const random = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0);
for (const capacity of [1, 2, 3, 5, 8]) {
  const h = history(0, capacity);
  let states = [0];
  let cursor = 0;
  for (let i = 0; i < 2400; i++) {
    const r = random();
    const op = (r >>> 16) % 4;
    let expected;
    let actual;
    if (op < 2) {
      const value = (r >>> 8) % 7;
      expected = value !== states[cursor];
      if (expected) {
        states = [...states.slice(0, cursor + 1), value].slice(-capacity);
        cursor = states.length - 1;
      }
      actual = h.commit(value);
    } else if (op === 2) {
      expected = cursor > 0;
      if (expected) cursor--;
      actual = h.undo();
    } else {
      expected = cursor < states.length - 1;
      if (expected) cursor++;
      actual = h.redo();
    }
    assert.equal(actual, expected, `return mismatch at ${transitions}`);
    assert.equal(h.read(), states[cursor]);
    assert.deepEqual(h.info(), { past: cursor,
      future: states.length - cursor - 1, size: states.length });
    assert.ok(h.info().size <= capacity);
    transitions++;
  }
}
assert.equal(transitions, 12000);
console.log('model: 12000 transitions ok');

运行输出:

model: 12000 transitions ok

官方依据与延伸阅读

本文实现与测试为围绕上述合同编写的教学示例,并非某个现成库的完整替代品。以下官方资料分别提供历史模型与所用运行时 API 的依据;容量、数据范围、检查点和异常策略是本文明确选择的设计。

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