Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ This project does not adhere to [Semantic Versioning](https://semver.org/) and m

### Changed

- Avoid duplicate numeric text-buffer reads when classifying JSON/YAML decimals; pin fast-path boundaries, randomized classification, and Jackson 3 name-matcher cache invalidation with regression tests. [#1368](https://github.com/networknt/json-schema-validator/issues/1368)
- Reduce decimal-preserving tree parser overhead by caching per token and avoiding text and decimal allocations for lossless floats. [#1362](https://github.com/networknt/json-schema-validator/issues/1362)
- `JsonMapperFactory.getInstance()` and `YamlMapperFactory.getInstance()` now return `DecimalNode` values for lossy finite floating-point spellings when reading trees, subject to explicit mapper settings and custom node factories. (#1357)
- Preserve lossy finite decimal literals uniformly in built-in JSON/YAML schema and instance readers and public mapper-factory tree reads. Bounds and `multipleOf` now validate decimal spellings such as `9007199254740993.0` exactly. Decimal nodes can surface in literals, defaults, examples, annotations and JSON output; finite numeric equality no longer depends on the field name. Lossless doubles and signed zero retain type/sign/serialization. Existing overflow/nonfinite behavior, count-specific precision, explicit mapper settings, custom node factories and scalar/POJO binding policies are retained. This intentionally changes validation where values previously rounded to the same double. (#1357)
Expand Down
25 changes: 22 additions & 3 deletions doc/issue-1362-performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,29 @@ result is stale and is not qualification evidence for this change.

## Measurement

The #1368 character-buffer reuse is allocation hygiene. YAML wall-clock
measurements reported during review of the master branch were within timing
noise. The historical table below predates that change and does not establish
a speedup from it.

### Historical standalone-harness results

The table below comes from the separate best-of-eight timing harness used for
#1362; that harness is not checked into this repository. It does **not** come
from the checked-in `DecimalTreeBenchmark` JMH benchmark. These are historical
results from before the #1368 character-buffer reuse change.

Corretto 25.0.3, 1 GiB fixed heap, eight warmups and best of eight reads.
Native means an unmodified Jackson JsonMapper/YAMLMapper; selective means
NodeReader.readTree using the default policy. These are tree-read timings,
not end-to-end Schema.validate timings or a before/after comparison.
JSON uses 200,000 elements. YAML uses 20,000 to stay below its default
3,145,728-code-point limit for every payload. Seed: 1362.
This lightweight harness is indicative; the checked-in JMH benchmark supplies
forked measurements and also covers the end-to-end validation path.
`DecimalTreeBenchmark` defaults to **20,000 elements for both formats**. The
standalone harness used **200,000 for JSON and 20,000 for YAML**. JMH uses
forked average-time measurements, while the table uses best-of-eight timings,
so its output is not a reproduction of this table. JMH also covers the
end-to-end validation path; that path is not measured in the table.

| Format | Payload | Elements | Native ms | Selective ms | Ratio |
|---|---|---:|---:|---:|---:|
Expand All @@ -56,7 +71,11 @@ plain/machine YAML floats meet the target in this measurement. The remaining
cost includes shortest-double formatting; precision has not been weakened to
meet a timing threshold. Issue #1362 should remain open pending that work.

## Repeat with JMH
## Run the checked-in JMH benchmark

These commands measure the current checkout. The JSON command overrides the
20,000-element default to match the historical JSON payload size; the YAML
command retains 20,000 elements. The measurement protocols remain different.

```sh
mvn -Pbenchmark -DskipTests package
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,18 @@ private boolean promote() {
if (nativeType == NumberTypeFP.BIG_DECIMAL || nativeType == NumberTypeFP.FLOAT32) {
return false;
}
if (isShortDecimal()) {
super.getDoubleValue();
return false;
int length = getStringLength();
char[] characters = null;
int offset = 0;
// Keep the buffer local to this decision. YAML builds a new array on
// each request; reuse it if the shortest-spelling comparison needs it.
if (length <= 16) {
characters = getStringCharacters();
offset = getStringOffset();
if (isShortDecimal(characters, offset, length)) {
super.getDoubleValue();
return false;
}
}
double number = super.getDoubleValue();
if (!Double.isFinite(number)) {
Expand All @@ -155,8 +164,14 @@ private boolean promote() {
}
}
String shortest = Double.toString(number);
if (matchesShortest(shortest)) {
return false; // Lossless machine-generated doubles need no token String or decimal.
if (length == shortest.length()) {
if (characters == null) {
characters = getStringCharacters();
offset = getStringOffset();
}
if (matchesShortest(shortest, characters, offset, length)) {
return false; // Lossless doubles need no token String or decimal.
}
}
String token = getString();
if (token.indexOf('_') >= 0) {
Expand All @@ -179,13 +194,7 @@ private boolean promote() {

// Binary64 preserves at least 15 significant decimal digits. Restrict this
// shortcut to short fixed-point tokens so underflow/overflow cannot apply.
private boolean isShortDecimal() {
int length = getStringLength();
if (length > 16) {
return false;
}
char[] characters = getStringCharacters();
int offset = getStringOffset();
private boolean isShortDecimal(char[] characters, int offset, int length) {
int digits = 0;
for (int i = 0; i < length; i++) {
char c = characters[offset + i];
Expand All @@ -198,13 +207,7 @@ private boolean isShortDecimal() {
return digits <= 15;
}

private boolean matchesShortest(String shortest) {
int length = getStringLength();
if (length != shortest.length()) {
return false;
}
char[] characters = getStringCharacters();
int offset = getStringOffset();
private boolean matchesShortest(String shortest, char[] characters, int offset, int length) {
for (int i = 0; i < length; i++) {
if (characters[offset + i] != shortest.charAt(i)) {
return false;
Expand Down
253 changes: 253 additions & 0 deletions src/test/java/com/networknt/schema/serialization/Issue1368Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
/*
* Copyright (c) 2016 Network New Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.schema.serialization;

import static org.junit.jupiter.api.Assertions.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

import com.networknt.schema.InputFormat;

import tools.jackson.core.JacksonException;
import tools.jackson.core.JsonParser;
import tools.jackson.core.JsonToken;
import tools.jackson.core.sym.PropertyNameMatcher;
import tools.jackson.core.sym.SimpleNameMatcher;
import tools.jackson.core.util.JsonParserDelegate;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.node.DecimalNode;
import tools.jackson.databind.node.DoubleNode;
import tools.jackson.dataformat.yaml.YAMLMapper;

/** Checked-in classification oracle and allocation-sensitive fast-path boundaries. */
@Tag("jackson-upgrade")
class Issue1368Test {
enum Format {
JSON, YAML;

ObjectMapper selective() {
return this == JSON ? JsonMapperFactory.getInstance() : YamlMapperFactory.getInstance();
}

ObjectMapper stock() {
return this == JSON ? JsonMapper.builder().build() : YAMLMapper.builder().build();
}
}

@ParameterizedTest
@EnumSource(Format.class)
void fixedPointDigitCharacterAndExponentBoundaries(Format format) throws Exception {
// Include equivalent but noncanonical spellings: the value alone does not pin shortcut selection.
String[] lossless = { "12345678901234.5", "1234567890123.40", "-1234567890123.40",
"12345678901234.50", "0.123456789012345", "1.234567890123456", "1.2345678901234567",
"0.10000000000000000000", "-0.0", "5.0", "1.25e+2", "1.2345E7", "1e-300" };
String[] lossy = { "9007199254740993.0", "-9007199254740993.0", "1.23456789012345678",
"1.00000000000000001e0", "1e-400", "-1e-400" };
for (String token : lossless) assertClassification(format, token, token, false);
for (String token : lossy) assertClassification(format, token, token, true);
assertEquals(16, "1234567890123.40".length());
assertEquals(17, "-1234567890123.40".length());
}

@Test
void yamlNumericSpellingsRetainTheirValuesAndTypes() throws Exception {
String[][] lossless = { { "5.", "5.0" }, { "!!float 123456789012345", "123456789012345" },
{ "!!float -123456789012345", "-123456789012345" }, { "!!float +123.25", "123.25" },
{ "!!float .5", "0.5" }, { "!!float 1_000.25", "1000.25" }, { "!!float 5.", "5.0" } };
String[][] lossy = { { "!!float 9007199254740993", "9007199254740993" },
{ "!!float 9_007_199_254_740_993.0", "9007199254740993.0" },
{ "!!float +9007199254740993", "9007199254740993" } };
for (String[] token : lossless) assertClassification(Format.YAML, token[0], token[1], false);
for (String[] token : lossy) assertClassification(Format.YAML, token[0], token[1], true);
}

@Test
void yamlCoreSchemaRetainsImplicitStringsForNonCoreSpellings() throws Exception {
// Jackson 3 uses YAML Core Schema; explicit !!float is tested separately above.
for (String token : new String[] { "+123.25", ".5", "1_000.25", "9_007_199_254_740_993.0" }) {
JsonNode actual = Format.YAML.selective().readTree(token);
assertFalse(actual.isNumber(), token);
assertEquals("\"" + token + "\"", actual.toString());
assertEquals(Format.YAML.stock().readTree(token).getClass(), actual.getClass());
}
}

@Test
void yamlOnlySpellingsRemainInvalidJson() {
for (String token : new String[] { "+123.25", ".5", "5.", "1_000.25", "!!float 123.25" }) {
assertThrows(JacksonException.class, () -> Format.JSON.selective().readTree(token), token);
}
}

@ParameterizedTest
@EnumSource(Format.class)
void fixedSeedClassificationMatchesIndependentDecimalOracle(Format format) throws Exception {
Random random = new Random(1368);
List<String> tokens = new ArrayList<>();
for (int i = 0; i < 4096; i++) {
String token;
switch (i % 6) {
case 0:
token = BigDecimal.valueOf(random.nextLong() % 1000000000000000L,
1 + random.nextInt(14)).toPlainString();
break;
case 1:
token = Double.toString(Math.scalb(random.nextDouble() - 0.5, random.nextInt(1800) - 900));
break;
case 2:
StringBuilder digits = new StringBuilder().append(1 + random.nextInt(9));
int length = 16 + random.nextInt(25);
for (int j = 1; j < length; j++) digits.append(random.nextInt(10));
digits.insert(1 + random.nextInt(length - 1), '.');
token = (random.nextBoolean() ? "-" : "") + digits;
break;
case 3:
token = "1." + Math.abs(random.nextLong() % 1000000000000000L) + "e-" + (400 + random.nextInt(100));
break;
case 4:
token = (9007199254740990L + random.nextInt(16)) + ".0";
break;
default:
token = BigDecimal.valueOf(random.nextLong(), random.nextInt(500) - 250).toString();
break;
}
if (token.indexOf('.') < 0 && token.indexOf('E') < 0 && token.indexOf('e') < 0) token += ".0";
tokens.add(token);
}
String input = "[" + String.join(",", tokens) + "]";
JsonNode[] trees = { format.selective().readTree(input),
NodeReader.builder().build().readTree(input, InputFormat.valueOf(format.name())) };
for (JsonNode tree : trees) {
assertEquals(tokens.size(), tree.size());
for (int i = 0; i < tokens.size(); i++) {
String token = tokens.get(i);
double number = Double.parseDouble(token);
assertTrue(Double.isFinite(number), token);
BigDecimal decimal = new BigDecimal(token);
boolean lossy = decimal.compareTo(BigDecimal.valueOf(number)) != 0;
assertValue(tree.get(i), decimal, number, lossy, format + ": " + token);
}
}
}

@ParameterizedTest
@EnumSource(Format.class)
void shortcutAndShortestComparisonAvoidRepeatedTextMaterialization(Format format) throws Exception {
// 16 vs 17 chars: widening the conservative limit is numerically safe for this
// negative 15-digit value, so also pin whether the fallback reads its full text.
assertAccesses(format, "1234567890123.40", 1, 0);
// A short negative token must retain the shortcut, even though fallback has the same value.
assertAccesses(format, "-123456789012.5", 1, 0);
assertAccesses(format, "-1234567890123.40", 0, 1);
// A canonical exponent fails the fixed-point shortcut, then reuses its characters.
assertAccesses(format, "1.2345E7", 1, 0);
// Long canonical machine doubles skip the shortcut and still avoid token Strings.
assertAccesses(format, "1.234567890123456", 1, 0);
}

@ParameterizedTest
@EnumSource(Format.class)
void nameMatcherAdvancementInvalidatesTheCachedClassification(Format format) throws Exception {
PropertyNameMatcher matcher = SimpleNameMatcher.construct(Locale.ROOT, Arrays.asList("a", "b"));
String input = "{\"a\":0.1234567890123456789,\"unknown\":123.25,\"b\":0.1234567890123456789}";
try (JsonParser parser = SchemaNodeReader.precisionParser(format.stock().createParser(input), false)) {
assertEquals(JsonToken.START_OBJECT, parser.nextToken());
assertEquals(0, parser.nextNameMatch(matcher));
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, parser.nextNameMatch(matcher));
assertEquals(JsonParser.NumberType.BIG_DECIMAL, parser.getNumberType());
assertEquals(new BigDecimal("0.1234567890123456789"), parser.getDecimalValue());
assertEquals(PropertyNameMatcher.MATCH_UNKNOWN_NAME, parser.nextNameMatch(matcher));
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, parser.nextNameMatch(matcher));
assertEquals(JsonParser.NumberType.DOUBLE, parser.getNumberType());
assertEquals(123.25, parser.getDoubleValue());
assertEquals(1, parser.nextNameMatch(matcher));
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, parser.nextNameMatch(matcher));
assertEquals(JsonParser.NumberType.BIG_DECIMAL, parser.getNumberType());
assertEquals(new BigDecimal("0.1234567890123456789"), parser.getDecimalValue());
assertEquals(PropertyNameMatcher.MATCH_END_OBJECT, parser.nextNameMatch(matcher));
}
}

private static void assertClassification(Format format, String input, String normalized, boolean lossy) throws Exception {
BigDecimal decimal = new BigDecimal(normalized);
double number = Double.parseDouble(normalized);
JsonNode factoryTree = format.selective().readTree(input);
JsonNode readerTree = NodeReader.builder().build().readTree(input, InputFormat.valueOf(format.name()));
assertValue(factoryTree, decimal, number, lossy, format + ": " + input);
assertValue(readerTree, decimal, number, lossy, format + ": " + input);
}

private static void assertValue(JsonNode node, BigDecimal decimal, double number, boolean lossy, String label) {
assertEquals(lossy ? DecimalNode.class : DoubleNode.class, node.getClass(), label);
if (lossy) {
assertEquals(0, decimal.compareTo(node.decimalValue()), label);
} else {
assertEquals(Double.doubleToRawLongBits(number), Double.doubleToRawLongBits(node.doubleValue()), label);
}
}

private static void assertAccesses(Format format, String token, int maxCharacterReads, int maxTextReads) throws Exception {
ObjectMapper mapper = format.stock();
// Put numbers inside an object so JSON exercises a nonzero text-buffer offset.
CountingParser source = new CountingParser(mapper.createParser("{\"value\": " + token + "}"));
try (JsonParser parser = SchemaNodeReader.precisionParser(source, false)) {
parser.nextToken();
parser.nextToken();
assertEquals(JsonToken.VALUE_NUMBER_FLOAT, parser.nextToken());
parser.getNumberType();
parser.getNumberTypeFP();
// Bound our classification requests, before Jackson binds the tree. Fewer
// requests are fine; incidental reads by a future tree deserializer are irrelevant.
assertTrue(source.characterReads <= maxCharacterReads,
() -> format + ": " + token + " character reads " + source.characterReads + " > " + maxCharacterReads);
assertTrue(source.textReads <= maxTextReads,
() -> format + ": " + token + " text reads " + source.textReads + " > " + maxTextReads);
JsonNode node = mapper.reader().without(tools.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(parser);
assertValue(node, new BigDecimal(token), Double.parseDouble(token), false, token);
}
}

private static class CountingParser extends JsonParserDelegate {
int characterReads;
int textReads;

CountingParser(JsonParser parser) { super(parser); }

@Override
public char[] getStringCharacters() {
characterReads++;
return super.getStringCharacters();
}

@Override
public String getString() {
textReads++;
return super.getString();
}
}
}
Loading