From 4b6a0e08bae9c6d0b4be32655fe2db38d585867e Mon Sep 17 00:00:00 2001 From: Mateusz Krawiec Date: Fri, 20 Nov 2026 01:22:55 -0800 Subject: [PATCH] feat(workflow): reject unknown keys in genai and event FunctionNode ports PiperOrigin-RevId: 1026280215 --- .../com/google/adk/workflow/FunctionNode.java | 6 +- .../google/adk/workflow/FunctionNodes.java | 3 + .../com/google/adk/workflow/PortCodec.java | 52 +++++- .../google/adk/workflow/FunctionNodeTest.java | 171 ++++++++++++++++-- 4 files changed, 200 insertions(+), 32 deletions(-) diff --git a/core/src/main/java/com/google/adk/workflow/FunctionNode.java b/core/src/main/java/com/google/adk/workflow/FunctionNode.java index ddf0f6d93..7a420dc90 100644 --- a/core/src/main/java/com/google/adk/workflow/FunctionNode.java +++ b/core/src/main/java/com/google/adk/workflow/FunctionNode.java @@ -160,7 +160,9 @@ public Builder toBuilder() { * JSON shape infers none. An edge into an inferred record or POJO fails at build if the * producer's output schema lists a key the type does not, while a builder schema checks only the * keys it lists and requires. On a {@code Content} port a builder schema describes the message - * text, and an edge is checked against the {@code Content} schema instead. + * text, and an edge is checked against the {@code Content} schema instead. On an {@code Event} or + * genai port, or a list, map or array of them, a builder schema does not let the port take keys + * its type lacks. */ @Override public Optional inputSchema() { @@ -189,7 +191,7 @@ Optional edgeInputSchema() { /** Whether a builder schema would let this port take keys its type does not list. */ boolean acceptsExtraKeysWithASchema() { - return inputSchemaInferred() && !inputCodec.takesContent(); + return inputSchemaInferred() && !inputCodec.rejectsUnknownKeys(); } /** Whether {@link #edgeInputSchema} was inferred, so its objects with properties are closed. */ 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 37f481d5e..225fd8712 100644 --- a/core/src/main/java/com/google/adk/workflow/FunctionNodes.java +++ b/core/src/main/java/com/google/adk/workflow/FunctionNodes.java @@ -35,6 +35,9 @@ * "3"}). An integer also accepts a whole number such as {@code 3.0}, and a char only one * character of text. *
  • An enum or boolean reads a number only where Jackson writes it as one. + *
  • A port of {@code Event} or of a {@code com.google.genai.types} type such as {@code + * Content}, or of a list, map or array of them, rejects unknown keys anywhere in its value. + * Other ports drop them. * * *

    A node's body asks the user for input with {@link #requestInput}. 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 9c4febec5..cbc47496f 100644 --- a/core/src/main/java/com/google/adk/workflow/PortCodec.java +++ b/core/src/main/java/com/google/adk/workflow/PortCodec.java @@ -99,12 +99,12 @@ 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. 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. + * The port mapper: unknown properties are ignored, null fields are written, {@code 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() @@ -131,6 +131,14 @@ final class PortCodec { /** Genai's own reader of the form genai writes, with the port rules for scalars. */ private static final ObjectReader GENAI_READER = genaiReader(); + /** {@link #GENAI_READER} rejecting unknown properties. */ + private static final ObjectReader STRICT_GENAI_READER = + GENAI_READER.with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + /** {@link #MAPPER} rejecting unknown properties, for a port that {@link #rejectsUnknownKeys}. */ + private static final ObjectMapper STRICT_MAPPER = + MAPPER.copy().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + /** The port's type, with a primitive boxed. */ private final JavaType type; @@ -139,6 +147,9 @@ final class PortCodec { /** Whether the declared type is primitive, so the port takes no null. */ private final boolean primitive; + /** {@link #STRICT_MAPPER} if this port {@link #rejectsUnknownKeys}, else {@link #MAPPER}. */ + private final ObjectMapper mapper; + private PortCodec(JavaType declared, boolean output) { this.primitive = declared.isPrimitive(); this.type = @@ -151,6 +162,7 @@ private PortCodec(JavaType declared, boolean output) { output && type.getRawClass() == Event.class ? () -> null : Suppliers.memoize(() -> PortSchemas.infer(type, output)); + this.mapper = rejectsUnknownKeys() ? STRICT_MAPPER : MAPPER; } static JavaType javaType(Class type) { @@ -494,6 +506,19 @@ boolean takesContent() { return type.getRawClass() == Content.class; } + /** + * Whether this port rejects unknown keys at any depth: it reads an {@code Event} or genai value, + * or a list, map or array of them. + */ + boolean rejectsUnknownKeys() { + JavaType value = type; + while (value.isContainerType()) { + value = value.getContentType(); + } + return Event.class.isAssignableFrom(value.getRawClass()) + || JsonSerializable.class.isAssignableFrom(value.getRawClass()); + } + /** * Returns {@code value} read as this port's type; {@code what} names the port in errors. * @@ -523,7 +548,7 @@ boolean takesContent() { } T converted; try { - converted = MAPPER.convertValue(value, type); + converted = mapper.convertValue(value, type); } catch (RuntimeException e) { // Jackson's and genai's messages can quote the value, so no cause. throw doesNotMatch(what); @@ -566,7 +591,7 @@ boolean takesContent() { // not be readable, so a generic type's own fields are trusted. if (!hasType(value, type, /* trustGenericFields= */ true)) { try { - value = MAPPER.convertValue(value, type); + value = mapper.convertValue(value, type); } catch (RuntimeException e) { // Jackson's message can quote the value, so no cause. throw new IllegalArgumentException(what + " does not match " + type.toCanonical() + "."); @@ -778,7 +803,10 @@ private static void rejectScalarsAsText(MutableCoercionConfig config) { .setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail); } - /** Reads a genai value with {@link #GENAI_READER}. */ + /** + * Reads a genai value with {@link #GENAI_READER}. Genai's reader drops unknown keys, so this + * rejects them when the calling mapper does. + */ private static final class GenaiDeserializer extends StdDeserializer { GenaiDeserializer(Class type) { super(type); @@ -786,7 +814,11 @@ private static final class GenaiDeserializer extends StdDeserializer { @Override public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - return GENAI_READER.treeToValue(ctxt.readTree(p), handledType()); + ObjectReader reader = + ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + ? STRICT_GENAI_READER + : GENAI_READER; + return reader.treeToValue(ctxt.readTree(p), handledType()); } } 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 0dacecdd5..112f2410d 100644 --- a/core/src/test/java/com/google/adk/workflow/FunctionNodeTest.java +++ b/core/src/test/java/com/google/adk/workflow/FunctionNodeTest.java @@ -463,6 +463,9 @@ record Flat(String label, @JsonUnwrapped Order order) {} @JsonFormat(shape = JsonFormat.Shape.ARRAY) record Pair(int x, int y) {} + /** A user record that holds an event. */ + record Envelope(String id, Event event) {} + /** Written as its ordinal wherever it appears, as its numeric shape asks. */ @JsonFormat(shape = JsonFormat.Shape.NUMBER) enum Rank { @@ -978,6 +981,44 @@ public void builder_bodyDelegatingAnOutputThatIsNotAnO_fails() { .contains("output of node 'router' does not match"); } + @Test + public void builder_contentBodyDelegatingAValueWithAnUnknownKey_fails() { + // Arrange + ImmutableMap message = + ImmutableMap.of("parts", ImmutableList.of(ImmutableMap.of("text", "hi", "extra", 1))); + + // Act + RunResult result = run(chain(delegating(Content.class, message))); + + // Assert + assertThat(result.errorMessage("IllegalArgumentException")) + .isEqualTo( + "validation error: output of node 'router' does not match " + + Content.class.getName() + + "."); + } + + @Test + public void of_partListBodyReturningAnUnknownKey_fails() { + // Arrange: an unchecked cast lets a map with an unknown key into the list. + Map part = new HashMap<>(); + part.put("text", "hi"); + part.put("extra", 1); + @SuppressWarnings("unchecked") + List parts = (List) (List) ImmutableList.of(part); + FunctionNode> node = + FunctionNodes.of( + "parts", Content.class, new TypeReference>() {}, (ctx, m) -> parts); + + // Act + RunResult result = run(chain(node)); + + // Assert + assertThat(result.errorMessage("IllegalArgumentException")) + .isEqualTo( + "output of node 'parts' does not match java.util.List<" + Part.class.getName() + ">."); + } + @Test public void builder_voidBodyDelegatingItsOutput_fails() { RunResult result = run(chain(delegating(Void.class, "x"))); @@ -2926,22 +2967,6 @@ public void build_integerIntoANullableIntegerSchema_buildsAndRuns() { assertThat(result.outputAt("wf@1/increment@1")).isEqualTo(4); } - @Test - public void build_recordIntoAContentPort_failsWithoutSuggestingABuilderSchema() { - // Arrange: a builder schema on a Content port describes the text, so it cannot help here. - FunctionNode full = fullOrder(); - FunctionNode read = - FunctionNodes.of("read", Content.class, String.class, (ctx, content) -> content.text()); - - // Act - WorkflowConfigurationException error = - assertThrows(WorkflowConfigurationException.class, () -> chain(full, read)); - - // Assert - assertThat(error).hasMessageThat().startsWith("Schema mismatch on edge full -> read."); - assertThat(error).hasMessageThat().doesNotContain("inputSchema on the builder"); - } - @Test public void build_contentIntoAStringPort_fails() { // Arrange: a returned Content is the output in its JSON form, an object. @@ -2959,18 +2984,31 @@ public void build_contentIntoAStringPort_fails() { } @Test - public void build_recordIntoAnEventPort_fails() { - // Arrange: an Event port takes only an event's keys, and a FullOrder has others. + public void build_recordIntoAnEventOrGenaiPort_failsWithoutSuggestingABuilderSchema() { + // Arrange: these ports reject a FullOrder's other keys at run time, whatever their schema. FunctionNode full = fullOrder(); + FunctionNode read = + FunctionNodes.of("read", Content.class, String.class, (ctx, content) -> content.text()); FunctionNode author = FunctionNodes.of("author", Event.class, String.class, (ctx, event) -> event.author()); + FunctionNode part = + FunctionNodes.of("part", Part.class, String.class, (ctx, p) -> p.text().orElse("")); // Act - WorkflowConfigurationException error = + WorkflowConfigurationException intoContent = + assertThrows(WorkflowConfigurationException.class, () -> chain(full, read)); + WorkflowConfigurationException intoEvent = assertThrows(WorkflowConfigurationException.class, () -> chain(full, author)); + WorkflowConfigurationException intoPart = + assertThrows(WorkflowConfigurationException.class, () -> chain(full, part)); // Assert - assertThat(error).hasMessageThat().startsWith("Schema mismatch on edge full -> author."); + assertThat(intoContent).hasMessageThat().startsWith("Schema mismatch on edge full -> read."); + assertThat(intoContent).hasMessageThat().doesNotContain("inputSchema on the builder"); + assertThat(intoEvent).hasMessageThat().startsWith("Schema mismatch on edge full -> author."); + assertThat(intoEvent).hasMessageThat().doesNotContain("inputSchema on the builder"); + assertThat(intoPart).hasMessageThat().startsWith("Schema mismatch on edge full -> part."); + assertThat(intoPart).hasMessageThat().doesNotContain("inputSchema on the builder"); } @Test @@ -5809,6 +5847,99 @@ public void of_primitiveArrayPortsFedScalars_readEachElementAsItsTypeDoes() { assertThat(singleValue).isEqualTo("[5]"); } + @Test + public void of_eventOrGenaiPortsFedAnUnknownKey_rejectIt() { + // Arrange: each value has an unknown key, at its top level or deeper. + ImmutableMap part = ImmutableMap.of("text", "hi", "extra", 1); + ImmutableList cases = + ImmutableList.of( + new Case(ImmutableMap.of("author", "a", "extra", 1), Event.class, "fails"), + new Case( + ImmutableMap.of("actions", ImmutableMap.of("stateDetla", 1)), Event.class, "fails"), + new Case( + ImmutableMap.of("nodeInfo", ImmutableMap.of("pathh", "wf@1")), + Event.class, + "fails"), + new Case(part, Part.class, "fails"), + new Case(ImmutableList.of(part), Part[].class, "fails"), + new Case(ImmutableMap.of("parts", ImmutableList.of(part)), Content.class, "fails")); + + // Act + ImmutableMap actual = readAll(cases); + + // Assert + assertThat(actual).containsExactlyEntriesIn(expected(cases)).inOrder(); + } + + @Test + public void of_userRecordPortsFedAnUnknownKey_dropIt() { + // Arrange: each value has unknown keys, also inside an event or genai value it holds. + ImmutableMap event = + ImmutableMap.of("author", "a", "extra", 1, "actions", ImmutableMap.of("stateDetla", 1)); + ImmutableMap part = ImmutableMap.of("text", "hi", "extra", 1); + ImmutableMap content = + ImmutableMap.of("parts", ImmutableList.of(part), "extra", 1); + FunctionNode order = + FunctionNodes.of("n", Order.class, String.class, (ctx, o) -> o.id() + " x" + o.quantity()); + FunctionNode envelope = + FunctionNodes.of( + "n", Envelope.class, String.class, (ctx, e) -> e.id() + " " + e.event().author()); + FunctionNode reply = + FunctionNodes.of( + "n", Reply.class, String.class, (ctx, r) -> r.id() + " " + r.content().text()); + + // Act + Object orderOutput = readWith(ImmutableMap.of("id", "a1", "quantity", 3, "extra", 1), order); + Object envelopeOutput = + readWith(ImmutableMap.of("id", "e1", "event", event, "extra", 1), envelope); + Object replyOutput = readWith(ImmutableMap.of("id", "r1", "content", content), reply); + + // Assert + assertThat(orderOutput).isEqualTo("a1 x3"); + assertThat(envelopeOutput).isEqualTo("e1 a"); + assertThat(replyOutput).isEqualTo("r1 hi"); + } + + @Test + public void of_eventListsAndGenaiMapPortsFedAnUnknownKey_rejectIt() { + // Arrange + FunctionNode, String> events = + FunctionNodes.of( + "n", new TypeReference>() {}, String.class, (ctx, l) -> l.get(0).author()); + FunctionNode>, String> nestedEvents = + FunctionNodes.of( + "n", + new TypeReference>>() {}, + String.class, + (ctx, l) -> l.get(0).get(0).author()); + FunctionNode, String> parts = + FunctionNodes.of( + "n", + new TypeReference>() {}, + String.class, + (ctx, m) -> m.get("a").text().orElse("")); + + // Act + Object known = readWith(ImmutableList.of(ImmutableMap.of("author", "a")), events); + Object eventsOutput = + readWith(ImmutableList.of(ImmutableMap.of("author", "a", "extra", 1)), events); + Object nestedKnown = + readWith(ImmutableList.of(ImmutableList.of(ImmutableMap.of("author", "a"))), nestedEvents); + Object nestedOutput = + readWith( + ImmutableList.of(ImmutableList.of(ImmutableMap.of("author", "a", "extra", 1))), + nestedEvents); + Object partsOutput = + readWith(ImmutableMap.of("a", ImmutableMap.of("text", "hi", "extra", 1)), parts); + + // Assert + assertThat(known).isEqualTo("a"); + assertThat(eventsOutput).isEqualTo("fails"); + assertThat(nestedKnown).isEqualTo("a"); + assertThat(nestedOutput).isEqualTo("fails"); + assertThat(partsOutput).isEqualTo("fails"); + } + @Test public void of_recordWithUntypedFields_keepsTheNumberTypesItIsFed() { // Arrange