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 213ff3c70e2 Refresh asset context after unmapping a task (#75751)
213ff3c70e2 is described below

commit 213ff3c70e278efcde87ec9318184be367b16c28
Author: Tzu-ping Chung <[email protected]>
AuthorDate: Thu Nov 26 15:26:35 2026 +0800

    Refresh asset context after unmapping a task (#75751)
    
    * Refresh asset context after unmapping a task
    
    A mapped task's template context is built from the MappedOperator,
    whose inlets and outlets only come from partial(). Anything the
    operator's __init__ added was missing from the asset entries of the
    context, so e.g. a mapped sensor adding its asset in __init__ got a
    KeyError from context["inlet_events"][asset].
    
    context_update_for_unmapped now refreshes inlets, outlets, inlet_events
    and asset_state_store from the unmapped task. To avoid duplicate
    supervisor calls, the asset accessors no longer resolve refs and
    aliases on construction; the task runner builds their lookups in
    _prepare(), after unmapping and before task code runs, so the lookups
    are never built from async task code.
    
    * Test dropping asset state store on unmapping
    
    * Test asset lookups are built before execute
---
 task-sdk/src/airflow/sdk/execution_time/context.py | 183 +++++++++++++++------
 .../src/airflow/sdk/execution_time/task_runner.py  |  22 +--
 .../task_sdk/definitions/test_mappedoperator.py    | 171 +++++++++++++++++++
 .../tests/task_sdk/execution_time/test_context.py  |  20 +++
 .../task_sdk/execution_time/test_task_runner.py    |  77 +++++++++
 5 files changed, 410 insertions(+), 63 deletions(-)

diff --git a/task-sdk/src/airflow/sdk/execution_time/context.py 
b/task-sdk/src/airflow/sdk/execution_time/context.py
index 60c245bf5a7..412a91f7451 100644
--- a/task-sdk/src/airflow/sdk/execution_time/context.py
+++ b/task-sdk/src/airflow/sdk/execution_time/context.py
@@ -21,6 +21,7 @@ import collections
 import contextlib
 import functools
 import inspect
+import itertools
 import json
 import os
 import warnings
@@ -111,7 +112,7 @@ if TYPE_CHECKING:
         ReceiveMsgType,
     )
     from airflow.sdk.state import BaseStoreBackend
-    from airflow.sdk.types import OutletEventAccessorsProtocol
+    from airflow.sdk.types import OutletEventAccessorsProtocol, 
RuntimeTaskInstanceProtocol
 
 
 DEFAULT_FORMAT_PREFIX = "airflow.ctx."
@@ -952,6 +953,7 @@ class TaskStateStoreAccessor:
             await backend.aclear(self._scope)
 
 
[email protected](kw_only=True, unsafe_hash=True)
 class AssetStateStoreAccessor:
     """
     Accessor for asset store scoped to a single asset.
@@ -960,26 +962,17 @@ class AssetStateStoreAccessor:
     tasks, directly as ``context['asset_state_store']``.
     """
 
-    def __init__(
-        self, *, name: str | None = None, uri: str | None = None, stats_tags: 
dict[str, str] | None = None
-    ) -> None:
-        if not name and not uri:
+    _name: str | None = None
+    _uri: str | None = None
+    _stats_tags: dict[str, str] = attrs.field(factory=dict, eq=False)
+
+    def __attrs_post_init__(self) -> None:
+        if not self._name and not self._uri:
             raise ValueError("Either `name` or `uri` must be provided")
-        self._name = name
-        self._uri = uri
-        self._stats_tags = stats_tags or {}
 
     def _incr(self, event: str) -> None:
         stats.incr(f"asset_state_store.{event}", tags=self._stats_tags)
 
-    def __eq__(self, other: object) -> bool:
-        if not isinstance(other, AssetStateStoreAccessor):
-            return False
-        return self._name == other._name and self._uri == other._uri
-
-    def __hash__(self) -> int:
-        return hash((self._name, self._uri))
-
     def __repr__(self) -> str:
         if self._name is not None:
             return f"<AssetStateStoreAccessor name={self._name!r}>"
@@ -1122,6 +1115,7 @@ class AssetStateStoreAccessor:
         return msg
 
 
[email protected]
 class AssetStateStoreAccessors:
     """
     Mapping of asset state accessors for all concrete inlets and outlets of a 
task.
@@ -1132,44 +1126,66 @@ class AssetStateStoreAccessors:
     For tasks with exactly one concrete inlet or outlet, the accessor methods 
(``get``,
     ``set``, ``delete``, ``clear``, and their async counterparts ``aget``, 
``aset``,
     ``adelete``, ``aclear``) can be called directly without subscripting.
+
+    The accessors are built on first use, or by :meth:`build_lookups`. 
Building resolves
+    alias inlets through a blocking supervisor call, so the task runner calls
+    :meth:`build_lookups` before the task executes.
     """
 
-    def __init__(
-        self, inlets: list, outlets: list | None = None, stats_tags: dict[str, 
str] | None = None
-    ) -> None:
-        self._by_name: dict[str, AssetStateStoreAccessor] = {}
-        self._by_uri: dict[str, AssetStateStoreAccessor] = {}
-        self._stats_tags = stats_tags
+    @attrs.frozen
+    class _Lookups:
+        by_name: dict[str, AssetStateStoreAccessor]
+        by_uri: dict[str, AssetStateStoreAccessor]
+
+    _inlets: list
+    _outlets: list = attrs.field(factory=list)
+    _stats_tags: dict[str, str] = attrs.field(factory=dict)
+    _lookups: _Lookups | None = attrs.field(default=None, init=False, eq=False)
 
-        for inlet in inlets:
+    def build_lookups(self) -> AssetStateStoreAccessors._Lookups:
+        """Build the accessors if they are not built yet, and return them."""
+        if self._lookups is not None:
+            return self._lookups
+
+        by_name: dict[str, AssetStateStoreAccessor] = {}
+        by_uri: dict[str, AssetStateStoreAccessor] = {}
+
+        for inlet in self._inlets:
             if isinstance(inlet, (Asset, AssetNameRef)):
-                self._by_name[inlet.name] = AssetStateStoreAccessor(
-                    name=inlet.name, stats_tags=self._stats_tags
-                )
+                by_name[inlet.name] = AssetStateStoreAccessor(name=inlet.name, 
stats_tags=self._stats_tags)
             elif isinstance(inlet, AssetUriRef):
-                self._by_uri[inlet.uri] = 
AssetStateStoreAccessor(uri=inlet.uri, stats_tags=self._stats_tags)
+                by_uri[inlet.uri] = AssetStateStoreAccessor(uri=inlet.uri, 
stats_tags=self._stats_tags)
             elif isinstance(inlet, AssetAlias):
                 from airflow.sdk.execution_time.task_runner import 
SUPERVISOR_COMMS
 
                 resp = 
SUPERVISOR_COMMS.send(GetAssetsByAlias(alias_name=inlet.name))
                 if isinstance(resp, AssetsByAliasResult):
                     for asset in resp.assets:
-                        self._by_name[asset.name] = AssetStateStoreAccessor(
+                        by_name[asset.name] = AssetStateStoreAccessor(
                             name=asset.name, stats_tags=self._stats_tags
                         )
 
-        for outlet in outlets or []:
+        for outlet in self._outlets:
             # AssetAlias outlets are for dynamic event emission, not state 
access, so skip them
-            if isinstance(outlet, (Asset, AssetNameRef)) and outlet.name not 
in self._by_name:
-                self._by_name[outlet.name] = AssetStateStoreAccessor(
-                    name=outlet.name, stats_tags=self._stats_tags
-                )
-            elif isinstance(outlet, AssetUriRef) and outlet.uri not in 
self._by_uri:
-                self._by_uri[outlet.uri] = AssetStateStoreAccessor(
-                    uri=outlet.uri, stats_tags=self._stats_tags
-                )
+            if isinstance(outlet, (Asset, AssetNameRef)) and outlet.name not 
in by_name:
+                by_name[outlet.name] = 
AssetStateStoreAccessor(name=outlet.name, stats_tags=self._stats_tags)
+            elif isinstance(outlet, AssetUriRef) and outlet.uri not in by_uri:
+                by_uri[outlet.uri] = AssetStateStoreAccessor(uri=outlet.uri, 
stats_tags=self._stats_tags)
+
+        self._lookups = self._Lookups(by_name, by_uri)
+        return self._lookups
 
-        self._total = len(self._by_name) + len(self._by_uri)
+    @property
+    def _by_name(self) -> dict[str, AssetStateStoreAccessor]:
+        return self.build_lookups().by_name
+
+    @property
+    def _by_uri(self) -> dict[str, AssetStateStoreAccessor]:
+        return self.build_lookups().by_uri
+
+    @property
+    def _total(self) -> int:
+        return len(self._by_name) + len(self._by_uri)
 
     def __getitem__(self, key: Asset | AssetNameRef | AssetUriRef) -> 
AssetStateStoreAccessor:
         try:
@@ -1555,33 +1571,56 @@ class InletEventsAccessor(Sequence["AssetEventResult"]):
         return self._asset_events[key]
 
 
[email protected](init=False)
[email protected]
 class InletEventsAccessors(
     Mapping["int | Asset | AssetAlias | AssetRef", Any],
     _AssetEventAccessorsMixin[Sequence["AssetEventResult"]],
 ):
-    """Lazy mapping of inlet asset event accessors."""
+    """
+    Lazy mapping of inlet asset event accessors.
+
+    The lookups are built on first use, or by :meth:`build_lookups`. Building 
resolves
+    asset references through a blocking supervisor call, so the task runner
+    calls :meth:`build_lookups` before the task executes.
+    """
+
+    @attrs.frozen
+    class _Lookups:
+        assets: dict[AssetUniqueKey, Asset]
+        asset_aliases: dict[AssetAliasUniqueKey, AssetAlias]
 
     _inlets: list[Any]
-    _assets: dict[AssetUniqueKey, Asset]
-    _asset_aliases: dict[AssetAliasUniqueKey, AssetAlias]
+    _lookups: _Lookups | None = attrs.field(default=None, init=False, eq=False)
 
-    def __init__(self, inlets: list) -> None:
-        self._inlets = inlets
-        self._assets = {}
-        self._asset_aliases = {}
+    def build_lookups(self) -> InletEventsAccessors._Lookups:
+        """Build the lookups if they are not built yet, and return them."""
+        if self._lookups is not None:
+            return self._lookups
 
-        for inlet in inlets:
+        assets: dict[AssetUniqueKey, Asset] = {}
+        asset_aliases: dict[AssetAliasUniqueKey, AssetAlias] = {}
+        for inlet in self._inlets:
             if isinstance(inlet, Asset):
-                self._assets[AssetUniqueKey.from_asset(inlet)] = inlet
+                assets[AssetUniqueKey.from_asset(inlet)] = inlet
             elif isinstance(inlet, AssetAlias):
-                
self._asset_aliases[AssetAliasUniqueKey.from_asset_alias(inlet)] = inlet
+                asset_aliases[AssetAliasUniqueKey.from_asset_alias(inlet)] = 
inlet
             elif isinstance(inlet, AssetNameRef):
                 asset = 
OutletEventAccessors._get_asset_from_db(name=inlet.name)
-                self._assets[AssetUniqueKey.from_asset(asset)] = asset
+                assets[AssetUniqueKey.from_asset(asset)] = asset
             elif isinstance(inlet, AssetUriRef):
                 asset = OutletEventAccessors._get_asset_from_db(uri=inlet.uri)
-                self._assets[AssetUniqueKey.from_asset(asset)] = asset
+                assets[AssetUniqueKey.from_asset(asset)] = asset
+
+        self._lookups = self._Lookups(assets, asset_aliases)
+        return self._lookups
+
+    @property
+    def _assets(self) -> dict[AssetUniqueKey, Asset]:
+        return self.build_lookups().assets
+
+    @property
+    def _asset_aliases(self) -> dict[AssetAliasUniqueKey, AssetAlias]:
+        return self.build_lookups().asset_aliases
 
     def __iter__(self) -> Iterator[Asset | AssetAlias]:
         return iter(self._inlets)
@@ -1699,6 +1738,34 @@ def set_current_context(context: Context) -> 
Generator[Context, None, None]:
             )
 
 
+def build_state_store_stats_tags(ti: RuntimeTaskInstanceProtocol) -> dict[str, 
str]:
+    """
+    Build tags for metrics emitted by a task instance's state store accessors.
+
+    These are the task instance's stats tags plus the operator name, attached 
to
+    ``task_state_store.*`` and ``asset_state_store.*`` metrics.
+
+    :meta private:
+    """
+    return {**ti.stats_tags, "operator": ti.task.task_type}
+
+
+def create_asset_state_store(ti: RuntimeTaskInstanceProtocol) -> 
AssetStateStoreAccessors | None:
+    """
+    Create the asset state store accessors for a task instance's task.
+
+    Return *None* if the task has no asset (or asset reference or alias) in its
+    inlets or outlets. This makes no supervisor calls; the accessors are built
+    when first used, or by the task runner before the task executes.
+
+    :meta private:
+    """
+    all_lets = itertools.chain((inlets := ti.task.inlets), (outlets := 
ti.task.outlets))
+    if not any(isinstance(t, (Asset, AssetNameRef, AssetUriRef, AssetAlias)) 
for t in all_lets):
+        return None
+    return AssetStateStoreAccessors(inlets, outlets, 
stats_tags=build_state_store_stats_tags(ti))
+
+
 def context_update_for_unmapped(context: Context, task: BaseOperator) -> None:
     """
     Update context after task unmapping.
@@ -1707,15 +1774,27 @@ def context_update_for_unmapped(context: Context, task: 
BaseOperator) -> None:
     contains information about the mapped task. We need to do some in-place
     updates to ensure the template context reflects the unmapped task instead.
 
+    This includes the asset accessors, since the operator's ``__init__`` (which
+    only runs on unmapping) may add inlets and outlets. Creating them makes no
+    supervisor calls; they are built later.
+
     :meta private:
     """
     from airflow.sdk.definitions.param import process_params
 
-    context["task"] = context["ti"].task = task
+    context["task"] = (ti := context["ti"]).task = task
     context["params"] = process_params(
         context["dag"], task, context["dag_run"].conf, suppress_exception=False
     )
 
+    context["inlets"] = task.inlets
+    context["outlets"] = task.outlets
+    context["inlet_events"] = InletEventsAccessors(task.inlets)
+    if (asset_state_store := create_asset_state_store(ti)) is None:
+        context.pop("asset_state_store", None)
+    else:
+        context["asset_state_store"] = asset_state_store
+
 
 def context_to_airflow_vars(context: Mapping[str, Any], in_env_var_format: 
bool = False) -> dict[str, str]:
     """
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 4ce2367c001..c1c40180554 100644
--- a/task-sdk/src/airflow/sdk/execution_time/task_runner.py
+++ b/task-sdk/src/airflow/sdk/execution_time/task_runner.py
@@ -144,7 +144,6 @@ from airflow.sdk.execution_time.comms import (
 )
 from airflow.sdk.execution_time.context import (
     _CURRENT_TEAM_NAME_ENV_VAR,
-    AssetStateStoreAccessors,
     ConnectionAccessor,
     InletEventsAccessors,
     MacrosAccessor,
@@ -153,8 +152,10 @@ from airflow.sdk.execution_time.context import (
     TriggeringAssetEventsAccessor,
     VariableAccessor,
     _get_worker_state_store_backend,
+    build_state_store_stats_tags,
     context_get_outlet_events,
     context_to_airflow_vars,
+    create_asset_state_store,
     get_previous_dagrun_success,
     set_current_context,
     set_current_team_name,
@@ -353,7 +354,6 @@ class RuntimeTaskInstance(TaskInstance):
         # Cache the context object, which ensures that all calls to 
get_template_context
         # are operating on the same context object.
         if self._cached_template_context is None:
-            state_store_stats_tags = {**self.stats_tags, "operator": 
self.task.task_type}
             self._cached_template_context = {
                 # From the Task Execution interface
                 "dag": self.task.dag,
@@ -377,7 +377,7 @@ class RuntimeTaskInstance(TaskInstance):
                 "conn": ConnectionAccessor(),
                 "task_state_store": TaskStateStoreAccessor(
                     ti_id=self.id,
-                    stats_tags=state_store_stats_tags,
+                    stats_tags=build_state_store_stats_tags(self),
                     scope=TaskScope(
                         dag_id=self.dag_id,
                         run_id=self.run_id,
@@ -387,14 +387,8 @@ class RuntimeTaskInstance(TaskInstance):
                     ),
                 ),
             }
-            _asset_types = (Asset, AssetNameRef, AssetUriRef, AssetAlias)
-            if any(isinstance(i, _asset_types) for i in self.task.inlets + 
self.task.outlets):
-                self._cached_template_context["asset_state_store"] = 
AssetStateStoreAccessors(
-                    self.task.inlets, self.task.outlets, 
stats_tags=state_store_stats_tags
-                )
-                # AssetAlias inlets are resolved to their concrete assets at 
context build time via
-                # GetAssetsByAlias comms. If an alias maps to no active 
assets, it doesn't contribute to
-                # asset_state. AssetAlias outlets are skipped downstream in 
context.py
+            if (asset_state_store := create_asset_state_store(self)) is not 
None:
+                self._cached_template_context["asset_state_store"] = 
asset_state_store
         if TYPE_CHECKING:
             assert self._cached_template_context is not None
         if from_server:
@@ -1564,6 +1558,12 @@ def _prepare(ti: RuntimeTaskInstance, log: Logger, 
context: Context) -> ToSuperv
     jinja_env = ti.task.dag.get_template_env()
     ti.render_templates(context=context, jinja_env=jinja_env)
 
+    # Build the asset lookups now. This makes sync supervisor calls, which may
+    # deadlock if they are first made from async task code instead.
+    context["inlet_events"].build_lookups()
+    if (asset_state_store := context.get("asset_state_store")) is not None:
+        asset_state_store.build_lookups()
+
     if rendered_fields := _serialize_rendered_fields(ti.task):
         # so that we do not call the API unnecessarily
         
SUPERVISOR_COMMS.send(msg=SetRenderedFields(rendered_fields=rendered_fields))
diff --git a/task-sdk/tests/task_sdk/definitions/test_mappedoperator.py 
b/task-sdk/tests/task_sdk/definitions/test_mappedoperator.py
index d852eb55065..ab893df21e9 100644
--- a/task-sdk/tests/task_sdk/definitions/test_mappedoperator.py
+++ b/task-sdk/tests/task_sdk/definitions/test_mappedoperator.py
@@ -19,6 +19,7 @@ from __future__ import annotations
 
 from collections.abc import Callable
 from datetime import datetime, timedelta
+from types import SimpleNamespace
 from typing import TYPE_CHECKING
 from unittest import mock
 
@@ -29,11 +30,16 @@ from airflow.providers.standard.operators.empty import 
EmptyOperator
 from airflow.sdk import ExceptionRetryPolicy, TaskInstanceState, TriggerRule
 from airflow.sdk.bases.operator import BaseOperator
 from airflow.sdk.bases.xcom import BaseXCom
+from airflow.sdk.definitions.asset import Asset, AssetAlias, AssetRef
 from airflow.sdk.definitions.dag import DAG
 from airflow.sdk.definitions.mappedoperator import MappedOperator
 from airflow.sdk.definitions.xcom_arg import XComArg
 from airflow.sdk.execution_time.comms import (
+    AssetResult,
+    AssetsByAliasResult,
     ErrorResponse,
+    GetAssetByName,
+    GetAssetsByAlias,
     GetTICount,
     GetXCom,
     GetXComSequenceItem,
@@ -44,6 +50,7 @@ from airflow.sdk.execution_time.comms import (
     XComSequenceIndexResult,
     XComSequenceSliceResult,
 )
+from airflow.sdk.execution_time.context import AssetStateStoreAccessor, 
InletEventsAccessor
 
 from tests_common.test_utils.mapping import expand_mapped_task  # noqa: F401
 from tests_common.test_utils.mock_operators import (
@@ -796,6 +803,170 @@ def 
test_operator_mapped_task_group_receives_value(create_runtime_ti, mock_super
     assert results == expected_values
 
 
+class _OperatorWithConstructorLineage(BaseOperator):
+    """Operator that derives inlets and outlets from constructor arguments."""
+
+    def __init__(
+        self, *, inlet: Asset | AssetRef | None = None, outlet: Asset | 
AssetRef | None = None, **kwargs
+    ):
+        super().__init__(**kwargs)
+        if inlet is not None:
+            self.inlets.append(inlet)
+        if outlet is not None:
+            self.outlets.append(outlet)
+
+
+def 
test_mapped_render_template_fields_refreshes_constructor_inlets(create_runtime_ti,
 mock_supervisor_comms):
+    with DAG("test_dag"):
+        mapped = 
_OperatorWithConstructorLineage.partial(task_id="t").expand(inlet=[Asset("a"), 
Asset("b")])
+
+    ti = create_runtime_ti(task=mapped, map_index=1)
+    context = ti.get_template_context()
+    assert context["inlets"] == []
+    assert "asset_state_store" not in context
+
+    ti.task.render_template_fields(context=context)
+
+    assert context["inlets"] == [Asset("b")]
+    assert context["outlets"] == []
+    assert list(context["inlet_events"]) == [Asset("b")]
+    assert context["inlet_events"][Asset("b")] == 
InletEventsAccessor(asset_name="b", asset_uri="b")
+    assert context["asset_state_store"][Asset("b")] == 
AssetStateStoreAccessor(name="b")
+
+
+def test_mapped_render_template_fields_refreshes_constructor_outlets(
+    create_runtime_ti, mock_supervisor_comms
+):
+    with DAG("test_dag"):
+        mapped = 
_OperatorWithConstructorLineage.partial(task_id="t").expand(outlet=[Asset("a"), 
Asset("b")])
+
+    ti = create_runtime_ti(task=mapped, map_index=0)
+    context = ti.get_template_context()
+    assert "asset_state_store" not in context
+
+    ti.task.render_template_fields(context=context)
+
+    assert context["inlets"] == []
+    assert context["outlets"] == [Asset("a")]
+    accessor = context["asset_state_store"][Asset("a")]
+    assert accessor._stats_tags == {**ti.stats_tags, "operator": 
"_OperatorWithConstructorLineage"}
+
+
+def 
test_mapped_render_template_fields_rebinds_asset_context(create_runtime_ti, 
mock_supervisor_comms):
+    with DAG("test_dag"):
+        mapped = MockOperator.partial(task_id="t", inlets=[Asset("a")], 
outlets=[Asset("b")]).expand(
+            arg1=["x", "y"]
+        )
+
+    ti = create_runtime_ti(task=mapped, map_index=0)
+    context = ti.get_template_context()
+    inlet_events = context["inlet_events"]
+    asset_state_store = context["asset_state_store"]
+
+    ti.task.render_template_fields(context=context)
+
+    assert context["inlets"] is ti.task.inlets
+    assert context["outlets"] is ti.task.outlets
+    assert context["inlet_events"] is not inlet_events
+    assert context["asset_state_store"] is not asset_state_store
+
+    ti.task.inlets.append(Asset("c"))
+    assert list(context["inlet_events"]) == [Asset("a"), Asset("c")]
+
+
+class _OperatorDroppingInlets(BaseOperator):
+    def __init__(self, *, arg1=None, **kwargs):
+        super().__init__(**kwargs)
+        self.inlets = []
+
+
+def 
test_mapped_render_template_fields_drops_asset_state_store(create_runtime_ti, 
mock_supervisor_comms):
+    with DAG("test_dag"):
+        mapped = _OperatorDroppingInlets.partial(task_id="t", 
inlets=[Asset("a")]).expand(arg1=["x", "y"])
+
+    ti = create_runtime_ti(task=mapped, map_index=0)
+    context = ti.get_template_context()
+    assert "asset_state_store" in context
+
+    ti.task.render_template_fields(context=context)
+    assert context["inlets"] == []
+    assert "asset_state_store" not in context
+
+
[email protected](
+    "make_mapped",
+    [
+        pytest.param(
+            lambda: MockOperator.partial(task_id="t", 
inlets=[Asset.ref(name="a")]).expand(arg1=["x", "y"]),
+            id="partial",
+        ),
+        pytest.param(
+            lambda: 
_OperatorWithConstructorLineage.partial(task_id="t").expand(
+                inlet=[Asset.ref(name="a"), Asset.ref(name="b")]
+            ),
+            id="constructor",
+        ),
+    ],
+)
+def test_mapped_asset_refs_resolved_once_after_unmapping(
+    make_mapped, create_runtime_ti, mock_supervisor_comms
+):
+    def get_asset_by_name_calls():
+        return [c for c in mock_supervisor_comms.send.call_args_list if 
isinstance(c.args[0], GetAssetByName)]
+
+    mock_supervisor_comms.send.return_value = AssetResult(name="a", uri="a", 
group="asset")
+    with DAG("test_dag"):
+        mapped = make_mapped()
+
+    ti = create_runtime_ti(task=mapped, map_index=0)
+    context = ti.get_template_context()
+    ti.task.render_template_fields(context=context)
+    assert get_asset_by_name_calls() == []
+
+    context["inlet_events"].build_lookups()
+    assert context["inlet_events"][Asset.ref(name="a")] == 
InletEventsAccessor(asset_name="a")
+    assert get_asset_by_name_calls() == [mock.call(GetAssetByName(name="a"))]
+
+
+def test_mapped_asset_aliases_resolved_once_after_unmapping(create_runtime_ti, 
mock_supervisor_comms):
+    def get_assets_by_alias_calls():
+        return [
+            c for c in mock_supervisor_comms.send.call_args_list if 
isinstance(c.args[0], GetAssetsByAlias)
+        ]
+
+    mock_supervisor_comms.send.return_value = AssetsByAliasResult(
+        assets=[AssetResult(name="resolved", uri="resolved", group="asset")]
+    )
+    with DAG("test_dag"):
+        mapped = MockOperator.partial(task_id="t", 
inlets=[AssetAlias(name="alias")]).expand(arg1=["x", "y"])
+
+    ti = create_runtime_ti(task=mapped, map_index=0)
+    context = ti.get_template_context()
+    ti.task.render_template_fields(context=context)
+    assert get_assets_by_alias_calls() == []
+
+    context["asset_state_store"].build_lookups()
+    assert context["asset_state_store"][Asset("resolved")] == 
AssetStateStoreAccessor(name="resolved")
+    assert get_assets_by_alias_calls() == 
[mock.call(GetAssetsByAlias(alias_name="alias"))]
+
+
+def test_mapped_render_template_fields_with_minimal_context():
+    """A task without assets can be rendered with a hand-built context lacking 
runtime-only values."""
+    with DAG("test_dag") as dag:
+        mapped = MockOperator.partial(task_id="t").expand(arg1=["{{ 
ti.map_index }}", "y"])
+
+    context: dict = {
+        "ti": SimpleNamespace(map_index=0),
+        "params": {},
+        "dag": dag,
+        "dag_run": SimpleNamespace(conf={}),
+    }
+    mapped.render_template_fields(context)
+
+    assert context["task"].arg1 == "0"
+    assert "asset_state_store" not in context
+
+
 def test_mapped_xcom_push_skipped_tasks(create_runtime_ti, 
mock_supervisor_comms):
     from airflow.sdk import task_group
 
diff --git a/task-sdk/tests/task_sdk/execution_time/test_context.py 
b/task-sdk/tests/task_sdk/execution_time/test_context.py
index 1e711074c65..db37fd19536 100644
--- a/task-sdk/tests/task_sdk/execution_time/test_context.py
+++ b/task-sdk/tests/task_sdk/execution_time/test_context.py
@@ -96,6 +96,7 @@ from airflow.sdk.execution_time.context import (
     AssetStateStoreAccessor,
     AssetStateStoreAccessors,
     ConnectionAccessor,
+    InletEventsAccessor,
     InletEventsAccessors,
     MacrosAccessor,
     OutletEventAccessor,
@@ -943,9 +944,25 @@ class TestInletEventAccessor:
             AssetResult(name="test_uri", uri="test://test", group="asset"),
         ]
         obj = InletEventsAccessors(inlets=TEST_INLETS)
+        obj.build_lookups()
         mock_supervisor_comms.reset_mock()
         return obj
 
+    def test_build_resolves_refs_once(self, mock_supervisor_comms):
+        mock_supervisor_comms.send.return_value = AssetResult(
+            name="test_uri", uri="test://test", group="asset"
+        )
+        ref = TEST_ASSET_REFS[0]
+
+        accessors = InletEventsAccessors(inlets=[ref])
+        assert list(accessors) == [ref]
+        mock_supervisor_comms.send.assert_not_called()
+
+        accessors.build_lookups()
+        accessors.build_lookups()
+        assert accessors[ref] == InletEventsAccessor(asset_name="test_uri")
+        assert mock_supervisor_comms.send.mock_calls == 
[mock.call(GetAssetByName(name="test_uri"))]
+
     @pytest.mark.usefixtures("mock_supervisor_comms")
     def test__iter__(self, sample_inlet_evnets_accessor):
         for actual, expected in zip(sample_inlet_evnets_accessor, TEST_INLETS):
@@ -2739,7 +2756,10 @@ class TestAssetStateStoreAccessors:
         )
 
         accessors = AssetStateStoreAccessors([alias])
+        mock_supervisor_comms.send.assert_not_called()
 
+        accessors.build_lookups()
+        accessors.build_lookups()
         
mock_supervisor_comms.send.assert_called_once_with(GetAssetsByAlias(alias_name="my_alias"))
         resolved = Asset(name="resolved_asset", uri="s3://bucket/resolved")
         assert resolved.name in accessors._by_name
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 5eebae558b6..109b3a9dff0 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
@@ -128,7 +128,9 @@ from airflow.sdk.execution_time.comms import (
     DeleteTaskStateStore,
     DRCount,
     ErrorResponse,
+    GetAssetByName,
     GetAssetByUri,
+    GetAssetEventByAsset,
     GetAssetsByAlias,
     GetAssetStateStoreByName,
     GetAssetStateStoreByUri,
@@ -2780,6 +2782,81 @@ def test_run_with_asset_inlets(create_runtime_ti, 
mock_supervisor_comms):
         inlet_events[Asset(name="no such asset in inlets")]
 
 
+def test_run_mapped_task_with_constructor_inlets(create_runtime_ti, 
mock_supervisor_comms):
+    """Inlets added by a mapped operator's ``__init__`` are accessible in the 
context during execution."""
+    asset_event_resp = AssetEventResult(
+        id=1,
+        created_dagruns=[],
+        timestamp=timezone.utcnow(),
+        asset=AssetResponse(name="b", uri="b", group="asset"),
+    )
+
+    def _send(msg=None, *args, **kwargs):
+        if isinstance(msg, ValidateInletsAndOutlets):
+            return InactiveAssetsResult(inactive_assets=[])
+        if isinstance(msg, GetAssetEventByAsset):
+            return AssetEventsResult(asset_events=[asset_event_resp])
+        return OKResponse(ok=True)
+
+    mock_supervisor_comms.send.side_effect = _send
+
+    captured = {}
+
+    class InletReaderOperator(BaseOperator):
+        def __init__(self, *, inlet_name: str, **kwargs):
+            super().__init__(**kwargs)
+            self.inlet_name = inlet_name
+            self.inlets.append(Asset(inlet_name))
+
+        def execute(self, context):
+            captured["inlets"] = context["inlets"]
+            captured["events"] = 
list(context["inlet_events"][Asset(self.inlet_name)])
+
+    with DAG("dag_with_mapped_inlet_task"):
+        mapped = 
InletReaderOperator.partial(task_id="t").expand(inlet_name=["a", "b"])
+
+    ti = create_runtime_ti(task=mapped, map_index=1)
+    state, _, error = run(ti, context=ti.get_template_context(), 
log=mock.MagicMock())
+
+    assert error is None
+    assert state == TaskInstanceState.SUCCESS
+    assert captured == {"inlets": [Asset("b")], "events": [asset_event_resp]}
+
+
[email protected](
+    ("inlet", "expected_message"),
+    [
+        pytest.param(Asset.ref(name="a"), GetAssetByName(name="a"), 
id="inlet-events-ref"),
+        pytest.param(AssetAlias(name="alias"), 
GetAssetsByAlias(alias_name="alias"), id="state-store-alias"),
+    ],
+)
+def test_asset_lookups_built_before_execute(
+    inlet, expected_message, create_runtime_ti, mock_supervisor_comms
+):
+    captured = {}
+
+    def get_sent_messages():
+        return [c.args[0] if c.args else c.kwargs["msg"] for c in 
mock_supervisor_comms.send.call_args_list]
+
+    def side_effect(msg=None, *args, **kwargs):
+        if isinstance(msg, ValidateInletsAndOutlets):
+            return InactiveAssetsResult(inactive_assets=[])
+        if isinstance(msg, GetAssetByName):
+            return AssetResult(name=msg.name, uri=msg.name, group="asset")
+        return OKResponse(ok=True)
+
+    class LookupCheckOperator(BaseOperator):
+        def execute(self, context):
+            captured["messages"] = get_sent_messages()
+
+    ti = create_runtime_ti(task=LookupCheckOperator(task_id="t", 
inlets=[inlet]))
+    mock_supervisor_comms.send.side_effect = side_effect
+    state, _, error = run(ti, context=ti.get_template_context(), 
log=mock.MagicMock())
+    assert error is None
+    assert state == TaskInstanceState.SUCCESS
+    assert expected_message in captured["messages"]
+
+
 @mock.patch("airflow.sdk.execution_time.task_runner.context_to_airflow_vars")
 @mock.patch.dict(os.environ, {}, clear=True)
 def test_execute_task_exports_env_vars(

Reply via email to