This is an automated email from the ASF dual-hosted git repository.
uranusjr pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 33e18ce6add Align and fix XCom set and retval push across SDKs (#77281)
33e18ce6add is described below
commit 33e18ce6adda5af4f27ffa91c858af88d0580f14
Author: Tzu-ping Chung <[email protected]>
AuthorDate: Wed Nov 25 13:40:26 2026 +0800
Align and fix XCom set and retval push across SDKs (#77281)
* Fix unneeded SQLAlchemy compat typing
* Align Go SDK XCom push behavior
A task function returning (*T, error) now always pushes its result,
so returning (nil, nil) pushes a null XCom instead of nothing. The
same applies to a decider's choice. A task function that returns
only error still never pushes a return value XCom. This matches the
TypeScript SDK.
A nil slice or map is now pushed as an empty list or map, both when
returned and when passed to PushXCom. Go code uses a nil slice as
its empty slice, so pushing null misrepresented an empty result.
Also fix the doc comments and docs that said GetXCom returns an
XComNotFound error for a missing XCom. It never did; it returns
(nil, nil).
* Allow Java SDK setXCom to accept null value
This allows null to be pushed as an XCom value, matching the
TypeScript and Go SDKs. It also fixes the return value push: a
non-void task method returning null compiled, but failed with a
NullPointerException at runtime.
SetXCom now keeps null fields when encoded, as PutVariable and
SetTaskStateStore do. Otherwise the null value would be dropped,
and the supervisor never replies to a message it cannot validate,
so the task would hang.
* Document when SDK return values are pushed
Returning nothing and returning null are different: only the former
skips the return value XCom; a null result is pushed as null. In
Java, a void method returns nothing. In TypeScript, a handler that
returns undefined (or has no return) returns nothing. This matches
Go, where a function returning only error pushes nothing.
* Only coerce nil-as-empty for return values
* Tighten Go comment docs
* Tighten Java docs on set null XCom
* Tighten Go docs
---
.../authoring-and-scheduling/language-sdks/go.rst | 11 +++--
.../language-sdks/java.rst | 7 +--
.../language-sdks/typescript.rst | 5 +-
.../api_fastapi/execution_api/routes/xcoms.py | 8 +--
go-sdk/airflow/task_handler.go | 4 +-
go-sdk/internal/bundle/task.go | 31 ++++++++----
go-sdk/internal/bundle/task_test.go | 57 ++++++++++++++++++++--
go-sdk/pkg/execution/client_test.go | 16 +++---
go-sdk/sdk/doc.go | 4 +-
go-sdk/sdk/errors.go | 3 +-
go-sdk/sdk/sdk.go | 3 +-
.../main/kotlin/org/apache/airflow/sdk/Client.kt | 7 +--
.../org/apache/airflow/sdk/execution/Client.kt | 4 +-
.../org/apache/airflow/sdk/execution/Frame.kt | 4 +-
.../org/apache/airflow/sdk/ArgTestSupport.kt | 2 +-
.../kotlin/org/apache/airflow/sdk/ClientTest.kt | 2 +-
.../org/apache/airflow/sdk/execution/CommTest.kt | 22 +++++++++
.../org/apache/airflow/sdk/execution/TaskTest.kt | 28 +++++++++--
.../airflow/sdk/execution/TriggerRunnerTest.kt | 4 +-
.../apache/airflow/sdk/internal/ArgValuesTest.kt | 2 +-
20 files changed, 172 insertions(+), 52 deletions(-)
diff --git a/airflow-core/docs/authoring-and-scheduling/language-sdks/go.rst
b/airflow-core/docs/authoring-and-scheduling/language-sdks/go.rst
index 66147f9bbe0..8b578324e35 100644
--- a/airflow-core/docs/authoring-and-scheduling/language-sdks/go.rst
+++ b/airflow-core/docs/authoring-and-scheduling/language-sdks/go.rst
@@ -481,8 +481,9 @@ that runs under ``context.WithoutCancel(actx)``. A helper
that takes a plain ``c
or ``len`` to check for configuration entries, or :ref:`read the conf into a
struct <go-sdk/dag-run-conf>` with
typed fields.
-A value the task returns becomes its ``return_value`` XCom. A non-nil
``error``, or a panic, fails the task, and
-retries it if the task has retries.
+A value the task returns becomes its ``return_value`` XCom. A function that
returns only ``error`` pushes nothing.
+A nil pointer or nil interface stores null, and a nil slice or map is pushed
as an empty list or mapping.
+A non-nil ``error``, or a panic, fails the task, and retries it if the task
has retries.
``airflow.NewContext`` builds a Context, so a unit test calls a task as an
ordinary function:
@@ -554,12 +555,12 @@ The ``sdk.Client``
index. A map index reads one instance of a mapped task; one that
selects no task instance reads ``nil``.
See :ref:`go-sdk/types`.
* - ``PushXCom(ctx, ti, key, value)``
- - Publishes an XCom value.
+ - Publishes an XCom value. ``nil``, including a nil slice or map, stores
null.
* - ``TaskStateStore()``
- This task instance's key/value store. See
:ref:`go-sdk/task-state-store`.
-A missing value returns an error that wraps ``sdk.VariableNotFound``,
``sdk.ConnectionNotFound``,
-``sdk.XComNotFound`` or ``sdk.TaskStateNotFound``, so test for it with
``errors.Is``.
+A missing Variable, Connection or task state value returns an error that wraps
``sdk.VariableNotFound``,
+``sdk.ConnectionNotFound`` or ``sdk.TaskStateNotFound``, so test for it with
``errors.Is``.
``sdk.Client`` is made of ``VariableClient``, ``ConnectionClient``,
``XComClient`` and ``TaskStateStoreClient``,
so a helper can take only the one it needs, and a test can pass a fake.
diff --git a/airflow-core/docs/authoring-and-scheduling/language-sdks/java.rst
b/airflow-core/docs/authoring-and-scheduling/language-sdks/java.rst
index c06f21f91b0..d35eb23e5f0 100644
--- a/airflow-core/docs/authoring-and-scheduling/language-sdks/java.rst
+++ b/airflow-core/docs/authoring-and-scheduling/language-sdks/java.rst
@@ -682,8 +682,9 @@ position, and the SDK passes them in. A ``Task`` class
receives both in ``execut
running task, such as ``context.ti.taskId``, ``context.ti.tryNumber`` and
``context.dagRun.logicalDate``.
A value a method returns, or a ``Task`` class passes to ``client.setXCom``,
becomes the task's ``return_value``
-XCom, and is what a downstream task receives. An uncaught exception fails the
task, and retries it if the task
-has retries.
+XCom, and is what a downstream task receives. A ``void`` method pushes
nothing. Any other method's result is
+pushed, so returning ``null`` stores a null XCom. An uncaught exception fails
the task, and retries it if the
+task has retries.
The ``Client``
~~~~~~~~~~~~~~
@@ -710,7 +711,7 @@ The ``Client``
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`.
* - ``setXCom(value)`` / ``setXCom(key, value)``
- - Publishes an XCom value. The value must be JSON-serializable.
+ - Publishes an XCom value. The value must be JSON-serializable; ``null``
stores a null XCom.
* - ``getTaskStateStore()``
- This task instance's key/value store, with ``get``, ``set``, ``delete``
and ``clear``. See
:ref:`java-sdk/task-state-store`.
diff --git
a/airflow-core/docs/authoring-and-scheduling/language-sdks/typescript.rst
b/airflow-core/docs/authoring-and-scheduling/language-sdks/typescript.rst
index e0b0eb7b862..e088c5d379e 100644
--- a/airflow-core/docs/authoring-and-scheduling/language-sdks/typescript.rst
+++ b/airflow-core/docs/authoring-and-scheduling/language-sdks/typescript.rst
@@ -564,8 +564,9 @@ throw outside it. Await everything the handler starts: work
still running after
after Airflow has recorded the task's result.
A value the handler returns becomes the task's ``return_value`` XCom, as with
Python's ``@task``, and is what a
-downstream task receives. An uncaught exception or a rejected promise fails
the task, and retries it if the task
-has retries.
+downstream task receives. A handler that returns nothing (``undefined``)
pushes nothing; returning ``null``
+stores a null XCom. An uncaught exception or a rejected promise fails the
task, and retries it if the task has
+retries.
The ``TaskClient``
~~~~~~~~~~~~~~~~~~
diff --git a/airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py
b/airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py
index c3ee9788591..77c3f09a49f 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py
@@ -379,7 +379,7 @@ def get_mapped_xcom_by_index(
else:
xcom_query = xcom_query.order_by(*xcom_read.get_order(entity,
descending=True)).offset(-1 - offset)
- result: tuple[XComModel] | None
+ result: XComModel | None
if (result := session.scalars(xcom_query.limit(1)).first()) is None:
message = (
f"XCom with {key=} {offset=} not found for task {task_id!r} in DAG
run {run_id!r} of {dag_id!r}"
@@ -388,7 +388,7 @@ def get_mapped_xcom_by_index(
status_code=status.HTTP_404_NOT_FOUND,
detail={"reason": "not_found", "message": message},
)
- return XComSequenceIndexResponse((result[0] if isinstance(result, tuple)
else result).value)
+ return XComSequenceIndexResponse(result.value)
def _get_sliced_query_or_empty(query: Select, low: int, high: int) -> Select:
@@ -637,7 +637,7 @@ def get_xcom(
# retrieves the raw serialized value from the database. By not relying on
`XCom.get_many` or `XCom.get_one`
# (which automatically deserializes using the backend), we avoid potential
# performance hits from retrieving large data files into the API server.
- result: tuple[XComModel] | None
+ result: XComModel | None
if (result := session.scalars(xcom_query.limit(1)).first()) is None:
if params.offset is None:
message = (
@@ -654,7 +654,7 @@ def get_xcom(
detail={"reason": "not_found", "message": message},
)
- return XComResponse(key=key, value=(result[0] if isinstance(result, tuple)
else result).value)
+ return XComResponse(key=key, value=result.value)
# TODO: once we have JWT tokens, then remove dag_id/run_id/task_id from the
URL and just use the info in
diff --git a/go-sdk/airflow/task_handler.go b/go-sdk/airflow/task_handler.go
index 1290d7749ef..39a32612a76 100644
--- a/go-sdk/airflow/task_handler.go
+++ b/go-sdk/airflow/task_handler.go
@@ -39,7 +39,9 @@ func (*taskHandler) registerable() {}
// fn takes a [Context] first, as the package documentation describes. Every
parameter after
// the Context is data, filled from the arguments of the Python stub's
TaskFlow call.
// fn returns either error or (result, error).
-// A non-nil error fails the task, and a non-nil result is pushed as the
task's return-value XCom.
+// A non-nil error fails the task. Otherwise the result, if fn returns one, is
pushed as the task's
+// return-value XCom: a nil pointer or nil interface stores null, and a nil
slice or map is pushed as
+// an empty one. A fn that returns only error pushes nothing.
//
// TaskHandler checks the signature of fn and panics if the check fails, for
example when fn is
// not a function, does not take a Context first, or does not return an error.
diff --git a/go-sdk/internal/bundle/task.go b/go-sdk/internal/bundle/task.go
index 6a8e2e67d82..b2b8ca1f730 100644
--- a/go-sdk/internal/bundle/task.go
+++ b/go-sdk/internal/bundle/task.go
@@ -97,8 +97,8 @@ func NewPositionalTaskFunction(fn any) (Task, error) {
// DecideFunc takes the result of the function of a task from
NewPositionalBranchFunction. It
// returns value, which the task pushes as its return_value XCom, and the
task_ids of the tasks to
-// skip. When value is a nil pointer, the task does not push the return_value
XCom. A non-nil error
-// fails the task.
+// skip. value is always pushed: a nil pointer or nil interface stores null,
and a nil slice or map
+// is pushed as an empty one. A non-nil error fails the task.
type DecideFunc func(result any) (value any, skipped []string, err error)
// NewPositionalBranchFunction is like NewPositionalTaskFunction, but the Task
also skips tasks
@@ -192,16 +192,13 @@ func (f *taskFunction) call(
if err != nil {
return err
}
- rv := reflect.ValueOf(value)
- if rv.Kind() != reflect.Ptr || !rv.IsNil() {
- if err := pushReturnValue(ctx, value, sdkClient); err
!= nil {
- return err
- }
+ if err := pushReturnValue(ctx, value, sdkClient); err != nil {
+ return err
}
return branch.skipDownstream(ctx, sdkClient, skipped, logger)
}
- // If there are two results, convert the first only if it's not a nil
pointer
- if len(retValues) > 1 && (retValues[0].Kind() != reflect.Ptr ||
!retValues[0].IsNil()) {
+ // A function that returns only an error has no result to push.
+ if len(retValues) > 1 {
return pushReturnValue(ctx, retValues[0].Interface(), sdkClient)
}
return nil
@@ -283,12 +280,26 @@ func pushReturnValue(ctx context.Context, value any, c
sdk.XComClient) error {
if err != nil {
return fmt.Errorf("setting the return value XCom: %w", err)
}
- if err := c.PushXCom(ctx, ti, sdk.XComReturnValueKey, value); err !=
nil {
+ if err := c.PushXCom(ctx, ti, sdk.XComReturnValueKey,
emptyIfNilCollection(value)); err != nil {
return fmt.Errorf("setting the return value XCom: %w", err)
}
return nil
}
+// emptyIfNilCollection replaces a nil slice or map with an empty one. Go code
+// uses a nil slice as its empty slice, so a task that, say, filters out every
+// row means an empty list, not null.
+func emptyIfNilCollection(value any) any {
+ rv := reflect.ValueOf(value)
+ switch {
+ case rv.Kind() == reflect.Slice && rv.IsNil():
+ return reflect.MakeSlice(rv.Type(), 0, 0).Interface()
+ case rv.Kind() == reflect.Map && rv.IsNil():
+ return reflect.MakeMap(rv.Type()).Interface()
+ }
+ return value
+}
+
func (f *taskFunction) validateFn(
fnType reflect.Type,
analyze func(fnType reflect.Type, fnName string) (*binding.Plan, error),
diff --git a/go-sdk/internal/bundle/task_test.go
b/go-sdk/internal/bundle/task_test.go
index b75fc9ea8de..4f6cb4a33af 100644
--- a/go-sdk/internal/bundle/task_test.go
+++ b/go-sdk/internal/bundle/task_test.go
@@ -316,7 +316,8 @@ func (s *TaskSuite)
TestBranchFunctionPushesTheValueAndSkipsTheTasksThatDecideRe
}, client.calls)
}
-func (s *TaskSuite) TestBranchFunctionPushesNoNilPointer() {
+// The decider's choice is pushed even when it is nil, which stores null.
+func (s *TaskSuite) TestBranchFunctionPushesANilPointer() {
task, err := NewPositionalBranchFunction(
func(contexttest.Context) (bool, error) { return true, nil },
func(any) (any, []string, error) { return (*int)(nil),
[]string{"load"}, nil },
@@ -327,6 +328,7 @@ func (s *TaskSuite) TestBranchFunctionPushesNoNilPointer() {
s.Require().NoError(runTask(task, client, true, true))
s.Equal([]string{
+ "PushXCom decide return_value <nil>",
"PushXCom decide skipmixin_key map[skipped:[load]]",
"SkipDownstreamTasks [load]",
}, client.calls)
@@ -479,8 +481,57 @@ func (s *TaskSuite) TestPushesTheReturnValue() {
s.Equal([]string{"PushXCom decide return_value 7"}, client.calls)
}
-func (s *TaskSuite) TestPushesNoNilPointer() {
- task, err := NewTaskFunction(func(contexttest.Context) (*int, error) {
return nil, nil })
+// A function that declares a result pushes it even when it is nil, which
stores null.
+func (s *TaskSuite) TestPushesANilResult() {
+ cases := map[string]any{
+ "nil pointer": func(contexttest.Context) (*int, error) {
return nil, nil },
+ "nil interface": func(contexttest.Context) (any, error) {
return nil, nil },
+ }
+ for name, fn := range cases {
+ s.Run(name, func() {
+ task, err := NewTaskFunction(fn)
+ s.Require().NoError(err)
+
+ client := &recordingClient{}
+ s.Require().NoError(runTask(task, client, true, false))
+
+ s.Equal([]string{"PushXCom decide return_value <nil>"},
client.calls)
+ })
+ }
+}
+
+// A nil slice or map result is Go's empty one, so it pushes an empty list or
mapping, not null.
+func (s *TaskSuite) TestPushesANilCollectionResultAsEmpty() {
+ cases := map[string]struct {
+ fn any
+ want any
+ }{
+ "nil slice": {
+ fn: func(contexttest.Context) ([]string, error) {
return nil, nil },
+ want: []string{},
+ },
+ "nil map": {
+ fn: func(contexttest.Context) (map[string]int, error)
{ return nil, nil },
+ want: map[string]int{},
+ },
+ }
+ for name, tt := range cases {
+ s.Run(name, func() {
+ task, err := NewTaskFunction(tt.fn)
+ s.Require().NoError(err)
+
+ client := &recordingClient{}
+ s.Require().NoError(runTask(task, client, true, false))
+
+ // %v prints a nil and an empty slice alike, so the
value itself is compared.
+ s.Equal(tt.want, client.values[sdk.XComReturnValueKey])
+ })
+ }
+}
+
+// A function that returns only an error has no result, so it pushes nothing.
+func (s *TaskSuite) TestErrorOnlyFunctionPushesNothing() {
+ task, err := NewTaskFunction(func(contexttest.Context) error { return
nil })
s.Require().NoError(err)
client := &recordingClient{}
diff --git a/go-sdk/pkg/execution/client_test.go
b/go-sdk/pkg/execution/client_test.go
index f8a5b76c1f4..035a42d3c92 100644
--- a/go-sdk/pkg/execution/client_test.go
+++ b/go-sdk/pkg/execution/client_test.go
@@ -438,15 +438,19 @@ func TestCoordinatorClientPushXComRejectsNonJSONValues(t
*testing.T) {
}
}
-// A task that returns a nil slice or a nil any pushes null, so PushXCom must
not
-// inherit the task state store's nil rule.
-func TestCoordinatorClientPushXComAllowsNil(t *testing.T) {
+// A nil value pushes null, so PushXCom must not inherit the task state store's
+// nil rule. Unlike a task's return value, an explicit nil slice or map is not
+// turned into an empty one.
+func TestCoordinatorClientPushXComNilValues(t *testing.T) {
tests := []struct {
name string
value any
+ want any
}{
- {name: "nil", value: nil},
- {name: "typed nil", value: []string(nil)},
+ {name: "nil", value: nil, want: nil},
+ {name: "nil pointer", value: (*string)(nil), want: nil},
+ {name: "nil slice", value: []string(nil), want: nil},
+ {name: "nil map", value: map[string]int(nil), want: nil},
}
for _, tc := range tests {
@@ -468,7 +472,7 @@ func TestCoordinatorClientPushXComAllowsNil(t *testing.T) {
require.NoError(t, err)
sentMap := rawToMap(t, sent.Body)
require.Contains(t, sentMap, "value")
- assert.Nil(t, sentMap["value"])
+ assert.Equal(t, tc.want, sentMap["value"])
})
}
}
diff --git a/go-sdk/sdk/doc.go b/go-sdk/sdk/doc.go
index a2961861357..cffd2009618 100644
--- a/go-sdk/sdk/doc.go
+++ b/go-sdk/sdk/doc.go
@@ -43,7 +43,7 @@ so a task can resume its progress after a retry.
To publish a result, return a value from the task function: the runtime pushes
it as the task's return-value XCom, so most tasks never call [XComClient]
directly. Lookups that miss return a wrapped sentinel error
([VariableNotFound],
-[ConnectionNotFound], [XComNotFound], [TaskStateNotFound]) you can test for
with
-errors.Is.
+[ConnectionNotFound], [TaskStateNotFound]) you can test for with errors.Is; a
+missing XCom reads as nil, the same as a stored null.
*/
package sdk
diff --git a/go-sdk/sdk/errors.go b/go-sdk/sdk/errors.go
index d6b42fbfbfd..c553482c927 100644
--- a/go-sdk/sdk/errors.go
+++ b/go-sdk/sdk/errors.go
@@ -36,7 +36,8 @@ var ConnectionNotFound = errors.New("connection not found")
// XComNotFound is an error value used to signal that an XCom value could not
be found (and that there were
// no communication issues with the API server).
//
-// See the “GetXCom“ method of [XComClient] for an example
+// [XComClient]'s GetXCom does not return it yet: Airflow reports a missing
XCom as a null value, so GetXCom
+// returns nil and no error.
var XComNotFound = errors.New("xcom not found")
// TaskStateNotFound is an error value used to signal that a task state value
could not be found (and that
diff --git a/go-sdk/sdk/sdk.go b/go-sdk/sdk/sdk.go
index aa2a8c89ba1..56304f8a390 100644
--- a/go-sdk/sdk/sdk.go
+++ b/go-sdk/sdk/sdk.go
@@ -140,7 +140,8 @@ type XComClient interface {
// PushXCom stores value under key for the given task instance ti.
//
- // value must be JSON serializable; nil is allowed and is pushed as
null.
+ // value must be JSON serializable; nil, including a nil pointer, slice
or
+ // map, is allowed and is pushed as null.
// A time.Time, a byte slice or array such as a uuid.UUID, or a
non-finite
// float is rejected before it is sent.
PushXCom(ctx context.Context, ti TaskInstance, key string, value any)
error
diff --git a/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/Client.kt
b/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/Client.kt
index 2922afa2e40..0abe32b70fa 100644
--- a/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/Client.kt
+++ b/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/Client.kt
@@ -188,15 +188,16 @@ class Client internal constructor(
* Pushes an XCom value for downstream tasks to read.
*
* @param key XCom key; defaults to [XCOM_RETURN_KEY].
- * @param value Value to push. Must be JSON-serializable. The SDK rejects
byte
- * arrays, so encode binary data as a string first, for example with
Base64.
+ * @param value Value to push. Must be JSON-serializable; `null` stores a
null
+ * XCom. The SDK rejects byte arrays, so encode binary data as a string
+ * first, for example with Base64.
* @throws ApiError if the API call fails.
* @throws IllegalArgumentException if [value] is or contains a type that the
* SDK cannot send, such as a byte array.
*/
@JvmOverloads fun setXCom(
key: String = XCOM_RETURN_KEY,
- value: Any,
+ value: Any?,
) = impl.setXCom(
key = key,
value = value,
diff --git
a/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Client.kt
b/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Client.kt
index 7bcef266297..82351843296 100644
--- a/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Client.kt
+++ b/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Client.kt
@@ -83,7 +83,7 @@ interface Client {
fun setXCom(
key: String,
- value: Any,
+ value: Any?,
dagId: String,
taskId: String,
runId: String,
@@ -191,7 +191,7 @@ class CoordinatorClient(
override fun setXCom(
key: String,
- value: Any,
+ value: Any?,
dagId: String,
taskId: String,
runId: String,
diff --git
a/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Frame.kt
b/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Frame.kt
index 9cd432692e2..7eac2da25fd 100644
--- a/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Frame.kt
+++ b/java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Frame.kt
@@ -28,6 +28,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import org.apache.airflow.sdk.execution.comm.Discriminator
import org.apache.airflow.sdk.execution.comm.PutVariable
import org.apache.airflow.sdk.execution.comm.SetTaskStateStore
+import org.apache.airflow.sdk.execution.comm.SetXCom
import org.msgpack.core.MessagePack
import org.msgpack.core.MessageUnpacker
import org.msgpack.core.buffer.ArrayBufferInput
@@ -46,7 +47,8 @@ data class RawFrame(
* fields to be present. When one is missing it fails validation, logs the
* frame and never replies, so the caller blocks forever.
*/
-private val REQUIRED_NULLABLE_REQUESTS = setOf(PutVariable::class.java,
SetTaskStateStore::class.java)
+private val REQUIRED_NULLABLE_REQUESTS =
+ setOf(PutVariable::class.java, SetTaskStateStore::class.java,
SetXCom::class.java)
@JsonInclude(JsonInclude.Include.ALWAYS)
private abstract class KeepNullFields
diff --git
a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/ArgTestSupport.kt
b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/ArgTestSupport.kt
index 95edc43bbcf..8384698c850 100644
--- a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/ArgTestSupport.kt
+++ b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/ArgTestSupport.kt
@@ -65,7 +65,7 @@ internal class FakeXComTransport(
override fun setXCom(
key: String,
- value: Any,
+ value: Any?,
dagId: String,
taskId: String,
runId: String,
diff --git a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/ClientTest.kt
b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/ClientTest.kt
index 239e2bbf954..bcd8456cda8 100644
--- a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/ClientTest.kt
+++ b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/ClientTest.kt
@@ -70,7 +70,7 @@ private class FakeTransport(
override fun setXCom(
key: String,
- value: Any,
+ value: Any?,
dagId: String,
taskId: String,
runId: String,
diff --git
a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/CommTest.kt
b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/CommTest.kt
index 1ee11aa8a9f..4684a4e7c56 100644
--- a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/CommTest.kt
+++ b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/CommTest.kt
@@ -639,6 +639,28 @@ class CommsTest {
Assertions.assertNull(body["description"])
}
+ @Test
+ @DisplayName("setXCom keeps a null value on the wire so the supervisor
stores a null XCom")
+ @Timeout(value = 30, unit = TimeUnit.SECONDS)
+ fun setXComKeepsNullValueOnTheWire() {
+ val details =
+ StartupDetails().also {
+ it.ti =
+ TaskInstance().also { ti ->
+ ti.dagId = "d"
+ ti.taskId = "t"
+ ti.runId = "r"
+ }
+ }
+ val (body, failure) = roundTrip(::emptyResponseFrame, details) {
it.setXCom(value = null) }
+
+ Assertions.assertNull(failure, "setXCom should return normally on an empty
response, got $failure")
+ Assertions.assertEquals("SetXCom", body["type"])
+ Assertions.assertEquals("return_value", body["key"])
+ Assertions.assertTrue(body.containsKey("value"), "value must be sent even
when null: $body")
+ Assertions.assertNull(body["value"])
+ }
+
@Test
@DisplayName("setVariable sends the description when one is given")
@Timeout(value = 30, unit = TimeUnit.SECONDS)
diff --git
a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/TaskTest.kt
b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/TaskTest.kt
index 35c13ad0ffa..f7315628212 100644
--- a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/TaskTest.kt
+++ b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/TaskTest.kt
@@ -81,6 +81,18 @@ class TaskTest {
Assertions.assertEquals(listOf("SIGTERM"), pollSignals(recorded, 1),
"running the task should not leave a trap open")
}
+ @Test
+ @DisplayName("Should push a null result as a null XCom")
+ fun shouldPushNullResult() {
+ val transport = RecordingTransport()
+
+ val details = startupDetails(taskId = "null_result")
+ val result = runTask(bundleWith("null_result",
NullResultTask::class.java), details, Client(details, transport))
+
+ Assertions.assertInstanceOf(SucceedTask::class.java, result)
+ Assertions.assertEquals(listOf("return_value" to null), transport.xComs)
+ }
+
@Test
@DisplayName("Should return removed when task is missing")
fun shouldReturnRemovedWhenTaskIsMissing() {
@@ -449,7 +461,7 @@ class TaskTest {
override fun setXCom(
key: String,
- value: Any,
+ value: Any?,
dagId: String,
taskId: String,
runId: String,
@@ -551,7 +563,7 @@ class TaskTest {
/** Records what a deciding task pushed and asked to skip, and the order of
the two. */
private class RecordingTransport : org.apache.airflow.sdk.execution.Client {
- val xComs = mutableListOf<Pair<String, Any>>()
+ val xComs = mutableListOf<Pair<String, Any?>>()
val skipped = mutableListOf<String>()
val events = mutableListOf<String>()
val triggered = mutableListOf<String>()
@@ -559,7 +571,7 @@ class TaskTest {
override fun setXCom(
key: String,
- value: Any,
+ value: Any?,
dagId: String,
taskId: String,
runId: String,
@@ -661,6 +673,16 @@ class TaskTest {
): Unit = throw CancellationException("the future this task waits for was
cancelled")
}
+ /** What the processor generates for a task method that returns a reference
type and returns null. */
+ class NullResultTask : Task {
+ override fun execute(
+ context: Context,
+ client: Client,
+ ) {
+ client.setXCom(value = null)
+ }
+ }
+
class FailingTask : Task {
override fun execute(
context: Context,
diff --git
a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/TriggerRunnerTest.kt
b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/TriggerRunnerTest.kt
index ad0b629fa2a..d67789b4d7b 100644
---
a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/TriggerRunnerTest.kt
+++
b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/TriggerRunnerTest.kt
@@ -56,7 +56,7 @@ private class FakeTrigger(
private val states: List<String> = emptyList(),
) : org.apache.airflow.sdk.execution.Client {
val triggered = mutableListOf<TriggerCall>()
- val xComs = mutableListOf<Pair<String, Any>>()
+ val xComs = mutableListOf<Pair<String, Any?>>()
var polls = 0
override fun triggerDagRun(
@@ -86,7 +86,7 @@ private class FakeTrigger(
override fun setXCom(
key: String,
- value: Any,
+ value: Any?,
dagId: String,
taskId: String,
runId: String,
diff --git
a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/internal/ArgValuesTest.kt
b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/internal/ArgValuesTest.kt
index bcb254547be..bbb4131b622 100644
---
a/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/internal/ArgValuesTest.kt
+++
b/java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/internal/ArgValuesTest.kt
@@ -103,7 +103,7 @@ internal class ArgValuesTest {
override fun setXCom(
key: String,
- value: Any,
+ value: Any?,
dagId: String,
taskId: String,
runId: String,