diff --git a/core/src/main/java/com/google/adk/workflow/FunctionNodes.java b/core/src/main/java/com/google/adk/workflow/FunctionNodes.java index 659c72d2b..37f481d5e 100644 --- a/core/src/main/java/com/google/adk/workflow/FunctionNodes.java +++ b/core/src/main/java/com/google/adk/workflow/FunctionNodes.java @@ -27,7 +27,17 @@ /** * Creates {@link FunctionNode}s with a type per port, as a {@code Class} or, for a generic type * such as {@code List}, a {@code TypeReference}, read and written as {@link FunctionNode} - * describes. A node's body asks the user for input with {@link #requestInput}. + * describes. Port values also follow these rules: + * + * + * + *

A node's body asks the user for input with {@link #requestInput}. */ @Experimental public final class FunctionNodes { diff --git a/core/src/main/java/com/google/adk/workflow/PortCodec.java b/core/src/main/java/com/google/adk/workflow/PortCodec.java index 7005c749d..9c4febec5 100644 --- a/core/src/main/java/com/google/adk/workflow/PortCodec.java +++ b/core/src/main/java/com/google/adk/workflow/PortCodec.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.BeanDescription; +import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.DeserializationConfig; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -31,10 +32,13 @@ import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.KeyDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.cfg.CoercionAction; import com.fasterxml.jackson.databind.cfg.CoercionInputShape; +import com.fasterxml.jackson.databind.cfg.MutableCoercionConfig; import com.fasterxml.jackson.databind.deser.AbstractDeserializer; import com.fasterxml.jackson.databind.deser.BeanDeserializerBase; import com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder; @@ -43,6 +47,7 @@ import com.fasterxml.jackson.databind.deser.ValueInstantiator; import com.fasterxml.jackson.databind.deser.impl.UnsupportedTypeDeserializer; import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer; +import com.fasterxml.jackson.databind.deser.std.EnumDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer; import com.fasterxml.jackson.databind.introspect.Annotated; @@ -58,11 +63,14 @@ import com.fasterxml.jackson.databind.ser.std.StdKeySerializers; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.fasterxml.jackson.databind.type.LogicalType; +import com.fasterxml.jackson.databind.util.TokenBuffer; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.google.adk.events.Event; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; +import com.google.common.collect.ImmutableList; +import com.google.common.primitives.Primitives; import com.google.genai.JsonSerializable; import com.google.genai.types.Content; import com.google.genai.types.Schema; @@ -92,16 +100,18 @@ final class PortCodec { /** * One mapper for every port: unknown properties are ignored, null fields are written, {@code - * java.time} values travel as ISO-8601 strings, and genai types as genai writes them. A whole - * number reads a float only when it has no fraction, while a null primitive, an empty string as a - * number, boolean, enum or date, a number or boolean as text, and a missing {@link - * RequiredProperties} property fail. + * java.time} values travel as ISO-8601 strings, and genai types as genai writes them. Numbers, + * booleans and chars, also inside genai types, read as {@link PortScalars} describes, and any + * other whole-number type reads a float only when it has no fraction. It rejects a null + * primitive, an empty string as a number, boolean, enum or date, a number as an enum not written + * as one, a number or boolean as text, and a missing {@link RequiredProperties} property. */ static final ObjectMapper MAPPER = JsonMapper.builder() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT) .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .enable(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS) .withCoercionConfigDefaults( config -> config.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail)) // A Locale or URI writes some values, such as Locale.ROOT, as an empty string. @@ -109,20 +119,18 @@ final class PortCodec { LogicalType.OtherScalar, config -> config.setCoercion(CoercionInputShape.EmptyString, CoercionAction.TryConvert)) - .withCoercionConfig( - LogicalType.Textual, - config -> - config - .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail)) + .withCoercionConfig(LogicalType.Textual, PortCodec::rejectScalarsAsText) .addModule(new Jdk8Module()) .addModule(new JavaTimeModule()) + .addModule(PortScalars.module()) .addModule(portModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) .build(); + /** Genai's own reader of the form genai writes, with the port rules for scalars. */ + private static final ObjectReader GENAI_READER = genaiReader(); + /** The port's type, with a primitive boxed. */ private final JavaType type; @@ -520,7 +528,7 @@ boolean takesContent() { // Jackson's and genai's messages can quote the value, so no cause. throw doesNotMatch(what); } - // A message's JSON null, or "null" read as a Character, is not a value. + // A message's JSON null is not a value. if (converted == null && fromMessage) { throw doesNotMatch(what); } @@ -704,6 +712,10 @@ public JsonDeserializer modifyDeserializer( DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer deserializer) { + if (Primitives.wrap(beanDesc.getBeanClass()) == Boolean.class) { + return new IndexedValueDeserializer( + deserializer, ImmutableList.of(false, true), /* readsIndex= */ false); + } // Number also reports Integer, but takes any number, fractions included. return deserializer.logicalType() == LogicalType.Integer && beanDesc.getBeanClass() != Number.class @@ -711,6 +723,21 @@ public JsonDeserializer modifyDeserializer( : deserializer; } + @Override + public JsonDeserializer modifyEnumDeserializer( + DeserializationConfig config, + JavaType type, + BeanDescription beanDesc, + JsonDeserializer deserializer) { + // A JsonCreator enum keeps its own reader. + return deserializer instanceof EnumDeserializer + ? new IndexedValueDeserializer( + deserializer, + ImmutableList.copyOf(type.getRawClass().getEnumConstants()), + /* readsIndex= */ false) + : deserializer; + } + @Override public BeanDeserializerBuilder updateBuilder( DeserializationConfig config, @@ -737,7 +764,21 @@ public void serialize(JsonSerializable value, JsonGenerator gen, SerializerProvi } } - /** Reads a genai value with genai's own mapper, the reader of the form it writes. */ + private static ObjectReader genaiReader() { + ObjectMapper mapper = + JsonSerializable.objectMapper().copy().registerModule(PortScalars.module()); + rejectScalarsAsText(mapper.coercionConfigFor(LogicalType.Textual)); + return mapper.reader(); + } + + private static void rejectScalarsAsText(MutableCoercionConfig config) { + config + .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) + .setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail); + } + + /** Reads a genai value with {@link #GENAI_READER}. */ private static final class GenaiDeserializer extends StdDeserializer { GenaiDeserializer(Class type) { super(type); @@ -745,7 +786,7 @@ private static final class GenaiDeserializer extends StdDeserializer { @Override public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - return JsonSerializable.objectMapper().treeToValue(ctxt.readTree(p), handledType()); + return GENAI_READER.treeToValue(ctxt.readTree(p), handledType()); } } @@ -780,4 +821,82 @@ public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOEx return ctxt.readTreeAsValue(BigIntegerNode.valueOf(whole.toBigIntegerExact()), handledType()); } } + + /** + * Reads like its delegate but rejects text padded with whitespace. Where Jackson writes each of + * {@code values} as its own index, it also reads an index n as {@code values.get(n)}. Jackson + * reads only the instance {@link #createContextual} returns, which decides {@code readsIndex}. + */ + private static final class IndexedValueDeserializer extends DelegatingDeserializer { + private final ImmutableList values; + private final boolean readsIndex; + + IndexedValueDeserializer( + JsonDeserializer delegate, ImmutableList values, boolean readsIndex) { + super(delegate); + this.values = values; + this.readsIndex = readsIndex; + } + + @Override + protected JsonDeserializer newDelegatingInstance(JsonDeserializer newDelegatee) { + return new IndexedValueDeserializer(newDelegatee, values, readsIndex); + } + + @Override + public JsonDeserializer createContextual( + DeserializationContext ctxt, @Nullable BeanProperty property) throws JsonMappingException { + JsonDeserializer delegate = + ctxt.handleSecondaryContextualization( + _delegatee, property, ctxt.constructType(handledType())); + return new IndexedValueDeserializer(delegate, values, writesIndexes(property)); + } + + @Override + public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + if (readsIndex + && PortScalars.scalarValue(p) instanceof Long n + && n >= 0 + && n < values.size()) { + return values.get(n.intValue()); + } + String text = p.hasToken(JsonToken.VALUE_STRING) ? p.getText() : null; + Object value = super.deserialize(p, ctxt); + // Jackson's enum reader trims a name it does not find; keep only names the type writes. + if (text != null + && value != null + && !text.equals(text.trim()) + && !text.equals(MAPPER.valueToTree(value).asText())) { + return ctxt.handleWeirdStringValue(handledType(), text, "not a name it writes"); + } + return value; + } + + /** + * Whether Jackson writes each of {@code values} as its own index in {@code property}, or as a + * top-level value when {@code property} is null. A field with its own {@code JsonSerialize}, or + * a serializer that fails here, counts as not writing them. + */ + private boolean writesIndexes(@Nullable BeanProperty property) { + if (property != null && property.getAnnotation(JsonSerialize.class) != null) { + return false; + } + SerializerProvider provider = MAPPER.getSerializerProviderInstance(); + try { + JsonSerializer serializer = provider.findValueSerializer(handledType(), property); + for (int i = 0; i < values.size(); i++) { + try (TokenBuffer tokens = new TokenBuffer(MAPPER, /* hasNativeIds= */ false)) { + serializer.serialize(values.get(i), tokens, provider); + JsonParser written = tokens.asParserOnFirstToken(); + if (!written.hasToken(JsonToken.VALUE_NUMBER_INT) || written.getLongValue() != i) { + return false; + } + } + } + return true; + } catch (IOException | RuntimeException e) { + return false; + } + } + } } diff --git a/core/src/main/java/com/google/adk/workflow/PortScalars.java b/core/src/main/java/com/google/adk/workflow/PortScalars.java new file mode 100644 index 000000000..faa4ed171 --- /dev/null +++ b/core/src/main/java/com/google/adk/workflow/PortScalars.java @@ -0,0 +1,311 @@ +/* + * Copyright 2026 Google LLC + * + * 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.google.adk.workflow; + +import static java.util.Objects.requireNonNull; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.BeanProperty; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.KeyDeserializer; +import com.fasterxml.jackson.databind.deser.ContextualDeserializer; +import com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.google.common.primitives.Longs; +import com.google.common.primitives.Primitives; +import java.io.IOException; +import java.lang.reflect.Array; +import java.math.BigInteger; +import java.util.function.Function; +import java.util.function.LongFunction; +import java.util.regex.Pattern; +import org.jspecify.annotations.Nullable; + +/** + * Number, boolean and char readers, also for primitive arrays and map keys. Each accepts a value's + * own JSON type, the same value quoted, and for an integer type a whole number such as {@code + * "1e2"}; Jackson's coercion configs cannot express this. {@code BigInteger}, {@code BigDecimal}, + * {@code Number}, {@code OptionalInt}, {@code OptionalLong}, {@code OptionalDouble} and the {@code + * Atomic} types keep Jackson's readers. + */ +final class PortScalars { + + // The strict JSON number grammar, the same as ADK Kotlin's SchemaUtils.JSON_NUMBER. + private static final Pattern JSON_NUMBER = + Pattern.compile("-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?"); + + private PortScalars() {} + + /** Returns the module that registers the readers. */ + static SimpleModule module() { + SimpleModule module = new SimpleModule("PortScalars"); + add(module, Long.class, long.class, 0L, PortScalars::integerLiteral); + add(module, Integer.class, int.class, 0, whole(n -> (int) n)); + add(module, Short.class, short.class, (short) 0, whole(n -> (short) n)); + add(module, Byte.class, byte.class, (byte) 0, whole(n -> (byte) n)); + add(module, Double.class, double.class, 0.0, PortScalars::doubleLiteral); + add(module, Float.class, float.class, 0f, PortScalars::floatLiteral); + add(module, Boolean.class, boolean.class, false, PortScalars::booleanLiteral); + add(module, Character.class, char.class, '\0', PortScalars::charLiteral); + // byte[] reads base64 and char[] text, as Jackson writes them. + addArray(module, long[].class); + addArray(module, int[].class); + addArray(module, short[].class); + addArray(module, double[].class); + addArray(module, float[].class); + addArray(module, boolean[].class); + return module; + } + + private static void add( + SimpleModule module, + Class boxed, + Class primitive, + T defaultValue, + Function<@Nullable Object, @Nullable T> reader) { + module.addDeserializer(boxed, new ScalarDeserializer<>(boxed, defaultValue, reader)); + module.addDeserializer(primitive, new ScalarDeserializer<>(primitive, defaultValue, reader)); + module.addKeyDeserializer(boxed, new ScalarKeyDeserializer(boxed, reader)); + } + + private static void addArray(SimpleModule module, Class type) { + module.addDeserializer(type, new ArrayDeserializer<>(type)); + } + + /** Reads a whole number that {@code narrow} keeps unchanged, so one in its type's range. */ + private static Function<@Nullable Object, @Nullable T> whole( + LongFunction narrow) { + return v -> { + Long n = integerLiteral(v); + if (n == null) { + return null; + } + T value = narrow.apply(n); + return value.longValue() == n ? value : null; + }; + } + + private static @Nullable Double doubleLiteral(@Nullable Object value) { + Number n = numberLiteral(value); + return n == null ? null : n.doubleValue(); + } + + private static @Nullable Float floatLiteral(@Nullable Object value) { + Number n = numberLiteral(value); + return n == null || !Float.isFinite(n.floatValue()) ? null : n.floatValue(); + } + + /** + * Returns {@code value} as a long if it is a whole number in the long range or a JSON literal of + * one, else null. A fraction reads as a double first, so digits past its precision round away. + */ + static @Nullable Long integerLiteral(@Nullable Object value) { + Number n = numberLiteral(value); + if (n == null) { + return null; + } + return n instanceof Long l ? l : wholeLong(n.doubleValue()); + } + + /** Returns {@code value} as a finite number if it is one or a JSON literal of one, else null. */ + private static @Nullable Number numberLiteral(@Nullable Object value) { + if (value instanceof Long n) { + return n; + } + if (value instanceof BigInteger n && n.bitLength() < Long.SIZE) { + return n.longValue(); + } + if (value instanceof Number n) { + return Double.isFinite(n.doubleValue()) ? n.doubleValue() : null; + } + if (value instanceof String text && JSON_NUMBER.matcher(text).matches()) { + Long n = Longs.tryParse(text); + if (n != null) { + return n; + } + double d = Double.parseDouble(text); + return Double.isFinite(d) ? d : null; + } + return null; + } + + /** Returns {@code value} as a boolean if it is one or the text true or false, else null. */ + private static @Nullable Boolean booleanLiteral(@Nullable Object value) { + if (value instanceof Boolean b) { + return b; + } + if (value instanceof String text) { + return switch (text) { + case "true" -> true; + case "false" -> false; + default -> null; + }; + } + return null; + } + + /** Returns {@code value} as a char if it is text of one character; Jackson takes a code point. */ + private static @Nullable Character charLiteral(@Nullable Object value) { + return value instanceof String text && text.length() == 1 ? text.charAt(0) : null; + } + + /** + * Returns {@code value} as a long if it is a whole number strictly inside the long range, else + * null; a double at either bound may be a rounded larger value. + */ + private static @Nullable Long wholeLong(double value) { + return value % 1.0 == 0.0 && value > Long.MIN_VALUE && value < Long.MAX_VALUE + ? (long) value + : null; + } + + /** The current token as a Long, BigInteger, Double, String or Boolean, else null. */ + static @Nullable Object scalarValue(JsonParser p) throws IOException { + return switch (p.currentToken()) { + case VALUE_NUMBER_INT -> + p.getNumberType() == JsonParser.NumberType.BIG_INTEGER + ? p.getBigIntegerValue() + : p.getLongValue(); + case VALUE_NUMBER_FLOAT -> p.getDoubleValue(); + case VALUE_STRING -> p.getText(); + case VALUE_TRUE -> true; + case VALUE_FALSE -> false; + default -> null; + }; + } + + /** + * Reads a {@code type} with a reader. A primitive defaults when absent, and takes null as its + * default only where FAIL_ON_NULL_FOR_PRIMITIVES is off, as in genai's mapper. + */ + private static final class ScalarDeserializer extends StdScalarDeserializer { + private final T defaultValue; + private final Function<@Nullable Object, @Nullable T> reader; + + ScalarDeserializer( + Class type, T defaultValue, Function<@Nullable Object, @Nullable T> reader) { + super(type); + this.defaultValue = defaultValue; + this.reader = reader; + } + + @Override + @SuppressWarnings("unchecked") // handleUnexpectedToken returns a T or throws. + public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + T value = reader.apply(scalarValue(p)); + return value != null ? value : (T) ctxt.handleUnexpectedToken(handledType(), p); + } + + @Override + public @Nullable T getNullValue(DeserializationContext ctxt) throws JsonMappingException { + // Genai's mapper leaves FAIL_ON_NULL_FOR_PRIMITIVES off and reads null as the default. + if (handledType().isPrimitive()) { + return ctxt.isEnabled(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + ? ctxt.reportInputMismatch(this, "null for a primitive") + : defaultValue; + } + return null; + } + + @Override + public @Nullable Object getAbsentValue(DeserializationContext ctxt) { + return handledType().isPrimitive() ? defaultValue : null; + } + + // Nulls.AS_EMPTY reads zero or false, as Jackson's own number and boolean readers do. + @Override + public T getEmptyValue(DeserializationContext ctxt) { + return defaultValue; + } + } + + /** Reads a map key, which JSON writes as text, as a value of its type is read. */ + private static final class ScalarKeyDeserializer extends KeyDeserializer { + private final Class type; + private final Function<@Nullable Object, ?> reader; + + ScalarKeyDeserializer(Class type, Function<@Nullable Object, ?> reader) { + this.type = type; + this.reader = reader; + } + + @Override + public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { + Object value = reader.apply(key); + return value != null ? value : ctxt.handleWeirdKey(type, key, "does not fit the key type"); + } + } + + /** + * Reads a primitive array with Jackson's array reader, which honors the field's content-null + * setting and {@code ACCEPT_SINGLE_VALUE_AS_ARRAY}, each element read as its type is above. + */ + private static final class ArrayDeserializer extends StdDeserializer + implements ContextualDeserializer { + private final Class type; + private final @Nullable JsonDeserializer boxed; + + ArrayDeserializer(Class type) { + this(type, null); + } + + private ArrayDeserializer(Class type, @Nullable JsonDeserializer boxed) { + super(type); + this.type = type; + this.boxed = boxed; + } + + @Override + @SuppressWarnings("unchecked") // A value reader reads Objects. + public JsonDeserializer createContextual( + DeserializationContext ctxt, @Nullable BeanProperty property) throws JsonMappingException { + Class element = type.getComponentType(); + // The primitive's own reader, so a null element reads as its default or fails. + ObjectArrayDeserializer boxed = + new ObjectArrayDeserializer( + ctxt.getTypeFactory().constructArrayType(Primitives.wrap(element)), + (JsonDeserializer) + ctxt.findRootValueDeserializer(ctxt.constructType(element)), + null); + return new ArrayDeserializer<>(type, boxed.createContextual(ctxt, property)); + } + + @Override + public A deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + Object[] values = + (Object[]) requireNonNull(boxed, "set by createContextual").deserialize(p, ctxt); + Object array = Array.newInstance(type.getComponentType(), values.length); + for (int i = 0; i < values.length; i++) { + if (values[i] == null) { + return ctxt.reportInputMismatch(this, "null in a primitive array"); + } + Array.set(array, i, values[i]); + } + return type.cast(array); + } + + @Override + public A getEmptyValue(DeserializationContext ctxt) { + return type.cast(Array.newInstance(type.getComponentType(), 0)); + } + } +} diff --git a/core/src/main/java/com/google/adk/workflow/SchemaFit.java b/core/src/main/java/com/google/adk/workflow/SchemaFit.java index 8b9551cf1..de821db2f 100644 --- a/core/src/main/java/com/google/adk/workflow/SchemaFit.java +++ b/core/src/main/java/com/google/adk/workflow/SchemaFit.java @@ -198,9 +198,9 @@ private static ImmutableSet readings(@Nullable String value) { case OBJECT -> Type.Known.OBJECT; case ARRAY -> Type.Known.ARRAY; case BOOLEAN -> Type.Known.BOOLEAN; - // An integer port does not read "1.0" or "1e2". + // A whole number such as "1e2" is an integer, as integer ports read it. case NUMBER -> - literal.isIntegralNumber() && literal.canConvertToLong() + PortScalars.integerLiteral(literal.numberValue()) != null ? Type.Known.INTEGER : Type.Known.NUMBER; default -> Type.Known.STRING; diff --git a/core/src/test/java/com/google/adk/workflow/FunctionNodeTest.java b/core/src/test/java/com/google/adk/workflow/FunctionNodeTest.java index 86f11d78e..0dacecdd5 100644 --- a/core/src/test/java/com/google/adk/workflow/FunctionNodeTest.java +++ b/core/src/test/java/com/google/adk/workflow/FunctionNodeTest.java @@ -46,16 +46,19 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.fasterxml.jackson.annotation.OptBoolean; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.databind.util.StdConverter; import com.google.adk.agents.Context; @@ -460,6 +463,96 @@ record Flat(String label, @JsonUnwrapped Order order) {} @JsonFormat(shape = JsonFormat.Shape.ARRAY) record Pair(int x, int y) {} + /** Written as its ordinal wherever it appears, as its numeric shape asks. */ + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + enum Rank { + LOW, + HIGH + } + + /** Each field is written as a number, through the numeric shape on its type or on itself. */ + record Voucher( + Rank rank, + @JsonFormat(shape = JsonFormat.Shape.NUMBER) Status status, + @JsonFormat(shape = JsonFormat.Shape.NUMBER) boolean open, + @JsonFormat(shape = JsonFormat.Shape.NUMBER) Boolean paid) {} + + /** An ARRAY shape makes Jackson write the enum as its ordinal but the boolean as a boolean. */ + record Listed( + @JsonFormat(shape = JsonFormat.Shape.ARRAY) Status status, + @JsonFormat(shape = JsonFormat.Shape.ARRAY) boolean lit) {} + + /** Each field is written as a string. */ + record Quoted( + @JsonFormat(shape = JsonFormat.Shape.STRING) int count, + @JsonFormat(shape = JsonFormat.Shape.STRING) long id, + @JsonFormat(shape = JsonFormat.Shape.STRING) double price, + @JsonFormat(shape = JsonFormat.Shape.STRING) boolean paid) {} + + /** Jackson writes a char as text even under a numeric shape. */ + record Initials( + @JsonFormat(shape = JsonFormat.Shape.NUMBER) char first, + @JsonFormat(shape = JsonFormat.Shape.NUMBER) Character last) {} + + /** Written as its {@code @JsonValue} string. */ + enum Answer { + YES("y"), + NO("n"); + + private final String code; + + Answer(String code) { + this.code = code; + } + + @JsonValue + String code() { + return code; + } + } + + static final class Shuffled extends StdConverter, Integer> { + private static final ImmutableMap, Integer> CODES = + ImmutableMap., Integer>of( + Coded.A, 0, Coded.B, 2, Coded.C, 1, Coded.D, 3, Rank.LOW, 0, Rank.HIGH, 2); + + @Override + public Integer convert(Enum value) { + return CODES.get(value); + } + } + + /** Written as ordinals 0, 2, 1, 3: only the first and last write their own index. */ + @JsonSerialize(converter = Shuffled.class) + enum Coded { + A, + B, + C, + D + } + + /** A field whose own converter writes {@link Rank#HIGH} as 2, not as its ordinal. */ + record Flipped(@JsonSerialize(converter = Shuffled.class) Rank rank) {} + + /** Its converter takes an Integer, so Jackson fails to write it. */ + @JsonSerialize(converter = NumberToText.class) + enum Unwritable { + ONE + } + + /** Written with a padded name, which it reads back. */ + enum Padded { + @JsonProperty(" a") + A + } + + /** Holds an array in a field, since a record component should not be an array. */ + static final class Counts { + @JsonSetter(nulls = Nulls.AS_EMPTY, contentNulls = Nulls.SKIP) + @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) + public int[] values; + } + /** A polymorphic base type with a property of its own. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME) abstract static class Pet { @@ -2754,6 +2847,35 @@ public void build_untypedEnumOfADigitIntoAnIntegerPort_buildsAndRuns() { assertThat(result.outputAt("wf@1/increment@1")).isEqualTo(2); } + @Test + public void build_untypedEnumOfAWholeNumberInExponentFormIntoAnIntegerPort_buildsAndRuns() { + // Arrange: an integer port reads "1e2" as 100. + FunctionNode increment = + FunctionNodes.of("increment", Integer.class, Integer.class, (ctx, n) -> n + 1); + + // Act + RunResult result = run(chain(untypedEnumNode("1e2"), increment)); + + // Assert + result.assertCompleted(); + assertThat(result.outputAt("wf@1/increment@1")).isEqualTo(101); + } + + @Test + public void build_untypedEnumOfAFractionIntoAnIntegerPort_fails() { + // Arrange + FunctionNode half = untypedEnumNode("2.5"); + FunctionNode increment = + FunctionNodes.of("increment", Integer.class, Integer.class, (ctx, n) -> n + 1); + + // Act + WorkflowConfigurationException error = + assertThrows(WorkflowConfigurationException.class, () -> chain(half, increment)); + + // Assert + assertThat(error).hasMessageThat().startsWith("Schema mismatch on edge constant -> increment."); + } + @Test public void build_untypedEnumOfADigitIntoAStringPort_fails() { // Arrange @@ -5412,10 +5534,12 @@ public void of_enumPortFedAnUnknownOrPaddedName_failsWithAValidationError() { // Act RunResult unknown = runOn(chain(status), "\"FOO\""); + RunResult padded = runOn(chain(status), " SHIPPED"); RunResult quotedPadded = runOn(chain(status), "\" SHIPPED\""); // Assert assertThat(unknown.errorMessage("NodeInputValidationException")).isEqualTo(error); + assertThat(padded.errorMessage("NodeInputValidationException")).isEqualTo(error); assertThat(quotedPadded.errorMessage("NodeInputValidationException")).isEqualTo(error); } @@ -5473,6 +5597,279 @@ public void of_recordPortFedAMessageThatIsNotJson_failsWithoutQuotingIt() { + "."); } + @Test + public void of_portsFedScalars_readOnlyTheJsonTypeAQuotedLiteralOrAWholeNumber() { + // Arrange + record Reading(int count, double ratio, boolean flag) {} + record Tally(List counts, Map flags) {} + record Blank(@JsonSetter(nulls = Nulls.AS_EMPTY) int n) {} + record Keyed(Map byId) {} + ImmutableList cases = + ImmutableList.of( + new Case("3", int.class, "Integer:3"), + new Case(3.0, int.class, "Integer:3"), + new Case("3.0", int.class, "Integer:3"), + new Case("1e2", int.class, "Integer:100"), + new Case(new BigDecimal("3.000"), int.class, "Integer:3"), + new Case("003", int.class, "fails"), + new Case("+3", int.class, "fails"), + new Case(" 3", int.class, "fails"), + new Case("1_000", int.class, "fails"), + new Case(3.5, int.class, "fails"), + new Case("1e999", int.class, "fails"), + new Case(3_000_000_000L, int.class, "fails"), + new Case(true, int.class, "fails"), + // As in ADK Kotlin, a fraction reads as a double first. + new Case("2.9999999999999999999", int.class, "Integer:3"), + new Case("1e-400", int.class, "Integer:0"), + new Case(new BigDecimal("3.0000000000000000001"), int.class, "Integer:3"), + new Case("9007199254740993.0", long.class, "Long:9007199254740992"), + // A long reads a BigInteger exactly, and nothing past its range. + new Case(new BigInteger("9007199254740993"), long.class, "Long:9007199254740993"), + new Case(new BigInteger("9223372036854775808"), long.class, "fails"), + new Case((double) Long.MAX_VALUE, long.class, "fails"), + new Case("300", short.class, "Short:300"), + new Case(70000, short.class, "fails"), + new Case(200, byte.class, "fails"), + new Case("1.5", Double.class, "Double:1.5"), + new Case("3", Double.class, "Double:3.0"), + new Case(3, Double.class, "Double:3.0"), + new Case("NaN", Double.class, "fails"), + new Case("Infinity", Double.class, "fails"), + new Case("1e999", Double.class, "fails"), + new Case(true, Double.class, "fails"), + new Case("1.5", float.class, "Float:1.5"), + new Case(1e39, float.class, "fails"), + new Case("true", boolean.class, "Boolean:true"), + new Case("false", boolean.class, "Boolean:false"), + new Case(1, boolean.class, "fails"), + new Case("TRUE", boolean.class, "fails"), + new Case("yes", boolean.class, "fails"), + // A char reads one character of text, not a code point or the text null. + new Case("A", char.class, "Character:A"), + new Case(65, char.class, "fails"), + new Case("AB", Character.class, "fails"), + new Case("null", Character.class, "fails"), + new Case(3, String.class, "fails"), + // A BigInteger reads a whole number. + new Case(3.0, BigInteger.class, "BigInteger:3"), + // Records, lists and maps read each field, element and value the same way. + new Case( + ImmutableMap.of("count", "1e2", "ratio", "1.5", "flag", "true"), + Reading.class, + "Reading:Reading[count=100, ratio=1.5, flag=true]"), + new Case( + ImmutableMap.of("count", "003", "ratio", 1, "flag", true), Reading.class, "fails"), + new Case( + ImmutableMap.of("count", 3, "ratio", "NaN", "flag", true), Reading.class, "fails"), + new Case(ImmutableMap.of("count", 3, "ratio", 1, "flag", 1), Reading.class, "fails"), + new Case( + JsonNodeFactory.instance.objectNode().putNull("n"), + Blank.class, + "Blank:Blank[n=0]"), + new Case( + ImmutableMap.of( + "counts", + ImmutableList.of("3", 3.0, "1e2"), + "flags", + ImmutableMap.of("a", "true")), + Tally.class, + "Tally:Tally[counts=[3, 3, 100], flags={a=true}]"), + new Case(ImmutableMap.of("counts", ImmutableList.of("+3")), Tally.class, "fails"), + new Case(ImmutableMap.of("flags", ImmutableMap.of("a", "yes")), Tally.class, "fails"), + // Map keys, which JSON writes as text, read as values of their type do. + new Case( + ImmutableMap.of("byId", ImmutableMap.of("3.0", "a")), + Keyed.class, + "Keyed:Keyed[byId={3=a}]"), + new Case(ImmutableMap.of("byId", ImmutableMap.of("003", "a")), Keyed.class, "fails")); + + // Act + ImmutableMap actual = readAll(cases); + + // Assert + assertThat(actual).containsExactlyEntriesIn(expected(cases)).inOrder(); + } + + @Test + public void of_enumPortsFedNumbers_readOnlyTheNumbersJacksonWritesForThem() { + // Arrange + ImmutableList cases = + ImmutableList.of( + new Case("SHIPPED", Status.class, "Status:SHIPPED"), + new Case(" SHIPPED", Status.class, "fails"), + new Case("SHIPPED\u0001", Status.class, "fails"), + new Case(0, Status.class, "fails"), + new Case("1", Status.class, "fails"), + // Level reads its JsonValue; Rank reads an int or long ordinal. + new Case(2, Level.class, "Level:HIGH"), + new Case(1L, Rank.class, "Rank:HIGH"), + new Case(2, Rank.class, "fails"), + new Case(-1, Rank.class, "fails"), + new Case(1.0, Rank.class, "fails"), + new Case(BigInteger.ZERO, Rank.class, "fails"), + // Coded and Flipped read no number; Unwritable reads names only. + new Case(0, Coded.class, "fails"), + new Case(1, Coded.class, "fails"), + new Case(2, Coded.class, "fails"), + new Case(3, Coded.class, "fails"), + new Case(ImmutableMap.of("rank", 0), Flipped.class, "fails"), + new Case(0, Unwritable.class, "fails"), + new Case("ONE", Unwritable.class, "Unwritable:ONE")); + + // Act + ImmutableMap actual = readAll(cases); + + // Assert + assertThat(actual).containsExactlyEntriesIn(expected(cases)).inOrder(); + } + + @Test + public void of_genaiPortsFedScalars_readThemAsOtherPortsDo() { + // Arrange + FunctionNode thought = + FunctionNodes.of( + "thought", Part.class, String.class, (ctx, p) -> "thought " + p.thought().orElse(null)); + FunctionNode role = + FunctionNodes.of( + "role", Content.class, String.class, (ctx, c) -> "role " + c.role().orElse(null)); + + // Act + Object quoted = readWith(ImmutableMap.of("thought", "true"), thought); + Object upperCase = readWith(ImmutableMap.of("thought", "TRUE"), thought); + Object number = readWith(ImmutableMap.of("thought", 1), thought); + Object numberAsText = readWith(ImmutableMap.of("role", 3), role); + + // Assert + assertThat(quoted).isEqualTo("thought true"); + assertThat(upperCase).isEqualTo("fails"); + assertThat(number).isEqualTo("fails"); + assertThat(numberAsText).isEqualTo("fails"); + } + + @Test + public void of_genaiPortsFedNullForAPrimitiveSetter_readTheDefault() { + // Arrange: genai binds Part.Builder.thought(boolean), unlike a record port, where null fails. + FunctionNode thought = + FunctionNodes.of( + "thought", Part.class, String.class, (ctx, p) -> "thought " + p.thought().orElse(null)); + FunctionNode role = + FunctionNodes.of( + "role", Content.class, String.class, (ctx, c) -> "role " + c.role().orElse(null)); + + // Act + Object nullThought = + readWith( + JsonNodeFactory.instance.objectNode().put("text", "hi").putNull("thought"), thought); + Object nullThoughtInPart = + readWith( + ImmutableMap.of( + "role", + "user", + "parts", + ImmutableList.of(JsonNodeFactory.instance.objectNode().putNull("thought"))), + role); + + // Assert + assertThat(nullThought).isEqualTo("thought false"); + assertThat(nullThoughtInPart).isEqualTo("role user"); + } + + @Test + public void of_primitiveArrayPortsFedScalars_readEachElementAsItsTypeDoes() { + // Arrange + FunctionNode ints = + FunctionNodes.of("ints", int[].class, String.class, (ctx, in) -> Arrays.toString(in)); + FunctionNode flags = + FunctionNodes.of("flags", boolean[].class, String.class, (ctx, in) -> Arrays.toString(in)); + FunctionNode counts = + FunctionNodes.of( + "counts", Counts.class, String.class, (ctx, in) -> Arrays.toString(in.values)); + + // Act + Object literals = readWith(ImmutableList.of("3", 3.0, "1e2"), ints); + Object paddedNumber = readWith(ImmutableList.of("003"), ints); + Object nullElement = readWith(Arrays.asList(1, null), ints); + Object booleans = readWith(ImmutableList.of("true", false), flags); + Object numberAsBoolean = readWith(ImmutableList.of(1), flags); + Object fieldElement = readWith(ImmutableMap.of("values", ImmutableList.of(" 4")), counts); + Object nullField = readWith(JsonNodeFactory.instance.objectNode().putNull("values"), counts); + Object skippedElement = readWith(ImmutableMap.of("values", Arrays.asList(1, null, 2)), counts); + Object singleValue = readWith(ImmutableMap.of("values", 5), counts); + + // Assert + assertThat(literals).isEqualTo("[3, 3, 100]"); + assertThat(paddedNumber).isEqualTo("fails"); + assertThat(nullElement).isEqualTo("fails"); + assertThat(booleans).isEqualTo("[true, false]"); + assertThat(numberAsBoolean).isEqualTo("fails"); + assertThat(fieldElement).isEqualTo("fails"); + assertThat(nullField).isEqualTo("[]"); + assertThat(skippedElement).isEqualTo("[1, 2]"); + assertThat(singleValue).isEqualTo("[5]"); + } + + @Test + public void of_recordWithUntypedFields_keepsTheNumberTypesItIsFed() { + // Arrange + record Loose(Object value, Map extra) {} + BigInteger big = new BigInteger("123456789012345678901234567890"); + FunctionNode describe = + FunctionNodes.of( + "n", + Loose.class, + String.class, + (ctx, l) -> l.value().getClass().getSimpleName() + " " + l.extra().get("big")); + + // Act + Object output = + readWith(ImmutableMap.of("value", 3, "extra", ImmutableMap.of("big", big)), describe); + + // Assert + assertThat(output).isEqualTo("Integer " + big); + } + + @Test + public void of_jacksonAnnotatedValues_roundTripToASuccessorTypedTheSame() { + // Arrange: each value and the JSON form its typed node writes. + record Written(Object value, Object json) { + String key() { + return value.getClass().getSimpleName() + ":" + value; + } + } + ImmutableList roundTrips = + ImmutableList.of( + // Jackson writes a number: under a numeric shape, or ARRAY on an enum. + new Written(Rank.HIGH, 1), + new Written( + new Voucher(Rank.HIGH, Status.SHIPPED, true, false), + ImmutableMap.of("rank", 1, "status", 1, "open", 1, "paid", 0)), + new Written( + new Listed(Status.SHIPPED, true), ImmutableMap.of("status", 1, "lit", true)), + // Jackson writes the @JsonValue, so LOW's 1, which is HIGH's ordinal, reads as LOW. + new Written(Level.LOW, 1), + new Written(Answer.NO, "n"), + new Written(Padded.A, " a"), + // Jackson writes text: STRING on scalars, and a char even under NUMBER. + new Written( + new Quoted(3, 9007199254740993L, 1.5, true), + ImmutableMap.of( + "count", "3", "id", "9007199254740993", "price", "1.5", "paid", "true")), + new Written(new Initials('A', 'B'), ImmutableMap.of("first", "A", "last", "B"))); + + // Act + ImmutableMap actual = + roundTrips.stream().collect(toImmutableMap(Written::key, row -> roundTrip(row.value()))); + + // Assert + assertThat(actual) + .containsExactlyEntriesIn( + roundTrips.stream() + .collect( + toImmutableMap(Written::key, row -> ImmutableList.of(row.json(), row.key())))) + .inOrder(); + } + @Test public void of_eventPortFedAMap_readsTheEvent() { FunctionNode read = @@ -6613,6 +7010,60 @@ private static Schema object(ImmutableMap properties, String... return (required.length == 0 ? object : object.required(required)).build(); } + /** + * Outputs {@code value} from a node typed as its class into a successor typed the same, and + * returns what the node wrote and what the successor read as {@code "Class:value"}, or {@code + * "fails"} when the successor rejects it. + */ + private static Object roundTrip(T value) { + @SuppressWarnings("unchecked") // The class of a value is its type. + Class type = (Class) value.getClass(); + FunctionNode write = + FunctionNodes.of("write", Content.class, type, (ctx, m) -> value); + RunResult result = run(chain(write, describing(type))); + return result.error() != null + ? failure(result) + : ImmutableList.of(result.outputAt("wf@1/write@1"), result.outputAt("wf@1/read@1")); + } + + /** An input, the port class it goes to, and what {@link #readWith} returns for them. */ + private record Case(Object input, Class port, String reads) { + /** The input, with a string in quotes, and the port, as a table key. */ + String key() { + return (input instanceof String ? "\"" + input + "\"" : String.valueOf(input)) + + " -> " + + port.getSimpleName(); + } + } + + /** Maps each case's key to what {@link #readWith} returns; a repeated key throws. */ + private static ImmutableMap readAll(ImmutableList cases) { + return cases.stream() + .collect(toImmutableMap(Case::key, c -> readWith(c.input(), describing(c.port())))); + } + + /** Maps each case's key to what it says {@link #readWith} returns. */ + private static ImmutableMap expected(ImmutableList cases) { + return cases.stream().collect(toImmutableMap(Case::key, Case::reads)); + } + + /** Feeds {@code value} to {@code node} and returns its output, or "fails". */ + private static @Nullable Object readWith(Object value, Node node) { + RunResult result = run(chain(emitter("make", value), node)); + return result.error() != null ? failure(result) : result.outputAt("wf@1/" + node.name() + "@1"); + } + + /** Returns "fails" for a run whose port rejected its input, and any other error as it is. */ + private static Object failure(RunResult result) { + return result.error() instanceof NodeInputValidationException ? "fails" : result.error(); + } + + /** Returns a node named {@code read} that outputs its input as {@code "Class:value"}. */ + private static FunctionNode describing(Class type) { + return FunctionNodes.of( + "read", type, String.class, (ctx, in) -> in.getClass().getSimpleName() + ":" + in); + } + /** Returns a model message with a thought part before its {@code answer}. */ private static Content answerWithThoughts(String answer) { return Content.builder() diff --git a/core/src/test/java/com/google/adk/workflow/SchemaFitTest.java b/core/src/test/java/com/google/adk/workflow/SchemaFitTest.java index 94114a59b..5ee8e3e72 100644 --- a/core/src/test/java/com/google/adk/workflow/SchemaFitTest.java +++ b/core/src/test/java/com/google/adk/workflow/SchemaFitTest.java @@ -162,8 +162,8 @@ public void fits_untypedEnum_readsEachValueAsTheNumberOrBooleanItSpells() { } @Test - public void fits_untypedEnumOfNumberText_isAnIntegerOnlyAsPlainIntegerTextThatFitsALong() { - // Arrange: an integer port reads neither "1.0" nor "1e2", so they fit only a number. + public void fits_untypedEnumOfNumberText_isAnIntegerOnlyAsAWholeNumberThatFitsALong() { + // Arrange: an integer port reads "1.0" and "1e2" as 1 and 100, but not "2.5" or 1e19. Schema maxLong = untypedEnum("9223372036854775807"); Schema pastMaxLong = untypedEnum("9223372036854775808"); @@ -172,8 +172,10 @@ public void fits_untypedEnumOfNumberText_isAnIntegerOnlyAsPlainIntegerTextThatFi assertThat(fits(untypedEnum("-1", "0", "-0"), INTEGER)).isTrue(); assertThat(fits(pastMaxLong, INTEGER)).isFalse(); assertThat(fits(pastMaxLong, NUMBER)).isTrue(); - assertThat(fits(untypedEnum("1.0"), INTEGER)).isFalse(); - assertThat(fits(untypedEnum("1e2"), INTEGER)).isFalse(); + assertThat(fits(untypedEnum("1.0", "1e2", "1E+2", "-0.0"), INTEGER)).isTrue(); + assertThat(fits(untypedEnum("2.5"), INTEGER)).isFalse(); + assertThat(fits(untypedEnum("1e-2"), INTEGER)).isFalse(); + assertThat(fits(untypedEnum("1e19"), INTEGER)).isFalse(); assertThat(fits(untypedEnum("1.5", "0.5", "1.0", "1e-2", "1e2", "1E+2"), NUMBER)).isTrue(); }