AI 代码审查:用 context.source 与 rawJSON 守住 JSON 大整数精度

10-18 5阅读

AI 代码审查分享:大整数的风险不只在计算中,也可能发生在 JSON 进入程序的第一步。本文用九个独立测试,把已经舍入的值、原始数字词素与接口契约分开检查,最终建立能被证明的精确往返链路。

AI 代码审查:用 context.source 与 rawJSON 守住 JSON 大整数精度
原创 AI 生成概念配图:同一段数字文本经过不同转换路径,可能保留原始词素,也可能丢失精度。图中数字仅为视觉元素,并非测试数据。

一、先验证运行时,别让新参数只存在于生成的代码里

让 AI 修改数据接入代码时,我会先把任务缩小成一个可证明的承诺:请求体中的大整数标识符,经过解码、业务处理和重新编码以后,每一位都不能变。这个承诺比支持 BigInt 更具体,因为后者可能只是最后一个变量的类型正确,而最初的数字已经被舍入。本文只审查数字原始词素这一条链路,不展开通用 reviver 的遍历、删除属性或日期恢复用法。

本文九段代码均在 Node.js v24.19.0 单独执行通过,每段可保存为一个 .cjs 文件运行。入口检查既读取大整数的 source,也实际序列化 rawJSON 对象;只检查函数名称存在,无法证明当前环境满足整条数据通路。部署目标应执行相同探针,不能因为开发机使用 Node 24,就推断旧浏览器、嵌入式运行时或测试替身也具有相同能力。

const assert = require("node:assert/strict");
let source;
JSON.parse("9007199254740993", (key, value, context) => {
  source = context?.source;
  return value;
});
assert.equal(source, "9007199254740993");
assert.equal(typeof JSON.rawJSON, "function");
assert.equal(typeof JSON.isRawJSON, "function");
assert.equal(JSON.stringify(JSON.rawJSON(source)), source);
console.log("01 feature probe passed");

审查结论:把能力探针放在部署验证或启动检查中。能力不满足时明确失败,或切换双方约定好的字符串协议,不能悄悄退回 Number。

二、普通 reviver 收到的数字,可能已经错了一位

最容易被 AI 写出的补丁,是在 reviver 中检测一个整数,然后调用 BigInt(value)。这个补丁改变了存储类型,却没有回到原始输入。例子中的十进制文本是一个精确的奇数,解析成 Number 后已经成为旁边的偶数;随后调用 BigInt,只会把那个偶数精确地保存下来。测试必须拿字符串或 BigInt 字面量作基准,不能把期望值写成同样无法精确表示的 Number 字面量。

这里还要区分可表示与安全整数。超过安全整数范围,并不表示每个值都立刻失真,而是无法保证相邻整数仍可区分。正因为某些偶数还能通过,少量成功样例反而容易掩盖问题。我会要求 AI 加入边界两侧的相邻值,并证明两个不同输入没有坍缩为同一个业务标识。

const assert = require("node:assert/strict");
const text = '{"id":9007199254740993}';
const naive = JSON.parse(text, (key, value) =>
  key === "id" ? BigInt(value) : value
);
assert.equal(naive.id, 9007199254740992n);
assert.notEqual(naive.id, 9007199254740993n);
assert.equal(JSON.parse("9007199254740992"),
             JSON.parse("9007199254740993"));
assert.equal(Number.isSafeInteger(JSON.parse("9007199254740993")), false);
console.log("02 precision loss reproduced");

MDN 的 JSON.parse 文档说明了转换发生在 reviver 之前;安全整数边界则解释了相邻整数测试的必要性。

三、source 保存的是数字写法,不只是一个更大的数

词素就是输入中表示某个值的那段文本。1000、1e3 和 1000.0 解析后都得到相同的 Number,但它们表达的书写选择并不相同。source 让代码能够检查原始写法,而不是从格式化后的结果倒猜。负零也是一个有用的审查样例:Number 可以区分负零,但常规序列化会把它写成零;如果业务要求保留原样,就不能只保存数值。

这个能力不等于给整个对象附赠一份原文。对象和数组的上下文没有对应的 source 属性;代码应检查具体属性是否存在,而不是假设第三个参数总能直接取到字符串。规范还把 source 与尚未被改动的原始基本类型属性关联起来,所以本文的收集回调只观察并原样返回,不通过 this 去改写其他待访问字段。这样可以避免把后来修改的值误当成原始证据。

const assert = require("node:assert/strict");
const seen = new Map();
JSON.parse('{"a":1000,"b":1e3,"c":1000.0,"z":-0}',
  (key, value, context) => {
    if (typeof value === "number") seen.set(key, [value, context.source]);
    if (value !== null && typeof value === "object") {
      assert.equal(Object.hasOwn(context ?? {}, "source"), false);
    }
    return value;
  });
assert.deepEqual([seen.get("a")[0], seen.get("b")[0], seen.get("c")[0]],
                 [1000, 1000, 1000]);
assert.deepEqual([seen.get("a")[1], seen.get("b")[1], seen.get("c")[1]],
                 ["1000", "1e3", "1000.0"]);
assert.equal(Object.is(seen.get("z")[0], -0), true);
assert.equal(seen.get("z")[1], "-0");
console.log("03 lexical forms retained");

关于上下文的精确条件,参见 ECMAScript 的 InternalizeJSONProperty 算法。这里的对象上下文检查也避免依赖文档概述中对第三参数的简化描述。

四、把恢复规则绑定到结构位置,别全局搜索同名字段

知道 source 后,另一个过度修复是见到名为 id 的属性就转换。真实接口中,根对象的流水编号和统计子对象里的小整数标签可能恰好同名。字段名称不是路径,reviver 也不会自动提供完整业务路径。下面先用 WeakMap 按属性所属对象记录数字词素,再在解析完成后验证根结构,只恢复账目结构的根 id。嵌套的 metrics.id 仍是 Number,证明修复范围没有被扩大。

这段代码刻意返回新对象,而不把中间的近似编号交给业务层。入口限制文本长度,编号限制为最多四十位非负十进制整数;这两个数字是示例接口的选择,应由实际协议确定。缺字段、错误结构、数字字符串或超过长度上限都不能靠宽松强制转换蒙混过关。若完整业务还规定 metrics 的内容,需要另行验证,下面只负责编号契约。

const assert = require("node:assert/strict");
function decodeEntry(text) {
  if (typeof text !== "string" || text.length > 4096) throw new TypeError("text");
  const tokens = new WeakMap();
  const doc = JSON.parse(text, function (key, value, context) {
    if (typeof value === "number" && typeof context?.source === "string") {
      if (!tokens.has(this)) tokens.set(this, new Map());
      tokens.get(this).set(key, context.source);
    }
    return value;
  });
  if (!doc || Array.isArray(doc) || typeof doc !== "object" ||
      doc.kind !== "entry" || !Object.hasOwn(doc, "id")) {
    throw new TypeError("entry schema");
  }
  const source = tokens.get(doc)?.get("id");
  if (typeof source !== "string" || source.length > 40 ||
      !/^(?:0|[1-9]\d*)$/.test(source)) throw new TypeError("integer id");
  return { ...doc, id: BigInt(source) };
}
const doc = decodeEntry('{"kind":"entry","id":9007199254740993,"metrics":{"id":7}}');
assert.equal(doc.id, 9007199254740993n);
assert.equal(doc.metrics.id, 7);
assert.throws(() => decodeEntry('{"kind":"entry","id":"123"}'), TypeError);
assert.throws(() => decodeEntry('{"kind":"other","id":123}'), TypeError);
console.log("04 schema scoped restoration passed");

给 AI 的修改要求应写明结构位置、允许的文本语法和长度上限,并明确哪些相似字段必须保持原类型。只写支持大整数,无法表达这些边界。

五、数学上是整数,不代表可以直接交给 BigInt

指数写法是这次审查最值得单列的反例。1e3 的数学值确实为整数,但 BigInt 的字符串转换并不把它当作十进制整数字符串。先 Number 再 BigInt 看似能够支持指数,却重新走过了精度可能丢失的道路。把 Number.isInteger 当作入场券也不够,因为它只看到转换后的值,看不到原始小数或指数形式。

这里采用容易审计的协议:编号只接受无指数、无小数部分的整数词素,并明确拒绝负零。拒绝合法 JSON 数字不是解析器缺陷,而是业务契约比 JSON 语法更严格。如果另一种接口确实需要任意指数形式,应使用能从十进制文本精确处理的方案,分别限制输入长度、指数范围和输出位数。不要让模型临时拼一套未经边界测试的十进制归一化器。

const assert = require("node:assert/strict");
function decodeInteger(text) {
  if (typeof text !== "string" || text.length > 80) throw new TypeError("length");
  let source;
  const value = JSON.parse(text, (key, value, context) => {
    source = context?.source;
    return value;
  });
  if (typeof value !== "number" || typeof source !== "string" ||
      source.length > 40 || !/^-?(?:0|[1-9]\d*)$/.test(source) || source === "-0") {
    throw new TypeError("plain integer token required");
  }
  return BigInt(source);
}
assert.equal(decodeInteger("9007199254740993"), 9007199254740993n);
assert.equal(decodeInteger("-42"), -42n);
for (const text of ["1e3", "1000.0", "-0", '"123"', "[123]", "1e400"]) {
  assert.throws(() => decodeInteger(text), TypeError);
}
assert.equal(Number.isInteger(JSON.parse("1e3")), true);
assert.throws(() => BigInt("1e3"), SyntaxError);
console.log("05 exponent and decimal forms rejected");

字符串转换规则可对照 MDN BigInt。上述检查顺序也保证巨大的指数文本不会进入大整数构造。

六、rawJSON 负责写入合法词素,不负责业务安全

恢复成功之后,还有写回这一半。JSON.rawJSON 可以让 stringify 写入已经验证过的 JSON 基本类型文本,从而避免再次经过 Number。它不是任意片段拼接器:数组、对象、逗号拼接、无效数字以及首尾空白都不能作为此处的原始基本值。返回对象有内部标识,普通对象即使也带一个 rawJSON 属性,也不会自动取得同样能力。

但语法合法和业务可接受仍是两件事。1e400 是合法 JSON 数字,rawJSON 可以保存它,普通 JavaScript 读取后却会得到 Infinity;再序列化这个 Number 时还会变成 null。所以不能把 rawJSON 验证通过理解为有限数、整数、金额合法或编号范围正确。来自外部的文本仍需类型、长度和范围校验;放入 HTML 页面时也需要相应的输出转义,JSON 的合法性不会替代 HTML 安全处理。

const assert = require("node:assert/strict");
const raw = JSON.rawJSON("9007199254740993");
assert.equal(JSON.isRawJSON(raw), true);
assert.equal(Object.isFrozen(raw), true);
assert.equal(Object.getPrototypeOf(raw), null);
assert.equal(JSON.isRawJSON({ rawJSON: "9007199254740993" }), false);
assert.equal(JSON.stringify({ id: raw }), '{"id":9007199254740993}');
for (const bad of [" 1", "1 ", "01", "NaN", "Infinity", "[]", "{}", "1,2"]) {
  assert.throws(() => JSON.rawJSON(bad), SyntaxError);
}
const extreme = JSON.stringify({ n: JSON.rawJSON("1e400") });
assert.equal(extreme, '{"n":1e400}');
assert.equal(JSON.parse(extreme).n, Infinity);
assert.equal(JSON.stringify(JSON.parse(extreme)), '{"n":null}');
console.log("06 raw JSON limits verified");

可核对 MDN rawJSON、isRawJSON以及 规范算法。无损输出所依赖的是有效原始词素,而不是给普通对象添加一个同名字段。

七、数值往返测试,必须覆盖发送端和接收端

下面把协议缩到单个整数文档,便于观察最小闭环:发送端只收 BigInt,转为十进制文本后交给 rawJSON;接收端只接受符合约定的整数数字词素,再从 source 构造 BigInt。这个闭环既检查精确数值,也检查恢复后的类型。普通 stringify 直接遇到 BigInt 会抛错,因此编码策略需要在接口边界显式提供,而不是期待所有调用点自动支持。

同一份输出如果交给普通 JSON.parse,精度仍可能丢失。rawJSON 只改变输出文本,不会给接收方安装高精度算术,也不会在 JSON 中附带 BigInt 类型标签。跨语言联调时,双方需要确认数字读取方式;只测试本服务的编码器,再用字符串包含断言证明数字还在,并不能证明真实消费链路安全。

const assert = require("node:assert/strict");
function encodeInteger(value) {
  if (typeof value !== "bigint") throw new TypeError("bigint required");
  const source = value.toString();
  if (source.replace(/^-/, "").length > 40) throw new RangeError("digits");
  return JSON.stringify(JSON.rawJSON(source));
}
function decodeInteger(text) {
  if (typeof text !== "string" || text.length > 80) throw new TypeError("text");
  let source;
  const value = JSON.parse(text, (key, value, context) => {
    source = context?.source;
    return value;
  });
  if (typeof value !== "number" || typeof source !== "string" ||
      source.replace(/^-/, "").length > 40 ||
      !/^-?(?:0|[1-9]\d*)$/.test(source) || source === "-0") throw new TypeError("token");
  return BigInt(source);
}
for (const original of [0n, -42n, 9007199254740993n, -(10n ** 39n)]) {
  assert.equal(decodeInteger(encodeInteger(original)), original);
}
assert.throws(() => JSON.stringify(9007199254740993n), TypeError);
const text = encodeInteger(9007199254740993n);
assert.notEqual(BigInt(JSON.parse(text)), 9007199254740993n);
console.log("07 exact value round trip passed");

审查结论:无损是协议双方共同维持的性质。生产链路中的日志、消息转发、缓存和其他语言消费者,也要避免先解析为低精度数值再重新输出。

八、保留数字词素,不等于保留整份 JSON 原文

有些工具需要保存数字的原始书写形式,而不是立即拿它计算。此时可以在读取时把数值转换成 rawJSON 包装对象,再序列化。下面的例子保留尾随零、指数中的加号以及负零;它得到的是词素保留的数据树,其中数值节点已经不再是可以直接参与算术的 Number。业务层必须知道自己操作的是哪一种表示。

这个操作仍然不是字节级往返。对象周围的空白消失,字符串的转义写法可能被规范化,重复成员名也不会作为多份成员保留下来。因此,不能拿重新生成的文本替代原文做签名验证、文件哈希或精确审计存档。需要原文证据时,应另行保留收到的原始文本或字节,并清楚区分原文、词素和数值三种保真目标。

const assert = require("node:assert/strict");
const text = '{ "n": 1.2300e+4, "minus": -0, "label": "\\u0061" }';
const tree = JSON.parse(text, (key, value, context) => {
  if (typeof value === "number") return JSON.rawJSON(context.source);
  return value;
});
assert.equal(JSON.isRawJSON(tree.n), true);
assert.equal(tree.n.rawJSON, "1.2300e+4");
const output = JSON.stringify(tree);
assert.equal(output, '{"n":1.2300e+4,"minus":-0,"label":"a"}');
assert.notEqual(output, text);
assert.equal(JSON.parse(output).n, 12300);
const duplicate = JSON.parse('{"id":1,"id":2}');
assert.equal(JSON.stringify(duplicate), '{"id":2}');
console.log("08 token preservation differs from byte preservation");

这段代码适合作为展示词素保留的最小试验,不应未经限制直接变成任意体积文档的通用代理。输入大小、嵌套深度和资源预算仍需在接入层治理。

九、兼容性优先时,把大整数明确写成字符串

如果接收方众多、运行时能力不一致,字符串协议往往更容易落地。关键是让编号从一开始就是字符串,而不是先接受 JSON 数字,发现不安全后才转字符串。后一种处理仍然来不及恢复丢失的位。下面的协议要求 id 始终为规范十进制字符串,小编号也不例外;读取后在内部转换为 BigInt,输出时显式恢复字符串形式。

这条路不需要 context.source 或 rawJSON,因此也适合缺少新能力的环境。不过字符串本身不会自动带来业务正确性:空字符串、前导零、正号、超长数字和错误字段类型都必须有一致规则。若编号本来允许前导零,它更像一个标识文本,不应先转为 BigInt 再期待恢复前导零。先确认身份标识和算术整数的业务含义,再决定模型该生成哪一种转换。

const assert = require("node:assert/strict");
function decodeStringId(text) {
  if (typeof text !== "string" || text.length > 4096) throw new TypeError("text");
  const doc = JSON.parse(text);
  if (!doc || Array.isArray(doc) || typeof doc !== "object" ||
      !Object.hasOwn(doc, "id") || typeof doc.id !== "string" ||
      doc.id.length > 40 || !/^(?:0|[1-9]\d*)$/.test(doc.id)) {
    throw new TypeError("canonical string id required");
  }
  return { ...doc, id: BigInt(doc.id) };
}
const text = JSON.stringify({ id: 9007199254740993n.toString(), count: 2 });
const doc = decodeStringId(text);
assert.equal(doc.id, 9007199254740993n);
assert.equal(doc.count, 2);
assert.equal(JSON.stringify({ ...doc, id: doc.id.toString() }), text);
for (const bad of ['{"id":123}', '{"id":"01"}', '{"id":"+1"}', '{"id":""}']) {
  assert.throws(() => decodeStringId(bad), TypeError);
}
console.log("09 string contract round trip passed");

对外协议应写出字段类型和规范形式,而不是把可靠性寄托在某个消费者的自动识别逻辑上。版本迁移时也要避免混合输出数字和字符串,让下游根据编号大小猜测类型。

把审查问题从支持大整数改成守住精度契约

我会让 AI 提交代码时同时回答四件事:数字在哪一步进入 Number,恢复时使用的是值还是原文,规则究竟绑定哪个结构位置,接收方是否能用相同契约读回来。测试再分别覆盖相邻大整数、指数和小数形式、负零、同名嵌套字段、超长输入以及真实往返。只有这些反例都被解释并验证,BigInt 与 rawJSON 才构成可靠方案,而不是两处看起来很现代的 API 调用。

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