Skip to content

Preserve literal numeric behavior for count-named fields (#1346) - #1347

Merged
stevehu merged 6 commits into
masterfrom
fix/1346-count-token-metadata
Oct 23, 2026
Merged

stevehu merged 6 commits into
masterfrom
fix/1346-count-token-metadata

Conversation

@stevehu

@stevehu stevehu commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Refs #1346. Follow-up to the unreleased #1334 change (#1341).

Preserve ordinary parsing for count-named literal data while retaining exact count-token semantics during schema binding. Fractional tokens such as 1e-400 keep their existing fallback; plain integer arguments such as 3000000000 print in full. Literal/annotation/unknown-keyword data can contain exponents outside BigDecimal's range without a count-specific load failure.

The configured node factory creates the tree unchanged. Raw lexemes are held in an internal weak identity sidecar. Each entry records its original numeric node weakly and a read-time numeric-value snapshot. A replaced or mutated node invalidates its old lexeme when a new schema is built from the tree; even a replacement with the same rounded value is distinguished by identity. This does not make already-compiled validators dynamically mutable.

Count binding parses/classifies once, caches error strings and uses shared defaults/static int-bound constants. Accepted YAML floating separators are normalized consistently with the YAML parser. Contains annotations use the node's own numberValue(), including its type; exact comparison information does not change annotation representation. Plain integer diagnostics use fixed literal expectations, not a formula copied from the implementation.

Known boundaries and retained choices:

  • Active exact tokens must fit BigDecimal's parsing range. 1e400 fits; 1e999999999999 remains rejected as on the base. This PR does not add an arbitrary-exponent numeric representation. Supplied floating-point Infinity nodes still use sign-aware saturation.
  • Lexical metadata belongs to the original tree. A deepCopy or reparse uses the supplied nodes' precision. Use USE_BIG_DECIMAL_FOR_FLOATS when copied schemas must retain exact count semantics; both ordinary-copy fallback and exact-reader copy behavior are tested.
  • Candidate tokens under literal or unknown fields are retained because an arbitrary $ref can activate those same objects as schemas. A reference into const is tested. Weak ownership prevents the sidecar from retaining released documents.
  • Implementation helpers have public Java visibility for internal cross-package use, but are not a supported classpath API. JPMS/OSGi do not export the internal package. Existing NodeReader schema-reading hook signatures match the target base.

Automated coverage now includes replaced/equal-rounded/mutable numeric nodes, YAML underscore floats, identity isolation, a released owner with a custom numeric-node back-reference, queue cleanup, eight concurrent compilation workers with GCs, copy precision, and the earlier literal/precision/reference/message suites.

A packaged-jar test runs automatically in Maven's verify phase, which CI already invokes. It checks class contents and OSGi exports on every JDK; Java 9+ additionally checks explicit module ownership and JPMS exports. No production test hooks or new plugin dependencies are introduced.

Validation: mvn -B clean verify passed independently on JDK 17/21/25: 10,423 unit tests + 1 packaged-artifact check per run, zero failures/errors, 30 existing skips. Focused regression suites: 400 tests, zero failures/errors. No existing tests are excluded. Whitespace checks passed.

Pre-change GitNexus reader/registry impact remains CRITICAL. Staged scans omit newer helper coverage and do not establish low risk; source review, sidecar tests, packaged-artifact verification and full JDK suites supplement the graph.

Message-format decision: retain the existing formatting in these PRs. The low-severity provenance difference (for example, 3000000000 from text versus 3E+9 from a supplied DoubleNode) remains documented, not marked fixed. A source-independent formatting policy is deferred to a separate decision. The snapshot ternary intentionally shares the captured String object when its content matches, avoiding retention of a duplicate String; the follow-up source comment explains this. That follow-up changes no executable code.

@stevehu

stevehu commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Review notes

Summary: the change fixes #1346. Literal data under count-named keys keeps its ordinary node type and equality, MinPropertiesValidator builds its CountLimit once, and the exact-limit behaviour from #1334 is preserved. I ran Issue1346Test and Issue1334Test on this head (309 tests across the classes I ran with my probe, 0 failures) and probed it with extra cases. I ignored CI as requested. Nothing below is a regression against the old behaviour, so none of it blocks. The first two are the ones worth deciding on.

Correctness

  1. Custom readers and JsonNode input still fail open. The fix only applies to the built-in readers. With a custom NodeReader that implements only readTree, {"minItems":1e400} against [] returns 0 errors, and registry.getSchema(JsonNode) does the same. The default reader reports must have at least 1E+400 items. A minimum is silently dropped. Treating an infinite DoubleNode as a saturated limit in CountLimit.of/isIntegralCountLimit would make every path fail closed. At minimum the CHANGELOG and NodeReader.readSchema javadoc should say it.
  2. The size of the mechanism. A JsonParserDelegate, a ~18-method JsonNodeFactory wrapper and a DoubleNode subclass exist to keep an exact BigDecimal past Jackson's double conversion. Only values above about 1.8e308 are actually lost, because double-exact limits such as 2147483648.0 or 1e30 already work. The Infinity handling above would cover both gaps and remove the field-name heuristic that caused Follow-ups for count-limit handling (#1334): parser field-name matching and MinPropertiesValidator reparse #1346. The trade-off is that the message text for beyond-double limits would no longer be the literal.
  3. Stateful coupling. isCountLimit() writes the countLimit field and CountLimitNodeFactory.numberNode(BigDecimal) reads it from the parser. This relies on Jackson calling getNumberTypeFP() on the same token just before numberNode. If that changes, a count limit could silently lose its exact value. A holder object updated in one method would make the dependency explicit.
  4. Hand-forwarded factory. pojoNode, rawValueNode and boxed numberNode variants fall back to the base class, and any future JsonNodeFactory method will bypass the delegate (including a location-aware one) with no compile error.
  5. Message text depends on the literal. 2147483648.0 prints 2147483648.0 and 1.0e+400 prints 1.0E+400, while the integer literal 2147483648 prints 2147483648 and 10e-1 prints 1. Equal limits give different messages.

Cleanup

  • The two readSchemaTree overloads, and the paired readSchema overrides in BasicNodeReader/DefaultNodeReader, are copy-paste. One private method taking the parser would do.
  • decimalValueForCountLimit, isIntegralCountLimit and readSchemaTree are public static on JsonNodes, and NodeReader gains two public default methods. These look like internal helpers that are hard to retract once released.

Tests and docs

@stevehu

stevehu commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Review notes for #1347 (head fb696ad).

What I checked: built the PR head and its base (b4e1b8c) and ran 304 schemas (8 count keywords x 38 limit spellings) against 9 instances through the default reader, comparing results and error arguments.

1. Fractional tokens that round to a whole double are now enforced (CountLimit.java:43)

isIntegral() tests the already-rounded double, so a fractional token that underflows or rounds to a whole value under ordinary floating-point parsing now counts as an integral limit. The description says fractional values retain their existing fallback. Differences from base:

  • {"maxItems":1e-400} and -1e-400: ignored on base; now reject [1] and [1,2] (argument 0).
  • maxItems:0.99999999999999999999 and 1.0000000000000000001: now behave as maxItems:1.
  • minItems:2147483647.9999999999: now behaves as 2147483648, so every array fails.
  • Same for minLength/maxLength/minProperties/maxProperties.
  • minContains:1e-400: a malformed-schema error on base, now silently accepted as 0. maxContains:1e-400 is now enforced as 0.

The new tests cover fractional behaviour only with 1.5f, so none of this is caught. Options: treat a double as integral only if it is also not a rounded-away fraction (for example require number == 0 or Math.abs(number) >= 1), keep these keywords' tokens as BigDecimal, or document the narrowing.

2. Error messages report the rounded value for large finite float limits (CountLimit.java:64)

minItems:9007199254740993.0 now reports 9007199254740992; minLength:1.23456789012345678901234567890e29 reports 1.2345678901234568E+29 (base: 123456789012345678901234567890); minItems:3000000000.0 reports 3E+9 while 3000000000 reports 3000000000. The description calls out 1e400 becoming Infinity, but not these. If they are accepted, please list them in the changelog.

3. Contains annotation value type depends on magnitude (CountLimit.java:54)

minContains:3e9 annotates a BigDecimal (3E+9), 1e400 annotates Double Infinity, and 2/2.0 annotate Integer. A consumer comparing with schemaNode.get("minContains").numberValue() gets equality for exact decimals but not for finite out-of-range doubles. Returning node.numberValue() for out-of-range values would make it uniform.

4. Cleanup

  • MinPropertiesValidator.java:46: node.size() < this.min || is redundant next to this.minimum.isMinimumSatisfiedBy(...), which decides the outcome by itself.
  • The isIntegral(x) ? of(x) : of(default) ternary is repeated in six validators plus MinMaxContainsValidator/ContainsValidator. A single CountLimit.ofIntegral(node, fallback) would keep the rule in one place, which matters given item 1.
  • messageArgument() runs stripTrailingZeros() with a try/catch on every error; normalising once in of(JsonNode) would avoid that. The two BigDecimal.valueOf(Integer.MAX/MIN_VALUE) bounds could be static constants.

Not a finding: the metaschema reports integer expected for 1e400, but base does the same.

🤖 Generated with Claude Code

@stevehu
stevehu marked this pull request as ready for review October 23, 2026 14:47
@stevehu

stevehu commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Review notes for #1347 (head c538772). The fractional-token regressions from my earlier notes are fixed: I reran my 304-schema probe against this head and 1e-400, 0.99999999999999999999 and 2147483647.9999999999 are back to the base fallback, and 9007199254740993.0 / 1e400 report their written value. Two new regressions remain.

1. Count-named literal data with an unrepresentable exponent now fails schema load (SchemaNodeReader.java:98)

The capture parser tracks every float whose field name matches a count keyword, including inside const, enum, default, examples and unknown keywords, and rethrows NumberFormatException for a finite token BigDecimal cannot represent. Each of these now throws "Too many nonzero exponent digits." from getSchema():

  • {"const":{"minItems":1e999999999999}}
  • {"enum":[{"maxLength":1e999999999999}]}
  • {"default":{"maxItems":1e999999999999}}
  • {"examples":[{"minLength":1e999999999999}]}
  • {"x-ext":{"minProperties":1e999999999999}}

The previous head (fb696ad) loaded all of them, since ordinary parsing gives Infinity. Keeping literal data on the reader's ordinary numeric behaviour is what #1346 asks for. Only fail (or only capture) at schema-keyword positions, or catch the exception and leave the ordinary node in place. Issue1346PrecisionTest (line ~142) only uses representable tokens, so nothing covers this. Please add const/enum/default/examples/x- cases with a huge exponent through JSON and YAML, string and stream, and a legacy reader.

2. Plain integer limits now print in exponent form (CountLimit.java:86)

Out-of-int-range arguments are formatted with stripTrailingZeros().toString():

  • minItems:3000000000 reports 3E+9 (base 3000000000)
  • maxLength:-3000000000 reports -3E+9
  • minItems:2147483650 reports 2.14748365E+9
  • minItems:123456789012345678901234567890 reports 1.2345678901234567890123456789E+29 (base printed the digits)
  • minItems:2147483648 still prints 2147483648, so adjacent integers format differently.

The earlier contract was that plain integers keep their full spelling. The tests integerLimitsUseCanonicalExactMessages and programmaticBigDecimalLimitsUseCanonicalExactMessages (Issue1346Test.java:329) now compute the expected value with new BigDecimal(limit).stripTrailingZeros().toString(), the same expression the implementation uses, so they cannot detect this. Please use fixed literal expectations. For integral values, toPlainString() (or the written spelling) would keep the digits, with scientific form kept only for exponent-sized values.

3. Design and cleanup

  • CountTokenNode is a new public DoubleNode subclass with a public countValue(), and NodeReader.readSchema is public again, although the description says the metadata mechanism and schema-specific reader API were removed. It is public only because keyword.CountLimit is in another package. A package-private carrier, or keeping exact values in a structure owned by the schema context, would avoid the new public surface. CountTokenNode.of also keeps only the location, so state on a custom factory's own DoubleNode subclass is dropped.
  • Exact tokens are attached by recording a JSON Pointer, then result.at(...) and ObjectNode.set(...) after parsing, and only for DoubleNode values under an ObjectNode parent. A FloatNode or other node type silently keeps the rounded value, which brings back the earlier behaviour with no error.
  • remember() is hooked into three accessors and rebuilds pathAsPointer().toString() and getString() on each call before the duplicate check.
  • The contains annotation type still depends on how the schema was read (Integer, BigDecimal for built-in-reader floats, Double for programmatic nodes). That is a visible change worth a changelog line.

I did not rerun the test suites or check CI.

🤖 Generated with Claude Code

@stevehu

stevehu commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up: my second round of notes is addressed in 250e6d2, going by the evidence in the PR and its CI results.

  • Count tokens are kept as raw strings and converted to BigDecimal only by an active count validator, so literal data with a huge exponent (const/enum/default/examples/unknown keywords) loads again.
  • Plain integer limits print their full digits again.
  • Message tests use fixed expectations instead of recomputing the formula.
  • CountTokenNode and the tree patching are removed; annotations now use the node's own numberValue().
  • A new literal suite covers all eight count names across those keywords.

I have not rerun my 304-schema probe or the edge cases against 250e6d2, so the above reflects the PR's tests and CI, not an independent check from me.

Two new pieces I have not reviewed and that I would look at before merging:

  • the sidecar that associates exact count tokens with schema objects by weak identity (synchronized weak keys, string values). Questions: can a token be lost when a schema tree is copied, re-wrapped or cached, and can the sidecar retain schema documents?
  • the POM change that excludes internal packages from the module exports. This affects what the built jar exposes to module users.

The retained NodeReader.readTree/readSchema hooks match the base branches, so I have no objection to them.

🤖 Generated with Claude Code

@stevehu

stevehu commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Independent pass on 250e6d2: I rebuilt the head and its base (b4e1b8c) and reran my probes.

Confirmed fixed. The 304-schema probe (8 count keywords x 38 limit spellings x 9 instances) and the literal-data probes behave as intended. 1e-400, 0.99999999999999999999 and 2147483647.9999999999 are back to the base fallback. Plain integers print in full (3000000000, 2147483650, 123456789012345678901234567890). const/enum/default/examples/x- literals containing 1e999999999999 load again. I did not re-probe the contains annotation types or run the new test classes.

Sidecar, lifetime, concurrency, exports. 20,000 compiled schemas drained to one entry after a GC plus one touch of the map. 8 threads compiling different schemas with GCs running showed no cross-talk. $defs/$ref, properties, allOf, items and $id siblings all kept the exact token. A 400,000-number schema parses in about 55-70 ms warm on both base and head. The built jar's module descriptor omits com.networknt.schema.internal.

1. A stale lexeme overrides a replaced value (CountLimit.java:55)

The guard owner.get(keyword) == node compares the node with itself, so it cannot detect that the number was replaced after reading. Reproduced: load {"minItems":3000000000.0}, replace minItems on the schema node with 2, call getSchema(node). Validating [1,2] reports an error with argument 3000000000; the base accepts it. The description says schema nodes are immutable after reading, but the failure is silent. Please record what the token belongs to (the value node instance, or its numeric value) and ignore the token unless it still matches.

2. Active keyword with an unrepresentable exponent throws at load (CountLimit.java:57)

{"minItems":1e999999999999} (and the other keywords) throws NumberFormatException: Too many nonzero exponent digits. The base throws too, but the previous heads enforced it as Infinity, and 1e400 is enforced as an exact bound. Falling back to the node's own value (Infinity/-Infinity, or 0 for underflow) when the lexeme is not representable would keep the huge-exponent range consistent.

3. Tests. Nothing in the suite would catch item 1, deepCopy/mutation, entries lingering after a schema is released, concurrent compiles of different schemas, or a regression in the moditect exclusion. A module-descriptor check in the build would protect the export change.

4. Design notes

  • CountTokens is a JVM-wide static map keyed by node identity, so any new node silently drops the precision: with {"minItems":0.99999999999999999999}, getSchema(schema.getSchemaNode().deepCopy()) enforces minItems 1 while the original ignores it. The put/get methods are also public on the classpath. Keeping the lexeme with the owning schema context, or making the lookup package-private, would narrow that.
  • The reader records every count-named float anywhere in the document, including literal data that is never consulted. Cost is memory only.

🤖 Generated with Claude Code

@stevehu

stevehu commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up on the fourth review, against 31a4b86.

I marked the findings in the review tool from the evidence you supplied (review4-evidence). I have not rebuilt this head, re-run my probes, or run the new test classes myself.

# Finding Status
1 Stale lexeme overrides a replaced value (CountLimit) Fixed per evidence (weak node reference plus value snapshot, replacement invalidates the entry)
4 No tests for sidecar mutation, GC, threads, copy, or module exports Fixed per evidence (CountTokensTest, Issue1346MutationTest, packaged-artifact check)
3 1e999999999999 in an active keyword throws at load Skipped. Kept as a documented boundary: active tokens must fit BigDecimal. This matches base behaviour.
5 deepCopy and rewritten trees lose lexemes; the helpers stay classpath-visible Skipped. Kept as a documented, tested boundary with the USE_BIG_DECIMAL_FOR_FLOATS workaround.
6 Tokens recorded for count-named floats that are never read Skipped. Kept because a $ref can activate literal objects, and the new #/const regression covers it.

Finding 5 can still change results: a deep-copied tree can enforce a different limit than the original. It is explicit in the tests and the PR description, which is a reasonable place to leave it.

The YAML underscore item applies to 2.x only and is covered on #1348.

I can rebuild the head and re-run the 304-schema probe plus the stale-token case to confirm independently if that is useful.

🤖 Generated with Claude Code

@stevehu

stevehu commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Independent verification of 31a4b86 (scratch build of the pushed head; the earlier comment relied on your evidence file).

Verified

  • 304-schema count-limit probe (8 keywords x 38 spellings x 9 instances): output identical to the previous head.
  • clean verify on JDK 17: 10,423 tests plus the 1 packaging check, 0 failures/errors (30 skips), matching your table.
  • Stale token: replacing a loaded minItems with 2, with an equal-rounded 1.0, or with 0.5, or moving the child node to another owner, all enforce the current value.
  • Sidecar: after 20,000 compiles it holds ~35,000 entries; after GC and one more call it holds 1. 8 threads x 2,000 compiles with periodic GCs: 0 mismatches.
  • Packaged jar descriptor exports 16 packages, none internal.
  • Pointer-escaped keys (a/b, a~b, a~1b, "", 0), duplicate keys and nested placement keep the exact token.

Outcomes

  • Fixed: stale lexeme, missing tests.
  • Skipped (kept as boundaries): finding 3 (1e999999999999 in an active keyword still fails to load, as on base), finding 5, finding 6.

Finding 5 is still a compatibility concern. It affects which limit is enforced, not only precision: for {"minItems":0.99999999999999999999} the loaded schema ignores the non-integral limit, while registry.getSchema(node.deepCopy()) enforces minItems 1 ([] errors). The tests and the USE_BIG_DECIMAL_FOR_FLOATS workaround document this but do not remove it. I'd suggest the maintainers explicitly accept that trade-off before merge.

Finding 6, measured: a const holding 100,000 objects that each carry count-named floats loads in ~160-260 ms versus ~28-45 ms on base. Ordinary schemas are unaffected.

New, low severity

  1. The same limit prints as 3000000000 when read from text but 3E+9 after deepCopy, from a plain ObjectMapper tree, or after moving the node (non-token path in CountLimit). Enforcement is correct; only the message text differs.
  2. CountTokens.Token: this.value = snapshot.equals(text) ? text : snapshot; always equals snapshot.

Observation, no finding: on master, YAML .inf in a count keyword now rejects every array, where base ignored it. That follows from the documented sign-saturation of infinite nodes.

🤖 Generated with Claude Code

@stevehu

stevehu commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up on 631bcf5.

I compared it with 31a4b86 through the GitHub compare API: the only change is one comment line in CountTokens.Token, so no executable behaviour changed. I did not rebuild or re-run anything for this commit; my earlier verification of 31a4b86 still applies.

  • Redundant ternary in Token: my claim was incomplete. snapshot.equals(text) ? text : snapshot shares the captured String so only one is retained per entry, and the new comment explains that. Resolved, no code change needed.
  • Message mismatch (3000000000 from text vs 3E+9 after deepCopy, a plain mapper tree, or a moved node): kept as is, with the decision recorded in the PR description. Enforcement is correct and only the text differs, so I've left it open as an accepted trade-off.

Still open from the earlier pass, unchanged: the 1e999999999999 active-keyword boundary, the sidecar's extra token capture for unread count-named floats, and the deepCopy compatibility concern. For the last one, I'd still like the maintainers to explicitly accept that trade-off before merge.

🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant