From 985c75067eccfdc2a18878ace5240e7e85309b85 Mon Sep 17 00:00:00 2001 From: Leo Romanovsky Date: Mon, 16 Nov 2026 18:02:06 -0500 Subject: [PATCH 1/3] Share frozen JSON variant values and keep their integers exact Each evaluation of a JSON flag converted the whole variant tree to a new OpenFeature Value. The cost grew with the variant size: about 21 us and 83 KB for a 712-node variant. The parser now builds one Value for each JSON object or array variant. Evaluations return that instance. Its structures are MutableStructure over unmodifiable maps and its lists are unmodifiable, so callers cannot change it, and equals is the same as Value.objectToValue. The plain-map form is built once and shared. Integers in JSON variant values now stay Integer or Long instead of Double, so 5 is returned as 5 and integers above 2^53 stay exact. Scalar flags keep Double values. --- .../internal/evaluation/FlagEvaluator.java | 6 +- .../internal/ufc/FrozenValues.java | 112 +++++++++++++++ .../ufc/UniversalFlagConfigParser.java | 92 ++++++++++--- .../openfeature/internal/ufc/Variant.java | 9 ++ .../openfeature/CanonicalFixtureTest.java | 27 +++- .../FlagEvaluatorJsonValueTest.java | 128 ++++++++++++++++++ 6 files changed, 354 insertions(+), 20 deletions(-) create mode 100644 dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java create mode 100644 dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/evaluation/FlagEvaluator.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/evaluation/FlagEvaluator.java index 55ba7dc45ce..376851e52d9 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/evaluation/FlagEvaluator.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/evaluation/FlagEvaluator.java @@ -476,7 +476,11 @@ private ProviderEvaluation resolveVariant( final T mappedValue; try { - mappedValue = mapValue(target, variant.value); + // A JSON variant is converted once, at parse time: share it instead of a copy per call. + mappedValue = + target == Value.class && variant.frozenValue != null + ? target.cast(variant.frozenValue) + : mapValue(target, variant.value); } catch (final NumberFormatException e) { return error( defaultValue, diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java new file mode 100644 index 00000000000..1c846c28dcb --- /dev/null +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java @@ -0,0 +1,112 @@ +package com.datadog.openfeature.internal.ufc; + +import dev.openfeature.sdk.MutableStructure; +import dev.openfeature.sdk.Structure; +import dev.openfeature.sdk.Value; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Builds the OpenFeature {@link Value} of a JSON variant once, when the configuration is parsed, so + * that each evaluation returns the same instance instead of a new deep copy. + * + *

Each JSON object becomes a {@link FrozenStructure}: a {@link MutableStructure} over an + * unmodifiable map, so {@code getValue} returns the shared child without a copy and {@code add} + * throws {@link UnsupportedOperationException}. The type is the one {@link Value#objectToValue} + * returns, so {@code equals} and {@code hashCode} are unchanged. Each JSON array becomes an + * unmodifiable list. A {@link Value} has no setters, so the whole tree cannot change. + */ +public final class FrozenValues { + private FrozenValues() {} + + /** Tells whether the value is a JSON object or array, the values that are frozen. */ + static boolean isContainer(final Object value) { + return value instanceof Map || value instanceof List; + } + + /** + * Converts a parsed JSON tree to a {@link Value} that cannot change. The result is equal to + * {@code Value.objectToValue(tree)}. + */ + static Value freeze(final Object tree) { + if (tree instanceof Map) { + final Map source = (Map) tree; + final Map attributes = new HashMap<>(capacity(source.size())); + for (final Map.Entry entry : source.entrySet()) { + attributes.put((String) entry.getKey(), freeze(entry.getValue())); + } + return new Value(new FrozenStructure(Collections.unmodifiableMap(attributes))); + } + if (tree instanceof List) { + final List source = (List) tree; + final List items = new ArrayList<>(source.size()); + for (final Object element : source) { + items.add(freeze(element)); + } + return new Value(Collections.unmodifiableList(items)); + } + return Value.objectToValue(tree); + } + + private static int capacity(final int size) { + return (int) Math.min(Integer.MAX_VALUE, (long) size * 4 / 3 + 1); + } + + /** + * A structure that cannot change. It also keeps its plain-map form, because applications often + * read a JSON flag with {@link #asObjectMap()}. + */ + static final class FrozenStructure extends MutableStructure { + private volatile Map objectMap; + + FrozenStructure(final Map attributes) { + super(attributes); + } + + /** + * Returns the plain-map form, built on the first call and then shared. The map and its nested + * maps and lists cannot change. + */ + @Override + public Map asObjectMap() { + Map map = this.objectMap; + if (map == null) { + map = toObjectMap(this); + // A race builds equal immutable maps; any of them can be kept. + this.objectMap = map; + } + return map; + } + + private static Map toObjectMap(final Structure structure) { + final Map attributes = structure.asUnmodifiableMap(); + final Map map = new HashMap<>(capacity(attributes.size())); + for (final Map.Entry entry : attributes.entrySet()) { + map.put(entry.getKey(), toObject(entry.getValue())); + } + return Collections.unmodifiableMap(map); + } + + /** + * The same conversion as {@link Structure#convertValue}, with unmodifiable containers. {@link + * #freeze} gives each child a non-null {@link Value}, and each nested structure is frozen. + */ + private static Object toObject(final Value value) { + if (value.isStructure()) { + return value.asStructure().asObjectMap(); + } + if (value.isList()) { + final List source = value.asList(); + final List items = new ArrayList<>(source.size()); + for (final Value item : source) { + items.add(toObject(item)); + } + return Collections.unmodifiableList(items); + } + return value.asObject(); + } + } +} diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java index d6fb0e435f4..43018d71d5f 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java @@ -23,9 +23,9 @@ * Parses Universal Flag Configuration (UFC) documents. * *

The document is first read as a generic JSON tree (objects, arrays, strings, {@link Double} - * numbers, booleans and nulls), then mapped onto the UFC model. Malformed flags are dropped - * individually and reported through {@link ServerConfiguration#invalidFlags}; a malformed envelope - * fails the whole document. + * numbers, booleans and nulls; integers in variant values stay {@link Integer} or {@link Long}), + * then mapped onto the UFC model. Malformed flags are dropped individually and reported through + * {@link ServerConfiguration#invalidFlags}; a malformed envelope fails the whole document. */ public final class UniversalFlagConfigParser { private static final Logger LOGGER = LoggerFactory.getLogger(UniversalFlagConfigParser.class); @@ -85,7 +85,7 @@ private static Object readDocument(final byte[] content) throws IOException { if (parser.nextToken() == null) { throw new JsonParseException(parser, "Empty document"); } - final Object document = readValue(parser, 1); + final Object document = readValue(parser, 1, Scope.UFC); if (parser.nextToken() != null) { throw new JsonParseException(parser, "Unexpected content after the document"); } @@ -93,7 +93,37 @@ private static Object readDocument(final byte[] content) throws IOException { } } - private static Object readValue(final JsonParser parser, final int depth) throws IOException { + /** + * Where the reader is in the document. UFC numbers are read as {@link Double}, but the numbers of + * a variant value ({@code variations..value}) keep their integer type, so that a JSON + * variant returns {@code 5} and not {@code 5.0}, and keeps integers above 2^53 exact. + */ + private enum Scope { + UFC, + VARIATIONS, + VARIANT, + VARIANT_VALUE; + + Scope field(final String name) { + switch (this) { + case UFC: + return "variations".equals(name) ? VARIATIONS : UFC; + case VARIATIONS: + return VARIANT; + case VARIANT: + return "value".equals(name) ? VARIANT_VALUE : UFC; + default: + return VARIANT_VALUE; + } + } + + Scope element() { + return this == VARIANT_VALUE ? VARIANT_VALUE : UFC; + } + } + + private static Object readValue(final JsonParser parser, final int depth, final Scope scope) + throws IOException { final JsonToken token = parser.currentToken(); if ((token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) && depth > MAX_NESTING_DEPTH) { @@ -105,24 +135,32 @@ private static Object readValue(final JsonParser parser, final int depth) throws while (parser.nextToken() == JsonToken.FIELD_NAME) { final String name = parser.currentName(); parser.nextToken(); - object.put(name, readValue(parser, depth + 1)); + object.put(name, readValue(parser, depth + 1, scope.field(name))); } return object; case START_ARRAY: final List array = new ArrayList<>(); while (parser.nextToken() != JsonToken.END_ARRAY) { - array.add(readValue(parser, depth + 1)); + array.add(readValue(parser, depth + 1, scope.element())); } return array; case VALUE_STRING: return parser.getText(); case VALUE_NUMBER_INT: - case VALUE_NUMBER_FLOAT: - final double number = parser.getDoubleValue(); - if (!Double.isFinite(number)) { - throw new JsonParseException(parser, "Non-finite JSON number"); + if (scope == Scope.VARIANT_VALUE) { + // OpenFeature values hold Integer, Long or Double: larger integers stay doubles. + switch (parser.getNumberType()) { + case INT: + return parser.getIntValue(); + case LONG: + return parser.getLongValue(); + default: + break; + } } - return number; + return finiteDouble(parser); + case VALUE_NUMBER_FLOAT: + return finiteDouble(parser); case VALUE_TRUE: return Boolean.TRUE; case VALUE_FALSE: @@ -134,6 +172,14 @@ private static Object readValue(final JsonParser parser, final int depth) throws } } + private static double finiteDouble(final JsonParser parser) throws IOException { + final double number = parser.getDoubleValue(); + if (!Double.isFinite(number)) { + throw new JsonParseException(parser, "Non-finite JSON number"); + } + return number; + } + @Nullable private static ServerConfiguration toServerConfiguration(@Nullable final Object value) throws IOException { @@ -200,33 +246,43 @@ private static Flag toFlag(@Nullable final Object value) { return null; } final Map json = asObject(value, "flag"); + final ValueType variationType = + asEnum(json.get("variationType"), ValueType.class, "variationType"); return new Flag( asString(json.get("key"), "key"), strictBoolean(json, "enabled"), - asEnum(json.get("variationType"), ValueType.class, "variationType"), - toVariants(json.get("variations")), + variationType, + toVariants(json.get("variations"), variationType), toList(json.get("allocations"), "allocations", UniversalFlagConfigParser::toAllocation)); } @Nullable - private static Map toVariants(@Nullable final Object value) { + private static Map toVariants( + @Nullable final Object value, @Nullable final ValueType variationType) { if (value == null) { return null; } final Map variants = new HashMap<>(); for (final Map.Entry entry : asObject(value, "variations").entrySet()) { - variants.put((String) entry.getKey(), toVariant(entry.getValue())); + variants.put((String) entry.getKey(), toVariant(entry.getValue(), variationType)); } return variants; } @Nullable - private static Variant toVariant(@Nullable final Object value) { + private static Variant toVariant( + @Nullable final Object value, @Nullable final ValueType variationType) { if (value == null) { return null; } final Map json = asObject(value, "variant"); - return new Variant(asString(json.get("key"), "key"), json.get("value")); + Object variantValue = json.get("value"); + // Only JSON values keep exact integers; scalar flags keep the double they always had. + if (variationType != ValueType.JSON + && (variantValue instanceof Integer || variantValue instanceof Long)) { + variantValue = ((Number) variantValue).doubleValue(); + } + return new Variant(asString(json.get("key"), "key"), variantValue); } @Nullable diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java index 4d9246c5965..13c06cd4688 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java @@ -1,11 +1,20 @@ package com.datadog.openfeature.internal.ufc; +import dev.openfeature.sdk.Value; + public final class Variant { public final String key; public final Object value; + /** + * The value as a shared {@link Value} that cannot change, for a JSON object or array value; or + * {@code null}. Evaluations return it instead of converting {@link #value} again. + */ + public final Value frozenValue; + public Variant(final String key, final Object value) { this.key = key; this.value = value; + this.frozenValue = FrozenValues.isContainer(value) ? FrozenValues.freeze(value) : null; } } diff --git a/dd-openfeature/src/test/java/com/datadog/openfeature/CanonicalFixtureTest.java b/dd-openfeature/src/test/java/com/datadog/openfeature/CanonicalFixtureTest.java index 787fefa1c11..32f290660d0 100644 --- a/dd-openfeature/src/test/java/com/datadog/openfeature/CanonicalFixtureTest.java +++ b/dd-openfeature/src/test/java/com/datadog/openfeature/CanonicalFixtureTest.java @@ -306,6 +306,28 @@ private static Object normalize(final Object value) { return value; } + /** + * Maps the integral numbers read as Long to Integer when they fit, as the UFC parser does for + * JSON variant values. + */ + private static Object exactIntegers(final Object value) { + if (value instanceof Long) { + final long number = (Long) value; + return number == (int) number ? (Object) (int) number : value; + } + if (value instanceof Map) { + final Map map = new java.util.LinkedHashMap<>(); + ((Map) value).forEach((k, v) -> map.put((String) k, exactIntegers(v))); + return map; + } + if (value instanceof List) { + final List list = new ArrayList<>(); + ((List) value).forEach(v -> list.add(exactIntegers(v))); + return list; + } + return value; + } + static final class FixtureCase { final Map json; final String fileName; @@ -356,7 +378,10 @@ static final class FixtureCase { if (result.containsKey("doLog")) { assertNotNull(this.resultDoLog, "A doLog expectation must be a boolean"); } - this.resultValue = normalize(result.get("value")); + this.resultValue = + "JSON".equals(this.variationType) + ? exactIntegers(result.get("value")) + : normalize(result.get("value")); this.resultReason = (String) result.get("reason"); this.resultErrorCode = (String) result.get("errorCode"); if (result.containsKey("errorCode")) { diff --git a/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java b/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java new file mode 100644 index 00000000000..60c7e382ba1 --- /dev/null +++ b/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java @@ -0,0 +1,128 @@ +package com.datadog.openfeature.internal.evaluation; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.datadog.openfeature.internal.ufc.ServerConfiguration; +import com.datadog.openfeature.internal.ufc.UniversalFlagConfigParser; +import dev.openfeature.sdk.MutableContext; +import dev.openfeature.sdk.MutableStructure; +import dev.openfeature.sdk.ProviderEvaluation; +import dev.openfeature.sdk.Value; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** JSON variants are converted once, at parse time, and shared by every evaluation. */ +class FlagEvaluatorJsonValueTest { + private static final String VARIANT = + "{\"name\":\"blue\",\"count\":5,\"big\":9007199254740993,\"ratio\":1.5,\"on\":true," + + "\"none\":null,\"tags\":[\"a\",\"b\"],\"nested\":{\"items\":[1,{\"n\":2}]}}"; + + private final FlagEvaluator evaluator = new FlagEvaluator(false, (f, s, a, v, id) -> false); + + @Test + void returnsTheSameValueForEachEvaluation() throws Exception { + final ServerConfiguration config = config(VARIANT); + + final Value first = evaluate(config).getValue(); + final Value second = evaluate(config).getValue(); + + assertSame(first, second); + } + + @Test + void returnsTheValueThatObjectToValueReturns() throws Exception { + final ServerConfiguration config = config(VARIANT); + final Object tree = config.flags.get("f").variations.get("on").value; + + final Value value = evaluate(config).getValue(); + + assertEquals(Value.objectToValue(tree), value); + assertEquals( + Value.objectToValue(tree).asStructure().asObjectMap(), value.asStructure().asObjectMap()); + assertTrue(value.asStructure() instanceof MutableStructure); + } + + @Test + void sharesThePlainMapForm() throws Exception { + final Value value = evaluate(config(VARIANT)).getValue(); + + assertSame(value.asStructure().asObjectMap(), value.asStructure().asObjectMap()); + } + + @Test + void keepsIntegersExact() throws Exception { + final Value value = evaluate(config(VARIANT)).getValue(); + final Map map = value.asStructure().asObjectMap(); + + assertEquals(5, map.get("count")); + assertEquals(9007199254740993L, map.get("big")); + assertEquals(1.5, map.get("ratio")); + assertEquals(5, value.asStructure().getValue("count").asObject()); + } + + @Test + void cannotBeChangedByTheCaller() throws Exception { + final Value value = evaluate(config(VARIANT)).getValue(); + final MutableStructure structure = (MutableStructure) value.asStructure(); + final Map map = structure.asObjectMap(); + @SuppressWarnings("unchecked") + final Map nested = (Map) map.get("nested"); + @SuppressWarnings("unchecked") + final List items = (List) nested.get("items"); + + assertThrows(UnsupportedOperationException.class, () -> structure.add("k", "v")); + assertThrows( + UnsupportedOperationException.class, + () -> structure.getValue("tags").asList().add(new Value("c"))); + assertThrows(UnsupportedOperationException.class, () -> map.put("k", "v")); + assertThrows(UnsupportedOperationException.class, () -> nested.put("k", "v")); + assertThrows(UnsupportedOperationException.class, () -> items.add(3)); + } + + @Test + void returnsAJsonArrayVariant() throws Exception { + final Value value = evaluate(config("[1,\"two\",{\"three\":3}]")).getValue(); + + assertTrue(value.isList()); + assertEquals(1, value.asList().get(0).asObject()); + assertEquals(3, value.asList().get(2).asStructure().getValue("three").asObject()); + assertThrows(UnsupportedOperationException.class, () -> value.asList().add(new Value())); + } + + @Test + void keepsDoublesOutsideVariantValues() throws Exception { + final ServerConfiguration config = + UniversalFlagConfigParser.parse( + ("{\"flags\":{\"f\":{\"key\":\"f\",\"enabled\":true,\"variationType\":\"JSON\"," + + "\"variations\":{\"on\":{\"key\":\"on\",\"value\":{\"n\":1}}}," + + "\"allocations\":[{\"key\":\"a\",\"rules\":[{\"conditions\":[" + + "{\"attribute\":\"age\",\"operator\":\"GTE\",\"value\":18}]}]," + + "\"splits\":[{\"variationKey\":\"on\",\"shards\":[]}]}]}}}") + .getBytes(UTF_8)); + + final Object conditionValue = + config.flags.get("f").allocations.get(0).rules.get(0).conditions.get(0).value; + + assertEquals(18.0, conditionValue); + } + + private ProviderEvaluation evaluate(final ServerConfiguration config) { + return evaluator.evaluate(config, Value.class, "f", new Value(), new MutableContext("user")); + } + + private static ServerConfiguration config(final String variantValue) throws Exception { + return UniversalFlagConfigParser.parse( + ("{\"flags\":{\"f\":{\"key\":\"f\",\"enabled\":true,\"variationType\":\"JSON\"," + + "\"variations\":{\"on\":{\"key\":\"on\",\"value\":" + + variantValue + + "}}," + + "\"allocations\":[{\"key\":\"a\",\"splits\":[{\"variationKey\":\"on\"," + + "\"shards\":[]}]}]}}}") + .getBytes(UTF_8)); + } +} From debbf5abd91fde3bff25790c446b3e5f332dc872 Mon Sep 17 00:00:00 2001 From: Leo Romanovsky Date: Mon, 16 Nov 2026 18:58:17 -0500 Subject: [PATCH 2/3] Fix review findings on frozen JSON variant values - Keep Long values only when the loaded OpenFeature SDK supports them. SDK 1.21.0 and older reject a Long with TypeMismatchError, which rejected the whole configuration. - Freeze JSON variants in the parser, and store the frozen tree's plain form as Variant.value. The parsed tree is no longer kept as well. - Make the parser scope follow positions, so a flag keyed "variations" keeps exact integers. - Change nested integers of non-JSON flags back to Double, as before. - Use one number model for JSON fixture defaults and results. - Size maps exactly, and make FrozenValues package-private. - Correct javadoc, and document the read-only values and exact integers. - Add tests for the CDN envelope, the "variations" key, non-JSON flags and integers beyond the long range. --- dd-openfeature/README.md | 2 + .../internal/evaluation/FlagEvaluator.java | 2 +- .../internal/ufc/FrozenValues.java | 37 ++++++++-- .../ufc/UniversalFlagConfigParser.java | 64 +++++++++++++---- .../openfeature/internal/ufc/Variant.java | 11 ++- .../openfeature/CanonicalFixtureTest.java | 11 ++- .../FlagEvaluatorJsonValueTest.java | 71 +++++++++++++++++-- 7 files changed, 167 insertions(+), 31 deletions(-) diff --git a/dd-openfeature/README.md b/dd-openfeature/README.md index 60c735c7cb1..6f8e7e0718c 100644 --- a/dd-openfeature/README.md +++ b/dd-openfeature/README.md @@ -300,6 +300,8 @@ tracing remain active. Previously recorded or queued data is not removed. * The provider moved to `com.datadog.openfeature.Provider`, and the exposure hook to `com.datadog.openfeature.ExposureHook`. `datadog.trace.api.openfeature.Provider` and `datadog.trace.api.openfeature.ExposureHook` are kept as deprecated aliases. * The SDK no longer requires `dd-java-agent` and no longer links against agent classes. * `dd-openfeature` releases before 1.69.0 link to agent classes that `dd-java-agent` 1.69.0 removes: with `dd-java-agent` 1.69.0 or later, they return the caller default values. Upgrade `dd-openfeature` to 1.69.0 or later together with `dd-java-agent`. +* JSON flag values are now shared and read-only. Changing the returned structure, list, or `asObjectMap()` map throws `UnsupportedOperationException`. Copy the value before you change it, for example with `asMap()` or `new HashMap<>(structure.asObjectMap())`. The copy is shallow: also copy each nested map or list that you change. A hook that changes the value in `after` makes the evaluation return the default value with the `GENERAL` error code. +* Integers in JSON flag values are now `Integer` or `Long` (for example `5`, not `5.0`), and integers up to `Long.MAX_VALUE` keep their exact value. This also applies to `Value.asObject()` and `Value.equals`. To read a number as a double, use `Value.asDouble()` or `((Number) map.get("n")).doubleValue()`. ## Design notes for contributors diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/evaluation/FlagEvaluator.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/evaluation/FlagEvaluator.java index 376851e52d9..e4645cd7704 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/evaluation/FlagEvaluator.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/evaluation/FlagEvaluator.java @@ -476,7 +476,7 @@ private ProviderEvaluation resolveVariant( final T mappedValue; try { - // A JSON variant is converted once, at parse time: share it instead of a copy per call. + // An object or array variant is converted once, at parse time: share it, not a new copy. mappedValue = target == Value.class && variant.frozenValue != null ? target.cast(variant.frozenValue) diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java index 1c846c28dcb..6d588ff3c92 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java @@ -15,13 +15,30 @@ * *

Each JSON object becomes a {@link FrozenStructure}: a {@link MutableStructure} over an * unmodifiable map, so {@code getValue} returns the shared child without a copy and {@code add} - * throws {@link UnsupportedOperationException}. The type is the one {@link Value#objectToValue} - * returns, so {@code equals} and {@code hashCode} are unchanged. Each JSON array becomes an - * unmodifiable list. A {@link Value} has no setters, so the whole tree cannot change. + * throws {@link UnsupportedOperationException}. It extends {@link MutableStructure}, the type that + * {@link Value#objectToValue} returns, and does not override {@code equals}, {@code hashCode} or + * {@code canEqual}, so equality is unchanged. Each JSON array becomes an unmodifiable list. The + * leaves are String, Boolean, Integer, Long, Double or null, and a {@link Value} has no setters, so + * no part of the tree can change. */ -public final class FrozenValues { +final class FrozenValues { + /** + * Tells whether the loaded OpenFeature SDK holds {@link Long} values. SDK 1.22.0 added them: an + * older SDK rejects a {@code Long} with a {@code TypeMismatchError}. + */ + static final boolean LONG_VALUES = hasLongValues(); + private FrozenValues() {} + private static boolean hasLongValues() { + try { + Value.class.getConstructor(Long.class); + return true; + } catch (final NoSuchMethodException e) { + return false; + } + } + /** Tells whether the value is a JSON object or array, the values that are frozen. */ static boolean isContainer(final Object value) { return value instanceof Map || value instanceof List; @@ -51,8 +68,18 @@ static Value freeze(final Object tree) { return Value.objectToValue(tree); } + /** + * Returns the plain form of a frozen value: the shared {@code asObjectMap()} map of an object, or + * an unmodifiable list of plain values for an array. It is equal to the tree that was frozen. + */ + static Object plain(final Value frozen) { + return frozen.isStructure() + ? frozen.asStructure().asObjectMap() + : FrozenStructure.toObject(frozen); + } + private static int capacity(final int size) { - return (int) Math.min(Integer.MAX_VALUE, (long) size * 4 / 3 + 1); + return (int) Math.min(Integer.MAX_VALUE, ((long) size * 4 + 2) / 3); } /** diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java index 43018d71d5f..df1c529a720 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; +import dev.openfeature.sdk.Value; import java.io.IOException; import java.time.Instant; import java.time.format.DateTimeFormatter; @@ -23,9 +24,10 @@ * Parses Universal Flag Configuration (UFC) documents. * *

The document is first read as a generic JSON tree (objects, arrays, strings, {@link Double} - * numbers, booleans and nulls; integers in variant values stay {@link Integer} or {@link Long}), - * then mapped onto the UFC model. Malformed flags are dropped individually and reported through - * {@link ServerConfiguration#invalidFlags}; a malformed envelope fails the whole document. + * numbers, booleans and nulls; an integer in a variant value that fits in a long is read as {@link + * Integer} or {@link Long}), then mapped onto the UFC model. Malformed flags are dropped + * individually and reported through {@link ServerConfiguration#invalidFlags}; a malformed envelope + * fails the whole document. */ public final class UniversalFlagConfigParser { private static final Logger LOGGER = LoggerFactory.getLogger(UniversalFlagConfigParser.class); @@ -94,12 +96,16 @@ private static Object readDocument(final byte[] content) throws IOException { } /** - * Where the reader is in the document. UFC numbers are read as {@link Double}, but the numbers of - * a variant value ({@code variations..value}) keep their integer type, so that a JSON - * variant returns {@code 5} and not {@code 5.0}, and keeps integers above 2^53 exact. + * Where the reader is in the document. Numbers are read as {@link Double}, except integers in a + * variant value ({@code flags..variations..value}): an integer that fits in a long is + * read as {@link Integer} or {@link Long}. So a JSON variant returns {@code 5} and not {@code + * 5.0}, and integers from 2^53 to 2^63-1 stay exact. The scopes follow positions, not only field + * names, so a flag key such as {@code "variations"} does not change them. */ private enum Scope { UFC, + FLAGS, + FLAG, VARIATIONS, VARIANT, VARIANT_VALUE; @@ -107,6 +113,10 @@ private enum Scope { Scope field(final String name) { switch (this) { case UFC: + return "flags".equals(name) ? FLAGS : UFC; + case FLAGS: + return FLAG; + case FLAG: return "variations".equals(name) ? VARIATIONS : UFC; case VARIATIONS: return VARIANT; @@ -153,7 +163,11 @@ private static Object readValue(final JsonParser parser, final int depth, final case INT: return parser.getIntValue(); case LONG: - return parser.getLongValue(); + // OpenFeature SDKs before 1.22.0 have no Long values: keep the double there. + if (FrozenValues.LONG_VALUES) { + return parser.getLongValue(); + } + break; default: break; } @@ -276,13 +290,37 @@ private static Variant toVariant( return null; } final Map json = asObject(value, "variant"); - Object variantValue = json.get("value"); - // Only JSON values keep exact integers; scalar flags keep the double they always had. - if (variationType != ValueType.JSON - && (variantValue instanceof Integer || variantValue instanceof Long)) { - variantValue = ((Number) variantValue).doubleValue(); + final String key = asString(json.get("key"), "key"); + final Object variantValue = json.get("value"); + if (variationType == ValueType.JSON && FrozenValues.isContainer(variantValue)) { + // A JSON object or array is converted once, here: evaluations share it. Its plain form + // replaces the parsed tree, so the parsed containers are not kept as well. + final Value frozen = FrozenValues.freeze(variantValue); + return new Variant(key, FrozenValues.plain(frozen), frozen); + } + if (variationType == ValueType.JSON) { + return new Variant(key, variantValue, null); + } + // Only JSON flags keep exact integers. Other or missing types get back the doubles they had. + return new Variant(key, withDoubles(variantValue), null); + } + + /** Replaces each Integer or Long in a variant value with the equal Double. */ + private static Object withDoubles(@Nullable final Object value) { + if (value instanceof Integer || value instanceof Long) { + return ((Number) value).doubleValue(); + } + if (value instanceof Map) { + final Map map = new LinkedHashMap<>(); + ((Map) value).forEach((k, v) -> map.put(k, withDoubles(v))); + return map; + } + if (value instanceof List) { + final List list = new ArrayList<>(); + ((List) value).forEach(v -> list.add(withDoubles(v))); + return list; } - return new Variant(asString(json.get("key"), "key"), variantValue); + return value; } @Nullable diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java index 13c06cd4688..a087cc4ca9a 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java @@ -7,14 +7,19 @@ public final class Variant { public final Object value; /** - * The value as a shared {@link Value} that cannot change, for a JSON object or array value; or - * {@code null}. Evaluations return it instead of converting {@link #value} again. + * For a JSON flag whose value is an object or an array: the value as a shared {@link Value} that + * cannot change; otherwise {@code null}. An evaluation that requests a {@link Value} returns it + * instead of converting {@link #value} again. */ public final Value frozenValue; public Variant(final String key, final Object value) { + this(key, value, null); + } + + public Variant(final String key, final Object value, final Value frozenValue) { this.key = key; this.value = value; - this.frozenValue = FrozenValues.isContainer(value) ? FrozenValues.freeze(value) : null; + this.frozenValue = frozenValue; } } diff --git a/dd-openfeature/src/test/java/com/datadog/openfeature/CanonicalFixtureTest.java b/dd-openfeature/src/test/java/com/datadog/openfeature/CanonicalFixtureTest.java index 32f290660d0..755b55236f6 100644 --- a/dd-openfeature/src/test/java/com/datadog/openfeature/CanonicalFixtureTest.java +++ b/dd-openfeature/src/test/java/com/datadog/openfeature/CanonicalFixtureTest.java @@ -288,7 +288,10 @@ private static Class targetType(final String variationType) { } } - /** Normalizes the integral numbers read as Long to Double, as the UFC parser does. */ + /** + * Normalizes the integral numbers read as Long to Double, as the UFC parser does outside JSON + * variant values. + */ private static Object normalize(final Object value) { if (value instanceof Long) { return ((Long) value).doubleValue(); @@ -356,10 +359,14 @@ static final class FixtureCase { this.index = index; final Object attributes = normalize(json.get("attributes")); this.attributes = attributes == null ? emptyMap() : (Map) attributes; - this.defaultValue = normalize(json.get("defaultValue")); this.flag = (String) json.get("flag"); this.targetingKey = (String) json.get("targetingKey"); this.variationType = (String) json.get("variationType"); + // The default value of a JSON case uses the same number model as its result. + this.defaultValue = + "JSON".equals(this.variationType) + ? exactIntegers(json.get("defaultValue")) + : normalize(json.get("defaultValue")); final Map result = (Map) json.get("result"); requireSupportedKeys( result, diff --git a/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java b/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java index 60c7e382ba1..40ceb8954a6 100644 --- a/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java +++ b/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java @@ -111,18 +111,75 @@ void keepsDoublesOutsideVariantValues() throws Exception { assertEquals(18.0, conditionValue); } + @Test + void keepsIntegersExactForAFlagKeyedVariations() throws Exception { + final ServerConfiguration config = config("variations", "JSON", "{\"n\":5}"); + + final Value value = + evaluator + .evaluate(config, Value.class, "variations", new Value(), new MutableContext("user")) + .getValue(); + + assertEquals(5, value.asStructure().asObjectMap().get("n")); + } + + @Test + void keepsIntegersExactInTheJsonApiEnvelope() throws Exception { + final ServerConfiguration config = + UniversalFlagConfigParser.parseJsonApi( + ("{\"data\":{\"type\":\"universal-flag-configuration\",\"attributes\":" + + "{\"createdAt\":\"2024-04-17T19:40:53.716Z\"," + + "\"environment\":{\"name\":\"Test\"}," + + flags("f", "JSON", "{\"big\":9007199254740993}") + + "}}}") + .getBytes(UTF_8)); + + assertEquals( + 9007199254740993L, evaluate(config).getValue().asStructure().getValue("big").asObject()); + } + + @Test + void keepsDoublesInOtherFlagTypes() throws Exception { + final ServerConfiguration integer = config("f", "INTEGER", "5"); + final ServerConfiguration string = config("f", "STRING", "{\"n\":5,\"l\":[1]}"); + + assertEquals(5.0, integer.flags.get("f").variations.get("on").value); + assertEquals( + "{n=5.0, l=[1.0]}", String.valueOf(string.flags.get("f").variations.get("on").value)); + assertEquals(null, string.flags.get("f").variations.get("on").frozenValue); + } + + @Test + void keepsDoublesForIntegersBeyondTheLongRange() throws Exception { + final Value value = evaluate(config("{\"n\":9223372036854775808}")).getValue(); + + assertEquals(9.223372036854776E18, value.asStructure().getValue("n").asObject()); + } + private ProviderEvaluation evaluate(final ServerConfiguration config) { return evaluator.evaluate(config, Value.class, "f", new Value(), new MutableContext("user")); } private static ServerConfiguration config(final String variantValue) throws Exception { + return config("f", "JSON", variantValue); + } + + private static ServerConfiguration config( + final String key, final String type, final String variantValue) throws Exception { return UniversalFlagConfigParser.parse( - ("{\"flags\":{\"f\":{\"key\":\"f\",\"enabled\":true,\"variationType\":\"JSON\"," - + "\"variations\":{\"on\":{\"key\":\"on\",\"value\":" - + variantValue - + "}}," - + "\"allocations\":[{\"key\":\"a\",\"splits\":[{\"variationKey\":\"on\"," - + "\"shards\":[]}]}]}}}") - .getBytes(UTF_8)); + ("{" + flags(key, type, variantValue) + "}").getBytes(UTF_8)); + } + + private static String flags(final String key, final String type, final String variantValue) { + return "\"flags\":{\"" + + key + + "\":{\"key\":\"" + + key + + "\",\"enabled\":true,\"variationType\":\"" + + type + + "\",\"variations\":{\"on\":{\"key\":\"on\",\"value\":" + + variantValue + + "}},\"allocations\":[{\"key\":\"a\",\"splits\":[{\"variationKey\":\"on\"," + + "\"shards\":[]}]}]}}"; } } From 1ef0bc516d3696944b004e258c1387e01ee7b54c Mon Sep 17 00:00:00 2001 From: Leo Romanovsky Date: Mon, 16 Nov 2026 19:07:00 -0500 Subject: [PATCH 3/3] Simplify the JSON variant parsing and its javadoc Handle non-JSON flags first in toVariant, use assertNull, and shorten the javadoc. No behavior change. --- .../internal/ufc/FrozenValues.java | 17 ++++---------- .../ufc/UniversalFlagConfigParser.java | 23 ++++++++----------- .../openfeature/internal/ufc/Variant.java | 6 +---- .../FlagEvaluatorJsonValueTest.java | 3 ++- 4 files changed, 17 insertions(+), 32 deletions(-) diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java index 6d588ff3c92..635a10d9ece 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/FrozenValues.java @@ -15,17 +15,11 @@ * *

Each JSON object becomes a {@link FrozenStructure}: a {@link MutableStructure} over an * unmodifiable map, so {@code getValue} returns the shared child without a copy and {@code add} - * throws {@link UnsupportedOperationException}. It extends {@link MutableStructure}, the type that - * {@link Value#objectToValue} returns, and does not override {@code equals}, {@code hashCode} or - * {@code canEqual}, so equality is unchanged. Each JSON array becomes an unmodifiable list. The - * leaves are String, Boolean, Integer, Long, Double or null, and a {@link Value} has no setters, so - * no part of the tree can change. + * throws {@link UnsupportedOperationException}. It keeps the equality of {@link + * Value#objectToValue}. Each JSON array becomes an unmodifiable list. */ final class FrozenValues { - /** - * Tells whether the loaded OpenFeature SDK holds {@link Long} values. SDK 1.22.0 added them: an - * older SDK rejects a {@code Long} with a {@code TypeMismatchError}. - */ + /** Tells whether the loaded OpenFeature SDK accepts {@link Long} values (1.22.0 or later). */ static final boolean LONG_VALUES = hasLongValues(); private FrozenValues() {} @@ -68,10 +62,7 @@ static Value freeze(final Object tree) { return Value.objectToValue(tree); } - /** - * Returns the plain form of a frozen value: the shared {@code asObjectMap()} map of an object, or - * an unmodifiable list of plain values for an array. It is equal to the tree that was frozen. - */ + /** Returns the plain form of a frozen value, equal to the tree that was frozen. */ static Object plain(final Value frozen) { return frozen.isStructure() ? frozen.asStructure().asObjectMap() diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java index df1c529a720..0886116c64e 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/UniversalFlagConfigParser.java @@ -96,11 +96,9 @@ private static Object readDocument(final byte[] content) throws IOException { } /** - * Where the reader is in the document. Numbers are read as {@link Double}, except integers in a - * variant value ({@code flags..variations..value}): an integer that fits in a long is - * read as {@link Integer} or {@link Long}. So a JSON variant returns {@code 5} and not {@code - * 5.0}, and integers from 2^53 to 2^63-1 stay exact. The scopes follow positions, not only field - * names, so a flag key such as {@code "variations"} does not change them. + * Where the reader is in the document. Numbers are read as {@link Double}, except integers in + * {@code flags..variations..value} that fit in a long: those are read as {@link + * Integer} or {@link Long}, so JSON variants keep exact integers. */ private enum Scope { UFC, @@ -292,17 +290,16 @@ private static Variant toVariant( final Map json = asObject(value, "variant"); final String key = asString(json.get("key"), "key"); final Object variantValue = json.get("value"); - if (variationType == ValueType.JSON && FrozenValues.isContainer(variantValue)) { - // A JSON object or array is converted once, here: evaluations share it. Its plain form - // replaces the parsed tree, so the parsed containers are not kept as well. - final Value frozen = FrozenValues.freeze(variantValue); - return new Variant(key, FrozenValues.plain(frozen), frozen); + if (variationType != ValueType.JSON) { + // Only JSON flags keep exact integers. + return new Variant(key, withDoubles(variantValue), null); } - if (variationType == ValueType.JSON) { + if (!FrozenValues.isContainer(variantValue)) { return new Variant(key, variantValue, null); } - // Only JSON flags keep exact integers. Other or missing types get back the doubles they had. - return new Variant(key, withDoubles(variantValue), null); + // Freeze once and share it. Keep its plain form instead of the parsed tree. + final Value frozen = FrozenValues.freeze(variantValue); + return new Variant(key, FrozenValues.plain(frozen), frozen); } /** Replaces each Integer or Long in a variant value with the equal Double. */ diff --git a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java index a087cc4ca9a..fac2db6a9fb 100644 --- a/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java +++ b/dd-openfeature/src/main/java/com/datadog/openfeature/internal/ufc/Variant.java @@ -6,11 +6,7 @@ public final class Variant { public final String key; public final Object value; - /** - * For a JSON flag whose value is an object or an array: the value as a shared {@link Value} that - * cannot change; otherwise {@code null}. An evaluation that requests a {@link Value} returns it - * instead of converting {@link #value} again. - */ + /** The shared, read-only value of a JSON object or array variant; otherwise {@code null}. */ public final Value frozenValue; public Variant(final String key, final Object value) { diff --git a/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java b/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java index 40ceb8954a6..15e5bb5e189 100644 --- a/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java +++ b/dd-openfeature/src/test/java/com/datadog/openfeature/internal/evaluation/FlagEvaluatorJsonValueTest.java @@ -2,6 +2,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -146,7 +147,7 @@ void keepsDoublesInOtherFlagTypes() throws Exception { assertEquals(5.0, integer.flags.get("f").variations.get("on").value); assertEquals( "{n=5.0, l=[1.0]}", String.valueOf(string.flags.get("f").variations.get("on").value)); - assertEquals(null, string.flags.get("f").variations.get("on").frozenValue); + assertNull(string.flags.get("f").variations.get("on").frozenValue); } @Test