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 46bded1f5f8 Return a mapped task’s XComs when no map index is given
(#76825)
46bded1f5f8 is described below
commit 46bded1f5f888e48b92cf0b517deb24cc2e25bc0
Author: Tzu-ping Chung <[email protected]>
AuthorDate: Sun Nov 22 22:29:50 2026 +0800
Return a mapped task’s XComs when no map index is given (#76825)
* Read a mapped task’s XComs for omitted map index
* Document reading a mapped task's result from the Java SDK
* Document reading a mapped task's result from the Go SDK
* Require taskId in the TS SDK's getXCom
mapIndex now defaults to null, which reads the task's result, instead
of the running task's map index.
* Read a mapped Python task's result in the lang-SDK e2e Dag
* Add note on explicit -1
* Add newsfragment for mapped xcom_pull
* Load a mapped task's XComs one by one
* Skip the slice fallback with prior dates
* Log a missing XCom only when not found
---
.../authoring-and-scheduling/language-sdks/go.rst | 5 +-
.../language-sdks/java.rst | 7 +-
.../language-sdks/typescript.rst | 18 +--
airflow-core/newsfragments/76825.significant.rst | 20 ++++
.../src/airflow/jobs/triggerer_job_runner.py | 2 +
.../execution_api/versions/head/test_xcoms.py | 40 +++++++
airflow-core/tests/unit/jobs/test_triggerer_job.py | 8 +-
.../bundle/concurrentxcom/concurrentxcom.go | 2 +-
go-sdk/sdk/sdk.go | 17 ++-
.../main/kotlin/org/apache/airflow/sdk/Client.kt | 19 ++-
.../org/apache/airflow/sdk/execution/CommTest.kt | 14 +++
.../lang_sdk/dags/lang_sdk_mixed_language.py | 14 ++-
kubernetes-tests/lang_sdk/go_example/main.go | 36 +++++-
.../airflow/k8sexample/MixedLanguageExample.java | 8 ++
kubernetes-tests/lang_sdk/ts_example/src/main.ts | 6 +
task-sdk/src/airflow/sdk/api/client.py | 90 ++++++++++----
task-sdk/src/airflow/sdk/bases/xcom.py | 87 +++++++-------
.../src/airflow/sdk/coordinators/_subprocess.py | 18 ++-
task-sdk/src/airflow/sdk/definitions/xcom_arg.py | 5 +-
.../airflow/sdk/execution_time/request_handlers.py | 2 +
.../src/airflow/sdk/execution_time/task_runner.py | 21 ++--
task-sdk/tests/task_sdk/api/test_client.py | 90 ++++++++++++++
task-sdk/tests/task_sdk/bases/test_xcom.py | 23 +++-
.../tests/task_sdk/coordinators/test_subprocess.py | 40 ++++++-
.../tests/task_sdk/definitions/test_xcom_arg.py | 16 +++
ts-sdk/example/src/main.ts | 5 +-
ts-sdk/example/src/taskflow.ts | 5 +-
ts-sdk/src/coordinator/arg-binding.ts | 9 +-
ts-sdk/src/coordinator/client.ts | 38 +++---
ts-sdk/src/coordinator/operator-runner.ts | 4 +-
ts-sdk/src/coordinator/runtime.ts | 4 +-
ts-sdk/src/sdk/client-types.ts | 34 ++++--
ts-sdk/src/sdk/client.ts | 13 +-
ts-sdk/src/sdk/task.ts | 2 +-
ts-sdk/tests/coordinator/client.test.ts | 133 +++++++++++++++------
ts-sdk/tests/public-api.test.ts | 6 +-
36 files changed, 665 insertions(+), 196 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 8ec64c5aece..66147f9bbe0 100644
--- a/airflow-core/docs/authoring-and-scheduling/language-sdks/go.rst
+++ b/airflow-core/docs/authoring-and-scheduling/language-sdks/go.rst
@@ -549,7 +549,10 @@ The ``sdk.Client``
- A ``Connection`` with ``ID``, ``Type``, ``Host``, ``Port``, ``Login``,
``Password``, ``Path`` and ``Extra``,
and a ``GetURI()`` helper.
* - ``GetXCom(ctx, dagID, runID, taskID, mapIndex, key, nil)``
- - An XCom value, as an ``any``. See :ref:`go-sdk/types`.
+ - An XCom value, as an ``any``, or ``nil`` when none was pushed. A
``nil`` ``mapIndex`` reads the task's
+ result: its value, or for a mapped task the values of all its instances
in a ``[]any`` ordered by map
+ 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.
* - ``TaskStateStore()``
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 f71e57a46cd..c06f21f91b0 100644
--- a/airflow-core/docs/authoring-and-scheduling/language-sdks/java.rst
+++ b/airflow-core/docs/authoring-and-scheduling/language-sdks/java.rst
@@ -705,9 +705,10 @@ The ``Client``
- A ``Connection`` with ``id``, ``type``, ``host``, ``schema``,
``login``, ``password``, ``port`` and
``extra``. Throws when the connection does not exist.
* - ``getXCom(taskId)``
- - The ``return_value`` XCom of a task in the same Dag run, or ``null``
when it does not exist. Overloads
- read another key, Dag or run; see the API reference. For the Java types
values arrive as, see
- :ref:`java-sdk/types`.
+ - The ``return_value`` XCom of a task in the same Dag run, or ``null``
when it does not exist. For a mapped
+ 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`.
* - ``setXCom(value)`` / ``setXCom(key, value)``
- Publishes an XCom value. The value must be JSON-serializable.
* - ``getTaskStateStore()``
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 d5976f6871a..e0b0eb7b862 100644
--- a/airflow-core/docs/authoring-and-scheduling/language-sdks/typescript.rst
+++ b/airflow-core/docs/authoring-and-scheduling/language-sdks/typescript.rst
@@ -452,7 +452,7 @@ on a ``Bundle``:
export async function buildMessage() {
const client = getClient();
- const upstream = await client.getXCom<string>({ key: "return_value",
taskId: "python_start" });
+ const upstream = await client.getXCom<string>({ taskId: "python_start"
});
const greeting = await client.getVariable("typescript_example_greeting");
return `${greeting ?? "hello from TypeScript"}; upstream=${upstream ??
"missing"}`;
}
@@ -591,13 +591,15 @@ The ``TaskClient``
exist.
* - ``getConnectionOrThrow(connId)``
- Same, but throws ``ConnectionNotFoundError``, like Python's
``BaseHook.get_connection``.
- * - ``getXCom<T>({ key, ... })``
- - An XCom value, or ``null`` when it does not exist. ``dagId``, ``runId``
and ``taskId`` default to the
- current task; pass ``taskId`` to read an upstream task's XCom.
``mapIndex`` defaults to the current
- task's own map index when the target is the current task, and to the
unmapped value otherwise. See
- :ref:`typescript-sdk/types`.
- * - ``setXCom({ key, value, ... })``
- - Publishes an XCom value. The target and ``mapIndex`` default the same
way as for ``getXCom``.
+ * - ``getXCom<T>({ taskId, ... })``
+ - The XCom value ``taskId`` pushed, or ``null`` when it does not exist.
``key`` defaults to
+ ``return_value``, and ``dagId`` and ``runId`` to the current task's.
For a mapped task, it is the values
+ of all its instances in an array ordered by map index; pass
``mapIndex`` to read one instance. A map
+ index that selects no task instance reads ``null``. See
:ref:`typescript-sdk/types`.
+ * - ``setXCom({ value, ... })``
+ - Publishes an XCom value. ``key`` defaults to ``return_value``, and
``dagId``, ``runId`` and ``taskId``
+ to the current task's. ``mapIndex`` defaults to the current task's own
map index when the target is the
+ current task, and to the unmapped value otherwise.
* - ``taskStateStore``
- This task instance's key/value store, with ``get<T>(key)``, ``set(key,
value, { retention? })``,
``delete(key)`` and ``clear()``. See
:ref:`typescript-sdk/task-state-store`.
diff --git a/airflow-core/newsfragments/76825.significant.rst
b/airflow-core/newsfragments/76825.significant.rst
new file mode 100644
index 00000000000..26338f92b48
--- /dev/null
+++ b/airflow-core/newsfragments/76825.significant.rst
@@ -0,0 +1,20 @@
+``xcom_pull`` without a map index returns every instance's values for a mapped
task
+
+``ti.xcom_pull(task_ids=..., map_indexes=None)`` on a mapped task used to look
only for an unmapped
+value, find none, and return the default. It now returns a list of the mapped
instances' values, in
+map index order, as pulling the task's ``XComArg`` from outside its mapped
task group does. The
+default is still returned with ``include_prior_dates=True``. Pass
``map_indexes=-1`` to keep reading
+only an unmapped value.
+
+``getXCom`` in the Go, Java and TypeScript SDKs behaves the same way when no
map index is given.
+
+* Types of change
+
+ * [ ] Dag changes
+ * [ ] Config changes
+ * [ ] API changes
+ * [ ] CLI changes
+ * [x] Behaviour changes
+ * [ ] Plugin changes
+ * [ ] Dependency changes
+ * [ ] Code interface changes
diff --git a/airflow-core/src/airflow/jobs/triggerer_job_runner.py
b/airflow-core/src/airflow/jobs/triggerer_job_runner.py
index 9f8e5a7a0b3..ec7fe23d1c2 100644
--- a/airflow-core/src/airflow/jobs/triggerer_job_runner.py
+++ b/airflow-core/src/airflow/jobs/triggerer_job_runner.py
@@ -106,6 +106,7 @@ from airflow.sdk.execution_time.comms import (
VariableKeysResult,
VariableResult,
XComResult,
+ XComSequenceSliceResult,
_new_encoder,
_RequestFrame,
)
@@ -485,6 +486,7 @@ ToTriggerRunner = Annotated[
| VariableResult
| VariableKeysResult
| XComResult
+ | XComSequenceSliceResult
| DagRunStateResult
| DRCount
| TICount
diff --git
a/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_xcoms.py
b/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_xcoms.py
index fd2df490449..118fa34fd66 100644
---
a/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_xcoms.py
+++
b/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_xcoms.py
@@ -53,6 +53,8 @@ from airflow.models.xcom import (
from airflow.providers.standard.operators.empty import EmptyOperator
from airflow.providers.standard.operators.python import PythonOperator
from airflow.sdk import task_group
+from airflow.sdk.api.client import Client
+from airflow.sdk.api.datamodels import _generated as client_models
from airflow.sdk.definitions._internal.loop import create_loop
from airflow.sdk.serde import deserialize, serialize
from airflow.utils.session import create_session
@@ -1380,6 +1382,44 @@ class TestXComsGetEndpoint:
assert "XCom" in response.json()["detail"]["message"]
+class TestTaskSdkClientGetXCom:
+ """The Task SDK client reads XComs from this tree's Execution API as both
sides intend."""
+
+ @pytest.fixture(autouse=True)
+ def dag_run(self, dag_maker, session):
+ with dag_maker(dag_id="dag", serialized=True):
+ EmptyOperator(task_id="plain")
+ PythonOperator.partial(task_id="mapped",
python_callable=str).expand(op_args=[[1], [2]])
+ dag_run = dag_maker.create_dagrun(run_id="runid")
+ for ti in dag_run.get_task_instances(session=session):
+ value = "plain" if ti.task_id == "plain" else ti.region_index
+ session.add(XComModelV2(key=XCOM_RETURN_KEY, value=value,
task_instance_id=ti.id))
+ session.commit()
+ return dag_run
+
+ @pytest.mark.parametrize(
+ ("task_id", "map_index", "expected"),
+ [
+ pytest.param(
+ "mapped", None, client_models.XComSequenceSliceResponse([0,
1]), id="mapped-omitted"
+ ),
+ pytest.param(
+ "mapped", 1, client_models.XComResponse(key=XCOM_RETURN_KEY,
value=1), id="mapped-one"
+ ),
+ pytest.param(
+ "plain",
+ None,
+ client_models.XComResponse(key=XCOM_RETURN_KEY, value="plain"),
+ id="unmapped-omitted",
+ ),
+ ],
+ )
+ def test_get(self, task_id, map_index, expected):
+ client = Client(base_url=None, token="", dry_run=True,
transport=InProcessExecutionAPI().transport)
+ client.base_url = "http://in-process.invalid/"
+ assert client.xcoms.get("dag", "runid", task_id, XCOM_RETURN_KEY,
map_index) == expected
+
+
class TestXComsSetEndpoint:
@pytest.mark.parametrize(
("value", "expected_value"),
diff --git a/airflow-core/tests/unit/jobs/test_triggerer_job.py
b/airflow-core/tests/unit/jobs/test_triggerer_job.py
index 78d9dda9260..82cc88fc7ba 100644
--- a/airflow-core/tests/unit/jobs/test_triggerer_job.py
+++ b/airflow-core/tests/unit/jobs/test_triggerer_job.py
@@ -121,6 +121,7 @@ from airflow.sdk.execution_time.comms import (
SetAssetStateStoreByUri,
ToSupervisor,
ToTask,
+ XComSequenceSliceResult,
_new_encoder,
_RequestFrame,
_ResponseFrame,
@@ -4898,7 +4899,6 @@ class TestTriggererMessageTypes:
"PrevSuccessfulDagRunResult",
"XComCountResponse",
"XComSequenceIndexResult",
- "XComSequenceSliceResult",
"PreviousDagRunResult",
"PreviousTIResult",
"HITLDetailRequestResult",
@@ -4926,6 +4926,12 @@ class TestTriggererMessageTypes:
+ "\n\nEither handle these types in ToTriggerRunner or update
in_task_but_not_in_trigger_runner list."
)
+ def test_trigger_runner_decodes_a_mapped_xcom_read(self):
+ """GetXCom on a mapped task is answered with a slice result, which a
trigger must decode."""
+ wire = _new_encoder().encode(XComSequenceSliceResult(root=[1,
2]).model_dump())
+ decoded =
TypeAdapter(ToTriggerRunner).validate_python(msgspec.msgpack.decode(wire))
+ assert decoded == XComSequenceSliceResult(root=[1, 2])
+
def _make_ti_dto(task_id="my_task", map_index=-1, context_carrier=None):
return TaskInstanceDTO(
diff --git a/go-sdk/example/bundle/concurrentxcom/concurrentxcom.go
b/go-sdk/example/bundle/concurrentxcom/concurrentxcom.go
index e85111421ec..fd558c469d4 100644
--- a/go-sdk/example/bundle/concurrentxcom/concurrentxcom.go
+++ b/go-sdk/example/bundle/concurrentxcom/concurrentxcom.go
@@ -60,7 +60,7 @@ func PullXComsConcurrently(actx airflow.Context) (any, error)
{
}
pull := func(key string) (any, error) {
- v, err := client.GetXCom(actx, ti.DagID, ti.RunID, ti.TaskID,
nil, key, nil)
+ v, err := client.GetXCom(actx, ti.DagID, ti.RunID, ti.TaskID,
ti.MapIndex, key, nil)
if err != nil {
return nil, err
}
diff --git a/go-sdk/sdk/sdk.go b/go-sdk/sdk/sdk.go
index 1c3f47c8f38..aa2a8c89ba1 100644
--- a/go-sdk/sdk/sdk.go
+++ b/go-sdk/sdk/sdk.go
@@ -112,8 +112,21 @@ type ConnectionClient interface {
// another task's XCom, or to push under a custom key.
type XComClient interface {
// GetXCom returns the value stored under key by the task identified by
- // dagID/runID/taskID. For a mapped task instance pass its mapIndex,
- // otherwise pass nil. If no value exists the error wraps XComNotFound.
+ // dagID/runID/taskID, or nil if none was pushed.
+ //
+ // A nil mapIndex reads the task's result, which depends on whether the
task
+ // is mapped, as its definition in the Dag says, not on how many
instances it
+ // ran:
+ //
+ // - For a task that is not mapped, nil reads its value.
+ // - For a mapped task, nil reads the values of all its instances as a
+ // []any ordered by map index. Instances that pushed nothing are
left
+ // out. If none pushed a value, including when the task expanded to
no
+ // instances, the result is an empty slice, or nil on Airflow 3.4.
+ //
+ // A map index reads that one instance's value. One that selects no task
+ // instance of the task, such as any map index of a task that is not
+ // mapped, reads nil.
//
// value is reserved for future typed decoding and is currently
ignored; the
// stored value is returned as the first result instead.
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 8b3311382b5..2922afa2e40 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
@@ -147,15 +147,24 @@ class Client internal constructor(
* @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 source task instance.
+ * @param mapIndex Map index of the task instance to read, or `null` to read
+ * the task's result. See below.
* @param includePriorDates If `true`, also search earlier Dag-run dates.
* @return The XCom value, or `null` if none was pushed.
* @throws ApiError if the API call fails.
*
- * If `map_index` is set to `null` against a mapped task, the task's
- * "collective result" is returned. Results from all mapped instances are
- * aggregated into a list, ordered by the map index (ascending). For a
- * non-mapped task, setting `map_index` to `null` is equivalent to `-1`.
+ * With [mapIndex] `null`, what is read depends on whether the task is
mapped,
+ * as its definition in the Dag says, not on how many instances it ran:
+ *
+ * - For a task that is not mapped, its value.
+ * - For a mapped task, its "collective result": the values of all its
+ * instances in a list, ordered by map index. Instances that pushed nothing
+ * are left out. If none pushed a value, including when the task expanded
+ * to no instances, the result is an empty list, or `null` on Airflow 3.4.
+ *
+ * A map index reads that one instance's value. One that selects no task
+ * instance of the task, such as any map index of a task that is not mapped,
+ * reads `null`.
*/
@JvmOverloads fun getXCom(
key: String = XCOM_RETURN_KEY,
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 7aa55adb7d5..1ee11aa8a9f 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
@@ -669,6 +669,20 @@ class CommsTest {
Assertions.assertInstanceOf(ApiError::class.java, failure)
}
+ @Test
+ @DisplayName("getXCom sends a null map index, which the server resolves by
the task's definition")
+ @Timeout(value = 30, unit = TimeUnit.SECONDS)
+ fun getXComSendsNullMapIndex() {
+ val (body, failure) =
+ roundTrip({ responseFrame(it) }) {
+ it.getXCom(dagId = "dag", runId = "run", taskId = "upstream")
+ }
+
+ Assertions.assertNull(failure, "getXCom should return normally on
XComResult, got $failure")
+ Assertions.assertEquals("GetXCom", body["type"])
+ Assertions.assertNull(body["map_index"])
+ }
+
private val tiId: UUID =
UUID.fromString("0199a5d6-1c2e-7c6a-9c1e-7a2f7f0d1e42")
private fun currentTaskInstance() = StartupDetails().also { it.ti =
TaskInstance().also { ti -> ti.id = tiId } }
diff --git a/kubernetes-tests/lang_sdk/dags/lang_sdk_mixed_language.py
b/kubernetes-tests/lang_sdk/dags/lang_sdk_mixed_language.py
index 0b53ee193cc..e9440a3657a 100644
--- a/kubernetes-tests/lang_sdk/dags/lang_sdk_mixed_language.py
+++ b/kubernetes-tests/lang_sdk/dags/lang_sdk_mixed_language.py
@@ -20,8 +20,8 @@ Mixed-language stub Dag for the KubernetesExecutor lang-SDK
system test.
A single ``lang_sdk_mixed_language`` Dag chains native Python tasks with Go,
Java and
TypeScript stub tasks so one run exercises every lang-SDK coordinator on
KubernetesExecutor::
- python_task_1 >> go_extract >> go_transform >> java_extract >>
java_transform
- >> ts_extract >> ts_transform >> python_task_2
+ python_task_1 >> python_fanout >> go_extract >> go_transform >>
java_extract
+ >> java_transform >> ts_extract >> ts_transform >>
python_task_2
* ``go_extract`` / ``go_transform`` are ``@task.stub(queue="golang")``; the
``golang`` queue is routed to the ``ExecutableCoordinator``. Their Go
@@ -32,7 +32,9 @@ TypeScript stub tasks so one run exercises every lang-SDK
coordinator on Kuberne
* ``ts_extract`` / ``ts_transform`` are ``@task.stub(queue="typescript")``; the
``typescript`` queue is routed to the ``NodeCoordinator``. Their TypeScript
implementations live in ``../ts_example`` under this same dag_id.
-* The Python tasks run on the default Python path.
+* The Python tasks run on the default Python path. ``python_fanout`` is
mapped, and each
+ ``*_transform`` task reads its result with no map index, which is every
instance's
+ value in a list.
The dag_id and the Go/Java/TypeScript task ids MUST match the identities the
bundles expose
so each coordinator can locate its artifact by dag_id and look up the task by
id.
@@ -48,6 +50,11 @@ def python_task_1():
return "value_from_python_task_1"
+@task()
+def python_fanout(value):
+ return value
+
+
@task.stub(queue="golang")
def go_extract(): ...
@@ -81,6 +88,7 @@ def python_task_2():
def lang_sdk_mixed_language():
(
python_task_1()
+ >> python_fanout.expand(value=[1, 2, 3])
>> go_extract()
>> go_transform()
>> java_extract()
diff --git a/kubernetes-tests/lang_sdk/go_example/main.go
b/kubernetes-tests/lang_sdk/go_example/main.go
index 350e5f29e9b..b29916ce10e 100644
--- a/kubernetes-tests/lang_sdk/go_example/main.go
+++ b/kubernetes-tests/lang_sdk/go_example/main.go
@@ -24,11 +24,14 @@
package main
import (
+ "fmt"
"log"
+ "reflect"
"runtime"
"time"
"github.com/apache/airflow/go-sdk/airflow"
+ "github.com/apache/airflow/go-sdk/sdk"
)
// Must match the dag_id of the Python stub Dag and the Java/TypeScript
bundles.
@@ -60,12 +63,43 @@ func goExtract(actx airflow.Context) (any, error) {
}
// goTransform reads the my_variable Airflow variable through the coordinator,
-// exercising a GetVariable round-trip over the Execution API.
+// exercising a GetVariable round-trip over the Execution API, and the result
of the
+// mapped python_fanout task, which is every instance's value in a list.
func goTransform(actx airflow.Context) error {
val, err := actx.Client().GetVariable(actx, "my_variable")
if err != nil {
return err
}
actx.Logger().InfoContext(actx, "go_transform obtained variable",
"my_variable", val)
+
+ ti := actx.TaskInstance()
+ fanout, err := actx.Client().GetXCom(
+ actx, ti.DagID, ti.RunID, "python_fanout", nil,
sdk.XComReturnValueKey, nil,
+ )
+ if err != nil {
+ return err
+ }
+ values, ok := fanout.([]any)
+ if !ok || len(values) != 3 {
+ return fmt.Errorf("python_fanout result is %#v, want []any{1,
2, 3}", fanout)
+ }
+ for i, v := range values {
+ if n, ok := asInt64(v); !ok || n != int64(i+1) {
+ return fmt.Errorf("python_fanout result is %#v, want
[]any{1, 2, 3}", fanout)
+ }
+ }
return nil
}
+
+// asInt64 returns v as an int64 if it is an integer. An integer XCom value
arrives
+// as a Go integer type whose width depends on the value.
+func asInt64(v any) (int64, bool) {
+ switch n := reflect.ValueOf(v); {
+ case n.CanInt():
+ return n.Int(), true
+ case n.CanUint():
+ return int64(n.Uint()), true
+ default:
+ return 0, false
+ }
+}
diff --git
a/kubernetes-tests/lang_sdk/java_example/src/java/org/apache/airflow/k8sexample/MixedLanguageExample.java
b/kubernetes-tests/lang_sdk/java_example/src/java/org/apache/airflow/k8sexample/MixedLanguageExample.java
index 64251d1defa..5aa33899505 100644
---
a/kubernetes-tests/lang_sdk/java_example/src/java/org/apache/airflow/k8sexample/MixedLanguageExample.java
+++
b/kubernetes-tests/lang_sdk/java_example/src/java/org/apache/airflow/k8sexample/MixedLanguageExample.java
@@ -20,6 +20,7 @@
package org.apache.airflow.k8sexample;
import java.util.Date;
+import java.util.List;
import org.apache.airflow.sdk.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -42,5 +43,12 @@ public class MixedLanguageExample {
public void transform(Client client) {
var variable = client.getVariable("my_variable");
logger.info("java_transform obtained variable {}", variable);
+
+ // python_fanout is mapped, so its result is every instance's value in a
list.
+ // Integers arrive as Long.
+ var fanout = client.getXCom("python_fanout");
+ if (!List.of(1L, 2L, 3L).equals(fanout)) {
+ throw new IllegalStateException("python_fanout result is " + fanout + ",
want [1, 2, 3]");
+ }
}
}
diff --git a/kubernetes-tests/lang_sdk/ts_example/src/main.ts
b/kubernetes-tests/lang_sdk/ts_example/src/main.ts
index e96fa1395b7..adae020652e 100644
--- a/kubernetes-tests/lang_sdk/ts_example/src/main.ts
+++ b/kubernetes-tests/lang_sdk/ts_example/src/main.ts
@@ -23,6 +23,8 @@
// ../dags. The coordinator locates this bundle by dag_id, so only the
TypeScript tasks
// are registered here.
+import { deepStrictEqual } from "node:assert/strict";
+
import { Bundle, getClient, TaskHandler } from "@apache-airflow/ts-sdk";
const MIXED_LANGUAGE_DAG_ID = "lang_sdk_mixed_language";
@@ -37,6 +39,10 @@ export async function tsExtract() {
export async function tsTransform() {
const value = await getClient().getVariable("my_variable");
console.log(`ts_transform obtained variable: ${value}`);
+
+ // python_fanout is mapped, so its result is every instance's value in a
list.
+ const fanout = await getClient().getXCom<number[]>({ taskId: "python_fanout"
});
+ deepStrictEqual(fanout, [1, 2, 3]);
}
const bundle = new Bundle();
diff --git a/task-sdk/src/airflow/sdk/api/client.py
b/task-sdk/src/airflow/sdk/api/client.py
index 632a2cafde7..0531b57e582 100644
--- a/task-sdk/src/airflow/sdk/api/client.py
+++ b/task-sdk/src/airflow/sdk/api/client.py
@@ -667,36 +667,86 @@ class XComOperations:
include_prior_dates: bool = False,
*,
previous_iteration: bool = False,
- ) -> XComResponse:
- """Get a XCom value from the API server."""
+ ) -> XComResponse | XComSequenceSliceResponse:
+ """
+ Get a XCom value from the API server.
+
+ Any *map_index* is sent as given. An omitted one reads the task's
+ result: its value, or for a mapped task the values of all its
+ instances, as a slice response. With *include_prior_dates*, a mapped
+ task reads as not found.
+ """
params: dict[str, str | int] = {}
if previous_iteration:
params["previous_iteration"] = True
- if map_index is not None and map_index >= 0:
- params.update({"map_index": map_index})
+ if map_index is not None:
+ params["map_index"] = map_index
if include_prior_dates:
params.update({"include_prior_dates": include_prior_dates})
try:
resp = self.client.get(_path("xcoms", dag_id, run_id, task_id,
tail=key), params=params)
except ServerResponseError as e:
- if e.response.status_code == HTTPStatus.NOT_FOUND:
- log.debug(
- "XCom not found",
- dag_id=dag_id,
- run_id=run_id,
- task_id=task_id,
- key=key,
- map_index=map_index,
- detail=e.detail,
- status_code=e.response.status_code,
- )
- # Airflow 2.x just ignores the absence of an XCom and moves on
with a return value of None
- # Hence returning with key as `key` and value as `None`, so
that the message is sent back to task runner
- # and the default value of None in xcom_pull is used.
- return XComResponse(key=key, value=None)
- raise
+ if e.response.status_code != HTTPStatus.NOT_FOUND:
+ raise
+ mapped = self._get_mapped_slice_or_none(
+ dag_id,
+ run_id,
+ task_id,
+ key,
+ map_index,
+ include_prior_dates=include_prior_dates,
+ previous_iteration=previous_iteration,
+ )
+ if mapped is not None:
+ return mapped
+ log.debug(
+ "XCom not found",
+ dag_id=dag_id,
+ run_id=run_id,
+ task_id=task_id,
+ key=key,
+ map_index=map_index,
+ detail=e.detail,
+ status_code=e.response.status_code,
+ )
+ # A missing XCom is not an error, as in Airflow 2; xcom_pull then
returns its default.
+ return XComResponse(key=key, value=None)
return XComResponse.model_validate_json(resp.read())
+ def _get_mapped_slice_or_none(
+ self,
+ dag_id: str,
+ run_id: str,
+ task_id: str,
+ key: str,
+ map_index: int | None,
+ *,
+ include_prior_dates: bool,
+ previous_iteration: bool,
+ ) -> XComSequenceSliceResponse | None:
+ """
+ Read a mapped task's values from the slice endpoint.
+
+ This is for a server that reads map index -1 for an omitted map index,
+ and so finds nothing for a mapped task. A server that resolves it by
+ how the task is defined never answers a mapped task as not found.
+ A read with *include_prior_dates* is left not found, since the slice
+ mixes earlier runs' values.
+ """
+ if map_index is not None or include_prior_dates:
+ return None
+ response = self.get_sequence_slice(
+ dag_id,
+ run_id,
+ task_id,
+ key,
+ None,
+ None,
+ None,
+ previous_iteration=previous_iteration,
+ )
+ return response if response.root else None # Empty may also be an
unmapped task.
+
def set(
self,
dag_id: str,
diff --git a/task-sdk/src/airflow/sdk/bases/xcom.py
b/task-sdk/src/airflow/sdk/bases/xcom.py
index 3c4b99ade18..a8f807cf4ac 100644
--- a/task-sdk/src/airflow/sdk/bases/xcom.py
+++ b/task-sdk/src/airflow/sdk/bases/xcom.py
@@ -465,7 +465,8 @@ class BaseXCom:
dag_id=dag_id,
task_id=task_id,
run_id=run_id,
- map_index=map_index,
+ # Sent explicitly: an omitted map index would read every
instance of a mapped task.
+ map_index=-1 if map_index is None else map_index,
),
)
@@ -502,8 +503,11 @@ class BaseXCom:
:param dag_id: Dag ID to pull the XCom from.
:param task_id: Task ID to pull the XCom from.
:param map_index: Map index of the task instance to pull the XCom from.
- *None* (default) pulls the XCom of a non-mapped task, which has
- map index ``-1``.
+ *None* (default) pulls the task's result: the XCom of a non-mapped
+ task, or for a mapped task the XComs of all its instances as a
+ list, the same values ``get_all`` returns. With
+ *include_prior_dates*, a mapped task reads *None*. Airflow 3.4
+ returns *None* instead of an empty list.
:param key: A key for the XCom. Only XCom with this key will be
returned.
:param include_prior_dates: If *False* (default), only XCom from the
specified Dag run is returned. If *True*, the latest matching XCom
is
@@ -523,20 +527,16 @@ class BaseXCom:
),
)
- if not isinstance(msg, XComResult):
- raise TypeError(f"Expected XComResult, received: {type(msg)}
{msg}")
-
- if msg.value is not None:
- return cls._load(msg)
- log.debug(
- "No XCom value found; defaulting to None.",
- key=key,
- dag_id=dag_id,
- task_id=task_id,
- run_id=run_id,
- map_index=map_index,
- )
- return None
+ if (value := cls._load_result(msg)) is None:
+ log.debug(
+ "No XCom value found; defaulting to None.",
+ key=key,
+ dag_id=dag_id,
+ task_id=task_id,
+ run_id=run_id,
+ map_index=map_index,
+ )
+ return value
@classmethod
async def aget_one(
@@ -565,8 +565,11 @@ class BaseXCom:
:param dag_id: Dag ID to pull the XCom from.
:param task_id: Task ID to pull the XCom from.
:param map_index: Map index of the task instance to pull the XCom from.
- *None* (default) pulls the XCom of a non-mapped task, which has
- map index ``-1``.
+ *None* (default) pulls the task's result: the XCom of a non-mapped
+ task, or for a mapped task the XComs of all its instances as a
+ list, the same values ``get_all`` returns. With
+ *include_prior_dates*, a mapped task reads *None*. Airflow 3.4
+ returns *None* instead of an empty list.
:param key: A key for the XCom. Only XCom with this key will be
returned.
:param include_prior_dates: If *False* (default), only XCom from the
specified Dag run is returned. If *True*, the latest matching XCom
is
@@ -585,20 +588,16 @@ class BaseXCom:
),
)
- if not isinstance(msg, XComResult):
- raise TypeError(f"Expected XComResult, received: {type(msg)}
{msg}")
-
- if msg.value is not None:
- return await asyncio.to_thread(cls._load, msg)
- log.debug(
- "No XCom value found; defaulting to None.",
- key=key,
- dag_id=dag_id,
- task_id=task_id,
- run_id=run_id,
- map_index=map_index,
- )
- return None
+ if (value := await asyncio.to_thread(cls._load_result, msg)) is None:
+ log.debug(
+ "No XCom value found; defaulting to None.",
+ key=key,
+ dag_id=dag_id,
+ task_id=task_id,
+ run_id=run_id,
+ map_index=map_index,
+ )
+ return value
@classmethod
def get_all(
@@ -646,10 +645,7 @@ class BaseXCom:
if not isinstance(msg, XComSequenceSliceResult):
raise TypeError(f"Expected XComSequenceSliceResult, received:
{type(msg)} {msg}")
- if not msg.root:
- return None
-
- return cls._load_many(msg.root)
+ return cls._load_result(msg)
@classmethod
async def aget_all(
@@ -697,10 +693,7 @@ class BaseXCom:
if not isinstance(msg, XComSequenceSliceResult):
raise TypeError(f"Expected XComSequenceSliceResult, received:
{type(msg)} {msg}")
- if not msg.root:
- return None
-
- return await asyncio.to_thread(cls._load_many, msg.root)
+ return await asyncio.to_thread(cls._load_result, msg)
@classmethod
def store_value(cls, coordinate: XComCoordinate, key: str, value: Any) ->
JsonValue:
@@ -736,6 +729,18 @@ class BaseXCom:
"""
return cls.deserialize_value(_XComValueWrapper(stored))
+ @classmethod
+ def _load_result(cls, result: Any) -> Any:
+ """Load an XCom read's result, one stored value or a mapped task's
values; *None* if empty."""
+ match result:
+ case XComResult(value=None) | XComSequenceSliceResult(root=[]):
+ return None
+ case XComResult():
+ return cls._load(result)
+ case XComSequenceSliceResult(root=values):
+ return cls._load_many(values)
+ raise TypeError(f"Expected XComResult or XComSequenceSliceResult,
received: {type(result)} {result}")
+
@classmethod
def _load_many(cls, values: list[JsonValue]) -> list[Any]:
return [cls._load(_XComValueWrapper(value)) for value in values]
diff --git a/task-sdk/src/airflow/sdk/coordinators/_subprocess.py
b/task-sdk/src/airflow/sdk/coordinators/_subprocess.py
index 41952403c2b..4fd053b7787 100644
--- a/task-sdk/src/airflow/sdk/coordinators/_subprocess.py
+++ b/task-sdk/src/airflow/sdk/coordinators/_subprocess.py
@@ -40,7 +40,7 @@ import subprocess
import time
from datetime import UTC, datetime
from pathlib import PurePosixPath
-from typing import TYPE_CHECKING, Any, ClassVar, NoReturn, TypeVar, cast
+from typing import TYPE_CHECKING, Any, ClassVar, Literal, NoReturn, TypeVar,
cast
import attrs
import psutil
@@ -816,11 +816,19 @@ class _PopenActivitySubprocess(ActivitySubprocess):
self, msg: GetXCom, log: FilteringBoundLogger, req_id: int
) -> RequestResult | ResponseSent:
result, dump_opts = handle_get_xcom(self.client, msg)
- if not (isinstance(result, XComResult) and result.value is not None
and _is_loaded_through_backend()):
- return result, dump_opts
+ # A mapped task's values are loaded one by one; the lang SDK gets
either as one XCom value.
+ match result:
+ case XComResult(value=stored) if stored is not None:
+ hook: Literal["load", "load_many"] = "load"
+ case XComSequenceSliceResult(root=stored) if stored:
+ hook = "load_many"
+ case _:
+ return result, dump_opts
+ if not _is_loaded_through_backend():
+ return XComResult(key=msg.key, value=stored), {}
return self._call_xcom_backend(
- XComBackendCall(hook="load", key=msg.key, value=result.value),
- lambda loaded: (result.model_copy(update={"value": loaded.value}),
dump_opts),
+ XComBackendCall(hook=hook, key=msg.key, value=stored),
+ lambda loaded: (XComResult(key=msg.key, value=loaded.value), {}),
req_id,
)
diff --git a/task-sdk/src/airflow/sdk/definitions/xcom_arg.py
b/task-sdk/src/airflow/sdk/definitions/xcom_arg.py
index db71701a0a7..7a184b908f2 100644
--- a/task-sdk/src/airflow/sdk/definitions/xcom_arg.py
+++ b/task-sdk/src/airflow/sdk/definitions/xcom_arg.py
@@ -337,8 +337,9 @@ class PlainXComArg(XComArg):
return LazyXComSequence(xcom_arg=self, ti=ti)
tg = self.operator.get_closest_mapped_task_group()
if tg is None:
- # No mapped task group - pull from unmapped instance
- map_indexes: int | range | None = None
+ # No mapped task group; pull from the unmapped instance explicitly
+ # to spare the server a definition lookup.
+ map_indexes: int | range = -1
else:
# Compute lazily - ti_count will be queried if needed
cached_context = getattr(ti, "_cached_template_context", None)
diff --git a/task-sdk/src/airflow/sdk/execution_time/request_handlers.py
b/task-sdk/src/airflow/sdk/execution_time/request_handlers.py
index 7141b3b0807..e9b20ffeabf 100644
--- a/task-sdk/src/airflow/sdk/execution_time/request_handlers.py
+++ b/task-sdk/src/airflow/sdk/execution_time/request_handlers.py
@@ -328,6 +328,8 @@ def handle_get_xcom(client: Client, msg: GetXCom) ->
tuple[BaseModel | None, dic
if isinstance(xcom, XComResponse):
xcom_result = XComResult.from_xcom_response(xcom)
return xcom_result, {"exclude_unset": True}
+ if isinstance(xcom, XComSequenceSliceResponse):
+ return XComSequenceSliceResult.from_response(xcom), {}
return xcom, {}
diff --git a/task-sdk/src/airflow/sdk/execution_time/task_runner.py
b/task-sdk/src/airflow/sdk/execution_time/task_runner.py
index 8bee11cefb9..303ae89b465 100644
--- a/task-sdk/src/airflow/sdk/execution_time/task_runner.py
+++ b/task-sdk/src/airflow/sdk/execution_time/task_runner.py
@@ -578,8 +578,8 @@ class RuntimeTaskInstance(TaskInstance):
:param dag_id: If provided, only pulls XComs from this Dag. If *None*
(default), the Dag of the calling task is used.
:param map_indexes: If provided, only pull XComs with matching indexes.
- If *None* (default), this is inferred from the task(s) being pulled
- (see below for details).
+ If not provided (default), every instance of the task(s) being
pulled
+ is pulled (see below for details).
:param include_prior_dates: If False, only XComs from the current
logical_date are returned. If *True*, XComs from previous dates
are returned as well.
@@ -587,14 +587,15 @@ class RuntimeTaskInstance(TaskInstance):
If *None* (default), the run_id of the calling task is used.
When pulling one single task (``task_id`` is *None* or a str) without
- specifying ``map_indexes``, the return value is a single XCom entry
- (map_indexes is set to map_index of the calling task instance).
-
- When pulling task is mapped the specified ``map_index`` is used, so by
default
- pulling on mapped task will result in no matching XComs if the task
instance
- of the method call is not mapped. Otherwise, the map_index of the
calling task
- instance is used. Setting ``map_indexes`` to *None* will pull XCom as
it would
- from a non mapped task.
+ specifying ``map_indexes``, the XComs of all its instances are pulled.
If
+ exactly one is found, it is returned on its own; otherwise they are
+ returned as a list.
+
+ Setting ``map_indexes`` to *None* pulls the task's result: the XCom of
a
+ non-mapped task, or for a mapped task the XComs of all its instances
as a
+ list (*None* instead of an empty list on Airflow 3.4). With
+ ``include_prior_dates``, a mapped task matches no XCom. A map index the
+ task has no instance at matches no XCom either.
In either case, ``default`` (*None* if not specified) is returned if no
matching XComs are found.
diff --git a/task-sdk/tests/task_sdk/api/test_client.py
b/task-sdk/tests/task_sdk/api/test_client.py
index 32c6fc6b003..a3d2c514c95 100644
--- a/task-sdk/tests/task_sdk/api/test_client.py
+++ b/task-sdk/tests/task_sdk/api/test_client.py
@@ -52,6 +52,7 @@ from airflow.sdk.api.datamodels._generated import (
TerminalTIState,
VariableResponse,
XComResponse,
+ XComSequenceSliceResponse,
)
from airflow.sdk.exceptions import ErrorType, TaskAlreadyRunningError
from airflow.sdk.execution_time.comms import (
@@ -1281,6 +1282,93 @@ class TestXCOMOperations:
assert result.key == "test_key"
assert result.value == "test_value"
+ @pytest.mark.parametrize(
+ ("kwargs", "expected_params"),
+ [
+ pytest.param({}, {}, id="omitted"),
+ pytest.param({"map_index": None}, {}, id="none"),
+ pytest.param({"map_index": -1}, {"map_index": "-1"},
id="minus-one"),
+ pytest.param({"map_index": 2}, {"map_index": "2"}, id="index"),
+ ],
+ )
+ def test_xcom_get_sends_map_index_as_given(self, kwargs, expected_params):
+ requests = []
+
+ def handle_request(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ return httpx2.Response(status_code=200, json={"key": "key",
"value": ["a", "b"]})
+
+ client = make_client(transport=httpx2.MockTransport(handle_request))
+ result = client.xcoms.get(dag_id="dag_id", run_id="run_id",
task_id="task_id", key="key", **kwargs)
+
+ assert dict(requests[0].url.params) == expected_params
+ assert result == XComResponse(key="key", value=["a", "b"])
+
+ @pytest.mark.parametrize(
+ ("slice_values", "expected"),
+ [
+ pytest.param(["a", "b"], XComSequenceSliceResponse(["a", "b"]),
id="mapped"),
+ pytest.param([], XComResponse(key="key", value=None),
id="nothing"),
+ ],
+ )
+ def test_xcom_get_omitted_map_index_reads_the_slice_when_not_found(self,
slice_values, expected):
+ requests = []
+
+ def handle_request(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ if request.url.path.endswith("/slice"):
+ return httpx2.Response(status_code=200, json=slice_values)
+ return httpx2.Response(
+ status_code=404, json={"detail": {"reason": "not_found",
"message": "XCom not found"}}
+ )
+
+ client = make_client(transport=httpx2.MockTransport(handle_request))
+ result = client.xcoms.get(dag_id="dag_id", run_id="run_id",
task_id="task_id", key="key")
+
+ assert result == expected
+ assert [request.url.path for request in requests] == [
+ "/xcoms/dag_id/run_id/task_id/key",
+ "/xcoms/dag_id/run_id/task_id/key/slice",
+ ]
+
+ def test_xcom_get_omitted_map_index_raises_when_the_slice_fails(self):
+ def handle_request(request: httpx2.Request) -> httpx2.Response:
+ if request.url.path.endswith("/slice"):
+ return httpx2.Response(status_code=403, json={"detail":
"Forbidden"})
+ return httpx2.Response(
+ status_code=404,
+ json={"detail": {"reason": "not_found", "message": "XCom not
found"}},
+ )
+
+ client = make_client(transport=httpx2.MockTransport(handle_request))
+ with pytest.raises(ServerResponseError) as ctx:
+ client.xcoms.get(dag_id="dag_id", run_id="run_id",
task_id="task_id", key="key")
+
+ assert ctx.value.response.status_code == 403
+
+ @pytest.mark.parametrize(
+ "kwargs",
+ [
+ pytest.param({"map_index": -1}, id="explicit-map-index"),
+ pytest.param({"include_prior_dates": True}, id="prior-dates"),
+ ],
+ )
+ def test_xcom_get_does_not_read_the_slice(self, kwargs):
+ requests = []
+
+ def handle_request(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ return httpx2.Response(
+ status_code=404,
+ json={"detail": {"reason": "not_found", "message": "XCom not
found"}},
+ )
+
+ client = make_client(transport=httpx2.MockTransport(handle_request))
+ result = client.xcoms.get(dag_id="dag_id", run_id="run_id",
task_id="task_id", key="key", **kwargs)
+
+ assert result == XComResponse(key="key", value=None)
+ assert len(requests) == 1
+
def test_xcom_get_500_error(self):
with time_machine.travel("2023-01-01T00:00:00Z", tick=False):
# Simulate a successful response from the server returning a 500
error
@@ -1312,6 +1400,8 @@ class TestXCOMOperations:
status_code=404,
json={"detail": {"reason": "not_found", "message": "XCom
not found"}},
)
+ if request.url.path == "/xcoms/dag_id/run_id/task_id/key/slice":
+ return httpx2.Response(status_code=200, json=[])
return httpx2.Response(status_code=400, json={"detail": "Bad
Request"})
client = make_client(transport=httpx2.MockTransport(handle_request))
diff --git a/task-sdk/tests/task_sdk/bases/test_xcom.py
b/task-sdk/tests/task_sdk/bases/test_xcom.py
index 44ceb92bc5c..988337ca7a2 100644
--- a/task-sdk/tests/task_sdk/bases/test_xcom.py
+++ b/task-sdk/tests/task_sdk/bases/test_xcom.py
@@ -102,10 +102,31 @@ class TestBaseXCom:
purge.assert_not_called()
assert mock_supervisor_comms.send.call_args_list == [
- mock.call(GetXCom(key="key", task_id="task", dag_id="dag",
run_id="run")),
+ mock.call(GetXCom(key="key", task_id="task", dag_id="dag",
run_id="run", map_index=-1)),
mock.call(DeleteXCom(key="key", task_id="task", dag_id="dag",
run_id="run")),
]
+ def
test_get_one_without_map_index_loads_each_of_a_mapped_tasks_values(self,
mock_supervisor_comms):
+ """A mapped task's values are answered as a slice, and loaded one by
one."""
+ mock_supervisor_comms.send.return_value =
XComSequenceSliceResult(root=["a", "b"])
+
+ result = StoreXCom.get_one(key="key", task_id="task", dag_id="dag",
run_id="run")
+
+ assert result == ["loaded a", "loaded b"]
+ mock_supervisor_comms.send.assert_called_once_with(
+ GetXCom(key="key", task_id="task", dag_id="dag", run_id="run",
map_index=None)
+ )
+
+ @pytest.mark.asyncio
+ async def
test_aget_one_without_map_index_loads_each_of_a_mapped_tasks_values(
+ self, mock_supervisor_comms
+ ):
+ mock_supervisor_comms.asend =
mock.AsyncMock(return_value=XComSequenceSliceResult(root=["a", "b"]))
+
+ result = await StoreXCom.aget_one(key="key", task_id="task",
dag_id="dag", run_id="run")
+
+ assert result == ["loaded a", "loaded b"]
+
@pytest.mark.asyncio
async def test_aget_one_returns_value(self, mock_supervisor_comms):
"""aget_one awaits asend and returns the deserialized value."""
diff --git a/task-sdk/tests/task_sdk/coordinators/test_subprocess.py
b/task-sdk/tests/task_sdk/coordinators/test_subprocess.py
index c2d4ecdb28a..ffddd2ebabf 100644
--- a/task-sdk/tests/task_sdk/coordinators/test_subprocess.py
+++ b/task-sdk/tests/task_sdk/coordinators/test_subprocess.py
@@ -1722,7 +1722,6 @@ class TestPopenActivitySubprocessXComBackend:
"ref://task_1/None/summary",
id="default-backend",
),
- pytest.param(_RefXCom, (404, {"detail": "not found"}), None,
id="missing"),
],
)
def test_get_xcom_loads_the_value_through_the_backend(self, make_proc,
xcom, response, expected):
@@ -1735,6 +1734,45 @@ class TestPopenActivitySubprocessXComBackend:
assert _sent_body(proc).get("value") == expected
+ def test_get_xcom_missing_reads_the_slice_and_sends_none(self, make_proc):
+ """With no map index, a missing value is looked for in the slice too,
as a mapped task's values."""
+ api = _FakeApi(
+ {("GET", _XCOM_PATH): (404, {"detail": "not found"}), ("GET",
f"{_XCOM_PATH}/slice"): (200, [])}
+ )
+ proc = make_proc(_RefXCom, api)
+ proc._handle_request(
+ GetXCom(key="summary", dag_id="tutorial_dag", run_id="run_1",
task_id="task_1"), log, 1
+ )
+ assert [(method, path) for method, path, _ in api.requests] == [
+ ("GET", _XCOM_PATH),
+ ("GET", f"{_XCOM_PATH}/slice"),
+ ]
+ assert _sent_body(proc).get("value") is None
+
+ @pytest.mark.parametrize(
+ ("xcom", "expected"),
+ [
+ pytest.param(_RefXCom, [serialize((12, 3402.0)), 5], id="loaded"),
+ pytest.param(BaseXCom, ["ref://task_1/None/summary", 5],
id="default-backend"),
+ ],
+ )
+ def
test_get_xcom_of_a_mapped_task_loads_each_value_through_the_backend(self,
make_proc, xcom, expected):
+ _RefXCom.stored["ref://task_1/None/summary"] = (12, 3402.0)
+ api = _FakeApi(
+ {
+ ("GET", _XCOM_PATH): (404, {"detail": "not found"}),
+ ("GET", f"{_XCOM_PATH}/slice"): (200,
["ref://task_1/None/summary", 5]),
+ }
+ )
+ proc = make_proc(xcom, api)
+
+ proc._handle_request(
+ GetXCom(key="summary", dag_id="tutorial_dag", run_id="run_1",
task_id="task_1"), log, 1
+ )
+
+ # The lang SDK gets the values as one XCom.
+ assert _sent_body(proc) == {"key": "summary", "value": expected,
"type": "XComResult"}
+
@pytest.mark.parametrize(
("item", "expected"),
[
diff --git a/task-sdk/tests/task_sdk/definitions/test_xcom_arg.py
b/task-sdk/tests/task_sdk/definitions/test_xcom_arg.py
index 9438810c309..06a03107881 100644
--- a/task-sdk/tests/task_sdk/definitions/test_xcom_arg.py
+++ b/task-sdk/tests/task_sdk/definitions/test_xcom_arg.py
@@ -482,6 +482,22 @@ class TestPlainXComArgResolveMappedGroup:
assert ti.xcom_pull.call_args.kwargs["map_indexes"] == 0
+class TestPlainXComArgResolveUnmapped:
+ """An unmapped upstream is pulled at map index -1, sparing the server a
lookup of how it is defined."""
+
+ def test_resolve_outside_a_mapped_task_group_pulls_minus_one(self):
+ operator = mock.MagicMock()
+ operator.is_mapped = False
+ operator.task_id = "upstream"
+ operator.dag_id = "test_dag"
+ operator.get_closest_mapped_task_group.return_value = None
+ ti = mock.MagicMock()
+ ti.xcom_pull.return_value = "value"
+
+ assert PlainXComArg(operator=operator, key="test").resolve({"ti": ti})
== "value"
+ assert ti.xcom_pull.call_args.kwargs["map_indexes"] == -1
+
+
class TestPlainXComArgResolveLoopTask:
@pytest.fixture
def dag(self):
diff --git a/ts-sdk/example/src/main.ts b/ts-sdk/example/src/main.ts
index d3c52b141e4..02af79dadaa 100644
--- a/ts-sdk/example/src/main.ts
+++ b/ts-sdk/example/src/main.ts
@@ -32,10 +32,7 @@ import { buildSummaryMessage, report, summarize } from
"./taskflow.js";
export async function buildMessage() {
const client = getClient();
- const upstream = await client.getXCom<string>({
- key: "return_value",
- taskId: "python_start",
- });
+ const upstream = await client.getXCom<string>({ taskId: "python_start" });
const greeting = await client.getVariable("typescript_example_greeting");
const message = `${greeting ?? "hello from TypeScript"}; upstream=${upstream
?? "missing"}`;
diff --git a/ts-sdk/example/src/taskflow.ts b/ts-sdk/example/src/taskflow.ts
index 464b98521a8..7b435ddf042 100644
--- a/ts-sdk/example/src/taskflow.ts
+++ b/ts-sdk/example/src/taskflow.ts
@@ -119,10 +119,7 @@ export const report = withArgNames(
export async function buildSummaryMessage() {
// Nothing was passed to this task, so its upstream's output is read
explicitly.
const ctx = getContext();
- const summary = await getClient().getXCom<Summary>({
- key: "return_value",
- taskId: "summarize",
- });
+ const summary = await getClient().getXCom<Summary>({ taskId: "summarize" });
if (summary === null) {
throw new Error(`task ${ctx.taskId} has no summary to report`);
}
diff --git a/ts-sdk/src/coordinator/arg-binding.ts
b/ts-sdk/src/coordinator/arg-binding.ts
index 7c208fc98eb..044c9f05282 100644
--- a/ts-sdk/src/coordinator/arg-binding.ts
+++ b/ts-sdk/src/coordinator/arg-binding.ts
@@ -28,7 +28,7 @@
// Names bind by folding on both sides, so nothing has to be declared for a
// Python `region_code` to reach a handler's `regionCode`.
-import type { CoordinatorClient } from "./client.js";
+import { XCOM_RETURN_KEY, type CoordinatorClient } from "./client.js";
import type { LogChannel } from "./log-channel.js";
import type {
ArgBindings,
@@ -38,9 +38,6 @@ import type {
} from "../generated/supervisor.js";
import type { JsonValue } from "../sdk/client-types.js";
-/** The key an upstream task's return value is stored under, as Python `@task`
does. */
-const RETURN_VALUE_KEY = "return_value";
-
/** What Airflow stamps on an argument the Dag declared as a Python `int`. */
const INT64_FORMAT = "int64";
@@ -158,11 +155,11 @@ function checkBindable(binding: TaskArgBinding): void {
/** Pull the upstream task's output this argument was called with. */
async function pullXComArg(binding: XComArgBinding, client:
CoordinatorClient): Promise<JsonValue> {
- const entry = await client.getXComEntry({ key: RETURN_VALUE_KEY, taskId:
binding.task_id });
+ const entry = await client.getXComEntry({ key: XCOM_RETURN_KEY, taskId:
binding.task_id });
if (!entry.found) {
throw new Error(
`Task argument "${binding.name}" takes the output of upstream task
"${binding.task_id}", ` +
- `which pushed no ${RETURN_VALUE_KEY} XCom; a task that returns nothing
pushes none`,
+ `which pushed no ${XCOM_RETURN_KEY} XCom; a task that returns nothing
pushes none`,
);
}
checkExactInteger(binding.name, entry.value, binding.value_schema);
diff --git a/ts-sdk/src/coordinator/client.ts b/ts-sdk/src/coordinator/client.ts
index e16aa21531a..8bd96aea454 100644
--- a/ts-sdk/src/coordinator/client.ts
+++ b/ts-sdk/src/coordinator/client.ts
@@ -58,12 +58,16 @@ import type {
*/
type AbsentRowPolicy = "throw" | { codes: readonly string[]; apiServer404:
boolean };
-type XComTargetOpts = Pick<GetXComOpts, "key" | "dagId" | "runId" | "taskId" |
"mapIndex">;
+/** The key a task's return value is stored under, as Python `@task` does. */
+export const XCOM_RETURN_KEY = "return_value";
+
+type XComTargetOpts = Pick<SetXComOpts, "key" | "dagId" | "runId" | "taskId" |
"mapIndex">;
function resolveXComTarget(opts: XComTargetOpts, ctx: TaskContext) {
// The supervisor never replies to a frame with a wrongly typed field, so the
// task would hang instead of failing fast.
- assertKey(opts.key, "XCom key");
+ const key = opts.key ?? XCOM_RETURN_KEY;
+ assertKey(key, "XCom key");
for (const [label, id] of [
["dagId", opts.dagId],
["taskId", opts.taskId],
@@ -72,20 +76,11 @@ function resolveXComTarget(opts: XComTargetOpts, ctx:
TaskContext) {
if (id != null) assertKey(id, `XCom ${label}`);
}
assertMapIndex(opts.mapIndex);
- const dag_id = opts.dagId ?? ctx.dagId;
- const task_id = opts.taskId ?? ctx.taskId;
- const run_id = opts.runId ?? ctx.runId;
- // A map index only names a row of the task that owns it, so another task or
- // run does not inherit it. `mapIndex` is nullable: an explicit null stays
null.
- const targetsSelf = dag_id === ctx.dagId && task_id === ctx.taskId && run_id
=== ctx.runId;
- const mapIndex =
- opts.mapIndex === undefined ? (targetsSelf ? ctx.mapIndex : null) :
opts.mapIndex;
return {
- key: opts.key,
- dag_id,
- task_id,
- run_id,
- map_index: mapIndex === null || mapIndex < 0 ? null : mapIndex,
+ key,
+ dag_id: opts.dagId ?? ctx.dagId,
+ task_id: opts.taskId ?? ctx.taskId,
+ run_id: opts.runId ?? ctx.runId,
};
}
@@ -373,9 +368,12 @@ export function createCoordinatorClient(
// ---- XCom ----
async getXComEntry(opts: GetXComOpts): Promise<XComEntry> {
+ assertKey(opts.taskId, "XCom taskId"); // Required: getXCom has no
default task.
const msg: GetXCom = {
type: "GetXCom",
...resolveXComTarget(opts, ctx),
+ // A null map index is resolved by the server by how the task is
defined.
+ map_index: opts.mapIndex ?? null,
include_prior_dates: opts.includePriorDates ?? false,
};
const entry = await rpc<XComEntry>(
@@ -400,10 +398,18 @@ export function createCoordinatorClient(
},
async setXCom(opts: SetXComOpts): Promise<void> {
+ const target = resolveXComTarget(opts, ctx);
+ // A map index only names a row of the task that owns it, so another
task or
+ // run does not inherit it. `mapIndex` is nullable: an explicit null
stays null.
+ const targetsSelf =
+ target.dag_id === ctx.dagId && target.task_id === ctx.taskId &&
target.run_id === ctx.runId;
+ const mapIndex =
+ opts.mapIndex === undefined ? (targetsSelf ? ctx.mapIndex : null) :
opts.mapIndex;
const msg: SetXCom = {
type: "SetXCom",
- ...resolveXComTarget(opts, ctx),
+ ...target,
value: opts.value,
+ map_index: mapIndex === null || mapIndex < 0 ? null : mapIndex,
};
await rpc("SetXCom", null, msg, () => undefined, "throw");
},
diff --git a/ts-sdk/src/coordinator/operator-runner.ts
b/ts-sdk/src/coordinator/operator-runner.ts
index bcb0cd47836..303ab3c3694 100644
--- a/ts-sdk/src/coordinator/operator-runner.ts
+++ b/ts-sdk/src/coordinator/operator-runner.ts
@@ -20,7 +20,7 @@
// Runs an operator the SDK executes itself: starts it, or resumes it after it
parked or deferred.
import { resolveArgs } from "./arg-binding.js";
-import type { CoordinatorClient } from "./client.js";
+import { XCOM_RETURN_KEY, type CoordinatorClient } from "./client.js";
import type { LogChannel } from "./log-channel.js";
import type {
RuntimeAwaitInputTask,
@@ -93,7 +93,7 @@ export function buildOperatorContext(deps:
OperatorContextDeps): OperatorContext
return bound.args;
},
async succeed(value?: JsonValue): Promise<RuntimeSucceedTask> {
- if (value !== undefined) await client.setXCom({ key: "return_value",
value });
+ if (value !== undefined) await client.setXCom({ key: XCOM_RETURN_KEY,
value });
// The Execution API's TISuccessStatePayload validator rejects null for
// `task_outlets` and `outlet_events`, so both are empty lists.
return {
diff --git a/ts-sdk/src/coordinator/runtime.ts
b/ts-sdk/src/coordinator/runtime.ts
index 62ad38c7394..742cd02ea02 100644
--- a/ts-sdk/src/coordinator/runtime.ts
+++ b/ts-sdk/src/coordinator/runtime.ts
@@ -37,7 +37,7 @@
// - StartupDetails → run task, respond Succeed or Fail, exit
//
import { resolveArgs, type BoundArgs } from "./arg-binding.js";
-import { createCoordinatorClient, type CoordinatorClient } from "./client.js";
+import { createCoordinatorClient, XCOM_RETURN_KEY, type CoordinatorClient }
from "./client.js";
import { CommChannel } from "./comm-channel.js";
import { LogChannel } from "./log-channel.js";
import {
@@ -425,7 +425,7 @@ async function runHandler(
// `getClient()` work at any depth without the handler being handed either.
const result = await runInTaskScope({ ctx, client }, () =>
handler(bound.args as never));
if (result !== undefined) {
- await client.setXCom({ key: "return_value", value: result as JsonValue
});
+ await client.setXCom({ key: XCOM_RETURN_KEY, value: result as JsonValue
});
}
// SucceedTask MUST include task_outlets and outlet_events as
// empty lists, since the Execution API's TISuccessStatePayload
diff --git a/ts-sdk/src/sdk/client-types.ts b/ts-sdk/src/sdk/client-types.ts
index 3fa3ad04913..d9e44f18dc6 100644
--- a/ts-sdk/src/sdk/client-types.ts
+++ b/ts-sdk/src/sdk/client-types.ts
@@ -24,18 +24,33 @@ export type JsonValue =
/**
* Options for pulling an XCom value.
*
- * `dagId`, `taskId`, and `runId` default to the running task's context when
- * omitted or `null`. Pass them only when pulling an XCom value from another
task or run.
- *
- * `mapIndex` defaults to the running task's own map index when the target is
- * the running task, and to the unmapped value for any other task or run. Pass
- * a number to pick one mapped instance, or `null` for the unmapped one.
+ * `dagId` and `runId` default to the running task's context when omitted or
+ * `null`. Pass them only when pulling an XCom value from another Dag or run.
*/
export interface GetXComOpts {
- key: string;
+ /** XCom key to read; defaults to `"return_value"`. */
+ key?: string;
dagId?: string | null;
runId?: string | null;
- taskId?: string | null;
+ /** Task that pushed the XCom value. */
+ taskId: string;
+ /**
+ * Map index of the task instance to read, or `null` (the default) to read
+ * the task's result.
+ *
+ * With `null`, what is read depends on whether the task is mapped, as its
+ * definition in the Dag says, not on how many instances it ran:
+ *
+ * - For a task that is not mapped, its value.
+ * - For a mapped task, the values of all its instances as an array ordered
+ * by map index. Instances that pushed nothing are left out. If none
+ * pushed a value, including when the task expanded to no instances, the
+ * result is an empty array, or `null` on Airflow 3.4.
+ *
+ * A map index reads that one instance's value. One that selects no task
+ * instance of the task, such as any map index of a task that is not
+ * mapped, reads `null`.
+ */
mapIndex?: number | null;
includePriorDates?: boolean;
}
@@ -51,7 +66,8 @@ export interface GetXComOpts {
* a number to pick one mapped instance, or `null` for the unmapped one.
*/
export interface SetXComOpts {
- key: string;
+ /** XCom key to write; defaults to `"return_value"`. */
+ key?: string;
value: JsonValue;
dagId?: string | null;
runId?: string | null;
diff --git a/ts-sdk/src/sdk/client.ts b/ts-sdk/src/sdk/client.ts
index 31c1f18da2d..2cebd8d75bd 100644
--- a/ts-sdk/src/sdk/client.ts
+++ b/ts-sdk/src/sdk/client.ts
@@ -72,20 +72,21 @@ export interface TaskClient {
deleteVariable(key: string): Promise<void>;
/**
- * Pull an XCom value.
+ * Pull an XCom value pushed by a task.
*
- * Returns `null` when the row is missing. Locator fields default to the
- * current task's context; see {@link GetXComOpts} for how `mapIndex`
defaults.
+ * Returns `null` when nothing was pushed. `key` defaults to
`"return_value"`,
+ * and `dagId` and `runId` to the current task's context. See
+ * {@link GetXComOpts.mapIndex} for what the map index selects.
*
* The generic `T` lets callers narrow the return type when the shape is
* known:
*
* ```ts
- * const data = await client.getXCom<{ count: number }>({ key: "result" });
+ * const data = await client.getXCom<{ count: number }>({ key: "result",
taskId: "extract" });
* // data is { count: number } | null
* ```
*
- * @throws `TypeError` when `key` is not a string, `dagId`, `taskId` or
`runId` is set to a non-string, or `mapIndex` is not a number or `null`.
+ * @throws `TypeError` when `taskId` is not a string, `key`, `dagId` or
`runId` is set to a non-string, or `mapIndex` is not a number or `null`.
* @throws `RangeError` when `key`, `dagId`, `taskId` or `runId` is an empty
string, or `mapIndex` is not an integer.
*/
getXCom<T = unknown>(opts: GetXComOpts): Promise<T | null>;
@@ -96,7 +97,7 @@ export interface TaskClient {
* Target fields default to the current task's context; see
* {@link SetXComOpts} for how `mapIndex` defaults.
*
- * @throws `TypeError` when `key` is not a string, `dagId`, `taskId` or
`runId` is set to a non-string, or `mapIndex` is not a number or `null`.
+ * @throws `TypeError` when `key`, `dagId`, `taskId` or `runId` is set to a
non-string, or `mapIndex` is not a number or `null`.
* @throws `RangeError` when `key`, `dagId`, `taskId` or `runId` is an empty
string, or `mapIndex` is not an integer.
*/
setXCom(opts: SetXComOpts): Promise<void>;
diff --git a/ts-sdk/src/sdk/task.ts b/ts-sdk/src/sdk/task.ts
index 393e1e18d71..89757534358 100644
--- a/ts-sdk/src/sdk/task.ts
+++ b/ts-sdk/src/sdk/task.ts
@@ -123,7 +123,7 @@ export function getContext<TConf = TaskContext["conf"]>():
TaskContext<TConf> {
* ```ts
* async function transform() {
* const client = getClient();
- * return await client.getXCom<number>({ key: "return_value", taskId:
"extract" });
+ * return await client.getXCom<number>({ taskId: "extract" });
* }
* ```
*
diff --git a/ts-sdk/tests/coordinator/client.test.ts
b/ts-sdk/tests/coordinator/client.test.ts
index 8c618539731..9a89ae4af20 100644
--- a/ts-sdk/tests/coordinator/client.test.ts
+++ b/ts-sdk/tests/coordinator/client.test.ts
@@ -23,7 +23,7 @@ import { NEVER_EXPIRE } from "../../src/sdk/client-types.js";
import { createCoordinatorClient } from "../../src/coordinator/client.js";
import type { CommChannel } from "../../src/coordinator/comm-channel.js";
import type { TaskClient } from "../../src/sdk/client.js";
-import type { GetXComOpts } from "../../src/sdk/client-types.js";
+import type { GetXComOpts, SetXComOpts } from "../../src/sdk/client-types.js";
import type { TaskContext } from "../../src/sdk/task.js";
const RETENTION_ENV_VAR = "AIRFLOW__STATE_STORE__DEFAULT_RETENTION_DAYS";
@@ -53,14 +53,15 @@ function client(frames: { body: unknown; error?: unknown
}[]) {
const MAPPED_CTX: TaskContext = { ...FAKE_CTX, mapIndex: 3 };
-type XComOpts = Pick<GetXComOpts, "key" | "dagId" | "runId" | "taskId" |
"mapIndex">;
+type XComOpts = Pick<SetXComOpts, "key" | "dagId" | "runId" | "taskId" |
"mapIndex">;
/** Each XCom call that takes a target, with the reply the supervisor gives
it. */
const XCOM_CALLS = [
[
"getXCom",
{ type: "XComResult", key: "k", value: null },
- (c: TaskClient, o: XComOpts) => c.getXCom(o),
+ // getXCom requires a taskId; a case may still override it.
+ (c: TaskClient, o: XComOpts) => c.getXCom({ taskId: "up", ...o } as
GetXComOpts),
],
["setXCom", null, (c: TaskClient, o: XComOpts) => c.setXCom({ ...o, value: 1
})],
] as const;
@@ -206,7 +207,61 @@ describe("writes do not read a supervisor 404 as absence",
() => {
describe("getXCom not-found contract", () => {
it("returns null for the exact XCOM_NOT_FOUND code", async () => {
const c = client([{ body: { type: "ErrorResponse", error: "XCOM_NOT_FOUND"
} }]);
- expect(await c.getXCom({ key: "k" })).toBeNull();
+ expect(await c.getXCom({ key: "k", taskId: "up" })).toBeNull();
+ });
+});
+
+describe("XCom key", () => {
+ it("defaults to return_value for getXCom and setXCom", async () => {
+ const { client: c, sent } = recordingClient({
+ type: "XComResult",
+ key: "return_value",
+ value: 1,
+ });
+
+ await c.getXCom({ taskId: "up" });
+ await c.setXCom({ value: 1 });
+
+ expect(sent.map((m) => [m.type, m.key])).toEqual([
+ ["GetXCom", "return_value"],
+ ["SetXCom", "return_value"],
+ ]);
+ });
+});
+
+describe("getXCom map index", () => {
+ it("defaults to null, even for the running task's own XCom", async () => {
+ const { client: c, sent } = recordingClient(
+ { type: "XComResult", key: "k", value: null },
+ MAPPED_CTX,
+ );
+
+ await c.getXCom({ key: "k", taskId: "t" });
+
+ expect(sent[0]).toMatchObject({ task_id: "t", map_index: null });
+ });
+
+ it("rejects a missing taskId without sending a request", async () => {
+ const { client: c, sent } = recordingClient({ type: "XComResult", key:
"k", value: null });
+
+ await expect(c.getXCom({ key: "k" } as
GetXComOpts)).rejects.toThrow(TypeError);
+
+ expect(sent).toHaveLength(0);
+ });
+
+ it("sends a map index as given", async () => {
+ const { client: c, sent } = recordingClient({ type: "XComResult", key:
"k", value: null });
+
+ await c.getXCom({ key: "k", taskId: "up", mapIndex: -1 });
+ await c.getXCom({ key: "k", taskId: "up", mapIndex: 2 });
+
+ expect(sent.map((m) => m.map_index)).toEqual([-1, 2]);
+ });
+
+ it("returns a mapped task's result as an array", async () => {
+ const c = client([{ body: { type: "XComResult", key: "k", value: [1, 2] }
}]);
+
+ expect(await c.getXCom({ key: "k", taskId: "up" })).toEqual([1, 2]);
});
});
@@ -217,23 +272,26 @@ describe("getXComEntry", () => {
// fails the task, while one that pushed null binds null.
it("reports an absent row as not found", async () => {
const c = client([{ body: { type: "ErrorResponse", error: "XCOM_NOT_FOUND"
} }]);
- expect(await c.getXComEntry({ key: "k" })).toEqual({ found: false, value:
null });
+ expect(await c.getXComEntry({ key: "k", taskId: "up" })).toEqual({ found:
false, value: null });
});
it("reports a stored null as found", async () => {
const c = client([{ body: { type: "XComResult", key: "k", value: null }
}]);
- expect(await c.getXComEntry({ key: "k" })).toEqual({ found: true, value:
null });
+ expect(await c.getXComEntry({ key: "k", taskId: "up" })).toEqual({ found:
true, value: null });
});
it("reports a stored value as found", async () => {
const c = client([{ body: { type: "XComResult", key: "k", value: { orders:
12 } } }]);
- expect(await c.getXComEntry({ key: "k" })).toEqual({ found: true, value: {
orders: 12 } });
+ expect(await c.getXComEntry({ key: "k", taskId: "up" })).toEqual({
+ found: true,
+ value: { orders: 12 },
+ });
});
it("is what getXCom reads, so both see one round-trip", async () => {
const c = client([{ body: { type: "XComResult", key: "k", value: false }
}]);
// `false` also pins that getXCom's `?? null` does not flatten a falsy
value.
- expect(await c.getXCom({ key: "k" })).toBe(false);
+ expect(await c.getXCom({ key: "k", taskId: "up" })).toBe(false);
});
});
@@ -273,7 +331,7 @@ describe("client is bound to TaskContext", () => {
});
});
- it("defaults getXCom locator fields from ctx with snake_case wire names",
async () => {
+ it("defaults getXCom dag and run from ctx with snake_case wire names", async
() => {
const sent: Record<string, unknown>[] = [];
const recordingComm = {
request: async (b: Record<string, unknown>) => {
@@ -281,15 +339,17 @@ describe("client is bound to TaskContext", () => {
return { body: { type: "XComResult", key: b.key, value: null } };
},
} as unknown as CommChannel;
- const c = createCoordinatorClient(recordingComm, FAKE_CTX, FAKE_TI_ID);
+ // A mapped ctx, to prove getXCom does not default to the running task's
map index.
+ const mappedCtx: TaskContext = { ...FAKE_CTX, mapIndex: 3 };
+ const c = createCoordinatorClient(recordingComm, mappedCtx, FAKE_TI_ID);
- await c.getXCom({ key: "k" });
+ await c.getXCom({ key: "k", taskId: "up" });
expect(sent[0]).toEqual({
type: "GetXCom",
key: "k",
dag_id: "d",
- task_id: "t",
+ task_id: "up",
run_id: "r",
map_index: null,
include_prior_dates: false,
@@ -319,7 +379,7 @@ describe("client is bound to TaskContext", () => {
dagId: "other_dag",
taskId: "upstream",
runId: "manual__1",
- mapIndex: -1,
+ mapIndex: 2,
includePriorDates: true,
});
await c.setXCom({ key: "k", value: 3, mapIndex: 5 });
@@ -331,43 +391,40 @@ describe("client is bound to TaskContext", () => {
dag_id: "other_dag",
task_id: "upstream",
run_id: "manual__1",
- map_index: null,
+ map_index: 2,
include_prior_dates: true,
});
expect(sent[3]).toMatchObject({ type: "SetXCom", map_index: 5 });
});
});
-describe("XCom map index default", () => {
- describe.each(XCOM_CALLS)("%s", (_name, reply, call) => {
- it.each([
- ["the running task", {}, 3],
- ["the running task named explicitly", { dagId: "d", taskId: "t", runId:
"r" }, 3],
- ["another task", { taskId: "extract" }, null],
- ["another Dag", { dagId: "other_dag" }, null],
- ["another run", { runId: "manual__1" }, null],
- ["another task with an explicit mapIndex", { taskId: "extract",
mapIndex: 2 }, 2],
- ["another task with mapIndex 0", { taskId: "extract", mapIndex: 0 }, 0],
- ["the running task with mapIndex null", { mapIndex: null }, null],
- ["the running task with null target ids", { dagId: null, taskId: null,
runId: null }, 3],
- ] as [string, Omit<XComOpts, "key">, number | null][])(
- "from a mapped task targeting %s sends map_index %s",
- async (_label, target, expected) => {
- const { client: c, sent } = recordingClient(reply, MAPPED_CTX);
-
- await call(c, { key: "k", ...target });
-
- expect(sent[0]).toMatchObject({ map_index: expected });
- },
- );
- });
+describe("setXCom map index default", () => {
+ it.each([
+ ["the running task", {}, 3],
+ ["the running task named explicitly", { dagId: "d", taskId: "t", runId:
"r" }, 3],
+ ["another task", { taskId: "extract" }, null],
+ ["another Dag", { dagId: "other_dag" }, null],
+ ["another run", { runId: "manual__1" }, null],
+ ["another task with an explicit mapIndex", { taskId: "extract", mapIndex:
2 }, 2],
+ ["another task with mapIndex 0", { taskId: "extract", mapIndex: 0 }, 0],
+ ["the running task with mapIndex null", { mapIndex: null }, null],
+ ["the running task with null target ids", { dagId: null, taskId: null,
runId: null }, 3],
+ ] as [string, Omit<XComOpts, "key">, number | null][])(
+ "from a mapped task targeting %s sends map_index %s",
+ async (_label, target, expected) => {
+ const { client: c, sent } = recordingClient(null, MAPPED_CTX);
+
+ await c.setXCom({ key: "k", value: 1, ...target });
+
+ expect(sent[0]).toMatchObject({ map_index: expected });
+ },
+ );
});
describe("XCom key and map index guards", () => {
describe.each(XCOM_CALLS)("%s", (_name, reply, call) => {
it.each([
["an empty key", { key: "" }, RangeError],
- ["an undefined key", { key: undefined }, TypeError],
["a numeric key", { key: 1 }, TypeError],
["a fractional mapIndex", { key: "k", mapIndex: 1.5 }, RangeError],
["a NaN mapIndex", { key: "k", mapIndex: Number.NaN }, RangeError],
diff --git a/ts-sdk/tests/public-api.test.ts b/ts-sdk/tests/public-api.test.ts
index ec24a41467b..490cb3982a0 100644
--- a/ts-sdk/tests/public-api.test.ts
+++ b/ts-sdk/tests/public-api.test.ts
@@ -413,15 +413,15 @@ describe("public API", () => {
readonly signal: AbortSignal;
}>();
expectTypeOf<GetXComOpts>().toEqualTypeOf<{
- key: string;
+ key?: string;
dagId?: string | null;
runId?: string | null;
- taskId?: string | null;
+ taskId: string;
mapIndex?: number | null;
includePriorDates?: boolean;
}>();
expectTypeOf<SetXComOpts>().toEqualTypeOf<{
- key: string;
+ key?: string;
value: SetXComOpts["value"];
dagId?: string | null;
runId?: string | null;