uranusjr commented on code in PR #77228: URL: https://github.com/apache/airflow/pull/77228#discussion_r4688996706
########## java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/internal/ValueBinder.kt: ########## @@ -0,0 +1,504 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.apache.airflow.sdk.internal + +import com.fasterxml.jackson.core.JsonParser +import com.fasterxml.jackson.core.JsonToken +import com.fasterxml.jackson.databind.BeanDescription +import com.fasterxml.jackson.databind.DatabindException +import com.fasterxml.jackson.databind.DeserializationConfig +import com.fasterxml.jackson.databind.DeserializationContext +import com.fasterxml.jackson.databind.DeserializationFeature +import com.fasterxml.jackson.databind.JsonDeserializer +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.PropertyName +import com.fasterxml.jackson.databind.deser.BeanDeserializerBase +import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier +import com.fasterxml.jackson.databind.deser.CreatorProperty +import com.fasterxml.jackson.databind.deser.SettableBeanProperty +import com.fasterxml.jackson.databind.deser.impl.NullsConstantProvider +import com.fasterxml.jackson.databind.deser.impl.NullsFailProvider +import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer +import com.fasterxml.jackson.databind.introspect.Annotated +import com.fasterxml.jackson.databind.introspect.AnnotatedField +import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector +import com.fasterxml.jackson.databind.json.JsonMapper +import com.fasterxml.jackson.databind.module.SimpleModule +import com.fasterxml.jackson.databind.util.NameTransformer +import org.apache.airflow.sdk.ArgName +import java.lang.reflect.Modifier +import java.lang.reflect.Type + +// A task declares the values that it reads from its arguments and from XComs, +// so a key that the target class does not declare fails the task. The Go SDK +// also fails a task when an argument value has a key that the target struct +// does not declare. +private val strictBinder = ValueBinder(failOnUnknownKeys = true) Review Comment: Typed `getXCom` shares the strict binder with task arguments. An XCom has many readers, so an unknown key should not fail a reader by default. Maybe a third binder for `bindXCom` with `failOnUnknownKeys = false`, or a parameter on `getXCom`. ########## java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/internal/ValueBinder.kt: ########## @@ -0,0 +1,504 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.apache.airflow.sdk.internal + +import com.fasterxml.jackson.core.JsonParser +import com.fasterxml.jackson.core.JsonToken +import com.fasterxml.jackson.databind.BeanDescription +import com.fasterxml.jackson.databind.DatabindException +import com.fasterxml.jackson.databind.DeserializationConfig +import com.fasterxml.jackson.databind.DeserializationContext +import com.fasterxml.jackson.databind.DeserializationFeature +import com.fasterxml.jackson.databind.JsonDeserializer +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.PropertyName +import com.fasterxml.jackson.databind.deser.BeanDeserializerBase +import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier +import com.fasterxml.jackson.databind.deser.CreatorProperty +import com.fasterxml.jackson.databind.deser.SettableBeanProperty +import com.fasterxml.jackson.databind.deser.impl.NullsConstantProvider +import com.fasterxml.jackson.databind.deser.impl.NullsFailProvider +import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer +import com.fasterxml.jackson.databind.introspect.Annotated +import com.fasterxml.jackson.databind.introspect.AnnotatedField +import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector +import com.fasterxml.jackson.databind.json.JsonMapper +import com.fasterxml.jackson.databind.module.SimpleModule +import com.fasterxml.jackson.databind.util.NameTransformer +import org.apache.airflow.sdk.ArgName +import java.lang.reflect.Modifier +import java.lang.reflect.Type + +// A task declares the values that it reads from its arguments and from XComs, +// so a key that the target class does not declare fails the task. The Go SDK +// also fails a task when an argument value has a key that the target struct +// does not declare. +private val strictBinder = ValueBinder(failOnUnknownKeys = true) + +// Other tasks in the Dag run may read keys that the target class does not +// declare, so those keys are ignored here. +private val confBinder = ValueBinder(failOnUnknownKeys = false) + +internal fun bindArgument( + value: Any?, + type: Type, +): Any? = strictBinder.bind(value, type, "a task argument") + +internal fun bindXCom( + value: Any?, + type: Type, +): Any? = strictBinder.bind(value, type, "the XCom value") + +@Suppress("UNCHECKED_CAST") +internal fun <T : Any> bindConf( + conf: Map<String, Any?>, + type: Type, +): T = confBinder.convert(conf, type, "the Dag run conf") as T + +internal fun writeConfJson(conf: Map<String, Any?>): String = confBinder.writeJson(conf) + +/** + * Makes Jackson use the name in [ArgName] as the property name of the annotated + * field. That field then reads from and writes to the key with that name. + */ +internal object ArgNameIntrospector : JacksonAnnotationIntrospector() { + override fun findNameForDeserialization(a: Annotated): PropertyName? = findPinnedName(a) ?: super.findNameForDeserialization(a) + + override fun findNameForSerialization(a: Annotated): PropertyName? = findPinnedName(a) ?: super.findNameForSerialization(a) + + private fun findPinnedName(a: Annotated): PropertyName? = a.getAnnotation(ArgName::class.java)?.let { PropertyName.construct(it.value) } +} + +/** + * Converts values from the wire into the types a task declares. + * [org.apache.airflow.sdk.DagRun.getConf] documents how keys match fields. + */ +private class ValueBinder( + failOnUnknownKeys: Boolean, +) { + // By default, Jackson moves a date-time that carries an offset to UTC. For + // example, 2024-01-31T02:00+08:00 would become 2024-01-30T18:00Z and fall on + // another date. This mapper keeps the offset as written instead. + // + // FAIL_ON_NULL_FOR_PRIMITIVES stops Jackson from turning a null into 0, for + // example in an int[]. It also rejects a record whose primitive component has + // no key, because Jackson handles the missing value as null. + private val mapper: ObjectMapper by lazy { + JsonMapper + .builder() + .annotationIntrospector(ArgNameIntrospector) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownKeys) + .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) + .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .addModule(KeyMatching) + .build() + .findAndRegisterModules() + } + + /** + * Converts [value] into [type], passing null through. A value that already + * has the type stays the same object, so reading a large XCom into a raw `Map` + * does not copy it. + * + * @param source What [value] is, for the error messages. + */ + fun bind( + value: Any?, + type: Type, + source: String, + ): Any? { + if (value == null) return null + if (type is Class<*> && type.isInstance(value)) return value + return convert(value, type, source) + } + + /** + * Converts [value] into a new object of [type], even if [value] already has + * that type. + * + * @param source What [value] is, for the error messages. + */ + fun convert( + value: Any, + type: Type, + source: String, + ): Any? = + try { + mapper.convertValue<Any?>(value, mapper.constructType(type)) + } catch (e: RuntimeException) { + val mismatch = generateSequence<Throwable>(e) { it.cause }.filterIsInstance<KeyMatchException>().firstOrNull() + when { + mismatch != null -> throw IllegalArgumentException(mismatch.describe(source), e) + e is IllegalArgumentException -> throw IllegalArgumentException("Cannot convert $source to ${type.typeName}: ${e.message}", e) + else -> throw e + } + } + + fun writeJson(value: Any?): String = mapper.writeValueAsString(value) +} + +/** + * Matches keys to field names inside Jackson. It wraps every deserializer that + * reads an object field by field, so a deserializer, a converter or a + * delegating creator that reads an object itself gets the keys as written. + */ +private object KeyMatching : SimpleModule("org.apache.airflow.sdk.KeyMatching") { + init { + setDeserializerModifier( + object : BeanDeserializerModifier() { + override fun modifyDeserializer( + config: DeserializationConfig, + beanDesc: BeanDescription, + deserializer: JsonDeserializer<*>, + ): JsonDeserializer<*> = + if (deserializer is BeanDeserializerBase && !deserializer.valueInstantiator.canCreateUsingDelegate()) { + KeyMatchingDeserializer(deserializer, DeclaredProperties(deserializer)) + } else { + deserializer + } + }, + ) + } +} + +/** + * Renames the keys of an object to the names of the properties that they match, + * right before the wrapped bean deserializer reads the object. + * + * @property declared The properties of the class, recorded before Jackson + * resolved the bean deserializer. Every copy of this + * `KeyMatchingDeserializer` that Jackson makes shares the same recorded + * properties. + */ +private class KeyMatchingDeserializer( + delegatee: JsonDeserializer<*>, + val declared: DeclaredProperties, +) : DelegatingDeserializer(delegatee) { + @Volatile + private var cachedKeys: PropertyKeys? = null + + override fun newDelegatingInstance(newDelegatee: JsonDeserializer<*>): JsonDeserializer<*> = + KeyMatchingDeserializer(newDelegatee, declared) + + override fun deserialize( + p: JsonParser, + ctxt: DeserializationContext, + ): Any? = _delegatee.deserialize(matchKeys(p, ctxt) ?: p, ctxt) + + @Suppress("UNCHECKED_CAST") + override fun deserialize( + p: JsonParser, + ctxt: DeserializationContext, + intoValue: Any?, + ): Any? = (_delegatee as JsonDeserializer<Any?>).deserialize(matchKeys(p, ctxt) ?: p, ctxt, intoValue) + + /** + * Returns a parser over the object at [p] with its keys renamed, or null when + * [p] is not at an object. The wrapped bean deserializer reads the object + * from the returned parser. This function leaves [p] at the end of the + * object, where the bean deserializer would leave it. + */ + private fun matchKeys( + p: JsonParser, + ctxt: DeserializationContext, + ): JsonParser? { + val bean = _delegatee as? BeanDeserializerBase ?: return null + var token = p.currentToken() + if (token != JsonToken.START_OBJECT && token != JsonToken.FIELD_NAME) return null + val asWritten = ctxt.bufferForInputBuffering(p) + val keys = mutableListOf<String>() + val nullKeys = mutableSetOf<String>() + if (token == JsonToken.START_OBJECT) token = p.nextToken() + asWritten.writeStartObject() + while (token == JsonToken.FIELD_NAME) { + val key = p.currentName() + keys += key + asWritten.writeFieldName(key) + if (p.nextToken() == JsonToken.VALUE_NULL) nullKeys += key + asWritten.copyCurrentStructure(p) + token = p.nextToken() + } + asWritten.writeEndObject() + val renames = propertyKeys(bean, ctxt).match(keys, nullKeys, ctxt) + if (renames.isEmpty()) return asWritten.asParserOnFirstToken() + val renamed = ctxt.bufferForInputBuffering(p) + val copy = asWritten.asParserOnFirstToken() + renamed.writeStartObject() + while (copy.nextToken() == JsonToken.FIELD_NAME) { + val key = copy.currentName() + renamed.writeFieldName(renames[key] ?: key) + copy.nextToken() + renamed.copyCurrentStructure(copy) + } + renamed.writeEndObject() + return renamed.asParserOnFirstToken() + } Review Comment: This buffers each object twice and re-buffers nested objects at every level. Can the rename be avoided when no key needs folding? Today `asWritten` is still built for every bean. Alternatively, register the folded names as aliases in `updateProperties` so that Jackson matches them while streaming. ########## java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/Context.kt: ########## @@ -125,38 +126,115 @@ data class DagRun( * is empty, no field has a matching key. * * The class needs a no-argument constructor and public fields or setters, so - * a nested class must be `static`. A record also works. A record component - * with no matching key is null. If the component has a primitive type, this - * method throws instead, so a task that reads the conf into a record with a - * primitive component fails in a scheduled run. In Kotlin, declare the fields - * with `@JvmField` so that a property such as `isEnabled` keeps its name. + * a nested class must be `static`. A record and a class with a builder also + * work. A class with a `@JsonCreator` constructor works when each parameter + * of the constructor has `@JsonProperty`, which gives the parameter its name. + * A record component or a constructor parameter with no matching key gets + * null. If the component or the parameter has a primitive type, this method + * throws instead. A scheduled run has an empty conf, so a task that reads the + * conf into a record with a primitive component fails in a scheduled run. In + * Kotlin, declare the fields with `@JvmField` so that a property such as + * `isEnabled` keeps its name. * - * Annotating a field with [ArgName] has no effect on this method. To set a - * field from a key that no Java name can match, such as `target-table`, add - * `@JsonProperty("target-table")` to that field. `@JsonProperty` needs - * `com.fasterxml.jackson.core:jackson-annotations` in your build, because the - * SDK keeps Jackson off your compile classpath. You can also read the key - * from [conf]. + * To set a field from a key that no Java name can match, such as + * `target-table`, annotate the field with [ArgName]. The field then takes + * only that key, as written. You can also read the value of the key from + * [conf]. Jackson's `@JsonProperty` also sets the key of a field, but other + * keys still match the name in `@JsonProperty` when case and underscores are + * ignored. Do not combine `@JsonProperty` with [ArgName] on one field. The + * SDK keeps Jackson off your compile classpath, so to use a Jackson + * annotation, add the library that contains the annotation to your build. + * Annotations such as `@JsonProperty`, `@JsonCreator` and `@JsonAlias` are in + * `com.fasterxml.jackson.core:jackson-annotations`. `@JsonDeserialize` is in + * `com.fasterxml.jackson.core:jackson-databind`. + * + * An `OffsetDateTime` or `ZonedDateTime` field keeps the offset in the value + * instead of moving the date-time to UTC. An integer field drops any fraction, + * so `5.9` reads as `5` in an `int` field. + * + * Keys match this way wherever Jackson reads an object field by field, for + * example in a class that `@JsonTypeInfo` or `@JsonDeserialize(as = ...)` + * picks, or in the class of a `@JsonUnwrapped` field. For a builder that + * `@JsonDeserialize(builder = ...)` names, keys match the names that the + * builder takes. A key that equals a name in `@JsonAlias` counts as an exact + * match. Two limits apply to `@JsonTypeInfo`. First, the key that holds the + * type id must equal the name of the type id. Second, with + * `use = JsonTypeInfo.Id.DEDUCTION`, Jackson picks the class from the keys as + * written. A deserializer that `@JsonDeserialize` sets on a class or on a + * field gets the keys of an object as written. So does a deserializer that a + * Jackson module on the classpath registers. A converter that + * `@JsonDeserialize` sets and a delegating `@JsonCreator` also get the keys + * as written when they take a `Map` or a `JsonNode`. When a converter or a + * delegating `@JsonCreator` takes a class with fields, keys match the fields + * of that class. + * + * In a class with `@JsonIgnoreProperties(ignoreUnknown = true)`, or with a + * `@JsonUnwrapped` field whose type is a class with fields, Jackson drops two + * kinds of key without an error. One is a key that matches no field. The + * other is a key that matches a field when another key has the field's exact + * name. A class with a `@JsonAnySetter` method receives both kinds of key in + * that method. Jackson handles the two kinds of key this way even in a task + * argument or a typed `getXCom`, which otherwise fail on such keys. Review Comment: These paragraphs describe Jackson behavior, not SDK API, and they will rot whenever the binder changes. Keep the key-matching rule, the exceptions, and one line saying Jackson annotations are honored. ########## java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/Client.kt: ########## @@ -184,6 +185,90 @@ class Client internal constructor( includePriorDates = includePriorDates, ).value + /** + * Reads an XCom value pushed by another task into an instance of [type]. + * + * ```java + * public static class Stats { + * public long rowCount; // set from the "row_count" key + * } + * + * Stats stats = client.getXCom("extract", Stats.class); + * Long rows = client.getXCom("count_rows", Long.class); + * ``` + * + * Keys match fields as [DagRun.getConf] describes, but a key that matches no + * field fails the read. A key that matches a field also fails the read when + * another key has the field's exact name. For example, a `ROW_COUNT` key fails + * the read when a `rowCount` key is also present. + * + * The current Dag run's [dagId][TaskInstance.dagId] and + * [runId][TaskInstance.runId] are used by default. Override them only when + * reading across Dags or runs. + * + * @param key XCom key to read. Defaults to [XCOM_RETURN_KEY]. + * @param dagId Dag that owns the XCom. Defaults to the current Dag. + * @param taskId Task that pushed the XCom. + * @param runId Run that produced the XCom. Defaults to the current run. + * @param mapIndex Map index of the task instance to read, or `null` to read + * the task's result. + * @param includePriorDates If `true`, also search earlier Dag-run dates. + * @param type Class to read the value into. + * @return The converted value, or `null` if none was pushed. + * @throws ApiError if the API call fails. + * @throws IllegalArgumentException if the value cannot be converted to [type]. + * This method reads a value as strictly as the SDK reads a task argument. So + * the conversion also fails on a key that matches no field. It also fails on + * a key that matches a field when another key has the field's exact name. + */ Review Comment: For a mapped upstream with `mapIndex = null`, the untyped read returns a `List` of all instance values. So `getXCom("extract", Stats.class)` fails with a Jackson "cannot deserialize from array" message. Mention this in the KDoc (use `TypeRef<List<Stats>>`) or give a clearer error. ########## airflow-core/docs/authoring-and-scheduling/language-sdks/java.rst: ########## @@ -709,6 +721,10 @@ The ``Client`` task, it is the values of all its instances in a ``List`` ordered by map index. Overloads read another key, Dag, run, or one instance of a mapped task; a map index that selects no task instance reads ``null``. See the API reference. For the Java types values arrive as, see :ref:`java-sdk/types`. + * - ``getXCom(taskId, type)`` + - The same XCom read into ``type`` (a ``Class`` or a ``TypeRef``), or ``null`` when it does not exist. Keys + match fields as they do for ``getConf``, but a key that matches no field fails the read. A key that matches a + field also fails the read when another key has the field's exact name. Review Comment: The last sentence appears three times in the document. ########## java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/internal/ValueBinder.kt: ########## @@ -0,0 +1,504 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.apache.airflow.sdk.internal + +import com.fasterxml.jackson.core.JsonParser +import com.fasterxml.jackson.core.JsonToken +import com.fasterxml.jackson.databind.BeanDescription +import com.fasterxml.jackson.databind.DatabindException +import com.fasterxml.jackson.databind.DeserializationConfig +import com.fasterxml.jackson.databind.DeserializationContext +import com.fasterxml.jackson.databind.DeserializationFeature +import com.fasterxml.jackson.databind.JsonDeserializer +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.PropertyName +import com.fasterxml.jackson.databind.deser.BeanDeserializerBase +import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier +import com.fasterxml.jackson.databind.deser.CreatorProperty +import com.fasterxml.jackson.databind.deser.SettableBeanProperty +import com.fasterxml.jackson.databind.deser.impl.NullsConstantProvider +import com.fasterxml.jackson.databind.deser.impl.NullsFailProvider +import com.fasterxml.jackson.databind.deser.std.DelegatingDeserializer +import com.fasterxml.jackson.databind.introspect.Annotated +import com.fasterxml.jackson.databind.introspect.AnnotatedField +import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector +import com.fasterxml.jackson.databind.json.JsonMapper +import com.fasterxml.jackson.databind.module.SimpleModule +import com.fasterxml.jackson.databind.util.NameTransformer +import org.apache.airflow.sdk.ArgName +import java.lang.reflect.Modifier +import java.lang.reflect.Type + +// A task declares the values that it reads from its arguments and from XComs, +// so a key that the target class does not declare fails the task. The Go SDK +// also fails a task when an argument value has a key that the target struct +// does not declare. +private val strictBinder = ValueBinder(failOnUnknownKeys = true) + +// Other tasks in the Dag run may read keys that the target class does not +// declare, so those keys are ignored here. +private val confBinder = ValueBinder(failOnUnknownKeys = false) + +internal fun bindArgument( + value: Any?, + type: Type, +): Any? = strictBinder.bind(value, type, "a task argument") + +internal fun bindXCom( + value: Any?, + type: Type, +): Any? = strictBinder.bind(value, type, "the XCom value") + +@Suppress("UNCHECKED_CAST") +internal fun <T : Any> bindConf( + conf: Map<String, Any?>, + type: Type, +): T = confBinder.convert(conf, type, "the Dag run conf") as T + +internal fun writeConfJson(conf: Map<String, Any?>): String = confBinder.writeJson(conf) + +/** + * Makes Jackson use the name in [ArgName] as the property name of the annotated + * field. That field then reads from and writes to the key with that name. + */ +internal object ArgNameIntrospector : JacksonAnnotationIntrospector() { + override fun findNameForDeserialization(a: Annotated): PropertyName? = findPinnedName(a) ?: super.findNameForDeserialization(a) + + override fun findNameForSerialization(a: Annotated): PropertyName? = findPinnedName(a) ?: super.findNameForSerialization(a) + + private fun findPinnedName(a: Annotated): PropertyName? = a.getAnnotation(ArgName::class.java)?.let { PropertyName.construct(it.value) } +} + +/** + * Converts values from the wire into the types a task declares. + * [org.apache.airflow.sdk.DagRun.getConf] documents how keys match fields. + */ +private class ValueBinder( + failOnUnknownKeys: Boolean, +) { + // By default, Jackson moves a date-time that carries an offset to UTC. For + // example, 2024-01-31T02:00+08:00 would become 2024-01-30T18:00Z and fall on + // another date. This mapper keeps the offset as written instead. + // + // FAIL_ON_NULL_FOR_PRIMITIVES stops Jackson from turning a null into 0, for + // example in an int[]. It also rejects a record whose primitive component has + // no key, because Jackson handles the missing value as null. + private val mapper: ObjectMapper by lazy { + JsonMapper + .builder() + .annotationIntrospector(ArgNameIntrospector) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownKeys) + .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) + .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .addModule(KeyMatching) + .build() + .findAndRegisterModules() + } + + /** + * Converts [value] into [type], passing null through. A value that already + * has the type stays the same object, so reading a large XCom into a raw `Map` + * does not copy it. + * + * @param source What [value] is, for the error messages. + */ + fun bind( + value: Any?, + type: Type, + source: String, + ): Any? { + if (value == null) return null + if (type is Class<*> && type.isInstance(value)) return value + return convert(value, type, source) + } + + /** + * Converts [value] into a new object of [type], even if [value] already has + * that type. + * + * @param source What [value] is, for the error messages. + */ + fun convert( + value: Any, + type: Type, + source: String, + ): Any? = + try { + mapper.convertValue<Any?>(value, mapper.constructType(type)) + } catch (e: RuntimeException) { + val mismatch = generateSequence<Throwable>(e) { it.cause }.filterIsInstance<KeyMatchException>().firstOrNull() + when { + mismatch != null -> throw IllegalArgumentException(mismatch.describe(source), e) + e is IllegalArgumentException -> throw IllegalArgumentException("Cannot convert $source to ${type.typeName}: ${e.message}", e) + else -> throw e + } + } + + fun writeJson(value: Any?): String = mapper.writeValueAsString(value) +} + +/** + * Matches keys to field names inside Jackson. It wraps every deserializer that + * reads an object field by field, so a deserializer, a converter or a + * delegating creator that reads an object itself gets the keys as written. + */ +private object KeyMatching : SimpleModule("org.apache.airflow.sdk.KeyMatching") { + init { + setDeserializerModifier( + object : BeanDeserializerModifier() { + override fun modifyDeserializer( + config: DeserializationConfig, + beanDesc: BeanDescription, + deserializer: JsonDeserializer<*>, + ): JsonDeserializer<*> = + if (deserializer is BeanDeserializerBase && !deserializer.valueInstantiator.canCreateUsingDelegate()) { + KeyMatchingDeserializer(deserializer, DeclaredProperties(deserializer)) + } else { + deserializer + } + }, + ) + } +} + +/** + * Renames the keys of an object to the names of the properties that they match, + * right before the wrapped bean deserializer reads the object. + * + * @property declared The properties of the class, recorded before Jackson + * resolved the bean deserializer. Every copy of this + * `KeyMatchingDeserializer` that Jackson makes shares the same recorded + * properties. + */ +private class KeyMatchingDeserializer( + delegatee: JsonDeserializer<*>, + val declared: DeclaredProperties, +) : DelegatingDeserializer(delegatee) { + @Volatile + private var cachedKeys: PropertyKeys? = null + + override fun newDelegatingInstance(newDelegatee: JsonDeserializer<*>): JsonDeserializer<*> = + KeyMatchingDeserializer(newDelegatee, declared) + + override fun deserialize( + p: JsonParser, + ctxt: DeserializationContext, + ): Any? = _delegatee.deserialize(matchKeys(p, ctxt) ?: p, ctxt) + + @Suppress("UNCHECKED_CAST") + override fun deserialize( + p: JsonParser, + ctxt: DeserializationContext, + intoValue: Any?, + ): Any? = (_delegatee as JsonDeserializer<Any?>).deserialize(matchKeys(p, ctxt) ?: p, ctxt, intoValue) + + /** + * Returns a parser over the object at [p] with its keys renamed, or null when + * [p] is not at an object. The wrapped bean deserializer reads the object + * from the returned parser. This function leaves [p] at the end of the + * object, where the bean deserializer would leave it. + */ + private fun matchKeys( + p: JsonParser, + ctxt: DeserializationContext, + ): JsonParser? { + val bean = _delegatee as? BeanDeserializerBase ?: return null + var token = p.currentToken() + if (token != JsonToken.START_OBJECT && token != JsonToken.FIELD_NAME) return null + val asWritten = ctxt.bufferForInputBuffering(p) + val keys = mutableListOf<String>() + val nullKeys = mutableSetOf<String>() + if (token == JsonToken.START_OBJECT) token = p.nextToken() + asWritten.writeStartObject() + while (token == JsonToken.FIELD_NAME) { + val key = p.currentName() + keys += key + asWritten.writeFieldName(key) + if (p.nextToken() == JsonToken.VALUE_NULL) nullKeys += key + asWritten.copyCurrentStructure(p) + token = p.nextToken() + } + asWritten.writeEndObject() + val renames = propertyKeys(bean, ctxt).match(keys, nullKeys, ctxt) + if (renames.isEmpty()) return asWritten.asParserOnFirstToken() + val renamed = ctxt.bufferForInputBuffering(p) + val copy = asWritten.asParserOnFirstToken() + renamed.writeStartObject() + while (copy.nextToken() == JsonToken.FIELD_NAME) { + val key = copy.currentName() + renamed.writeFieldName(renames[key] ?: key) + copy.nextToken() + renamed.copyCurrentStructure(copy) + } + renamed.writeEndObject() + return renamed.asParserOnFirstToken() + } + + private fun propertyKeys( + bean: BeanDeserializerBase, + ctxt: DeserializationContext, + ): PropertyKeys = cachedKeys ?: PropertyKeys.of(bean, declared, ctxt).also { cachedKeys = it } +} + +/** + * This object copies the properties that Jackson built for one class, before + * Jackson resolves the bean deserializer. Resolving removes two kinds of + * property from [BeanDeserializerBase.properties]. The first kind is a + * `@JsonUnwrapped` property whose type Jackson can unwrap. Jackson can unwrap a + * class with fields, but Jackson cannot unwrap a `Map`. The second kind is a + * property with an EXTERNAL_PROPERTY type id. After resolving, the deserializer + * no longer lists properties of either kind. + */ +private class DeclaredProperties( + private val bean: BeanDeserializerBase, +) { + private val all = bean.properties().asSequence().toList() + + /** + * Finds the properties with an EXTERNAL_PROPERTY type id. Call this function + * only after Jackson has resolved the bean deserializer. + */ + fun findExternal(ctxt: DeserializationContext): List<SettableBeanProperty> { + val kept = findKeptNames() + return all.filter { it.name !in kept && findUnwrapper(it, ctxt) == null } + } + + /** + * Checks that no two keys that the class takes differ only in case or + * underscores. The keys include the keys of each class that a + * `@JsonUnwrapped` field reads, with the prefix and the suffix from + * `@JsonUnwrapped`. The check walks into each of those classes and into the + * unwrapped classes inside them. When a class unwraps a field of its own + * class, directly or through other classes, the walk reaches that class a + * second time. The walk then adds the keys of that class's own fields once + * more, with the prefix and the suffix, and stops there. Two equal keys pass + * the check. Jackson gives a shared key to an outer field that has the key as + * its name. If no outer field has that name, Jackson gives the key to every + * `@JsonUnwrapped` field that takes the key. + */ + fun checkKeyNames(ctxt: DeserializationContext) { + val byFold = mutableMapOf<String, KeyName>() + findKeyNames(ctxt, emptySet()).forEach { name -> + val previous = byFold.putIfAbsent(foldArgName(name.key), name) + if (previous != null && previous.key != name.key) { + throw KeyMatchException { previous.describeClash(name) } + } + } + } + + private fun findKeyNames( + ctxt: DeserializationContext, + visited: Set<DeclaredProperties>, + ): List<KeyName> { + val expand = this !in visited + val owner = bean.handledType().simpleName + val kept = findKeptNames() + return all.flatMap { property -> + val unwrapper = if (property.name in kept) null else findUnwrapper(property, ctxt) + when { + unwrapper == null -> listOf(KeyName(property.name, owner, (property.member as? AnnotatedField)?.name ?: property.name)) + !expand -> emptyList() + else -> { + val unwrapped = ctxt.findNonContextualValueDeserializer(property.type) as? KeyMatchingDeserializer + val names = unwrapped?.declared?.findKeyNames(ctxt, visited + this).orEmpty() + names.map { it.copy(key = unwrapper.transform(it.key)) } + } + } + } + } + + private fun findKeptNames(): Set<String> = bean.properties().asSequence().mapTo(mutableSetOf()) { it.name } + + private fun findUnwrapper( + property: SettableBeanProperty, + ctxt: DeserializationContext, + ): NameTransformer? = property.member?.let { ctxt.annotationIntrospector.findUnwrappingNameTransformer(it) } +} + +/** + * A key that a class takes, with the field that the key sets. + * + * @property key The key. For a field of a class that a `@JsonUnwrapped` field + * reads, the key includes the prefix and the suffix from `@JsonUnwrapped`. + * @property owner The simple name of the class that Jackson reads. The class + * either declares the field or inherits the field from a superclass. + * @property field The Java name of the field, when Jackson sets the value + * through a field. When Jackson sets the value through a setter or a + * constructor parameter, the name of the property is used instead. The name + * of the property is the key without the prefix or the suffix from + * `@JsonUnwrapped`. + */ +private data class KeyName( + val key: String, + val owner: String, + val field: String, +) { + fun describeClash(other: KeyName): String = + if (key == field && other.key == other.field) { + "Fields $owner.$field and ${other.owner}.${other.field} differ only in case or underscores, so the SDK " + + "cannot tell which one a key should go to. Rename one of them." + } else { + "Fields $owner.$field and ${other.owner}.${other.field} take the keys '$key' and '${other.key}', which differ " + + "only in case or underscores, so the SDK cannot tell which of the two fields a key should go to. Rename one " + + "of the fields." + } +} + +/** + * The names that the keys of an object can match for one bean deserializer. + * + * @property exact Each property name and each `@JsonAlias` name, with its + * property. A key with one of these names is used as written. + * @property byFold Each property, keyed by its folded token from [foldArgName]. + * A property whose name [ArgName] pins is left out. + * @property typeIdNames The names of the external type ids of the class. + */ +private class PropertyKeys( + private val className: String, + private val exact: Map<String, SettableBeanProperty>, + private val byFold: Map<String, SettableBeanProperty>, + private val typeIdNames: Set<String>, +) { + /** + * Returns the new name of each key that matches a property only when case and + * underscores are ignored. Such a key loses to another key that has an exact + * name of the same property. The losing key stays as written, so Jackson + * ignores it or fails on it. A key that equals the name of an external type + * id also stays as written, so that Jackson reads the key as the type id. + */ + fun match( + keys: List<String>, + nullKeys: Set<String>, + ctxt: DeserializationContext, + ): Map<String, String> { + val present = keys.toSet() + val keyOfProperty = mutableMapOf<String, String>() + val renames = mutableMapOf<String, String>() + keys.forEach { key -> + if (key !in exact && key in typeIdNames) return@forEach + val property = + exact[key] ?: byFold[foldArgName(key)]?.takeUnless { candidate -> + exact.any { (name, property) -> property === candidate && name in present } + } ?: return@forEach + if (key !in exact) { + val other = keyOfProperty.put(property.name, key) + if (other != null) { + throw KeyMatchException { source -> + "Keys '$other' and '$key' of $source both match field $className.${property.name} when case and " + + "underscores are ignored, so the SDK cannot tell which one to use. Name the field exactly as the key " + + "it should take." + } + } + renames[key] = property.name + } + if (key in nullKeys && property.failsOnNull(ctxt)) { + throw KeyMatchException { source -> + "Key '$key' of $source is null, but field $className.${property.name} has a primitive type that cannot " + + "be null. Declare a boxed type (e.g. Integer instead of int) to receive null." + } + } + } + return renames + } + + companion object { + fun of( + bean: BeanDeserializerBase, + declared: DeclaredProperties, + ctxt: DeserializationContext, + ): PropertyKeys { + checkPinnedNames(bean.handledType()) + declared.checkKeyNames(ctxt) Review Comment: These run lazily on first read and throw from inside deserialization. Since a member with both `@ArgName` and `@JsonProperty` is already visible here, reject that combination here too instead of documenting "do not combine". ########## java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/ArgName.kt: ########## @@ -33,9 +34,17 @@ package org.apache.airflow.sdk * * Reach for it when the argument name is not a legal or usable Java * identifier. A pinned name is matched as written, with no folding, so the - * annotation says exactly which argument the field takes. + * annotation says exactly which argument the field takes. An argument with the + * field's own name does not match the field when the pinned name is different. Review Comment: A wired `TaskInput` was decoded by plain Jackson, so `@ArgName` was ignored and the key had to be the Java field name. Prior to this change, only the pinned name matches, and the Java name fails as an unknown key. With the `Frame` change, objects with `@ArgName` fields are also pushed with the pinned key, so Python readers and the UI see different keys. Stub-bound `TaskInput`s don't change since they already matched only the pinned name. The change itself can be justified (Java SDK is still experimental), but this must be called out in the PR description. It should also be moved to its own PR if possible. ########## airflow-core/docs/authoring-and-scheduling/language-sdks/java.rst: ########## @@ -238,6 +238,10 @@ value one call returned into another call makes the second task wait for the fir * Every task method is called in the wiring class. A task the wiring leaves out fails when the Dag is read. * A task method that takes arguments is called once; keep its result in a local variable to use it twice. * Values move between tasks as XComs, so a task returns data JSON can hold (see :ref:`java-sdk/types`). +* When a task method receives an object as a parameter, from an upstream task or from ``lit(...)``, the SDK reads the + object into the class of the parameter with the rules in :ref:`the Dag run conf section <java-sdk/dag-run-conf>`. + Two kinds of key that ``getConf`` ignores fail the task: a key that matches no field, and a key that matches a + field when another key has the field's exact name. Review Comment: This is also described in the addition below. A reference should be used instead. ########## java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Frame.kt: ########## @@ -56,6 +57,9 @@ object Frame { private val mapper = ObjectMapper().apply { + // The SDK reads a field pinned with @ArgName only from the pinned key, so an + // object that a task pushes has to use that key too. + setAnnotationIntrospector(ArgNameIntrospector) Review Comment: `Frame.mapper` serializes every comms message, not just user XCom values. Putting a user-facing annotation's introspector on the protocol mapper couples the two. Apply the pinned-name serialization only where user values are written (the XCom/`setXCom` path), or use a separate mapper for user values. ########## java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/Client.kt: ########## @@ -184,6 +185,90 @@ class Client internal constructor( includePriorDates = includePriorDates, ).value + /** + * Reads an XCom value pushed by another task into an instance of [type]. + * + * ```java + * public static class Stats { + * public long rowCount; // set from the "row_count" key + * } + * + * Stats stats = client.getXCom("extract", Stats.class); + * Long rows = client.getXCom("count_rows", Long.class); + * ``` + * + * Keys match fields as [DagRun.getConf] describes, but a key that matches no + * field fails the read. A key that matches a field also fails the read when + * another key has the field's exact name. For example, a `ROW_COUNT` key fails + * the read when a `rowCount` key is also present. + * + * The current Dag run's [dagId][TaskInstance.dagId] and + * [runId][TaskInstance.runId] are used by default. Override them only when + * reading across Dags or runs. + * + * @param key XCom key to read. Defaults to [XCOM_RETURN_KEY]. + * @param dagId Dag that owns the XCom. Defaults to the current Dag. + * @param taskId Task that pushed the XCom. + * @param runId Run that produced the XCom. Defaults to the current run. + * @param mapIndex Map index of the task instance to read, or `null` to read + * the task's result. + * @param includePriorDates If `true`, also search earlier Dag-run dates. + * @param type Class to read the value into. + * @return The converted value, or `null` if none was pushed. + * @throws ApiError if the API call fails. + * @throws IllegalArgumentException if the value cannot be converted to [type]. + * This method reads a value as strictly as the SDK reads a task argument. So + * the conversion also fails on a key that matches no field. It also fails on + * a key that matches a field when another key has the field's exact name. + */ + @JvmOverloads fun <T : Any> getXCom( Review Comment: `@JvmOverloads fun ...` is on one line here but split across lines in the `TypeRef` overload below. Pick one style. ########## airflow-core/docs/authoring-and-scheduling/language-sdks/java.rst: ########## @@ -667,6 +671,14 @@ An argument the Python call leaves at its default does not count towards the arg method may leave it out. A method declares flat parameters or one ``TaskInput``, not both, and two fields whose names match the same argument fail the build. +The table covers the arguments themselves. When the value of an argument is an object, the SDK reads the object into +the class of the parameter or field that takes the argument. The SDK uses the rules that +:ref:`the Dag run conf section <java-sdk/dag-run-conf>` describes for ``getConf``. Two kinds of key in the object +fail the task. One is a key that matches no field. The other is a key that matches a field when another key has the +field's exact name. ``getConf`` ignores both kinds of key. In a class with +``@JsonIgnoreProperties(ignoreUnknown = true)``, or with a ``@JsonUnwrapped`` field whose type is a class with +fields, Jackson drops both kinds of key without an error. Review Comment: Jackson internals are not relevant to users (the worker using Jackson internally is itself not a guarentee) and must be removed. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
