Repository navigation
fix(schema): compare numeric enum values consistently - #7907
hutiefang76 wants to merge 2 commits into
Conversation
Signed-off-by: hutiefang76 <137664623+hutiefang76@users.noreply.github.com>
wenshao
left a comment
There was a problem hiding this comment.
Reviewed. Suggestions are inline.
Not explored to full depth (tool budget reached): "agent 4": static bytecode sizing of canonicalize vs. the 325-byte FreqInlineSize gate (no JDK available in the review container)..
中文说明
已审查。 建议见行内评论。
未探索到全部深度(达到工具调用预算):"agent 4":static bytecode sizing of canonicalize vs. the 325-byte FreqInlineSize gate (no JDK available in the review container).。
— DeepSeek/deepseek-v4.1-flash via Qwen Code /review (v0.26.0)
| if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { | ||
| return value; | ||
| } | ||
| return canonicalize(BigDecimal.valueOf(doubleValue)); |
There was a problem hiding this comment.
[Suggestion] R1-1: Every validated Double/Float pays Double.toString plus 2-3 BigDecimal/BigInteger allocations on the per-value path, where the integer path costs zero
Members are canonicalized in the constructor, so the items.contains(value) fast path can never hit for a boxed Double/Float: each validated double or float runs BigDecimal.valueOf(double) (= Double.toString → String → BigDecimal parse), then stripTrailingZeros, then toBigIntegerExact() for integral values, before one set lookup. Integral doubles are the common numeric-enum case, and they are exactly representable as a long — so the decimal round-trip buys nothing there.
Measured over 500k iterations after warmup (allocated bytes via ThreadMXBean):
alloc-bytes/op: double=176.0 int=0.0 long=0.0
ns/op: double=241.5 int=26.1
That is roughly a 9x slowdown plus garbage proportional to record count, on a per-value validation path. AGENTS.md is explicit: "Performance-first project: every change must consider performance impact".
| return canonicalize(BigDecimal.valueOf(doubleValue)); | |
| if (doubleValue == Math.rint(doubleValue) && doubleValue > -0x1p63 && doubleValue < 0x1p63) { | |
| return canonicalize((long) doubleValue); | |
| } | |
| return canonicalize(BigDecimal.valueOf(doubleValue)); |
The upper bound has to stay strictly below 2^63: (long) 9.223372036854775808E18 saturates to Long.MAX_VALUE, which would let the double 2^63 match a 9223372036854775807 member. Values outside long range must keep falling through to the BigDecimal path, since testLargeMagnitudes asserts 1.0E19d matches the member 10^19.
The equivalence the fast path must preserve is already pinned by testIntegralMembersAcceptEqualNumbers, testLargeMagnitudes and testDoubleExactBoundary; please add the 2^63 clamp assertion (new EnumSchema(Long.MAX_VALUE).isValid(9.223372036854775808E18) must be false) and confirm it reds if the bound is relaxed.
中文说明
成员在构造时已归一,因此 items.contains(value) 快路径对装箱的 Double/Float 永远不会命中:每个被校验的 double/float 都要走 BigDecimal.valueOf(double)(即 Double.toString → String → BigDecimal 解析)、stripTrailingZeros,整数值还要 toBigIntegerExact(),然后才做一次集合查找。而整数 double 是数值 enum 的常见场景,且能精确表示为 long,这段十进制往返完全没有收益。
预热后 50 万次实测(ThreadMXBean 统计分配字节):double 每次 176.0 字节、241.5 ns;int 每次 0 字节、26.1 ns。约 9 倍差距,且垃圾量与记录数成正比。AGENTS.md 明确要求性能优先。
建议在任何十进制运算之前先短路"可精确表示"的整数情形。上界必须严格小于 2^63:(long) 9.223372036854775808E18 会饱和成 Long.MAX_VALUE,导致 double 的 2^63 错误匹配 9223372036854775807 成员。超出 long 范围的值仍需走 BigDecimal 路径(testLargeMagnitudes 断言 1.0E19d 匹配 10^19)。
请补一条 2^63 边界断言,并确认放宽上界后该断言变红。
— DeepSeek/deepseek-v4.1-flash via Qwen Code /review (v0.26.0)
There was a problem hiding this comment.
Updated in 74b375e2. The shortcut is limited to integral values within ±2^53: near 10^18, a direct long cast can differ from BigDecimal.valueOf(double), so the wider range keeps the old path. The 2^63 clamp and both signs of that decimal boundary are covered. A local allocation probe for preboxed 1/2 inputs measured Double/Float at 88 → 0 B/op; this is not a throughput benchmark.
中文
已在 74b375e2 修订。快速路径只覆盖 ±2^53 内的整数;约 10^18 处直接转 long 会与原十进制往返结果不同,因此大数保留原路径。已覆盖 2^63 饱和边界及正负大数。预装箱 1/2 输入的本地分配探针测得 Double/Float 为 88→0 B/op,不作为吞吐量基准。
| } | ||
|
|
||
| return SUCCESS; | ||
| return value; |
There was a problem hiding this comment.
[Suggestion] R1-2: canonicalize leaves Short/Byte/AtomicInteger/AtomicLong untouched, so four Number types still never match a numeric enum member
Members are canonicalized to Integer/Long/stripped BigDecimal in the constructor, but canonicalize only handles BigDecimal, BigInteger, Long, Double and Float (Integer passes through) and falls through to return value; for everything else. For those four types the first items.contains(value) misses (Short.equals(Integer) is false) and the second misses as well, so a mathematically equal value is rejected — while the javadoc added in this PR states that "enum members and instances of different numeric types are compared by mathematical value", and IntegerSchema already classifies exactly these four as integers.
Measured against {"enum":[1,2]} on this PR's code:
type=Short valid=false msg=expect type Enum, but class java.lang.Short
type=Byte valid=false | AtomicInteger valid=false | AtomicLong valid=false
type=Integer valid=true | Long valid=true | Double valid=true | Float valid=true
type=BigDecimal valid=true | BigInteger valid=true
This is reachable through the public JSONSchema.isValid(Object) / EnumSchema API and through Object-typed or container values (ArraySchema validates each item), so an enum attached to such a value rejects a member.
| return value; | |
| if (value instanceof Short || value instanceof Byte) { | |
| return ((Number) value).intValue(); | |
| } | |
| if (value instanceof AtomicInteger || value instanceof AtomicLong) { | |
| return canonicalize(((Number) value).longValue()); | |
| } | |
| return value; |
These types must land on Integer/Long rather than stay Short/Byte: validateInternal decides membership with Set.contains over members canonicalized by canonicalizeInteger (EnumSchema.java:101-110), and IntegerSchema.java:74-80 already lists Byte/Short/Integer/Long/BigInteger/AtomicInteger/AtomicLong as integers, so enum and integer schemas currently disagree about the same value.
Please pin it with a test in NumericEnumSchemaTest asserting isValid((Object) Short.valueOf((short) 2)), Byte, AtomicInteger and AtomicLong are true against {"enum":[1,2]} (and false for (short) 3), and confirm those assertions go red when the new branches are removed.
中文说明
canonicalize 没有覆盖 Short/Byte/AtomicInteger/AtomicLong:成员在构造时已归一为 Integer/Long/stripped BigDecimal,而这四种类型走到最后的 return value; 原样返回。于是 items.contains(Short 2) 不成立(Short.equals(Integer) 为 false),第二次 contains 同样不成立,数学上相等的值被判为不合法——但本 PR 新增的 javadoc 声称"不同类型的 enum 成员与实例按数学数值比较",且 IntegerSchema 早已把这四种类型归为整数。
在本 PR 代码上对 {"enum":[1,2]} 实测:Short/Byte/AtomicInteger/AtomicLong 均返回 false(报错 expect type Enum, but class java.lang.Short),而 Integer/Long/Double/Float/BigDecimal/BigInteger 均为 true。
该路径可通过公开的 JSONSchema.isValid(Object) / EnumSchema API 以及 Object 类型或容器值(ArraySchema 会逐项校验)触发。
建议在 canonicalize 落空分支前补齐:Short/Byte 走 intValue(),AtomicInteger/AtomicLong 走 canonicalize(longValue())。注意必须落到 Integer/Long 键上(否则 Set.contains 仍然失配);IntegerSchema.java:74-80 已把这几种类型列为整数,两者应当一致。
请补测试固定:{"enum":[1,2]} 下 Short/Byte/AtomicInteger/AtomicLong 形式的 2 应为 true、(short) 3 为 false,并确认删掉新增分支后这些断言变红。
— DeepSeek/deepseek-v4.1-flash via Qwen Code /review (v0.26.0)
There was a problem hiding this comment.
Added normalization and regressions for Short, Byte, AtomicInteger and AtomicLong, on both the member and input sides, in 74b375e2. The four new cases failed before the fix and pass now; unlisted values remain rejected. The original Long branch is unchanged.
中文
74b375e2 补齐了四种整数类型的成员端和输入端归一化。四项新回归在修复前失败、修复后通过,未列出的值仍被拒绝,原 Long 分支保持不变。
| } | ||
|
|
||
| @Test | ||
| public void testLargeMagnitudes() { |
There was a problem hiding this comment.
[Suggestion] R1-3: No test pins the int32/int64 canonicalization boundaries, and a > to >= change in fitsInt64 keeps all 15 tests green while breaking long-boundary enum matching
The values used here are 16, 20 and 30 digits — none is 19, and none is an int32 boundary — so the three-way split in canonicalizeInteger and the > comparison in fitsInt64 are unpinned. I applied the mutation and measured both halves:
mutation `>` -> `>=` at EnumSchema.java:120
mvn -pl core test -Dtest=NumericEnumSchemaTest -> Tests run: 15, Failures: 0, Errors: 0
new EnumSchema(Long.MAX_VALUE).isValid(new BigDecimal("9223372036854775807"))
unmodified -> true
mutated -> false
The trace: with >=, a 19-digit stripped decimal has precision - scale == 19, is rejected by the digit pre-check, and stays a BigDecimal — while the member canonicalized to Long, so Set.contains finds no equal key. Every long-boundary enum silently stops matching its own boundary value. The int32 edge has the same shape if <= is relaxed to <.
Suggestions to add, alongside the existing cases:
assertTrue(new EnumSchema(Long.MAX_VALUE).isValid(new BigDecimal("9223372036854775807")));
assertTrue(new EnumSchema(Long.MIN_VALUE).isValid(new BigDecimal("-9223372036854775808")));
assertFalse(new EnumSchema(Long.MAX_VALUE).isValid(new BigInteger("9223372036854775808")));
assertTrue(new EnumSchema(Integer.MAX_VALUE).isValid(new BigDecimal("2147483647")));
assertTrue(new EnumSchema(Integer.MIN_VALUE).isValid(new BigDecimal("-2147483648")));INT64_MAX_DIGITS is 19, so a 19-digit magnitude must pass the digit pre-check to reach the exact compareTo bounds at EnumSchema.java:123-124 — that is the boundary these assertions would pin. Please confirm each one goes red under the > to >= mutation above.
中文说明
现有用例是 16、20、30 位,没有 19 位,也没有 int32 边界,因此 canonicalizeInteger 的三段区间划分和 fitsInt64 的 > 比较都没有被固定。实测:把 EnumSchema.java:120 的 > 改成 >= 后,NumericEnumSchemaTest 仍然是 15 个用例全绿;而 new EnumSchema(Long.MAX_VALUE).isValid(new BigDecimal("9223372036854775807")) 由 true 变为 false。
原因:改成 >= 后,19 位 stripped decimal 的 precision - scale == 19 被位数预检直接判负,保持 BigDecimal,而成员侧已归一为 Long,Set.contains 因此找不到相等的键——所有 long 边界上的 enum 会悄悄不再匹配自己的边界值。int32 边界在把 <= 放宽为 < 时同样成立。
建议补充上面那几条边界断言(Long.MAX/MIN_VALUE、超出 long 的相邻值、Integer.MAX/MIN_VALUE)。INT64_MAX_DIGITS 为 19,19 位数值必须通过位数预检才能走到 EnumSchema.java:123-124 的精确 compareTo 边界,这正是这些断言要固定的位置。请确认上述变异下每条断言都会变红。
— DeepSeek/deepseek-v4.1-flash via Qwen Code /review (v0.26.0)
There was a problem hiding this comment.
Added the int/long boundaries in 74b375e2 and checked the mutations separately. Changing > 19 to >= 19 fails the two Long boundary tests; excluding either int boundary fails its corresponding test. The beyond-long assertions remain controls. Standard and reflect reactor runs each covered 10,069 tests, with only the three existing reflect skips; validate passed.
中文
已补齐 int/long 边界并分别验证变异:19 位预检变异触发两个 Long 边界用例,排除 int 最大或最小值分别触发对应用例,超出 long 的断言作为控制保留。标准和反射模式各覆盖 10,069 项,仅反射模式有三项原有跳过;validate 通过。
What this PR does / why we need it?
{"enum":[100.0]}rejected integer100, and{"enum":[1.5]}rejected1.5d. Members and validated values used different normalization rules.Short,Byte,AtomicIntegerandAtomicLongalso failed to match equal numeric members.Summary of your change
Use the same canonicalization for members and values, including the four integral wrappers. Small integral floating-point values avoid decimal conversion; the shortcut is limited to ±2^53. Larger values retain the existing
BigDecimal.valueOf(double)semantics, since a direct long cast can produce a different value near 10^18. Keep large exponents compact, ordinary Long matches unchanged, and non-finite and string handling intact. Add numeric boundary regressions and English/Chinese usage notes. Exported numeric spelling may change while its value stays the same.Validation
Microsoft JDK 17.0.18, macOS arm64, current revision:
./mvnw -B clean package: 10,069 tests, zero failures, errors or skips../mvnw -B -Dfastjson2.creator=reflect clean test: 10,069 tests, zero failures/errors, three existing conditional skips../mvnw -B validate: passed.Typed-schema dispatch (#7902) and
uniqueItems(#7893) remain separate changes.Fixes #7904
Please indicate you've done the following:
中文
原来
100.0枚举成员不能匹配整数100,1.5不能匹配1.5d,Short、Byte、AtomicInteger、AtomicLong 也会拒绝相等的数值。本次统一成员和输入的归一化,补齐四种整数包装类型。浮点整数快速路径限定在 ±2^53,范围之外保留原有十进制往返语义,避免在约 10^18 处直接转 long 改变结果;巨大指数、原 Long 路径及非有限值处理保持原有行为。当前修订在 Microsoft JDK 17.0.18/macOS arm64 下,根目录 clean package 和 reflect clean test 各覆盖 10,069 项,均零失败、零错误;reflect 有三项原有条件跳过。validate 通过,新增用例已先复现失败,五个隔离变异均被发现。已完成独立源码审查,未运行吞吐量基准。
实现与审查使用 Codex/DeepSeek 辅助;以上测试结果已根据实际运行记录核对。
Implementation and review assisted by Codex/DeepSeek; reported validation was checked against actual local executions.