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 00954198c2b Resolve an omitted XCom map index by the task's definition
(#76826)
00954198c2b is described below
commit 00954198c2b35ca49c95d80361ab50540de450a5
Author: Tzu-ping Chung <[email protected]>
AuthorDate: Wed Nov 25 13:40:46 2026 +0800
Resolve an omitted XCom map index by the task's definition (#76826)
* Resolve omitted XCom map index by task defn
* Share one resolver and the caller's Dag version in XCom reads
* Share the XCom slice read with Get XCom
* Minor refactoring and test amend
* Use main-only test helpers for XCom reads
* Read -1 for omitted map index w/ prior dates
* Redirect a mapped task's XCom read to slice
Get XCom now only returns one stored value. An omitted map index on a
mapped task redirects to the slice endpoint, which the client follows,
so custom XCom backends load each value. A Python task pulling a mapped
task of its own run reads the slice directly.
* Load the Dag only for a task with regions
* Redirect to the XCom slice by a relative URL
* Skip the XCom slice fallback on new servers
* Keep unrelated XCom code as on main
* Follow only the XCom slice redirect
* Minimize diff
---
.../api_fastapi/execution_api/datamodels/xcom.py | 14 +-
.../api_fastapi/execution_api/routes/xcoms.py | 138 ++++++++++---
.../api_fastapi/execution_api/versions/__init__.py | 2 +
.../execution_api/versions/v2027_02_28.py | 18 ++
.../execution_api/test_task_sdk_client_contract.py | 8 +
.../execution_api/versions/head/test_xcoms.py | 217 ++++++++++++++++++---
.../versions/v2027_02_28/test_xcoms.py | 52 +++++
.../tests/unit/models/test_task_coordinates.py | 4 +-
go-sdk/sdk/sdk.go | 2 +-
.../main/kotlin/org/apache/airflow/sdk/Client.kt | 2 +-
kubernetes-tests/lang_sdk/go_example/main.go | 24 +--
task-sdk/src/airflow/sdk/api/client.py | 45 ++++-
task-sdk/src/airflow/sdk/bases/xcom.py | 10 +-
.../src/airflow/sdk/execution_time/task_runner.py | 58 ++++--
task-sdk/tests/task_sdk/api/test_client.py | 65 +++++-
.../tests/task_sdk/coordinators/test_subprocess.py | 15 +-
.../task_sdk/execution_time/test_task_runner.py | 56 ++++++
ts-sdk/src/sdk/client-types.ts | 2 +-
18 files changed, 611 insertions(+), 121 deletions(-)
diff --git
a/airflow-core/src/airflow/api_fastapi/execution_api/datamodels/xcom.py
b/airflow-core/src/airflow/api_fastapi/execution_api/datamodels/xcom.py
index f04bc97ebb1..0632f77686b 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/datamodels/xcom.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/datamodels/xcom.py
@@ -41,9 +41,19 @@ class GetXComSliceFilterParams(BaseModel):
class GetXcomFilterParams(BaseModel):
- """Class to house the params that can optionally be set for Get XCom."""
+ """
+ Optional query params of Get XCom, selecting which value to read.
- map_index: int = -1
+ ``map_index`` reads one task instance, and ``offset`` one value of a mapped
+ task by position. Without them, the read returns the task's result: an
+ unmapped task's value, or a mapped task's values as a list, as the slice
+ endpoint returns them.
+
+ With ``include_prior_dates``, an omitted ``map_index`` reads -1 instead,
+ since the slice mixes earlier runs' values.
+ """
+
+ map_index: int | None = None
include_prior_dates: bool = False
offset: int | None = None
previous_iteration: bool = False
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 77c3f09a49f..4de6bf9b3a6 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
@@ -21,11 +21,14 @@ import logging
from contextlib import suppress
from functools import partial
from typing import TYPE_CHECKING, Annotated
+from urllib.parse import quote
from uuid import UUID
import attrs
from cadwyn import current_dependency_solver
from fastapi import APIRouter, Body, Depends, HTTPException, Path, Query,
Request, Response, status
+from fastapi.datastructures import URL
+from fastapi.responses import RedirectResponse
from pydantic import JsonValue
from sqlalchemy import select
from sqlalchemy.sql.selectable import Select
@@ -52,6 +55,7 @@ from airflow.api_fastapi.execution_api.security import (
require_task_token,
)
from airflow.api_fastapi.execution_api.versions.v2026_10_30 import
IdentifyArchivedTaskStateUpdates
+from airflow.api_fastapi.execution_api.versions.v2027_02_28 import
ResolveOmittedXComMapIndexByTaskDefinition
from airflow.exceptions import TaskNotFound
from airflow.models.dagrun import DagRun
from airflow.models.dynamic_region import (
@@ -148,6 +152,10 @@ def has_xcom_access(
)
+def _get_resolver(dag_bag: DagBagDep, session: SessionDep) ->
TaskCoordinateResolver:
+ return TaskCoordinateResolver(dag_bag, session)
+
+
router = APIRouter(
route_class=ExecutionAPIRoute,
responses={
@@ -160,6 +168,15 @@ router = APIRouter(
log = logging.getLogger(__name__)
+_ResolverDep = Annotated[TaskCoordinateResolver, Depends(_get_resolver)]
+
+
+def _get_calling_ti(token: ExecutionToken, *, session: Session) ->
TaskInstance | None:
+ """Return the requesting task instance, or None for any other caller."""
+ if token.claims.scope != "execution":
+ return None
+ return session.get(TaskInstance, token.id)
+
@attrs.frozen
class _XComRead:
@@ -184,13 +201,13 @@ def _build_xcom_read(
run_id: str,
task_id: str,
key: str,
- session: Session,
- dag_bag: DBDagBag,
+ resolver: TaskCoordinateResolver,
token: ExecutionToken,
map_index: int | None = None,
include_prior_dates: bool = False,
previous_iteration: bool = False,
sequence: bool = False,
+ session: Session,
) -> _XComRead:
"""
Select the XCom rows of the producers visible to the calling task instance.
@@ -198,7 +215,6 @@ def _build_xcom_read(
A ``sequence`` read returns several values in order. When it targets a
loop task from outside that
loop, it covers every iteration of the task rather than the one a caller
inside the loop would see.
"""
- resolver = TaskCoordinateResolver(dag_bag, session)
read = partial(
XComModel.get_many,
dag_ids=dag_id,
@@ -214,7 +230,7 @@ def _build_xcom_read(
dag_id, None if include_prior_dates else run_id, task_id
):
return _XComRead(read(region_id=SENTINEL_REGION_ID,
map_indexes=map_index))
- caller = session.get(TaskInstance, token.id) if token.claims.scope ==
"execution" else None
+ caller = _get_calling_ti(token, session=session)
if include_prior_dates:
task = None
if session.scalar(select(DagRun.id).where(DagRun.dag_id == dag_id,
DagRun.run_id == run_id)):
@@ -357,7 +373,7 @@ def get_mapped_xcom_by_index(
key: Annotated[str, Path(min_length=1)],
offset: int,
session: SessionDep,
- dag_bag: DagBagDep,
+ resolver: _ResolverDep,
previous_iteration: bool = False,
token: ExecutionToken = _TriggerAwareToken,
) -> XComSequenceIndexResponse:
@@ -367,7 +383,7 @@ def get_mapped_xcom_by_index(
task_id=task_id,
key=key,
session=session,
- dag_bag=dag_bag,
+ resolver=resolver,
token=token,
previous_iteration=previous_iteration,
sequence=True,
@@ -416,7 +432,7 @@ def get_mapped_xcom_by_slice(
key: Annotated[str, Path(min_length=1)],
params: Annotated[GetXComSliceFilterParams, Query()],
session: SessionDep,
- dag_bag: DagBagDep,
+ resolver: _ResolverDep,
token: ExecutionToken = _TriggerAwareToken,
) -> XComSequenceSliceResponse:
xcom_read = _build_xcom_read(
@@ -425,7 +441,7 @@ def get_mapped_xcom_by_slice(
task_id=task_id,
key=key,
session=session,
- dag_bag=dag_bag,
+ resolver=resolver,
token=token,
include_prior_dates=params.include_prior_dates,
previous_iteration=params.previous_iteration,
@@ -525,7 +541,7 @@ def head_xcom(
key: str,
response: Response,
session: SessionDep,
- dag_bag: DagBagDep,
+ resolver: _ResolverDep,
map_index: Annotated[int | None, Query()] = None,
previous_iteration: bool = False,
token: ExecutionToken = _TriggerAwareToken,
@@ -543,7 +559,7 @@ def head_xcom(
task_id=task_id,
key=key,
session=session,
- dag_bag=dag_bag,
+ resolver=resolver,
token=token,
previous_iteration=previous_iteration,
sequence=True,
@@ -554,28 +570,92 @@ def head_xcom(
response.headers["Content-Range"] = f"map_indexes {count}"
+def _resolve_omitted_map_index(
+ *,
+ dag_id: str,
+ run_id: str,
+ task_id: str,
+ params: GetXcomFilterParams,
+ resolver: TaskCoordinateResolver,
+ caller: TaskInstance | None,
+) -> int | None:
+ """
+ Return the map index to read for an omitted one, or None for every
instance.
+
+ A mapped operator, or a task in a mapped task group, reads every instance,
+ however many it expanded to. The task is looked up in the Dag version its
+ run uses, or the caller's own if the caller is in the same run, as reads of
+ a given map index do.
+
+ Everything else reads -1: an unmapped task, one that cannot be found, a
read
+ with ``offset`` or ``include_prior_dates``, and older API versions. A task
+ with no regional instances in the run is never mapped, so the Dag is only
+ loaded for a task that has some.
+ """
+ if params.offset is not None or params.include_prior_dates:
+ return -1
+ if not ResolveOmittedXComMapIndexByTaskDefinition.is_applied:
+ return -1
+ if not resolver.has_regions(dag_id, run_id, task_id):
+ return -1
+ if caller is not None and (caller.dag_id, caller.run_id) == (dag_id,
run_id):
+ dag_version_id = caller.dag_version_id
+ else:
+ dag_version_id = None
+ try:
+ task = resolver.get_task(dag_id, run_id, task_id,
dag_version_id=dag_version_id)
+ except AmbiguousProducerError as error:
+ raise HTTPException(status.HTTP_409_CONFLICT, str(error)) from error
+ except (TaskNotFound, ValueError):
+ return -1
+ return None if task.get_needs_expansion() else -1
+
+
@router.get(
"/{dag_id}/{run_id}/{task_id}/{key:path}",
dependencies=[ExecutionOrDagParseToken, DagInGrantedBundle],
- responses=create_openapi_http_exception_doc(
- [
- (status.HTTP_400_BAD_REQUEST, "The request selects an invalid
combination of producers"),
- (status.HTTP_409_CONFLICT, "Several live task instances produce
the requested value"),
- ]
- ),
+ responses={
+ **create_openapi_http_exception_doc(
+ [
+ (status.HTTP_400_BAD_REQUEST, "The request selects an invalid
combination of producers"),
+ (status.HTTP_409_CONFLICT, "Several live task instances
produce the requested value"),
+ ]
+ ),
+ status.HTTP_307_TEMPORARY_REDIRECT: {
+ "description": "An omitted map index reads every instance of a
mapped task, from the slice",
+ },
+ },
description="Get a single XCom Value",
+ response_model=XComResponse,
)
def get_xcom(
dag_id: str,
run_id: str,
task_id: str,
key: Annotated[str, Path(min_length=1)],
- session: SessionDep,
params: Annotated[GetXcomFilterParams, Query()],
- dag_bag: DagBagDep,
+ request: Request,
+ session: SessionDep,
+ resolver: _ResolverDep,
token: ExecutionToken = _TriggerAwareToken,
-) -> XComResponse:
- """Get an Airflow XCom from database - not other XCom Backends."""
+) -> XComResponse | RedirectResponse:
+ """
+ Get an Airflow XCom from database - not other XCom Backends.
+
+ A read of every instance of a mapped task is redirected to the slice
+ endpoint, which lists one stored value per instance.
+ """
+ if params.map_index is not None:
+ map_index: int | None = params.map_index
+ else:
+ map_index = _resolve_omitted_map_index(
+ dag_id=dag_id,
+ run_id=run_id,
+ task_id=task_id,
+ params=params,
+ resolver=resolver,
+ caller=_get_calling_ti(token, session=session),
+ )
owner = None
if token.claims.scope == "execution":
owner = session.execute(
@@ -585,7 +665,7 @@ def get_xcom(
TaskInstance.dag_id == dag_id,
TaskInstance.run_id == run_id,
TaskInstance.task_id == task_id,
- *build_coordinate_filters(TaskInstance,
map_index=params.map_index),
+ *build_coordinate_filters(TaskInstance, map_index=map_index),
)
.limit(1)
.execution_options(include_all_attempts=True)
@@ -608,15 +688,19 @@ def get_xcom(
),
},
)
+ if map_index is None:
+ segment = quote(key, safe="")
+ segment = {".": "%2E", "..": "%2E%2E"}.get(segment, segment)
+ return RedirectResponse(URL(path=f"{segment}/slice",
query=request.url.query))
xcom_read = _build_xcom_read(
dag_id=dag_id,
run_id=run_id,
task_id=task_id,
key=key,
session=session,
- dag_bag=dag_bag,
+ resolver=resolver,
token=token,
- map_index=params.map_index if params.offset is None else None,
+ map_index=map_index if params.offset is None else None,
include_prior_dates=params.include_prior_dates,
previous_iteration=params.previous_iteration,
sequence=params.offset is not None,
@@ -641,7 +725,7 @@ def get_xcom(
if (result := session.scalars(xcom_query.limit(1)).first()) is None:
if params.offset is None:
message = (
- f"XCom with {key=} map_index={params.map_index} not found for "
+ f"XCom with {key=} map_index={map_index} not found for "
f"task {task_id!r} in DAG run {run_id!r} of {dag_id!r}"
)
else:
@@ -756,8 +840,8 @@ def set_xcom(
run_id=run_id,
task_id=task_id,
map_index=map_index,
- session=session,
dag_bag=dag_bag,
+ session=session,
)
if owner is None:
raise HTTPException(
@@ -824,8 +908,8 @@ def delete_xcom(
run_id=run_id,
task_id=task_id,
map_index=map_index,
- session=session,
dag_bag=dag_bag,
+ session=session,
)
if owner is not None:
XComModel.delete_for_attempts(
@@ -843,8 +927,8 @@ def _find_writer_id(
run_id: str,
task_id: str,
map_index: int,
- session: Session,
dag_bag: DBDagBag,
+ session: Session,
) -> UUID | None:
"""Resolve the task instance a write targets with the rule reads use,
working from the caller."""
caller = session.get(TaskInstance, token.id,
execution_options={"include_all_attempts": True})
diff --git
a/airflow-core/src/airflow/api_fastapi/execution_api/versions/__init__.py
b/airflow-core/src/airflow/api_fastapi/execution_api/versions/__init__.py
index 5afdfd49f32..7d828483598 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/versions/__init__.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/versions/__init__.py
@@ -74,6 +74,7 @@ from airflow.api_fastapi.execution_api.versions.v2027_02_28
import (
AddExecutionTimeoutToTIRunContext,
AddExternalClearTargetField,
MakeVariableValueNonNullable,
+ ResolveOmittedXComMapIndexByTaskDefinition,
)
bundle = VersionBundle(
@@ -85,6 +86,7 @@ bundle = VersionBundle(
AddExternalClearTargetField,
MakeVariableValueNonNullable,
AddCallbackStateEndpoint,
+ ResolveOmittedXComMapIndexByTaskDefinition,
),
Version(
"2026-10-30",
diff --git
a/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2027_02_28.py
b/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2027_02_28.py
index 85a544c5067..b7d6fc60f65 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2027_02_28.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2027_02_28.py
@@ -21,6 +21,7 @@ from cadwyn import (
RequestInfo,
ResponseInfo,
VersionChange,
+ VersionChangeWithSideEffects,
convert_request_to_next_version_for,
convert_response_to_previous_version_for,
endpoint,
@@ -29,6 +30,7 @@ from cadwyn import (
from airflow.api_fastapi.execution_api.datamodels.taskinstance import
TIRunContext, TISuccessStatePayload
from airflow.api_fastapi.execution_api.datamodels.variable import
VariablePostBody, VariableResponse
+from airflow.api_fastapi.execution_api.datamodels.xcom import
GetXcomFilterParams
class AddDagProcessorJobEndpoints(VersionChange):
@@ -103,3 +105,19 @@ class AddCallbackStateEndpoint(VersionChange):
instructions_to_migrate_to_previous_version = (
endpoint("/callbacks/{callback_id}/state", ["PATCH"]).didnt_exist,
)
+
+
+class ResolveOmittedXComMapIndexByTaskDefinition(VersionChangeWithSideEffects):
+ """
+ Resolve an omitted XCom ``map_index`` by the producing task's definition.
+
+ A mapped task is now redirected to the slice endpoint, which lists the
values
+ of all its instances, except with ``include_prior_dates``. An unmapped task
+ still reads map index -1, as do older clients.
+ """
+
+ description = __doc__
+
+ instructions_to_migrate_to_previous_version = (
+ schema(GetXcomFilterParams).field("map_index").had(type=int,
default=-1),
+ )
diff --git
a/airflow-core/tests/unit/api_fastapi/execution_api/test_task_sdk_client_contract.py
b/airflow-core/tests/unit/api_fastapi/execution_api/test_task_sdk_client_contract.py
index 2572d1a97fa..f8d28808aa9 100644
---
a/airflow-core/tests/unit/api_fastapi/execution_api/test_task_sdk_client_contract.py
+++
b/airflow-core/tests/unit/api_fastapi/execution_api/test_task_sdk_client_contract.py
@@ -58,6 +58,7 @@ from tests_common.test_utils.db import clear_db_connections,
clear_db_variables
pytestmark = pytest.mark.db_test
MAPPED_VALUES = ["a", "b"]
+SLASHED_KEY = "nested/key"
class TestXComOperations:
@@ -70,6 +71,8 @@ class TestXComOperations:
for ti in dag_run.get_task_instances(session=session):
value = "plain" if ti.task_id == "plain" else
MAPPED_VALUES[ti.region_index]
session.add(XComModelV2(key=XCOM_RETURN_KEY, value=value,
task_instance_id=ti.id))
+ if ti.task_id == "mapped":
+ session.add(XComModelV2(key=SLASHED_KEY, value=value,
task_instance_id=ti.id))
session.commit()
return dag_run
@@ -86,6 +89,11 @@ class TestXComOperations:
result = task_sdk_client.xcoms.get("dag", "runid", task_id,
XCOM_RETURN_KEY, map_index)
assert result == XComResponse(key=XCOM_RETURN_KEY, value=expected)
+ @pytest.mark.parametrize("key", [XCOM_RETURN_KEY, SLASHED_KEY])
+ def test_get_mapped_omitted(self, task_sdk_client, key):
+ result = task_sdk_client.xcoms.get("dag", "runid", "mapped", key)
+ assert result == XComSequenceSliceResponse(MAPPED_VALUES)
+
def test_get_missing_key(self, task_sdk_client):
result = task_sdk_client.xcoms.get("dag", "runid", "plain", "missing")
assert result == XComResponse(key="missing", value=None)
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 118fa34fd66..832045e5b77 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,8 +53,6 @@ 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
@@ -550,6 +548,53 @@ def
test_loop_task_reads_from_inside_the_loop_stay_on_one_pass(client, outside_l
assert client.get(f"{fanout_url}/item/-1").json() == "2-1"
+def test_outside_caller_reads_every_iteration_of_a_mapped_loop_task(client,
outside_loop_run):
+ dr = outside_loop_run[0]
+ url = get_loop_url(dr, "body.fanout")
+
+ response = client.get(url)
+
+ assert [r.status_code for r in response.history] == [307]
+ assert response.json() == LOOP_SEQUENCES["mapped"][1]
+ assert response.json() == client.get(f"{url}/slice").json()
+
+
[email protected](
+ ("task_id", "params", "expected"),
+ [
+ pytest.param("body.step", {}, "step-2", id="unmapped"),
+ pytest.param("body.fanout", {"map_index": 1}, "2-1", id="mapped-one"),
+ ],
+)
+def test_inside_caller_reads_a_loop_task_on_its_own_pass(client,
outside_loop_run, task_id, params, expected):
+ dr, _, _, steps, authenticate_as = outside_loop_run
+ authenticate_as(steps[2])
+
+ response = client.get(get_loop_url(dr, task_id), params=params)
+
+ assert response.status_code == 200
+ assert response.json() == {"key": "key", "value": expected}
+
+
+def
test_inside_caller_reads_every_instance_of_a_loop_task_on_its_own_pass(client,
outside_loop_run):
+ dr, _, _, steps, authenticate_as = outside_loop_run
+ authenticate_as(steps[2])
+
+ response = client.get(get_loop_url(dr, "body.fanout"))
+
+ assert [r.status_code for r in response.history] == [307]
+ assert response.json() == ["2-0", "2-1"]
+
+
+def
test_inside_caller_reads_a_map_index_past_the_expansion_as_not_found(client,
outside_loop_run):
+ dr, _, _, steps, authenticate_as = outside_loop_run
+ authenticate_as(steps[2])
+
+ response = client.get(get_loop_url(dr, "body.fanout"),
params={"map_index": 2})
+
+ assert response.status_code == 404
+
+
@pytest.fixture
def deferred_loop_pass(session, outside_loop_run):
dr, _, _, steps, _ = outside_loop_run
@@ -1382,42 +1427,164 @@ 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."""
+class TestXComsGetOmittedMapIndex:
+ """An omitted map index reads a task's value by how the task is defined."""
@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]])
+ PythonOperator.partial(task_id="mapped",
python_callable=str).expand(op_args=[[1], [2], [3]])
+ PythonOperator.partial(task_id="empty",
python_callable=str).expand(op_args=[])
+
+ @task_group
+ def group(value):
+ PythonOperator(task_id="inner", python_callable=str)
+ PythonOperator(task_id="sibling", python_callable=str)
+
+ group.expand(value=[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))
+ tis = {(ti.task_id, ti.region_index): ti for ti in
dag_run.get_task_instances(session=session)}
+ # The mapped task's instance 1 pushes nothing.
+ values = {
+ ("plain", -1): "plain",
+ ("mapped", 0): "mapped 0",
+ ("mapped", 2): "mapped 2",
+ ("group.inner", 0): "inner 0",
+ ("group.inner", 1): "inner 1",
+ }
+ for coordinates, value in values.items():
+ session.add(XComModelV2(key=XCOM_RETURN_KEY, value=value,
task_instance_id=tis[coordinates].id))
session.commit()
return dag_run
+ @staticmethod
+ def get(client, task_id, *, dag_id="dag", run_id="runid", **params):
+ return client.get(
+ f"/execution/xcoms/{dag_id}/{run_id}/{task_id}/{XCOM_RETURN_KEY}",
+ params=params,
+ follow_redirects=False,
+ )
+
+ @staticmethod
+ def assert_redirected_to_slice(response):
+ assert response.status_code == 307
+ location = response.headers["location"]
+ assert not urllib.parse.urlsplit(location).netloc # Relative, so a
proxy's URL is kept.
+ target = response.request.url.join(location)
+ assert target.path == f"{response.request.url.path}/slice"
+ assert target.query == response.request.url.query
+
@pytest.mark.parametrize(
- ("task_id", "map_index", "expected"),
+ ("task_id", "params", "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",
- ),
+ pytest.param("plain", {}, "plain", id="unmapped"),
+ pytest.param("plain", {"map_index": -1}, "plain",
id="unmapped-minus-one"),
+ pytest.param("plain", {"map_index": 0}, None, id="unmapped-index"),
+ pytest.param("mapped", {"map_index": 0}, "mapped 0",
id="mapped-one"),
+ pytest.param("mapped", {"map_index": 1}, None,
id="mapped-one-not-pushed"),
+ pytest.param("mapped", {"map_index": 3}, None,
id="mapped-past-end"),
+ pytest.param("mapped", {"map_index": -1}, None,
id="mapped-minus-one"),
+ pytest.param("mapped", {"offset": -1}, "mapped 2",
id="mapped-offset"),
+ pytest.param("mapped", {"include_prior_dates": True}, None,
id="mapped-prior-dates"),
+ pytest.param("group.inner", {"map_index": 1}, "inner 1",
id="mapped-group-one"),
+ pytest.param("missing", {}, None, id="unknown-task"),
+ ],
+ )
+ def test_read(self, client, task_id, params, expected):
+ response = self.get(client, task_id, **params)
+
+ if expected is None:
+ assert response.status_code == 404
+ assert response.json()["detail"]["reason"] == "not_found"
+ else:
+ assert response.status_code == 200
+ assert response.json() == {"key": XCOM_RETURN_KEY, "value":
expected}
+
+ @pytest.mark.parametrize(
+ ("task_id", "params"),
+ [
+ pytest.param("mapped", {}, id="mapped"),
+ pytest.param("mapped", {"previous_iteration": True},
id="mapped-keeps-query"),
+ pytest.param("empty", {}, id="mapped-to-none"),
+ pytest.param("group.inner", {}, id="mapped-group"),
+ ],
+ )
+ def test_every_instance_is_redirected_to_the_slice(self, client, task_id,
params):
+ self.assert_redirected_to_slice(self.get(client, task_id, **params))
+
+ @pytest.mark.parametrize(
+ ("sent_key", "expected"),
+ [
+ pytest.param("a%2Fb", "a%2Fb/slice", id="slash"),
+ pytest.param("%2E", "%2E/slice", id="dot"),
+ pytest.param("my%20key", "my%20key/slice", id="space"),
],
)
- 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
+ def test_redirect_quotes_the_key_as_one_segment(self, client, sent_key,
expected):
+ response = client.get(f"/execution/xcoms/dag/runid/mapped/{sent_key}",
follow_redirects=False)
+ assert response.status_code == 307
+ assert response.headers["location"] == expected
+
+ @pytest.mark.parametrize("task_id", ["plain", "missing"])
+ def test_task_without_regional_instances_does_not_load_the_dag(self,
client, mocker, task_id):
+ get_task = mocker.spy(TaskCoordinateResolver, "get_task")
+ self.get(client, task_id)
+ assert get_task.call_count == 0
+
+ @pytest.mark.parametrize("same_run_caller", [True, False],
ids=["same-run-caller", "no-caller"])
+ def test_same_run_caller_reads_by_its_own_dag_version(
+ self, client, mocker, session, dag_run, authenticate_as,
same_run_caller
+ ):
+ # The task's live instances disagree on its definition across Dag
versions.
+ mocker.patch.object(
+ TaskCoordinateResolver, "_producer_task",
side_effect=AmbiguousProducerError("differ")
+ )
+ if same_run_caller:
+ authenticate_as(dag_run.get_task_instance("plain",
session=session))
+
+ response = self.get(client, "mapped")
+
+ if same_run_caller:
+ self.assert_redirected_to_slice(response)
+ else:
+ assert response.status_code == 409
+
+ def test_caller_in_the_same_mapped_group_reads_every_instance(
+ self, client, session, dag_run, authenticate_as
+ ):
+ """The caller's own map index doesn't narrow an omitted one, even for
a task in its mapped group."""
+ sibling = next(
+ ti
+ for ti in dag_run.get_task_instances(session=session)
+ if ti.task_id == "group.sibling" and ti.region_index == 1
+ )
+ authenticate_as(sibling)
+
+ response = self.get(client, "group.inner")
+
+ self.assert_redirected_to_slice(response)
+
+ def test_another_dag_is_read_by_its_own_definition(
+ self, client, dag_maker, session, dag_run, authenticate_as
+ ):
+ # "plain" is mapped in the other Dag, and not in the caller's.
+ with dag_maker(dag_id="other", serialized=True):
+ PythonOperator.partial(task_id="plain",
python_callable=str).expand(op_args=[[1], [2]])
+ other_run = dag_maker.create_dagrun(run_id="other_run")
+ for ti in other_run.get_task_instances(session=session):
+ session.add(
+ XComModelV2(key=XCOM_RETURN_KEY, value=f"other
{ti.region_index}", task_instance_id=ti.id)
+ )
+ session.commit()
+ authenticate_as(dag_run.get_task_instance("plain", session=session))
+
+ other = self.get(client, "plain", dag_id="other", run_id="other_run")
+ own = self.get(client, "plain")
+
+ self.assert_redirected_to_slice(other)
+ assert own.status_code == 200
+ assert own.json() == {"key": XCOM_RETURN_KEY, "value": "plain"}
class TestXComsSetEndpoint:
diff --git
a/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2027_02_28/test_xcoms.py
b/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2027_02_28/test_xcoms.py
new file mode 100644
index 00000000000..6c48382dedd
--- /dev/null
+++
b/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2027_02_28/test_xcoms.py
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import pytest
+
+from airflow.models.xcom import XCOM_RETURN_KEY, XComModelV2
+from airflow.providers.standard.operators.python import PythonOperator
+
+pytestmark = pytest.mark.db_test
+
+
+class TestOmittedMapIndexVersioning:
+ """An omitted ``map_index`` on Get XCom read -1 before the 2027-02-28 API
version."""
+
+ @pytest.fixture(autouse=True)
+ def dag_run(self, dag_maker, session):
+ with dag_maker(dag_id="dag", serialized=True):
+ 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):
+ session.add(XComModelV2(key=XCOM_RETURN_KEY,
value=ti.region_index, task_instance_id=ti.id))
+ session.commit()
+ return dag_run
+
+ def test_old_version_reads_minus_one(self, client):
+ client.headers["Airflow-API-Version"] = "2026-10-30"
+
+ response =
client.get(f"/execution/xcoms/dag/runid/mapped/{XCOM_RETURN_KEY}")
+
+ assert response.status_code == 404
+ assert response.json()["detail"]["message"].startswith("XCom with
key='return_value' map_index=-1")
+
+ def test_head_version_redirects_to_the_slice(self, client):
+ response =
client.get(f"/execution/xcoms/dag/runid/mapped/{XCOM_RETURN_KEY}",
follow_redirects=False)
+
+ assert response.status_code == 307
+ assert response.headers["location"] == f"{XCOM_RETURN_KEY}/slice"
diff --git a/airflow-core/tests/unit/models/test_task_coordinates.py
b/airflow-core/tests/unit/models/test_task_coordinates.py
index 57af3454f80..7b5dc387225 100644
--- a/airflow-core/tests/unit/models/test_task_coordinates.py
+++ b/airflow-core/tests/unit/models/test_task_coordinates.py
@@ -646,7 +646,7 @@ def
test_xcom_read_of_one_mapped_slot_loads_no_producer_rows(mapped_run, session
task_id="mapped",
key="return_value",
session=session,
- dag_bag=DBDagBag(),
+ resolver=TaskCoordinateResolver(DBDagBag(), session),
token=token,
map_index=2,
)
@@ -695,7 +695,7 @@ def
test_loop_read_of_one_mapped_slot_loads_no_producer_rows(dag_maker, session,
task_id="body.mapped",
key="return_value",
session=session,
- dag_bag=DBDagBag(),
+ resolver=TaskCoordinateResolver(DBDagBag(), session),
token=token,
map_index=2,
)
diff --git a/go-sdk/sdk/sdk.go b/go-sdk/sdk/sdk.go
index 56304f8a390..26928e0d5f9 100644
--- a/go-sdk/sdk/sdk.go
+++ b/go-sdk/sdk/sdk.go
@@ -122,7 +122,7 @@ type XComClient interface {
// - 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.
+ // instances, the result is nil.
//
// 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
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 0abe32b70fa..45ed65eea69 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
@@ -160,7 +160,7 @@ class Client internal constructor(
* - 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.
+ * to no instances, the result is `null`.
*
* 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,
diff --git a/kubernetes-tests/lang_sdk/go_example/main.go
b/kubernetes-tests/lang_sdk/go_example/main.go
index b29916ce10e..af07acf35ed 100644
--- a/kubernetes-tests/lang_sdk/go_example/main.go
+++ b/kubernetes-tests/lang_sdk/go_example/main.go
@@ -79,27 +79,9 @@ func goTransform(actx airflow.Context) error {
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)
- }
+ want := []any{int64(1), int64(2), int64(3)}
+ if !reflect.DeepEqual(fanout, want) {
+ return fmt.Errorf("python_fanout result is %#v, want %#v",
fanout, want)
}
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/task-sdk/src/airflow/sdk/api/client.py
b/task-sdk/src/airflow/sdk/api/client.py
index 45572681a2b..ea07233e497 100644
--- a/task-sdk/src/airflow/sdk/api/client.py
+++ b/task-sdk/src/airflow/sdk/api/client.py
@@ -203,7 +203,7 @@ def get_json_error(response: httpx2.Response):
raise err
-def raise_on_4xx_5xx(response: httpx2.Response):
+def require_2xx(response: httpx2.Response):
try:
return get_json_error(response) or response.raise_for_status()
except httpx2.HTTPStatusError as e:
@@ -617,6 +617,26 @@ class VariableOperations:
return VariableKeysResponse.model_validate_json(resp.read())
+_OMITTED_MAP_INDEX_RESOLVED_VERSION = "2027-02-28"
+
+
+def _build_xcom_slice_path(xcom_path: str) -> str:
+ return f"{xcom_path}/slice"
+
+
+def _find_slice_redirect(response: httpx2.Response) -> httpx2.URL | None:
+ """
+ Return where a Get XCom response redirects to, if that is its slice
endpoint.
+
+ The server does so for an omitted map index on a mapped task, since the
+ slice lists one stored value per instance.
+ """
+ if response.status_code != HTTPStatus.TEMPORARY_REDIRECT or "location" not
in response.headers:
+ return None
+ target = response.request.url.join(response.headers["location"])
+ return target if target.path ==
_build_xcom_slice_path(response.request.url.path) else None
+
+
class XComOperations:
__slots__ = ("client",)
@@ -661,8 +681,8 @@ class XComOperations:
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.
+ instances, as a slice response. A mapped task with no values, or one
+ read with *include_prior_dates*, reads as not found.
"""
params: dict[str, str | int] = {}
if previous_iteration:
@@ -684,6 +704,7 @@ class XComOperations:
map_index,
include_prior_dates=include_prior_dates,
previous_iteration=previous_iteration,
+ server_version=e.response.headers.get("Airflow-API-Version",
API_VERSION),
)
if mapped is not None:
return mapped
@@ -699,6 +720,12 @@ class XComOperations:
)
# A missing XCom is not an error, as in Airflow 2; xcom_pull then
returns its default.
return XComResponse(key=key, value=None)
+ except httpx2.HTTPStatusError as e: # require_2xx raises for the
redirect too.
+ if (slice_url := _find_slice_redirect(e.response)) is None:
+ raise
+ mapped =
XComSequenceSliceResponse.model_validate_json(self.client.get(slice_url).read())
+ # A mapped task with no values is not found not an empty slice.
+ return mapped if mapped.root else XComResponse(key=key, value=None)
return XComResponse.model_validate_json(resp.read())
def _get_mapped_slice_or_none(
@@ -711,18 +738,21 @@ class XComOperations:
*,
include_prior_dates: bool,
previous_iteration: bool,
+ server_version: str,
) -> 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.
+ how the task is defined redirects a mapped task's read instead.
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
+ if server_version >= _OMITTED_MAP_INDEX_RESOLVED_VERSION:
+ return None
response = self.get_sequence_slice(
dag_id,
run_id,
@@ -846,7 +876,10 @@ class XComOperations:
params["step"] = step
if include_prior_dates:
params["include_prior_dates"] = include_prior_dates
- resp = self.client.get(f"{_path('xcoms', dag_id, run_id, task_id,
tail=key)}/slice", params=params)
+ resp = self.client.get(
+ _build_xcom_slice_path(_path("xcoms", dag_id, run_id, task_id,
tail=key)),
+ params=params,
+ )
return XComSequenceSliceResponse.model_validate_json(resp.read())
@@ -1364,7 +1397,7 @@ class Client(httpx2.Client):
"airflow-api-version": API_VERSION,
},
event_hooks={
- "response": [self._update_auth, raise_on_4xx_5xx],
+ "response": [self._update_auth, require_2xx],
"request": [add_correlation_id, inject_trace_context],
},
**kwargs,
diff --git a/task-sdk/src/airflow/sdk/bases/xcom.py
b/task-sdk/src/airflow/sdk/bases/xcom.py
index a8f807cf4ac..e3373817204 100644
--- a/task-sdk/src/airflow/sdk/bases/xcom.py
+++ b/task-sdk/src/airflow/sdk/bases/xcom.py
@@ -505,9 +505,8 @@ class BaseXCom:
:param map_index: Map index of the task instance to pull the XCom from.
*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.
+ list, the same values ``get_all`` returns. A mapped task with no
+ values, or one read with *include_prior_dates*, reads *None*.
: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
@@ -567,9 +566,8 @@ class BaseXCom:
:param map_index: Map index of the task instance to pull the XCom from.
*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.
+ list, the same values ``get_all`` returns. A mapped task with no
+ values, or one read with *include_prior_dates*, reads *None*.
: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
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 303ae89b465..4ce2367c001 100644
--- a/task-sdk/src/airflow/sdk/execution_time/task_runner.py
+++ b/task-sdk/src/airflow/sdk/execution_time/task_runner.py
@@ -552,6 +552,20 @@ class RuntimeTaskInstance(TaskInstance):
return None
return LazyXComSequence(xcom_arg=PlainXComArg(producer, key), ti=self)
+ def _is_task_mapped(self, dag_id: str, run_id: str, task_id: str) -> bool:
+ """
+ Whether a task of this Dag run is mapped, by this task's Dag.
+
+ A task of another run or Dag reads False, since its Dag version may
+ differ; the server decides for those.
+ """
+ if not (dag_id == self.dag_id and run_id == self.run_id):
+ return False
+ try:
+ return self.task.dag.get_task(task_id).get_needs_expansion()
+ except TaskNotFound:
+ return False
+
def xcom_pull(
self,
task_ids: str | Iterable[str] | None = None,
@@ -593,9 +607,9 @@ class RuntimeTaskInstance(TaskInstance):
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.
+ list. A mapped task with no XComs, or one pulled with
+ ``include_prior_dates``, 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.
@@ -640,14 +654,17 @@ class RuntimeTaskInstance(TaskInstance):
return xcoms
for t_id, m_idx in product(task_ids, map_indexes_iterable):
- value = XCom.get_one(
- run_id=run_id,
- key=key,
- task_id=t_id,
- dag_id=dag_id,
- map_index=m_idx,
- include_prior_dates=include_prior_dates,
- )
+ if m_idx is None and not include_prior_dates and
self._is_task_mapped(dag_id, run_id, t_id):
+ value = XCom.get_all(run_id=run_id, key=key, task_id=t_id,
dag_id=dag_id)
+ else:
+ value = XCom.get_one(
+ run_id=run_id,
+ key=key,
+ task_id=t_id,
+ dag_id=dag_id,
+ map_index=m_idx,
+ include_prior_dates=include_prior_dates,
+ )
xcoms.append(default if value is None else value)
if single_task_requested and single_map_index_requested:
@@ -703,14 +720,17 @@ class RuntimeTaskInstance(TaskInstance):
return xcoms
for t_id, m_idx in product(task_ids, map_indexes_iterable):
- value = await XCom.aget_one(
- run_id=run_id,
- key=key,
- task_id=t_id,
- dag_id=dag_id,
- map_index=m_idx,
- include_prior_dates=include_prior_dates,
- )
+ if m_idx is None and not include_prior_dates and
self._is_task_mapped(dag_id, run_id, t_id):
+ value = await XCom.aget_all(run_id=run_id, key=key,
task_id=t_id, dag_id=dag_id)
+ else:
+ value = await XCom.aget_one(
+ run_id=run_id,
+ key=key,
+ task_id=t_id,
+ dag_id=dag_id,
+ map_index=m_idx,
+ include_prior_dates=include_prior_dates,
+ )
xcoms.append(default if value is None else value)
if single_task_requested and single_map_index_requested:
diff --git a/task-sdk/tests/task_sdk/api/test_client.py
b/task-sdk/tests/task_sdk/api/test_client.py
index a3d2c514c95..e916a6b8774 100644
--- a/task-sdk/tests/task_sdk/api/test_client.py
+++ b/task-sdk/tests/task_sdk/api/test_client.py
@@ -69,6 +69,8 @@ from airflow.sdk.execution_time.comms import (
if TYPE_CHECKING:
from time_machine import TimeMachineFixture
+MAP_INDEX_UNRESOLVED_SERVER_HEADERS = {"Airflow-API-Version": "2026-10-30"}
+
@pytest.fixture
def ca_file(tmp_path):
@@ -1304,6 +1306,54 @@ class TestXCOMOperations:
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_follows_a_redirect_to_the_slice(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)
+ location = request.url.copy_with(path=f"{request.url.path}/slice")
+ return httpx2.Response(status_code=307, headers={"Location":
str(location)})
+
+ 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",
previous_iteration=True
+ )
+
+ 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",
+ ]
+ assert requests[1].url.params["previous_iteration"] == "true"
+
+ def test_xcom_get_does_not_read_another_redirect_as_a_slice(self):
+ def handle_request(request: httpx2.Request) -> httpx2.Response:
+ if request.url.path.endswith("/slice"):
+ return httpx2.Response(status_code=200, json=["a", "b"])
+ location =
request.url.copy_with(path="/xcoms/dag_id/run_id/other/key/slice")
+ return httpx2.Response(status_code=307, headers={"Location":
str(location)})
+
+ client = make_client(transport=httpx2.MockTransport(handle_request))
+ with pytest.raises(httpx2.HTTPStatusError):
+ client.xcoms.get(dag_id="dag_id", run_id="run_id",
task_id="task_id", key="key")
+
+ def test_redirect_on_another_endpoint_raises(self):
+ def handle_request(request: httpx2.Request) -> httpx2.Response:
+ return httpx2.Response(status_code=307, headers={"Location":
str(request.url)})
+
+ client = make_client(transport=httpx2.MockTransport(handle_request))
+ with pytest.raises(httpx2.HTTPStatusError):
+ client.variables.get("key")
+
@pytest.mark.parametrize(
("slice_values", "expected"),
[
@@ -1319,7 +1369,9 @@ class TestXCOMOperations:
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"}}
+ status_code=404,
+ headers=MAP_INDEX_UNRESOLVED_SERVER_HEADERS,
+ json={"detail": {"reason": "not_found", "message": "XCom not
found"}},
)
client = make_client(transport=httpx2.MockTransport(handle_request))
@@ -1337,6 +1389,7 @@ class TestXCOMOperations:
return httpx2.Response(status_code=403, json={"detail":
"Forbidden"})
return httpx2.Response(
status_code=404,
+ headers=MAP_INDEX_UNRESOLVED_SERVER_HEADERS,
json={"detail": {"reason": "not_found", "message": "XCom not
found"}},
)
@@ -1347,19 +1400,21 @@ class TestXCOMOperations:
assert ctx.value.response.status_code == 403
@pytest.mark.parametrize(
- "kwargs",
+ ("kwargs", "headers"),
[
- pytest.param({"map_index": -1}, id="explicit-map-index"),
- pytest.param({"include_prior_dates": True}, id="prior-dates"),
+ pytest.param({"map_index": -1}, {}, id="explicit-map-index"),
+ pytest.param({"include_prior_dates": True}, {}, id="prior-dates"),
+ pytest.param({}, {"Airflow-API-Version": "2027-02-28"},
id="server-resolves-map-index"),
],
)
- def test_xcom_get_does_not_read_the_slice(self, kwargs):
+ def test_xcom_get_does_not_read_the_slice(self, kwargs, headers):
requests = []
def handle_request(request: httpx2.Request) -> httpx2.Response:
requests.append(request)
return httpx2.Response(
status_code=404,
+ headers=headers,
json={"detail": {"reason": "not_found", "message": "XCom not
found"}},
)
diff --git a/task-sdk/tests/task_sdk/coordinators/test_subprocess.py
b/task-sdk/tests/task_sdk/coordinators/test_subprocess.py
index ffddd2ebabf..30b0d1107a8 100644
--- a/task-sdk/tests/task_sdk/coordinators/test_subprocess.py
+++ b/task-sdk/tests/task_sdk/coordinators/test_subprocess.py
@@ -1515,15 +1515,17 @@ class _FakeApi:
responses: dict[tuple[str, str], tuple[int, Any]] =
attrs.field(factory=dict)
requests: list[tuple[str, str, Any]] = attrs.field(factory=list)
+ api_version: str | None = None
def __call__(self, request: httpx2.Request) -> httpx2.Response:
body = json.loads(request.content) if request.content else None
self.requests.append((request.method, request.url.path, body))
status, content = self.responses.get((request.method,
request.url.path), (200, {}))
# json=None would send an empty body, but a null XCom item is the body
"null".
- return httpx2.Response(
- status, content=json.dumps(content), headers={"content-type":
"application/json"}
- )
+ headers = {"content-type": "application/json"}
+ if self.api_version is not None:
+ headers["Airflow-API-Version"] = self.api_version
+ return httpx2.Response(status, content=json.dumps(content),
headers=headers)
def _sent_body(proc: _PopenActivitySubprocess) -> Any:
@@ -1538,6 +1540,7 @@ def _sent_error(proc: _PopenActivitySubprocess) -> Any:
_XCOM_PATH = "/xcoms/tutorial_dag/run_1/task_1/summary"
+_MAP_INDEX_UNRESOLVED_API_VERSION = "2026-10-30"
_STORED_SUMMARY = {("GET", _XCOM_PATH): (200, {"key": "summary", "value":
"ref://task_1/None/summary"})}
@@ -1737,7 +1740,8 @@ class TestPopenActivitySubprocessXComBackend:
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, [])}
+ {("GET", _XCOM_PATH): (404, {"detail": "not found"}), ("GET",
f"{_XCOM_PATH}/slice"): (200, [])},
+ api_version=_MAP_INDEX_UNRESOLVED_API_VERSION,
)
proc = make_proc(_RefXCom, api)
proc._handle_request(
@@ -1762,7 +1766,8 @@ class TestPopenActivitySubprocessXComBackend:
{
("GET", _XCOM_PATH): (404, {"detail": "not found"}),
("GET", f"{_XCOM_PATH}/slice"): (200,
["ref://task_1/None/summary", 5]),
- }
+ },
+ api_version=_MAP_INDEX_UNRESOLVED_API_VERSION,
)
proc = make_proc(xcom, api)
diff --git a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py
b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py
index 64beb944057..5eebae558b6 100644
--- a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py
+++ b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py
@@ -3632,6 +3632,62 @@ class TestRuntimeTaskInstance:
assert not isinstance(result, LazyXComSequence)
+ @staticmethod
+ def _make_mapped_dag():
+ @task_decorator
+ def mapped(value): ...
+
+ with DAG("mapped_dag", schedule=None) as dag:
+ mapped.expand(value=[1, 2]) >> BaseOperator(task_id="after")
+ return dag
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("pull_method", "get_all_method"),
+ [
+ pytest.param("xcom_pull", "get_all", id="sync"),
+ pytest.param("axcom_pull", "aget_all", id="async"),
+ ],
+ )
+ async def
test_xcom_pull_of_a_mapped_task_in_this_run_reads_the_slice_directly(
+ self, create_runtime_ti, pull_method, get_all_method
+ ):
+ dag = self._make_mapped_dag()
+ runtime_ti = create_runtime_ti(task=dag.get_task("after"),
dag_id="mapped_dag")
+
+ with patch.object(XCom, get_all_method, autospec=True,
return_value=[1, 2]) as get_all:
+ result = getattr(runtime_ti, pull_method)(key="k",
task_ids="mapped", map_indexes=None)
+ if inspect.isawaitable(result):
+ result = await result
+
+ assert result == [1, 2]
+ get_all.assert_called_once_with(
+ run_id=runtime_ti.run_id, key="k", task_id="mapped",
dag_id=runtime_ti.dag_id
+ )
+
+ @pytest.mark.parametrize(
+ "pull_kwargs",
+ [
+ pytest.param({"task_ids": "mapped", "run_id": "other_run"},
id="other run"),
+ pytest.param({"task_ids": "mapped", "dag_id": "other_dag"},
id="other dag"),
+ pytest.param({"task_ids": "mapped", "include_prior_dates": True},
id="prior dates"),
+ pytest.param({"task_ids": "after"}, id="unmapped task"),
+ pytest.param({"task_ids": "removed"}, id="task missing from the
dag"),
+ ],
+ )
+ def test_xcom_pull_leaves_other_omitted_map_indexes_to_the_server(self,
create_runtime_ti, pull_kwargs):
+ dag = self._make_mapped_dag()
+ runtime_ti = create_runtime_ti(task=dag.get_task("after"),
dag_id="mapped_dag")
+
+ with (
+ patch.object(XCom, "get_all", autospec=True) as get_all,
+ patch.object(XCom, "get_one", autospec=True, return_value=7) as
get_one,
+ ):
+ assert runtime_ti.xcom_pull(key="k", map_indexes=None,
**pull_kwargs) == 7
+
+ get_all.assert_not_called()
+ assert get_one.call_args.kwargs["map_index"] is None
+
@pytest.mark.asyncio
async def
test_axcom_pull_of_a_loop_task_from_outside_the_loop_returns_a_list_for_one_iteration(
self, create_runtime_ti, mock_supervisor_comms
diff --git a/ts-sdk/src/sdk/client-types.ts b/ts-sdk/src/sdk/client-types.ts
index d9e44f18dc6..881d9817579 100644
--- a/ts-sdk/src/sdk/client-types.ts
+++ b/ts-sdk/src/sdk/client-types.ts
@@ -45,7 +45,7 @@ export interface GetXComOpts {
* - 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.
+ * result is `null`.
*
* 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