From 92b532c5b96be64c1228b49c05f10a06539b02c8 Mon Sep 17 00:00:00 2001 From: Hussein Awala Date: Wed, 22 Jul 2026 11:41:23 +0200 Subject: [PATCH 01/21] Add AssetEventSensor to standard provider --- providers/standard/provider.yaml | 2 + .../providers/standard/sensors/asset.py | 208 ++++++++++++++++++ .../providers/standard/triggers/asset.py | 202 +++++++++++++++++ .../tests/unit/standard/sensors/test_asset.py | 170 ++++++++++++++ .../unit/standard/triggers/test_asset.py | 138 ++++++++++++ 5 files changed, 720 insertions(+) create mode 100644 providers/standard/src/airflow/providers/standard/sensors/asset.py create mode 100644 providers/standard/src/airflow/providers/standard/triggers/asset.py create mode 100644 providers/standard/tests/unit/standard/sensors/test_asset.py create mode 100644 providers/standard/tests/unit/standard/triggers/test_asset.py diff --git a/providers/standard/provider.yaml b/providers/standard/provider.yaml index d9d30c4bf003..9aef64aa0283 100644 --- a/providers/standard/provider.yaml +++ b/providers/standard/provider.yaml @@ -104,6 +104,7 @@ operators: sensors: - integration-name: Standard python-modules: + - airflow.providers.standard.sensors.asset - airflow.providers.standard.sensors.date_time - airflow.providers.standard.sensors.time_delta - airflow.providers.standard.sensors.time @@ -122,6 +123,7 @@ hooks: triggers: - integration-name: Standard python-modules: + - airflow.providers.standard.triggers.asset - airflow.providers.standard.triggers.external_task - airflow.providers.standard.triggers.file - airflow.providers.standard.triggers.temporal diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py new file mode 100644 index 000000000000..0a2cff36be4e --- /dev/null +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -0,0 +1,208 @@ +# 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 + +from typing import TYPE_CHECKING, Any + +from airflow.exceptions import AirflowException +from airflow.providers.common.compat.module_loading import import_string +from airflow.providers.common.compat.sdk import ( + Asset, + AssetAlias, + BaseSensorOperator, + PokeReturnValue, + conf, +) +from airflow.providers.standard.triggers.asset import ( + AssetEventTrigger, + _count_satisfied, + _fetch_asset_events, + _serialize_events, +) +from airflow.providers.standard.version_compat import AIRFLOW_V_3_4_PLUS + +if TYPE_CHECKING: + from collections.abc import Callable + from datetime import datetime + + from airflow.providers.common.compat.sdk import Context + + +class AssetEventSensor(BaseSensorOperator): + """ + Wait for asset events matching the given filters to reach an expected count. + + The sensor fetches asset events (by asset or asset alias) matching the supplied filters, + optionally applies a ``process_result`` callable to transform, deduplicate or filter them, + and succeeds once the resulting number of events satisfies ``expected_count``. + + This sensor requires Apache Airflow 3.4+ because the ``partition_key``, + ``partition_key_regexp_pattern`` and ``extra`` asset-event filters are only available there. + + :param asset: The :class:`~airflow.sdk.Asset` or :class:`~airflow.sdk.AssetAlias` to wait on. + As an alternative, pass ``name``/``uri``/``alias_name`` directly. + :param name: The asset name to fetch events for. + :param uri: The asset uri to fetch events for. + :param alias_name: The asset alias name to fetch events for. + :param after: Only include events at or after this timestamp. + :param before: Only include events at or before this timestamp. + :param ascending: Whether events are returned in ascending timestamp order. + :param limit: Maximum number of events to fetch. + :param partition_key: Filter by exact partition key match. + :param partition_key_regexp_pattern: Filter by partition key regexp pattern. + :param extra: Filter by key/value pairs contained in the event ``extra`` field. + :param expected_count: The number of events required to succeed. ``-1`` (the default) means + "at least one"; any other value requires an exact match. + :param process_result: A callable (or a dotted import path to one) applied to the fetched + events before the count check, to transform, deduplicate or filter them. It receives the + list of asset events and must return a list. In ``deferrable`` mode it must be a top-level + importable function (not a lambda or nested function) and its return value must be + JSON-serializable, because it runs in the triggerer and its result is returned via the + trigger event. + :param deferrable: Run the sensor in deferrable mode. + """ + + def __init__( + self, + *, + asset: Asset | AssetAlias | None = None, + name: str | None = None, + uri: str | None = None, + alias_name: str | None = None, + after: datetime | str | None = None, + before: datetime | str | None = None, + ascending: bool = True, + limit: int | None = None, + partition_key: str | None = None, + partition_key_regexp_pattern: str | None = None, + extra: dict[str, str] | None = None, + expected_count: int = -1, + process_result: Callable[[list[Any]], list[Any]] | str | None = None, + deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), + **kwargs, + ) -> None: + super().__init__(**kwargs) + if not AIRFLOW_V_3_4_PLUS: + raise RuntimeError( + "AssetEventSensor requires Apache Airflow 3.4+ because the asset event filters " + "it relies on are only available from 3.4 onwards." + ) + if asset is not None: + if isinstance(asset, AssetAlias): + alias_name = asset.name + elif isinstance(asset, Asset): + name = asset.name + uri = asset.uri + else: + raise TypeError(f"`asset` must be an Asset or AssetAlias, got {type(asset).__name__}") + if not (name or uri or alias_name): + raise ValueError("One of `asset`, `name`, `uri`, or `alias_name` must be provided.") + + self.name = name + self.uri = uri + self.alias_name = alias_name + self.after = after + self.before = before + self.ascending = ascending + self.limit = limit + self.partition_key = partition_key + self.partition_key_regexp_pattern = partition_key_regexp_pattern + self.extra = extra + self.expected_count = expected_count + self.process_result = process_result + self.deferrable = deferrable + + def _apply_process_result(self, events: list[Any]) -> list[Any]: + if self.process_result is None: + return events + func = self.process_result if callable(self.process_result) else import_string(self.process_result) + return func(events) + + def _resolve_process_result_path(self) -> str | None: + """Resolve ``process_result`` to a dotted import path for use in the trigger.""" + if self.process_result is None: + return None + if isinstance(self.process_result, str): + return self.process_result + func = self.process_result + module = getattr(func, "__module__", "") + qualname = getattr(func, "__qualname__", "") + if not module or not qualname or "<" in qualname: + raise ValueError( + "In deferrable mode, `process_result` must be a top-level importable function " + "(or a dotted import path string), not a lambda or a nested/local function." + ) + return f"{module}.{qualname}" + + def poke(self, context: Context) -> PokeReturnValue: + events = _fetch_asset_events( + name=self.name, + uri=self.uri, + alias_name=self.alias_name, + after=self.after, + before=self.before, + ascending=self.ascending, + limit=self.limit, + partition_key=self.partition_key, + partition_key_regexp_pattern=self.partition_key_regexp_pattern, + extra=self.extra, + ) + processed = self._apply_process_result(events) + count = len(processed) + done = _count_satisfied(count, self.expected_count) + self.log.info( + "Found %d matching asset events (expected %s): %s", + count, + self.expected_count, + "condition met" if done else "still waiting", + ) + return PokeReturnValue(is_done=done, xcom_value=_serialize_events(processed) if done else None) + + def execute(self, context: Context) -> Any: + if not self.deferrable: + return super().execute(context=context) + + # Deferrable path: do an initial synchronous check to avoid deferring needlessly. + poke_result = self.poke(context) + if poke_result: + return poke_result.xcom_value if isinstance(poke_result, PokeReturnValue) else None + + self.defer( + trigger=AssetEventTrigger( + name=self.name, + uri=self.uri, + alias_name=self.alias_name, + after=self.after, + before=self.before, + ascending=self.ascending, + limit=self.limit, + partition_key=self.partition_key, + partition_key_regexp_pattern=self.partition_key_regexp_pattern, + extra=self.extra, + expected_count=self.expected_count, + process_result_path=self._resolve_process_result_path(), + poke_interval=self.poke_interval, + ), + method_name="execute_complete", + timeout=self.timeout, + ) + + def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> Any: + """Return the processed events once the trigger fires successfully.""" + if event and event.get("status") == "success": + return event.get("events") + raise AirflowException(f"AssetEventSensor received an unexpected trigger event: {event}") diff --git a/providers/standard/src/airflow/providers/standard/triggers/asset.py b/providers/standard/src/airflow/providers/standard/triggers/asset.py new file mode 100644 index 000000000000..bd7ffd0284d1 --- /dev/null +++ b/providers/standard/src/airflow/providers/standard/triggers/asset.py @@ -0,0 +1,202 @@ +# 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 asyncio +from typing import TYPE_CHECKING, Any + +from asgiref.sync import sync_to_async + +from airflow.providers.common.compat.module_loading import import_string +from airflow.triggers.base import BaseTrigger, TriggerEvent + +if TYPE_CHECKING: + from collections.abc import AsyncIterator + from datetime import datetime + + +def _count_satisfied(count: int, expected_count: int) -> bool: + """ + Return whether the number of (processed) asset events satisfies the expectation. + + ``expected_count == -1`` means "at least one" (``count >= 1``); any other value + requires an exact match (``count == expected_count``). + """ + if expected_count == -1: + return count >= 1 + return count == expected_count + + +def _fetch_asset_events( + *, + name: str | None, + uri: str | None, + alias_name: str | None, + after: datetime | str | None, + before: datetime | str | None, + ascending: bool, + limit: int | None, + partition_key: str | None, + partition_key_regexp_pattern: str | None, + extra: dict[str, str] | None, +) -> list[Any]: + """ + Fetch asset events matching the given filters. + + This uses the Task SDK :class:`InletEventsAccessor`, which lazily fetches events + from the supervisor. It is a blocking call and must be wrapped with + ``sync_to_async`` when used from within the triggerer. + """ + from airflow.sdk.execution_time.context import InletEventsAccessor + + accessor = InletEventsAccessor(asset_name=name, asset_uri=uri, alias_name=alias_name) + if after is not None: + accessor.after(after) # type: ignore[arg-type] + if before is not None: + accessor.before(before) # type: ignore[arg-type] + accessor.ascending(ascending) + if limit is not None: + accessor.limit(limit) + if partition_key is not None: + accessor.partition_key(partition_key) + if partition_key_regexp_pattern is not None: + accessor.partition_key_regexp_pattern(partition_key_regexp_pattern) + if extra: + for key, value in extra.items(): + accessor.extra(key, value) + return list(accessor) + + +def _serialize_events(events: list[Any]) -> list[Any]: + """Serialize a list of (processed) asset events to JSON-safe values.""" + serialized: list[Any] = [] + for event in events: + model_dump = getattr(event, "model_dump", None) + if callable(model_dump): + serialized.append(model_dump(mode="json")) + else: + serialized.append(event) + return serialized + + +class AssetEventTrigger(BaseTrigger): + """ + A trigger that waits until asset events matching the given filters reach an expected count. + + The trigger periodically fetches asset events (by asset name/uri or alias) matching the + supplied filters, optionally applies a ``process_result`` callable to transform, deduplicate + or filter them, and fires once the resulting count satisfies ``expected_count``. + + :param name: The asset name to fetch events for. + :param uri: The asset uri to fetch events for. + :param alias_name: The asset alias name to fetch events for. + :param after: Only include events at or after this timestamp. + :param before: Only include events at or before this timestamp. + :param ascending: Whether events are returned in ascending timestamp order. + :param limit: Maximum number of events to fetch. + :param partition_key: Filter by exact partition key match. + :param partition_key_regexp_pattern: Filter by partition key regexp pattern. + :param extra: Filter by key/value pairs contained in the event ``extra`` field. + :param expected_count: The number of events required to succeed. ``-1`` means at least one. + :param process_result_path: Dotted import path to a callable applied to the fetched events + before the count check. Its return value must be JSON-serializable. + :param poke_interval: Number of seconds to wait between fetches. + """ + + def __init__( + self, + *, + name: str | None = None, + uri: str | None = None, + alias_name: str | None = None, + after: datetime | str | None = None, + before: datetime | str | None = None, + ascending: bool = True, + limit: int | None = None, + partition_key: str | None = None, + partition_key_regexp_pattern: str | None = None, + extra: dict[str, str] | None = None, + expected_count: int = -1, + process_result_path: str | None = None, + poke_interval: float = 60, + ) -> None: + super().__init__() + self.name = name + self.uri = uri + self.alias_name = alias_name + self.after = after + self.before = before + self.ascending = ascending + self.limit = limit + self.partition_key = partition_key + self.partition_key_regexp_pattern = partition_key_regexp_pattern + self.extra = extra + self.expected_count = expected_count + self.process_result_path = process_result_path + self.poke_interval = poke_interval + + def serialize(self) -> tuple[str, dict[str, Any]]: + return ( + "airflow.providers.standard.triggers.asset.AssetEventTrigger", + { + "name": self.name, + "uri": self.uri, + "alias_name": self.alias_name, + "after": self.after, + "before": self.before, + "ascending": self.ascending, + "limit": self.limit, + "partition_key": self.partition_key, + "partition_key_regexp_pattern": self.partition_key_regexp_pattern, + "extra": self.extra, + "expected_count": self.expected_count, + "process_result_path": self.process_result_path, + "poke_interval": self.poke_interval, + }, + ) + + async def run(self) -> AsyncIterator[TriggerEvent]: + process_result = import_string(self.process_result_path) if self.process_result_path else None + while True: + events = await sync_to_async(_fetch_asset_events)( + name=self.name, + uri=self.uri, + alias_name=self.alias_name, + after=self.after, + before=self.before, + ascending=self.ascending, + limit=self.limit, + partition_key=self.partition_key, + partition_key_regexp_pattern=self.partition_key_regexp_pattern, + extra=self.extra, + ) + if process_result is not None: + # ``process_result`` may be an ordinary (non-async) callable, so run it in a + # separate thread to avoid blocking the triggerer event loop. + events = await sync_to_async(process_result, thread_sensitive=False)(events) + count = len(events) + if _count_satisfied(count, self.expected_count): + self.log.info("Found %d matching asset events; firing trigger.", count) + yield TriggerEvent({"status": "success", "events": _serialize_events(events)}) + return + self.log.info( + "Found %d matching asset events, expected %s; sleeping %s seconds.", + count, + self.expected_count, + self.poke_interval, + ) + await asyncio.sleep(self.poke_interval) diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py new file mode 100644 index 000000000000..21247c2ea0b5 --- /dev/null +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -0,0 +1,170 @@ +# 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 + +from typing import Any + +import pytest + +from airflow.exceptions import AirflowException +from airflow.providers.common.compat.sdk import Asset, AssetAlias, PokeReturnValue, TaskDeferred +from airflow.providers.standard.sensors.asset import AssetEventSensor +from airflow.providers.standard.triggers.asset import AssetEventTrigger + +FETCH_PATH = "airflow.providers.standard.sensors.asset._fetch_asset_events" + + +def sample_process_result(events: list[Any]) -> list[Any]: + """A top-level (importable) process_result callable used in deferrable tests.""" + return events + + +def _events(*partition_keys: str) -> list[dict[str, Any]]: + return [{"id": i, "partition_key": pk} for i, pk in enumerate(partition_keys)] + + +class TestAssetEventSensor: + def test_requires_a_target(self): + with pytest.raises(ValueError, match="One of `asset`, `name`, `uri`, or `alias_name`"): + AssetEventSensor(task_id="s") + + def test_target_from_asset(self): + sensor = AssetEventSensor(task_id="s", asset=Asset(name="my_asset", uri="s3://bucket/key")) + assert sensor.name == "my_asset" + assert sensor.uri == "s3://bucket/key" + assert sensor.alias_name is None + + def test_target_from_asset_alias(self): + sensor = AssetEventSensor(task_id="s", asset=AssetAlias(name="my_alias")) + assert sensor.alias_name == "my_alias" + assert sensor.name is None + assert sensor.uri is None + + def test_target_rejects_bad_type(self): + with pytest.raises(TypeError, match="must be an Asset or AssetAlias"): + AssetEventSensor(task_id="s", asset=object()) # type: ignore[arg-type] + + def test_poke_at_least_one(self, mocker): + mocker.patch(FETCH_PATH, return_value=_events("a", "b")) + sensor = AssetEventSensor(task_id="s", name="my_asset") # expected_count=-1 by default + result = sensor.poke({}) + assert isinstance(result, PokeReturnValue) + assert bool(result) is True + assert result.xcom_value == _events("a", "b") + + def test_poke_at_least_one_no_events(self, mocker): + mocker.patch(FETCH_PATH, return_value=[]) + sensor = AssetEventSensor(task_id="s", name="my_asset") + result = sensor.poke({}) + assert bool(result) is False + assert result.xcom_value is None + + @pytest.mark.parametrize( + ("expected_count", "num_events", "done"), + [(2, 2, True), (3, 2, False), (1, 2, False)], + ) + def test_poke_exact_count(self, mocker, expected_count, num_events, done): + mocker.patch(FETCH_PATH, return_value=_events(*[str(i) for i in range(num_events)])) + sensor = AssetEventSensor(task_id="s", name="my_asset", expected_count=expected_count) + assert bool(sensor.poke({})) is done + + def test_poke_applies_process_result_before_count(self, mocker): + mocker.patch(FETCH_PATH, return_value=_events("a", "a", "b")) + + def dedup(events): + seen, out = set(), [] + for event in events: + if event["partition_key"] not in seen: + seen.add(event["partition_key"]) + out.append(event) + return out + + sensor = AssetEventSensor(task_id="s", name="my_asset", expected_count=2, process_result=dedup) + result = sensor.poke({}) + assert bool(result) is True + assert result.xcom_value == [ + {"id": 0, "partition_key": "a"}, + {"id": 2, "partition_key": "b"}, + ] + + def test_poke_process_result_by_import_path(self, mocker): + mocker.patch(FETCH_PATH, return_value=_events("a")) + sensor = AssetEventSensor( + task_id="s", + name="my_asset", + process_result=f"{__name__}.sample_process_result", + ) + assert bool(sensor.poke({})) is True + + def test_execute_deferrable_defers(self, mocker): + mocker.patch(FETCH_PATH, return_value=[]) + sensor = AssetEventSensor( + task_id="s", + name="my_asset", + partition_key_regexp_pattern="da.*", + extra={"k": "v"}, + expected_count=3, + deferrable=True, + ) + with pytest.raises(TaskDeferred) as exc: + sensor.execute({}) + trigger = exc.value.trigger + assert isinstance(trigger, AssetEventTrigger) + assert trigger.name == "my_asset" + assert trigger.expected_count == 3 + assert trigger.partition_key_regexp_pattern == "da.*" + assert trigger.extra == {"k": "v"} + assert trigger.process_result_path is None + + def test_execute_deferrable_short_circuits(self, mocker): + mocker.patch(FETCH_PATH, return_value=_events("a", "b")) + sensor = AssetEventSensor(task_id="s", name="my_asset", deferrable=True) + # Already satisfied on the initial poke, so it should not defer. + assert sensor.execute({}) == _events("a", "b") + + def test_execute_deferrable_passes_process_result_path(self, mocker): + mocker.patch(FETCH_PATH, return_value=[]) + sensor = AssetEventSensor( + task_id="s", + name="my_asset", + process_result=sample_process_result, + deferrable=True, + ) + with pytest.raises(TaskDeferred) as exc: + sensor.execute({}) + assert exc.value.trigger.process_result_path.endswith("test_asset.sample_process_result") + + def test_execute_deferrable_rejects_non_importable_callable(self, mocker): + mocker.patch(FETCH_PATH, return_value=[]) + sensor = AssetEventSensor( + task_id="s", + name="my_asset", + process_result=lambda events: events, + deferrable=True, + ) + with pytest.raises(ValueError, match="top-level importable function"): + sensor.execute({}) + + def test_execute_complete_success(self): + sensor = AssetEventSensor(task_id="s", name="my_asset") + events = _events("a") + assert sensor.execute_complete({}, {"status": "success", "events": events}) == events + + def test_execute_complete_failure(self): + sensor = AssetEventSensor(task_id="s", name="my_asset") + with pytest.raises(AirflowException, match="unexpected trigger event"): + sensor.execute_complete({}, {"status": "boom"}) diff --git a/providers/standard/tests/unit/standard/triggers/test_asset.py b/providers/standard/tests/unit/standard/triggers/test_asset.py new file mode 100644 index 000000000000..5cce41f014a0 --- /dev/null +++ b/providers/standard/tests/unit/standard/triggers/test_asset.py @@ -0,0 +1,138 @@ +# 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 + +from typing import Any +from unittest import mock + +import pytest + +from airflow.providers.standard.triggers.asset import ( + AssetEventTrigger, + _count_satisfied, + _serialize_events, +) +from airflow.triggers.base import TriggerEvent + +FETCH_PATH = "airflow.providers.standard.triggers.asset._fetch_asset_events" + + +def keep_filter(events: list[Any]) -> list[Any]: + """A top-level (importable) process_result callable used in trigger tests.""" + return [event for event in events if event["partition_key"] == "keep"] + + +def _events(*partition_keys: str) -> list[dict[str, Any]]: + return [{"id": i, "partition_key": pk} for i, pk in enumerate(partition_keys)] + + +@pytest.mark.parametrize( + ("count", "expected_count", "result"), + [(0, -1, False), (1, -1, True), (5, -1, True), (2, 2, True), (1, 2, False), (3, 2, False)], +) +def test_count_satisfied(count, expected_count, result): + assert _count_satisfied(count, expected_count) is result + + +def test_serialize_events_uses_model_dump(): + class FakeEvent: + def model_dump(self, mode=None): + return {"dumped": mode} + + assert _serialize_events([FakeEvent(), {"plain": 1}]) == [{"dumped": "json"}, {"plain": 1}] + + +def test_serialize_round_trip(): + trigger = AssetEventTrigger( + name="my_asset", + uri="s3://bucket/key", + partition_key_regexp_pattern="da.*", + extra={"k": "v"}, + expected_count=2, + process_result_path="my.module.func", + poke_interval=30, + ) + classpath, kwargs = trigger.serialize() + assert classpath == "airflow.providers.standard.triggers.asset.AssetEventTrigger" + assert kwargs == { + "name": "my_asset", + "uri": "s3://bucket/key", + "alias_name": None, + "after": None, + "before": None, + "ascending": True, + "limit": None, + "partition_key": None, + "partition_key_regexp_pattern": "da.*", + "extra": {"k": "v"}, + "expected_count": 2, + "process_result_path": "my.module.func", + "poke_interval": 30, + } + # Re-instantiation from the serialized kwargs must work. + AssetEventTrigger(**kwargs) + + +class TestAssetEventTriggerRun: + @pytest.mark.asyncio + async def test_fires_when_count_satisfied(self, mocker): + mocker.patch(FETCH_PATH, return_value=_events("a", "b")) + trigger = AssetEventTrigger(name="my_asset") # expected_count=-1 + event = await trigger.run().__anext__() + assert isinstance(event, TriggerEvent) + assert event.payload == {"status": "success", "events": _events("a", "b")} + + @pytest.mark.asyncio + async def test_sleeps_until_count_satisfied(self, mocker): + mocker.patch(FETCH_PATH, side_effect=[[], _events("a")]) + sleep_mock = mocker.patch("asyncio.sleep", new=mock.AsyncMock()) + trigger = AssetEventTrigger(name="my_asset", poke_interval=5) + event = await trigger.run().__anext__() + assert event.payload["status"] == "success" + assert event.payload["events"] == _events("a") + sleep_mock.assert_awaited_once_with(5) + + @pytest.mark.asyncio + async def test_applies_process_result_before_count(self, mocker): + mocker.patch(FETCH_PATH, return_value=_events("keep", "drop", "keep")) + trigger = AssetEventTrigger( + name="my_asset", + expected_count=2, + process_result_path=f"{__name__}.keep_filter", + ) + event = await trigger.run().__anext__() + assert event.payload["events"] == [ + {"id": 0, "partition_key": "keep"}, + {"id": 2, "partition_key": "keep"}, + ] + + @pytest.mark.asyncio + async def test_process_result_reduces_below_expected_keeps_waiting(self, mocker): + # After process_result there is only 1 "keep", below the expected 2, so it must sleep. + mocker.patch( + FETCH_PATH, + side_effect=[_events("keep", "drop"), _events("keep", "keep", "drop")], + ) + sleep_mock = mocker.patch("asyncio.sleep", new=mock.AsyncMock()) + trigger = AssetEventTrigger( + name="my_asset", + expected_count=2, + process_result_path=f"{__name__}.keep_filter", + ) + event = await trigger.run().__anext__() + assert event.payload["events"] == _events("keep", "keep") + sleep_mock.assert_awaited_once() From bcc3a87d06fc094e06eee9f4fb43d7d9069c7eec Mon Sep 17 00:00:00 2001 From: Hussein Awala Date: Wed, 22 Jul 2026 13:19:03 +0200 Subject: [PATCH 02/21] Scope asset event sensor/trigger tests to Airflow 3.4+ and regenerate provider build files --- .../src/airflow/providers/standard/get_provider_info.py | 2 ++ .../standard/tests/unit/standard/sensors/test_asset.py | 6 ++++++ .../standard/tests/unit/standard/triggers/test_asset.py | 6 ++++++ 3 files changed, 14 insertions(+) diff --git a/providers/standard/src/airflow/providers/standard/get_provider_info.py b/providers/standard/src/airflow/providers/standard/get_provider_info.py index 1f7b2049454d..35f8c2ecb1c8 100644 --- a/providers/standard/src/airflow/providers/standard/get_provider_info.py +++ b/providers/standard/src/airflow/providers/standard/get_provider_info.py @@ -67,6 +67,7 @@ def get_provider_info(): { "integration-name": "Standard", "python-modules": [ + "airflow.providers.standard.sensors.asset", "airflow.providers.standard.sensors.date_time", "airflow.providers.standard.sensors.time_delta", "airflow.providers.standard.sensors.time", @@ -92,6 +93,7 @@ def get_provider_info(): { "integration-name": "Standard", "python-modules": [ + "airflow.providers.standard.triggers.asset", "airflow.providers.standard.triggers.external_task", "airflow.providers.standard.triggers.file", "airflow.providers.standard.triggers.temporal", diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index 21247c2ea0b5..456d8676ec45 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -25,6 +25,12 @@ from airflow.providers.standard.sensors.asset import AssetEventSensor from airflow.providers.standard.triggers.asset import AssetEventTrigger +from tests_common.test_utils.version_compat import AIRFLOW_V_3_4_PLUS + +pytestmark = pytest.mark.skipif( + not AIRFLOW_V_3_4_PLUS, reason="AssetEventSensor requires Airflow 3.4+" +) + FETCH_PATH = "airflow.providers.standard.sensors.asset._fetch_asset_events" diff --git a/providers/standard/tests/unit/standard/triggers/test_asset.py b/providers/standard/tests/unit/standard/triggers/test_asset.py index 5cce41f014a0..81074abd2c23 100644 --- a/providers/standard/tests/unit/standard/triggers/test_asset.py +++ b/providers/standard/tests/unit/standard/triggers/test_asset.py @@ -28,6 +28,12 @@ ) from airflow.triggers.base import TriggerEvent +from tests_common.test_utils.version_compat import AIRFLOW_V_3_4_PLUS + +pytestmark = pytest.mark.skipif( + not AIRFLOW_V_3_4_PLUS, reason="AssetEventTrigger requires Airflow 3.4+" +) + FETCH_PATH = "airflow.providers.standard.triggers.asset._fetch_asset_events" From 9e33649ce7a9af12908f68815493bf0386ef3ac1 Mon Sep 17 00:00:00 2001 From: Hussein Awala Date: Wed, 22 Jul 2026 14:54:28 +0200 Subject: [PATCH 03/21] Address review: dedicated exception, validation, docstring, and tests for AssetEventSensor --- .../airflow/providers/standard/exceptions.py | 8 + .../providers/standard/sensors/asset.py | 68 ++- .../providers/standard/triggers/asset.py | 4 + .../standard/tests/unit/standard/conftest.py | 215 +++++++++ .../tests/unit/standard/sensors/test_asset.py | 413 ++++++++++++++---- .../unit/standard/triggers/test_asset.py | 250 +++++++++-- 6 files changed, 826 insertions(+), 132 deletions(-) create mode 100644 providers/standard/tests/unit/standard/conftest.py diff --git a/providers/standard/src/airflow/providers/standard/exceptions.py b/providers/standard/src/airflow/providers/standard/exceptions.py index df13fd5040b2..b3550f1a2e62 100644 --- a/providers/standard/src/airflow/providers/standard/exceptions.py +++ b/providers/standard/src/airflow/providers/standard/exceptions.py @@ -57,6 +57,14 @@ class DuplicateStateError(AirflowExternalTaskSensorException): """Raised when duplicate states are provided across allowed, skipped and failed states.""" +class AssetEventSensorException(AirflowException): + """Base exception for all AssetEventSensor related errors.""" + + +class UnexpectedAssetEventTriggerEventError(AssetEventSensorException): + """Raised when the AssetEventTrigger returns an unexpected event to the sensor.""" + + class HITLTriggerEventError(Exception): """Raised when TriggerEvent contains error.""" diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index 0a2cff36be4e..393af347f7c4 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -18,7 +18,6 @@ from typing import TYPE_CHECKING, Any -from airflow.exceptions import AirflowException from airflow.providers.common.compat.module_loading import import_string from airflow.providers.common.compat.sdk import ( Asset, @@ -27,6 +26,7 @@ PokeReturnValue, conf, ) +from airflow.providers.standard.exceptions import UnexpectedAssetEventTriggerEventError from airflow.providers.standard.triggers.asset import ( AssetEventTrigger, _count_satisfied, @@ -36,7 +36,7 @@ from airflow.providers.standard.version_compat import AIRFLOW_V_3_4_PLUS if TYPE_CHECKING: - from collections.abc import Callable + from collections.abc import Callable, Sequence from datetime import datetime from airflow.providers.common.compat.sdk import Context @@ -66,16 +66,32 @@ class AssetEventSensor(BaseSensorOperator): :param partition_key_regexp_pattern: Filter by partition key regexp pattern. :param extra: Filter by key/value pairs contained in the event ``extra`` field. :param expected_count: The number of events required to succeed. ``-1`` (the default) means - "at least one"; any other value requires an exact match. + "at least one" (``count >= 1``); ``0`` means "exactly zero"; any other positive value + requires an exact match. Note that if ``limit`` is set below an exact ``expected_count`` + the condition can never be satisfied (the sensor will wait until it times out). :param process_result: A callable (or a dotted import path to one) applied to the fetched events before the count check, to transform, deduplicate or filter them. It receives the list of asset events and must return a list. In ``deferrable`` mode it must be a top-level - importable function (not a lambda or nested function) and its return value must be - JSON-serializable, because it runs in the triggerer and its result is returned via the - trigger event. + importable function (not a lambda, nested function, or bound method) that lives in a module + installed on the triggerer -- a function defined in a DAG file will import on the worker but + typically fail to import in the triggerer process. Its return value must be JSON-serializable, + because it runs in the triggerer and its result is returned via the trigger event. It should + be **idempotent / side-effect free**: in deferrable mode it runs once during the initial + synchronous poke and again on every fetch in the triggerer. :param deferrable: Run the sensor in deferrable mode. """ + template_fields: Sequence[str] = ( + "name", + "uri", + "alias_name", + "partition_key", + "partition_key_regexp_pattern", + "extra", + "after", + "before", + ) + def __init__( self, *, @@ -111,6 +127,10 @@ def __init__( raise TypeError(f"`asset` must be an Asset or AssetAlias, got {type(asset).__name__}") if not (name or uri or alias_name): raise ValueError("One of `asset`, `name`, `uri`, or `alias_name` must be provided.") + if expected_count < -1: + raise ValueError( + f"`expected_count` must be -1 (at least one) or a non-negative integer, got {expected_count}." + ) self.name = name self.uri = uri @@ -137,16 +157,30 @@ def _resolve_process_result_path(self) -> str | None: if self.process_result is None: return None if isinstance(self.process_result, str): - return self.process_result - func = self.process_result - module = getattr(func, "__module__", "") - qualname = getattr(func, "__qualname__", "") - if not module or not qualname or "<" in qualname: + path = self.process_result + else: + func = self.process_result + module = getattr(func, "__module__", "") + qualname = getattr(func, "__qualname__", "") + if not module or not qualname or "<" in qualname: + raise ValueError( + "In deferrable mode, `process_result` must be a top-level importable function " + "(or a dotted import path string), not a lambda or a nested/local function." + ) + path = f"{module}.{qualname}" + # Fail fast at defer time rather than in the triggerer: e.g. a bound method resolves to + # ``module.Class.method`` which ``import_string`` cannot import. This validates importability + # on the *worker*; the callable must also live in a module installed on the triggerer (a + # function defined in a DAG file may import here yet fail there). + try: + import_string(path) + except Exception as exc: raise ValueError( - "In deferrable mode, `process_result` must be a top-level importable function " - "(or a dotted import path string), not a lambda or a nested/local function." - ) - return f"{module}.{qualname}" + "In deferrable mode, `process_result` must be importable by a dotted path, but the " + f"resolved path {path!r} is not importable ({exc}). Pass a top-level function " + "(defined in an installed module, not a DAG file) or an explicit import-path string." + ) from exc + return path def poke(self, context: Context) -> PokeReturnValue: events = _fetch_asset_events( @@ -205,4 +239,6 @@ def execute_complete(self, context: Context, event: dict[str, Any] | None = None """Return the processed events once the trigger fires successfully.""" if event and event.get("status") == "success": return event.get("events") - raise AirflowException(f"AssetEventSensor received an unexpected trigger event: {event}") + raise UnexpectedAssetEventTriggerEventError( + f"AssetEventSensor received an unexpected trigger event: {event}" + ) diff --git a/providers/standard/src/airflow/providers/standard/triggers/asset.py b/providers/standard/src/airflow/providers/standard/triggers/asset.py index bd7ffd0284d1..d523b50cc9b9 100644 --- a/providers/standard/src/airflow/providers/standard/triggers/asset.py +++ b/providers/standard/src/airflow/providers/standard/triggers/asset.py @@ -135,6 +135,10 @@ def __init__( poke_interval: float = 60, ) -> None: super().__init__() + if expected_count < -1: + raise ValueError( + f"`expected_count` must be -1 (at least one) or a non-negative integer, got {expected_count}." + ) self.name = name self.uri = uri self.alias_name = alias_name diff --git a/providers/standard/tests/unit/standard/conftest.py b/providers/standard/tests/unit/standard/conftest.py new file mode 100644 index 000000000000..dbc1d2d453eb --- /dev/null +++ b/providers/standard/tests/unit/standard/conftest.py @@ -0,0 +1,215 @@ +# 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. +""" +Shared fixtures for the database-backed asset sensor/trigger tests. + +The :class:`AssetEventSensor` / :class:`AssetEventTrigger` always fetch through the Task SDK +:class:`~airflow.sdk.execution_time.context.InletEventsAccessor`, which talks to +``SUPERVISOR_COMMS`` (normally a socket to the supervisor, which calls the execution API, which +queries the DB). There is no supervisor in a unit test, so :class:`_DBBackedComms` replaces only +that transport seam: it runs the *real* execution-API SQL against the test metadata DB, so the +partition-key / extra / time-range / limit filters execute for real. ``process_result`` and the +count check then run unmocked on the returned events. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from typing import Any + +import pytest + +ASSET_NAME = "my_asset" +ASSET_URI = "s3://bucket/key" +ALIAS_NAME = "my_alias" + + +def event_timestamp(day: int) -> datetime: + return datetime(2024, 1, day, tzinfo=timezone.utc) + + +class _DBBackedComms: + """A ``SUPERVISOR_COMMS`` stand-in that answers asset-event queries from the metadata DB. + + It mirrors what :class:`~airflow.sdk.execution_time.supervisor.ActivitySubprocess` does for + ``GetAssetEventByAsset`` / ``GetAssetEventByAssetAlias``, but instead of an HTTP round-trip it + calls the execution-API route function directly against a fresh session (so it is safe to use + from the triggerer's worker thread as well). + """ + + def send(self, msg: Any) -> Any: + from airflow.api_fastapi.common.parameters import FilterParam, _RegexParam + from airflow.api_fastapi.execution_api.routes.asset_events import ( + get_asset_event_by_asset_alias, + get_asset_event_by_asset_name_uri, + ) + from airflow.models.asset import AssetEvent + from airflow.sdk.execution_time.comms import ( + AssetEventsResult, + GetAssetEventByAsset, + GetAssetEventByAssetAlias, + ) + from airflow.utils.session import create_session + + def _extra_list(extra: dict[str, str] | None) -> list[str] | None: + return [f"{k}={v}" for k, v in extra.items()] if extra else None + + with create_session() as session: + partition_key = FilterParam(AssetEvent.partition_key, msg.partition_key) + partition_key_regexp = _RegexParam(AssetEvent.partition_key, msg.partition_key_regexp_pattern) + if isinstance(msg, GetAssetEventByAsset): + response = get_asset_event_by_asset_name_uri( + name=msg.name, + uri=msg.uri, + session=session, + partition_key=partition_key, + partition_key_regexp_pattern=partition_key_regexp, + after=msg.after, + before=msg.before, + ascending=msg.ascending, + limit=msg.limit, + extra=_extra_list(msg.extra), + ) + elif isinstance(msg, GetAssetEventByAssetAlias): + response = get_asset_event_by_asset_alias( + name=msg.alias_name, + session=session, + partition_key=partition_key, + partition_key_regexp_pattern=partition_key_regexp, + after=msg.after, + before=msg.before, + ascending=msg.ascending, + limit=msg.limit, + extra=_extra_list(msg.extra), + ) + else: # pragma: no cover - defensive + raise AssertionError(f"unexpected supervisor message: {msg!r}") + return AssetEventsResult.from_asset_events_response(response) + + +@pytest.fixture +def db_supervisor_comms(monkeypatch): + """Route the Task SDK ``SUPERVISOR_COMMS`` to the metadata DB for the duration of a test.""" + from airflow.sdk.execution_time import task_runner + + comms = _DBBackedComms() + monkeypatch.setattr(task_runner, "SUPERVISOR_COMMS", comms, raising=False) + return comms + + +@pytest.fixture +def asset_event_rows(session): + """Create one active asset with five events (varied partition keys / extras / timestamps). + + Layout (ascending by timestamp): + id=1 us|2024-01-01 {"region": "us"} + id=2 us|2024-01-02 {"region": "us"} + id=3 eu|2024-01-01 {"region": "eu"} + id=4 us|2024-01-01 {"region": "us"} # duplicate partition key of id=1 (exercises dedup) + id=5 None {} + Also links every event to an alias named ``my_alias``. + """ + from airflow.models.asset import AssetActive, AssetAliasModel, AssetEvent, AssetModel + + from tests_common.test_utils.db import clear_db_assets + + clear_db_assets() + + asset = AssetModel(id=1, name=ASSET_NAME, uri=ASSET_URI, group="asset", extra={}) + session.add_all([asset, AssetActive.for_asset(asset)]) + session.commit() + + common = { + "asset_id": 1, + "source_dag_id": "producer", + "source_task_id": "emit", + "source_run_id": "run_1", + "source_map_index": -1, + } + events = [ + AssetEvent( + id=1, + timestamp=event_timestamp(1), + partition_key="us|2024-01-01", + extra={"region": "us"}, + **common, + ), + AssetEvent( + id=2, + timestamp=event_timestamp(2), + partition_key="us|2024-01-02", + extra={"region": "us"}, + **common, + ), + AssetEvent( + id=3, + timestamp=event_timestamp(3), + partition_key="eu|2024-01-01", + extra={"region": "eu"}, + **common, + ), + AssetEvent( + id=4, + timestamp=event_timestamp(4), + partition_key="us|2024-01-01", + extra={"region": "us"}, + **common, + ), + AssetEvent(id=5, timestamp=event_timestamp(5), partition_key=None, extra={}, **common), + ] + session.add_all(events) + session.commit() + + alias = AssetAliasModel(id=1, name=ALIAS_NAME) + alias.asset_events = events + alias.assets.append(asset) + session.add(alias) + session.commit() + + yield events + + clear_db_assets() + + +@pytest.fixture +def add_asset_event(session): + """Return a helper that inserts (and commits) an extra asset event for ``asset_id=1``. + + Useful for exercising the trigger's polling loop: insert a new matching event "between" two + fetches (e.g. from a patched ``asyncio.sleep``) and watch the trigger fire. + """ + from airflow.models.asset import AssetEvent + from airflow.utils.session import create_session + + def _add(*, id: int, day: int, partition_key: str | None, extra: dict[str, str] | None = None) -> None: + with create_session() as new_session: + new_session.add( + AssetEvent( + id=id, + timestamp=event_timestamp(day), + partition_key=partition_key, + extra=extra or {}, + asset_id=1, + source_dag_id="producer", + source_task_id="emit", + source_run_id="run_1", + source_map_index=-1, + ) + ) + new_session.commit() + + return _add diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index 456d8676ec45..fe342e567214 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -14,36 +14,77 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +""" +Tests for :class:`AssetEventSensor`. + +Most tests are database-backed (``db_test``): they create real ``AssetEvent`` rows and exercise the +whole fetch path (real ``InletEventsAccessor`` -> DB-backed ``SUPERVISOR_COMMS`` -> real +execution-API SQL), rather than patching ``_fetch_asset_events``. The DB harness lives in the +``conftest.py`` one directory up (``db_supervisor_comms`` / ``asset_event_rows`` fixtures). +""" + from __future__ import annotations +from datetime import datetime, timezone from typing import Any import pytest -from airflow.exceptions import AirflowException from airflow.providers.common.compat.sdk import Asset, AssetAlias, PokeReturnValue, TaskDeferred +from airflow.providers.standard.exceptions import UnexpectedAssetEventTriggerEventError from airflow.providers.standard.sensors.asset import AssetEventSensor from airflow.providers.standard.triggers.asset import AssetEventTrigger +from tests_common.test_utils.config import conf_vars from tests_common.test_utils.version_compat import AIRFLOW_V_3_4_PLUS -pytestmark = pytest.mark.skipif( - not AIRFLOW_V_3_4_PLUS, reason="AssetEventSensor requires Airflow 3.4+" -) +pytestmark = pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="AssetEventSensor requires Airflow 3.4+") FETCH_PATH = "airflow.providers.standard.sensors.asset._fetch_asset_events" +ASSET_NAME = "my_asset" +ASSET_URI = "s3://bucket/key" +ALIAS_NAME = "my_alias" + + +def _ts(day: int) -> datetime: + return datetime(2024, 1, day, tzinfo=timezone.utc) + + +# top-level (importable) process_result callables, so they also work in deferrable mode +def only_us_partitions(events: list[Any]) -> list[Any]: + """Keep only events whose partition key targets the ``us`` region.""" + return [event for event in events if (event.partition_key or "").startswith("us|")] + + +def dedup_by_partition_key(events: list[Any]) -> list[Any]: + """Keep the first event seen for each distinct partition key (order preserved).""" + seen: set[str | None] = set() + out: list[Any] = [] + for event in events: + if event.partition_key in seen: + continue + seen.add(event.partition_key) + out.append(event) + return out -def sample_process_result(events: list[Any]) -> list[Any]: - """A top-level (importable) process_result callable used in deferrable tests.""" - return events +class _Processor: + """A callable holder whose bound method cannot be serialized to an import path.""" -def _events(*partition_keys: str) -> list[dict[str, Any]]: - return [{"id": i, "partition_key": pk} for i, pk in enumerate(partition_keys)] + def run(self, events: list[Any]) -> list[Any]: + return events -class TestAssetEventSensor: +def _partition_keys(result: Any) -> list[str | None]: + """Extract partition keys from a poke result's (serialized) xcom value.""" + assert isinstance(result, PokeReturnValue) + return [event["partition_key"] for event in (result.xcom_value or [])] + + +class TestInit: + """Pure construction/validation logic (no DB access).""" + def test_requires_a_target(self): with pytest.raises(ValueError, match="One of `asset`, `name`, `uri`, or `alias_name`"): AssetEventSensor(task_id="s") @@ -64,113 +105,331 @@ def test_target_rejects_bad_type(self): with pytest.raises(TypeError, match="must be an Asset or AssetAlias"): AssetEventSensor(task_id="s", asset=object()) # type: ignore[arg-type] - def test_poke_at_least_one(self, mocker): - mocker.patch(FETCH_PATH, return_value=_events("a", "b")) - sensor = AssetEventSensor(task_id="s", name="my_asset") # expected_count=-1 by default + def test_rejects_invalid_expected_count(self): + with pytest.raises(ValueError, match="expected_count"): + AssetEventSensor(task_id="s", name=ASSET_NAME, expected_count=-2) + + def test_requires_airflow_3_4(self, mocker): + # The version guard is dead code in CI (the module is skipped below 3.4), so patch the flag. + mocker.patch("airflow.providers.standard.sensors.asset.AIRFLOW_V_3_4_PLUS", False) + with pytest.raises(RuntimeError, match="requires Apache Airflow 3.4"): + AssetEventSensor(task_id="s", name=ASSET_NAME) + + def test_template_fields(self): + assert set(AssetEventSensor.template_fields) >= { + "name", + "uri", + "alias_name", + "partition_key", + "partition_key_regexp_pattern", + "extra", + "after", + "before", + } + + def test_deferrable_default_from_config(self): + # ``deferrable``'s default is bound to ``[operators] default_deferrable`` at import time, so + # the module has to be reloaded under the patched config to observe the new default. + import importlib + + from airflow.providers.standard.sensors import asset as asset_module + + try: + with conf_vars({("operators", "default_deferrable"): "True"}): + importlib.reload(asset_module) + sensor = asset_module.AssetEventSensor(task_id="s", name=ASSET_NAME) + assert sensor.deferrable is True + finally: + importlib.reload(asset_module) # restore the default-config version for other tests + + def test_non_deferrable_execute_delegates_to_base(self, mocker): + base_execute = mocker.patch( + "airflow.providers.standard.sensors.asset.BaseSensorOperator.execute", + return_value="delegated", + ) + sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, deferrable=False) + assert sensor.execute({"k": "v"}) == "delegated" + base_execute.assert_called_once() + + def test_execute_complete_success(self): + sensor = AssetEventSensor(task_id="s", name="my_asset") + events = [{"id": 1, "partition_key": "a"}] + assert sensor.execute_complete({}, {"status": "success", "events": events}) == events + + def test_execute_complete_failure(self): + sensor = AssetEventSensor(task_id="s", name="my_asset") + with pytest.raises(UnexpectedAssetEventTriggerEventError, match="unexpected trigger event"): + sensor.execute_complete({}, {"status": "boom"}) + + def test_execute_complete_none_event(self): + sensor = AssetEventSensor(task_id="s", name="my_asset") + with pytest.raises(UnexpectedAssetEventTriggerEventError, match="unexpected trigger event"): + sensor.execute_complete({}) + + def test_execute_complete_missing_status(self): + sensor = AssetEventSensor(task_id="s", name="my_asset") + with pytest.raises(UnexpectedAssetEventTriggerEventError, match="unexpected trigger event"): + sensor.execute_complete({}, {"events": []}) + + +@pytest.mark.db_test +class TestPoke: + """poke() against real ``AssetEvent`` rows (no patching of the fetch).""" + + def test_returns_all_events(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor(task_id="s", name=ASSET_NAME) # expected_count=-1 (at least one) result = sensor.poke({}) - assert isinstance(result, PokeReturnValue) assert bool(result) is True - assert result.xcom_value == _events("a", "b") + assert _partition_keys(result) == [ + "us|2024-01-01", + "us|2024-01-02", + "eu|2024-01-01", + "us|2024-01-01", + None, + ] - def test_poke_at_least_one_no_events(self, mocker): - mocker.patch(FETCH_PATH, return_value=[]) - sensor = AssetEventSensor(task_id="s", name="my_asset") + def test_no_match_is_not_done(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor(task_id="s", name="does_not_exist") result = sensor.poke({}) assert bool(result) is False assert result.xcom_value is None - @pytest.mark.parametrize( - ("expected_count", "num_events", "done"), - [(2, 2, True), (3, 2, False), (1, 2, False)], - ) - def test_poke_exact_count(self, mocker, expected_count, num_events, done): - mocker.patch(FETCH_PATH, return_value=_events(*[str(i) for i in range(num_events)])) - sensor = AssetEventSensor(task_id="s", name="my_asset", expected_count=expected_count) + def test_exact_partition_key_filter(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, partition_key="us|2024-01-01") + assert _partition_keys(sensor.poke({})) == ["us|2024-01-01", "us|2024-01-01"] + + def test_extra_filter(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, extra={"region": "eu"}) + assert _partition_keys(sensor.poke({})) == ["eu|2024-01-01"] + + def test_time_range_limit_and_descending(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor( + task_id="s", name=ASSET_NAME, after=_ts(2), before=_ts(4), ascending=False, limit=2 + ) + # events in [day2, day4] are ids 2,3,4; descending -> 4,3; limited to 2 + assert _partition_keys(sensor.poke({})) == ["us|2024-01-01", "eu|2024-01-01"] + + @pytest.mark.parametrize(("expected_count", "done"), [(5, True), (4, False), (1, False)]) + def test_exact_expected_count(self, asset_event_rows, db_supervisor_comms, expected_count, done): + sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, expected_count=expected_count) assert bool(sensor.poke({})) is done - def test_poke_applies_process_result_before_count(self, mocker): - mocker.patch(FETCH_PATH, return_value=_events("a", "a", "b")) + def test_by_uri(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor(task_id="s", uri=ASSET_URI) + assert len(sensor.poke({}).xcom_value) == 5 - def dedup(events): - seen, out = set(), [] - for event in events: - if event["partition_key"] not in seen: - seen.add(event["partition_key"]) - out.append(event) - return out + def test_by_alias(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor(task_id="s", asset=AssetAlias(name=ALIAS_NAME)) + assert len(sensor.poke({}).xcom_value) == 5 - sensor = AssetEventSensor(task_id="s", name="my_asset", expected_count=2, process_result=dedup) + def test_expected_count_zero_matches_none(self, asset_event_rows, db_supervisor_comms): + # expected_count=0 means "exactly zero events"; a filter matching nothing satisfies it. + sensor = AssetEventSensor( + task_id="s", name=ASSET_NAME, partition_key="does-not-exist", expected_count=0 + ) result = sensor.poke({}) assert bool(result) is True - assert result.xcom_value == [ - {"id": 0, "partition_key": "a"}, - {"id": 2, "partition_key": "b"}, - ] + assert result.xcom_value == [] + + def test_limit_below_exact_expected_count_never_satisfied(self, asset_event_rows, db_supervisor_comms): + # limit caps the DB result below the exact expected_count, so the condition can never be met. + sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, limit=1, expected_count=3) + assert bool(sensor.poke({})) is False - def test_poke_process_result_by_import_path(self, mocker): - mocker.patch(FETCH_PATH, return_value=_events("a")) + def test_combined_filters(self, asset_event_rows, db_supervisor_comms): + # partition_key AND extra AND time-range together, resolved by real SQL -> only id=1. sensor = AssetEventSensor( task_id="s", - name="my_asset", - process_result=f"{__name__}.sample_process_result", + name=ASSET_NAME, + partition_key="us|2024-01-01", + extra={"region": "us"}, + after=_ts(1), + before=_ts(1), + ) + assert _partition_keys(sensor.poke({})) == ["us|2024-01-01"] + + def test_string_datetime_bounds(self, asset_event_rows, db_supervisor_comms): + # after/before accept ISO strings (coerced to datetime by the comms message model). + sensor = AssetEventSensor( + task_id="s", + name=ASSET_NAME, + after="2024-01-02T00:00:00+00:00", + before="2024-01-03T00:00:00+00:00", + ) + assert _partition_keys(sensor.poke({})) == ["us|2024-01-02", "eu|2024-01-01"] + + +@pytest.mark.db_test +class TestProcessResult: + """process_result (filter / dedup) applied to real DB events before the count check.""" + + def test_filters_out_events(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor( + task_id="s", name=ASSET_NAME, process_result=only_us_partitions, expected_count=3 + ) + result = sensor.poke({}) + assert bool(result) is True + assert _partition_keys(result) == ["us|2024-01-01", "us|2024-01-02", "us|2024-01-01"] + + def test_dedup(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor( + task_id="s", name=ASSET_NAME, process_result=dedup_by_partition_key, expected_count=4 + ) + result = sensor.poke({}) + assert bool(result) is True + assert _partition_keys(result) == ["us|2024-01-01", "us|2024-01-02", "eu|2024-01-01", None] + + def test_by_import_path(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor( + task_id="s", + name=ASSET_NAME, + process_result=f"{__name__}.only_us_partitions", + expected_count=3, ) assert bool(sensor.poke({})) is True - def test_execute_deferrable_defers(self, mocker): - mocker.patch(FETCH_PATH, return_value=[]) + def test_reduces_below_expected(self, asset_event_rows, db_supervisor_comms): + # only 3 "us" events remain after filtering, so an exact expectation of 5 is not met + sensor = AssetEventSensor( + task_id="s", name=ASSET_NAME, process_result=only_us_partitions, expected_count=5 + ) + assert bool(sensor.poke({})) is False + + def test_returns_empty_list_not_done(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, process_result=lambda events: []) + result = sensor.poke({}) # expected_count=-1 -> "at least one" -> not satisfied by [] + assert bool(result) is False + assert result.xcom_value is None + + def test_returns_empty_list_with_expected_zero(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor( + task_id="s", name=ASSET_NAME, process_result=lambda events: [], expected_count=0 + ) + result = sensor.poke({}) + assert bool(result) is True + assert result.xcom_value == [] + + def test_returns_more_events_than_fetched(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor( + task_id="s", name=ASSET_NAME, process_result=lambda events: events + events, expected_count=10 + ) + result = sensor.poke({}) + assert bool(result) is True + assert len(result.xcom_value) == 10 + + def test_exception_propagates(self, asset_event_rows, db_supervisor_comms): + def boom(events): + raise RuntimeError("process_result exploded") + + sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, process_result=boom) + with pytest.raises(RuntimeError, match="process_result exploded"): + sensor.poke({}) + + +@pytest.mark.db_test +class TestDeferrable: + def test_short_circuits_when_already_satisfied(self, asset_event_rows, db_supervisor_comms): + # Initial poke already satisfies expected_count, so execute() returns without deferring. sensor = AssetEventSensor( task_id="s", - name="my_asset", - partition_key_regexp_pattern="da.*", - extra={"k": "v"}, + name=ASSET_NAME, + process_result=only_us_partitions, expected_count=3, deferrable=True, ) + events = sensor.execute({}) + assert [event["partition_key"] for event in events] == [ + "us|2024-01-01", + "us|2024-01-02", + "us|2024-01-01", + ] + + def test_defers_and_forwards_process_result_path(self, asset_event_rows, db_supervisor_comms): + # Ask for more events than exist so the initial poke fails and the sensor defers. + sensor = AssetEventSensor( + task_id="s", + name=ASSET_NAME, + partition_key="us|2024-01-01", + process_result=only_us_partitions, + expected_count=99, + deferrable=True, + ) with pytest.raises(TaskDeferred) as exc: sensor.execute({}) trigger = exc.value.trigger assert isinstance(trigger, AssetEventTrigger) - assert trigger.name == "my_asset" - assert trigger.expected_count == 3 - assert trigger.partition_key_regexp_pattern == "da.*" - assert trigger.extra == {"k": "v"} - assert trigger.process_result_path is None + assert trigger.name == ASSET_NAME + assert trigger.partition_key == "us|2024-01-01" + assert trigger.expected_count == 99 + assert trigger.process_result_path.endswith("test_asset.only_us_partitions") - def test_execute_deferrable_short_circuits(self, mocker): - mocker.patch(FETCH_PATH, return_value=_events("a", "b")) - sensor = AssetEventSensor(task_id="s", name="my_asset", deferrable=True) - # Already satisfied on the initial poke, so it should not defer. - assert sensor.execute({}) == _events("a", "b") + def test_rejects_non_importable_callable(self, asset_event_rows, db_supervisor_comms): + # A lambda cannot be serialized to an import path for the trigger, so deferring must fail. + sensor = AssetEventSensor( + task_id="s", + name=ASSET_NAME, + expected_count=99, # force a defer past the initial poke + process_result=lambda events: events, + deferrable=True, + ) + with pytest.raises(ValueError, match="top-level importable function"): + sensor.execute({}) - def test_execute_deferrable_passes_process_result_path(self, mocker): - mocker.patch(FETCH_PATH, return_value=[]) + def test_rejects_bound_method_callable(self, asset_event_rows, db_supervisor_comms): + # A bound method resolves to ``module.Class.method`` which import_string cannot import; + # this must fail at defer time (not later in the triggerer). sensor = AssetEventSensor( task_id="s", - name="my_asset", - process_result=sample_process_result, + name=ASSET_NAME, + expected_count=99, + process_result=_Processor().run, deferrable=True, ) + with pytest.raises(ValueError, match="not importable"): + sensor.execute({}) + + def test_forwards_poke_interval_to_trigger(self, asset_event_rows, db_supervisor_comms): + sensor = AssetEventSensor( + task_id="s", name=ASSET_NAME, expected_count=99, deferrable=True, poke_interval=42 + ) with pytest.raises(TaskDeferred) as exc: sensor.execute({}) - assert exc.value.trigger.process_result_path.endswith("test_asset.sample_process_result") + assert exc.value.trigger.poke_interval == 42 + + +class TestDeferrableFilterForwarding: + """The regexp filter cannot run on SQLite, so verify filter -> trigger forwarding with a mock. + + This is the one place we still patch the fetch: it lets us assert that *all* filters (including + ``partition_key_regexp_pattern``) are forwarded to the trigger without executing a regexp query + that the local SQLite backend does not support. + """ - def test_execute_deferrable_rejects_non_importable_callable(self, mocker): + def test_forwards_all_filters_to_trigger(self, mocker): mocker.patch(FETCH_PATH, return_value=[]) sensor = AssetEventSensor( task_id="s", - name="my_asset", - process_result=lambda events: events, + name=ASSET_NAME, + uri=ASSET_URI, + after=_ts(1), + before=_ts(9), + ascending=False, + limit=7, + partition_key="us|2024-01-01", + partition_key_regexp_pattern="us.*", + extra={"region": "us"}, + expected_count=3, deferrable=True, ) - with pytest.raises(ValueError, match="top-level importable function"): + with pytest.raises(TaskDeferred) as exc: sensor.execute({}) - - def test_execute_complete_success(self): - sensor = AssetEventSensor(task_id="s", name="my_asset") - events = _events("a") - assert sensor.execute_complete({}, {"status": "success", "events": events}) == events - - def test_execute_complete_failure(self): - sensor = AssetEventSensor(task_id="s", name="my_asset") - with pytest.raises(AirflowException, match="unexpected trigger event"): - sensor.execute_complete({}, {"status": "boom"}) + trigger = exc.value.trigger + assert isinstance(trigger, AssetEventTrigger) + assert (trigger.name, trigger.uri) == (ASSET_NAME, ASSET_URI) + assert (trigger.after, trigger.before) == (_ts(1), _ts(9)) + assert trigger.ascending is False + assert trigger.limit == 7 + assert trigger.partition_key == "us|2024-01-01" + assert trigger.partition_key_regexp_pattern == "us.*" + assert trigger.extra == {"region": "us"} + assert trigger.expected_count == 3 diff --git a/providers/standard/tests/unit/standard/triggers/test_asset.py b/providers/standard/tests/unit/standard/triggers/test_asset.py index 81074abd2c23..fe8b19ca59bb 100644 --- a/providers/standard/tests/unit/standard/triggers/test_asset.py +++ b/providers/standard/tests/unit/standard/triggers/test_asset.py @@ -14,6 +14,15 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +""" +Tests for :class:`AssetEventTrigger`. + +The ``TestRun`` cases are database-backed (``db_test``): the trigger fetches from real +``AssetEvent`` rows via a DB-backed ``SUPERVISOR_COMMS`` (see the ``conftest.py`` one directory up), +imports the ``process_result`` callable by path, applies it, and fires once the count is satisfied. +Only the pure helpers and the serialization contract are tested without a DB. +""" + from __future__ import annotations from typing import Any @@ -21,6 +30,8 @@ import pytest +from airflow.providers.common.compat.sdk import TaskDeferred +from airflow.providers.standard.sensors.asset import AssetEventSensor from airflow.providers.standard.triggers.asset import ( AssetEventTrigger, _count_satisfied, @@ -30,20 +41,51 @@ from tests_common.test_utils.version_compat import AIRFLOW_V_3_4_PLUS -pytestmark = pytest.mark.skipif( - not AIRFLOW_V_3_4_PLUS, reason="AssetEventTrigger requires Airflow 3.4+" -) +pytestmark = pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="AssetEventTrigger requires Airflow 3.4+") + +ASSET_NAME = "my_asset" +ASSET_URI = "s3://bucket/key" +ALIAS_NAME = "my_alias" + + +# top-level (importable) process_result callables +def only_us_partitions(events: list[Any]) -> list[Any]: + """Keep only events whose partition key targets the ``us`` region.""" + return [event for event in events if (event.partition_key or "").startswith("us|")] + + +def dedup_by_partition_key(events: list[Any]) -> list[Any]: + """Keep the first event seen for each distinct partition key (order preserved).""" + seen: set[str | None] = set() + out: list[Any] = [] + for event in events: + if event.partition_key in seen: + continue + seen.add(event.partition_key) + out.append(event) + return out -FETCH_PATH = "airflow.providers.standard.triggers.asset._fetch_asset_events" +def drop_all(events: list[Any]) -> list[Any]: + """A process_result that always yields nothing (keeps the trigger waiting).""" + return [] -def keep_filter(events: list[Any]) -> list[Any]: - """A top-level (importable) process_result callable used in trigger tests.""" - return [event for event in events if event["partition_key"] == "keep"] +def duplicate_all(events: list[Any]) -> list[Any]: + """A process_result that returns more events than it received.""" + return events + events -def _events(*partition_keys: str) -> list[dict[str, Any]]: - return [{"id": i, "partition_key": pk} for i, pk in enumerate(partition_keys)] + +def boom(events: list[Any]) -> list[Any]: + raise RuntimeError("process_result exploded") + + +class _Stop(Exception): + """Sentinel raised from a patched ``asyncio.sleep`` to break the polling loop.""" + + +def _keys(event: TriggerEvent) -> list[str | None]: + return [e["partition_key"] for e in event.payload["events"]] @pytest.mark.parametrize( @@ -93,52 +135,182 @@ def test_serialize_round_trip(): AssetEventTrigger(**kwargs) -class TestAssetEventTriggerRun: +def test_rejects_invalid_expected_count(): + with pytest.raises(ValueError, match="expected_count"): + AssetEventTrigger(name="my_asset", expected_count=-2) + + +def test_serialize_round_trip_with_datetimes(): + from datetime import datetime, timezone + + after = datetime(2024, 1, 1, tzinfo=timezone.utc) + before = datetime(2024, 1, 9, tzinfo=timezone.utc) + trigger = AssetEventTrigger(name="my_asset", after=after, before=before) + _, kwargs = trigger.serialize() + assert kwargs["after"] == after + assert kwargs["before"] == before + reborn = AssetEventTrigger(**kwargs) + assert reborn.after == after + assert reborn.before == before + + +@pytest.mark.db_test +class TestRun: + """run() against real ``AssetEvent`` rows (no patching of the fetch).""" + @pytest.mark.asyncio - async def test_fires_when_count_satisfied(self, mocker): - mocker.patch(FETCH_PATH, return_value=_events("a", "b")) - trigger = AssetEventTrigger(name="my_asset") # expected_count=-1 + async def test_fires_at_least_one(self, asset_event_rows, db_supervisor_comms): + trigger = AssetEventTrigger(name=ASSET_NAME, poke_interval=0.01) # expected_count=-1 event = await trigger.run().__anext__() assert isinstance(event, TriggerEvent) - assert event.payload == {"status": "success", "events": _events("a", "b")} + assert event.payload["status"] == "success" + assert len(event.payload["events"]) == 5 + + @pytest.mark.asyncio + async def test_fires_on_exact_count(self, asset_event_rows, db_supervisor_comms): + trigger = AssetEventTrigger(name=ASSET_NAME, expected_count=5, poke_interval=0.01) + event = await trigger.run().__anext__() + assert len(event.payload["events"]) == 5 + + @pytest.mark.asyncio + async def test_exact_partition_key_filter(self, asset_event_rows, db_supervisor_comms): + trigger = AssetEventTrigger(name=ASSET_NAME, partition_key="us|2024-01-01", poke_interval=0.01) + event = await trigger.run().__anext__() + assert _keys(event) == ["us|2024-01-01", "us|2024-01-01"] + + @pytest.mark.asyncio + async def test_extra_filter(self, asset_event_rows, db_supervisor_comms): + trigger = AssetEventTrigger(name=ASSET_NAME, extra={"region": "eu"}, poke_interval=0.01) + event = await trigger.run().__anext__() + assert _keys(event) == ["eu|2024-01-01"] + + @pytest.mark.asyncio + async def test_by_alias(self, asset_event_rows, db_supervisor_comms): + trigger = AssetEventTrigger(alias_name=ALIAS_NAME, poke_interval=0.01) + event = await trigger.run().__anext__() + assert len(event.payload["events"]) == 5 + + @pytest.mark.asyncio + async def test_applies_process_result_filter(self, asset_event_rows, db_supervisor_comms): + trigger = AssetEventTrigger( + name=ASSET_NAME, + expected_count=3, + process_result_path=f"{__name__}.only_us_partitions", + poke_interval=0.01, + ) + event = await trigger.run().__anext__() + assert _keys(event) == ["us|2024-01-01", "us|2024-01-02", "us|2024-01-01"] + + @pytest.mark.asyncio + async def test_applies_process_result_dedup(self, asset_event_rows, db_supervisor_comms): + trigger = AssetEventTrigger( + name=ASSET_NAME, + expected_count=4, + process_result_path=f"{__name__}.dedup_by_partition_key", + poke_interval=0.01, + ) + event = await trigger.run().__anext__() + assert _keys(event) == ["us|2024-01-01", "us|2024-01-02", "eu|2024-01-01", None] @pytest.mark.asyncio - async def test_sleeps_until_count_satisfied(self, mocker): - mocker.patch(FETCH_PATH, side_effect=[[], _events("a")]) - sleep_mock = mocker.patch("asyncio.sleep", new=mock.AsyncMock()) - trigger = AssetEventTrigger(name="my_asset", poke_interval=5) + async def test_sleeps_until_matching_event_appears( + self, asset_event_rows, db_supervisor_comms, add_asset_event, mocker + ): + # No event matches the filter yet; a new one is inserted "during" the first sleep, after + # which the next fetch finds it and the trigger fires. This exercises the real polling loop. + async def _insert(_seconds): + add_asset_event(id=100, day=9, partition_key="zz|only", extra={"region": "zz"}) + + sleep_mock = mocker.patch("asyncio.sleep", new=mock.AsyncMock(side_effect=_insert)) + trigger = AssetEventTrigger(name=ASSET_NAME, partition_key="zz|only", poke_interval=5) event = await trigger.run().__anext__() assert event.payload["status"] == "success" - assert event.payload["events"] == _events("a") + assert _keys(event) == ["zz|only"] sleep_mock.assert_awaited_once_with(5) @pytest.mark.asyncio - async def test_applies_process_result_before_count(self, mocker): - mocker.patch(FETCH_PATH, return_value=_events("keep", "drop", "keep")) + async def test_process_result_reduces_below_expected_keeps_waiting( + self, asset_event_rows, db_supervisor_comms, add_asset_event, mocker + ): + # only_us -> 3 events initially (< expected 4), so the trigger must sleep; a 4th "us" event + # is inserted during that sleep, after which the trigger fires. + async def _insert(_seconds): + add_asset_event(id=101, day=9, partition_key="us|2024-01-09", extra={"region": "us"}) + + sleep_mock = mocker.patch("asyncio.sleep", new=mock.AsyncMock(side_effect=_insert)) trigger = AssetEventTrigger( - name="my_asset", - expected_count=2, - process_result_path=f"{__name__}.keep_filter", + name=ASSET_NAME, + expected_count=4, + process_result_path=f"{__name__}.only_us_partitions", + poke_interval=5, ) event = await trigger.run().__anext__() - assert event.payload["events"] == [ - {"id": 0, "partition_key": "keep"}, - {"id": 2, "partition_key": "keep"}, - ] + assert len(event.payload["events"]) == 4 + assert all((k or "").startswith("us|") for k in _keys(event)) + sleep_mock.assert_awaited_once_with(5) @pytest.mark.asyncio - async def test_process_result_reduces_below_expected_keeps_waiting(self, mocker): - # After process_result there is only 1 "keep", below the expected 2, so it must sleep. - mocker.patch( - FETCH_PATH, - side_effect=[_events("keep", "drop"), _events("keep", "keep", "drop")], + async def test_callable_serialized_by_sensor_runs_in_trigger(self, asset_event_rows, db_supervisor_comms): + # End-to-end: pass a *real callable* to the sensor. The sensor's serialization util turns it + # into a dotted path and hands it to the trigger; we then run the exact trigger the sensor + # built and confirm the trigger imports and executes that callable against the DB. + sensor = AssetEventSensor( + task_id="s", + name=ASSET_NAME, + process_result=only_us_partitions, # a real function object, not an import path + expected_count=99, # force the initial poke to fail so the sensor defers + deferrable=True, ) - sleep_mock = mocker.patch("asyncio.sleep", new=mock.AsyncMock()) + with pytest.raises(TaskDeferred) as exc: + sensor.execute({}) + trigger = exc.value.trigger + assert isinstance(trigger, AssetEventTrigger) + assert trigger.process_result_path.endswith("test_asset.only_us_partitions") + + # Relax the (deliberately unreachable) expectation so the same trigger can fire, then run it. + trigger.expected_count = 3 + trigger.poke_interval = 0.01 + event = await trigger.run().__anext__() + assert event.payload["status"] == "success" + assert _keys(event) == ["us|2024-01-01", "us|2024-01-02", "us|2024-01-01"] + + @pytest.mark.asyncio + async def test_empty_extra_is_no_filter(self, asset_event_rows, db_supervisor_comms): + # An empty ``extra`` dict must be treated as "no filter", not as an impossible match. + trigger = AssetEventTrigger(name=ASSET_NAME, extra={}, poke_interval=0.01) + event = await trigger.run().__anext__() + assert len(event.payload["events"]) == 5 + + @pytest.mark.asyncio + async def test_process_result_returns_more_events(self, asset_event_rows, db_supervisor_comms): trigger = AssetEventTrigger( - name="my_asset", - expected_count=2, - process_result_path=f"{__name__}.keep_filter", + name=ASSET_NAME, + expected_count=10, + process_result_path=f"{__name__}.duplicate_all", + poke_interval=0.01, ) event = await trigger.run().__anext__() - assert event.payload["events"] == _events("keep", "keep") - sleep_mock.assert_awaited_once() + assert len(event.payload["events"]) == 10 + + @pytest.mark.asyncio + async def test_process_result_exception_propagates(self, asset_event_rows, db_supervisor_comms): + trigger = AssetEventTrigger( + name=ASSET_NAME, process_result_path=f"{__name__}.boom", poke_interval=0.01 + ) + with pytest.raises(RuntimeError, match="process_result exploded"): + await trigger.run().__anext__() + + @pytest.mark.asyncio + async def test_empty_process_result_keeps_waiting(self, asset_event_rows, db_supervisor_comms, mocker): + # process_result drops everything -> count never satisfied -> the trigger must sleep. + # A patched sleep raises to break the otherwise-infinite polling loop after one iteration. + async def _stop(_seconds): + raise _Stop() + + sleep_mock = mocker.patch("asyncio.sleep", new=mock.AsyncMock(side_effect=_stop)) + trigger = AssetEventTrigger( + name=ASSET_NAME, process_result_path=f"{__name__}.drop_all", poke_interval=3 + ) + with pytest.raises(_Stop): + await trigger.run().__anext__() + sleep_mock.assert_awaited_once_with(3) From d5cee35e863e30657c55d356065508f115505d16 Mon Sep 17 00:00:00 2001 From: Hussein Awala Date: Wed, 22 Jul 2026 15:15:31 +0200 Subject: [PATCH 04/21] Coerce datetime after/before to ISO strings, drop type: ignore (Copilot review) --- .../standard/src/airflow/providers/standard/triggers/asset.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/providers/standard/src/airflow/providers/standard/triggers/asset.py b/providers/standard/src/airflow/providers/standard/triggers/asset.py index d523b50cc9b9..d8899e56293e 100644 --- a/providers/standard/src/airflow/providers/standard/triggers/asset.py +++ b/providers/standard/src/airflow/providers/standard/triggers/asset.py @@ -65,9 +65,9 @@ def _fetch_asset_events( accessor = InletEventsAccessor(asset_name=name, asset_uri=uri, alias_name=alias_name) if after is not None: - accessor.after(after) # type: ignore[arg-type] + accessor.after(after if isinstance(after, str) else after.isoformat()) if before is not None: - accessor.before(before) # type: ignore[arg-type] + accessor.before(before if isinstance(before, str) else before.isoformat()) accessor.ascending(ascending) if limit is not None: accessor.limit(limit) From 57d9e127acddbe3e29ba51c0d97bf3884917aada Mon Sep 17 00:00:00 2001 From: Hussein Awala Date: Wed, 22 Jul 2026 15:41:24 +0200 Subject: [PATCH 05/21] Add AssetEventSensor howto docs and example DAG --- providers/standard/docs/sensors/asset.rst | 87 +++++++++++++++++++ providers/standard/provider.yaml | 1 + .../example_dags/example_asset_sensor.py | 78 +++++++++++++++++ .../providers/standard/get_provider_info.py | 1 + 4 files changed, 167 insertions(+) create mode 100644 providers/standard/docs/sensors/asset.rst create mode 100644 providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst new file mode 100644 index 000000000000..dcdc4d3d406a --- /dev/null +++ b/providers/standard/docs/sensors/asset.rst @@ -0,0 +1,87 @@ + .. 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. + + + +.. _howto/sensor:AssetEventSensor: + +AssetEventSensor +================ + +Use the :class:`~airflow.providers.standard.sensors.asset.AssetEventSensor` to wait for +:ref:`asset events ` matching a set of filters to reach an expected count. + +.. note:: + + This sensor requires **Apache Airflow 3.4+**, because the ``partition_key``, + ``partition_key_regexp_pattern`` and ``extra`` asset-event filters it relies on are only + available from 3.4 onwards. + +Basic usage +----------- + +Point the sensor at an :class:`~airflow.sdk.Asset` (or :class:`~airflow.sdk.AssetAlias`, or the raw +``name`` / ``uri`` / ``alias_name``). By default the sensor succeeds once **at least one** matching +event exists. + +.. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py + :language: python + :dedent: 4 + :start-after: [START example_asset_event_sensor] + :end-before: [END example_asset_event_sensor] + +Filtering events and expected count +----------------------------------- + +Events can be narrowed with ``after`` / ``before`` (time range), ``ascending`` / ``limit`` +(ordering and cap), ``partition_key`` / ``partition_key_regexp_pattern`` and ``extra`` (key/value +pairs contained in the event ``extra`` field). Use ``expected_count`` to control how many +(processed) events are required to succeed: ``-1`` (the default) means "at least one", ``0`` means +"exactly zero", and any other positive value requires an exact match. + +.. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py + :language: python + :dedent: 4 + :start-after: [START example_asset_event_sensor_filtered] + :end-before: [END example_asset_event_sensor_filtered] + +Post-processing results +----------------------- + +Pass a ``process_result`` callable (or a dotted import path to one) to transform, deduplicate or +filter the fetched events **before** the count check. It receives the list of asset events and must +return a list; the processed events are pushed to XCom. + +.. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py + :language: python + :dedent: 0 + :start-after: [START example_asset_event_process_result] + :end-before: [END example_asset_event_process_result] + +Deferrable mode +--------------- + +Set ``deferrable=True`` to run the sensor in :ref:`deferrable mode `. In this +mode ``process_result`` runs in the triggerer, so it must be a **top-level importable function** +(defined in an installed module, not a lambda, nested function, or bound method) and its return +value must be JSON-serializable. + +.. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py + :language: python + :dedent: 4 + :start-after: [START example_asset_event_sensor_async] + :end-before: [END example_asset_event_sensor_async] diff --git a/providers/standard/provider.yaml b/providers/standard/provider.yaml index 9aef64aa0283..38524449e590 100644 --- a/providers/standard/provider.yaml +++ b/providers/standard/provider.yaml @@ -87,6 +87,7 @@ integrations: - /docs/apache-airflow-providers-standard/sensors/datetime.rst - /docs/apache-airflow-providers-standard/sensors/file.rst - /docs/apache-airflow-providers-standard/sensors/external_task_sensor.rst + - /docs/apache-airflow-providers-standard/sensors/asset.rst operators: - integration-name: Standard diff --git a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py new file mode 100644 index 000000000000..175c9266d8f8 --- /dev/null +++ b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py @@ -0,0 +1,78 @@ +# 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. +"""Example DAG demonstrating the usage of the ``AssetEventSensor``.""" + +from __future__ import annotations + +from typing import Any + +from airflow.providers.common.compat.sdk import AirflowOptionalProviderFeatureException +from airflow.providers.standard.version_compat import AIRFLOW_V_3_4_PLUS + +if not AIRFLOW_V_3_4_PLUS: + raise AirflowOptionalProviderFeatureException("AssetEventSensor needs Airflow 3.4+.") + +import pendulum + +from airflow.providers.standard.sensors.asset import AssetEventSensor +from airflow.sdk import DAG, Asset + +my_asset = Asset("s3://bucket/my-file.csv") + + +# [START example_asset_event_process_result] +def latest_event_only(events: list[Any]) -> list[Any]: + """Keep only the most recent event (must be a top-level importable function in deferrable mode).""" + return events[-1:] + + +# [END example_asset_event_process_result] + + +with DAG( + dag_id="example_asset_sensor", + schedule=None, + start_date=pendulum.datetime(2021, 1, 1, tz="UTC"), + catchup=False, + tags=["example"], +) as dag: + # [START example_asset_event_sensor] + wait_for_asset_event = AssetEventSensor( + task_id="wait_for_asset_event", + asset=my_asset, + ) + # [END example_asset_event_sensor] + + # [START example_asset_event_sensor_filtered] + wait_for_partition_events = AssetEventSensor( + task_id="wait_for_partition_events", + asset=my_asset, + partition_key="2021-01-01", + expected_count=3, + ) + # [END example_asset_event_sensor_filtered] + + # [START example_asset_event_sensor_async] + wait_for_asset_event_async = AssetEventSensor( + task_id="wait_for_asset_event_async", + asset=my_asset, + process_result=latest_event_only, + deferrable=True, + ) + # [END example_asset_event_sensor_async] + + [wait_for_asset_event, wait_for_partition_events, wait_for_asset_event_async] diff --git a/providers/standard/src/airflow/providers/standard/get_provider_info.py b/providers/standard/src/airflow/providers/standard/get_provider_info.py index 35f8c2ecb1c8..13155d14f86e 100644 --- a/providers/standard/src/airflow/providers/standard/get_provider_info.py +++ b/providers/standard/src/airflow/providers/standard/get_provider_info.py @@ -43,6 +43,7 @@ def get_provider_info(): "/docs/apache-airflow-providers-standard/sensors/datetime.rst", "/docs/apache-airflow-providers-standard/sensors/file.rst", "/docs/apache-airflow-providers-standard/sensors/external_task_sensor.rst", + "/docs/apache-airflow-providers-standard/sensors/asset.rst", ], } ], From b00c9b73b7043f7fd40178cf62afdf6026fe24d5 Mon Sep 17 00:00:00 2001 From: Hussein Awala Date: Thu, 23 Jul 2026 18:03:10 +0200 Subject: [PATCH 06/21] Fix docs build: drop unresolved asset ref and reword to fix spellcheck --- providers/standard/docs/sensors/asset.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index dcdc4d3d406a..c2e373cc8075 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -23,13 +23,13 @@ AssetEventSensor ================ Use the :class:`~airflow.providers.standard.sensors.asset.AssetEventSensor` to wait for -:ref:`asset events ` matching a set of filters to reach an expected count. +asset events matching a set of filters to reach an expected count. .. note:: This sensor requires **Apache Airflow 3.4+**, because the ``partition_key``, ``partition_key_regexp_pattern`` and ``extra`` asset-event filters it relies on are only - available from 3.4 onwards. + available in Airflow 3.4 and later. Basic usage ----------- From ebf83d24e9a3929a27ee6a1bc597c0e4c018750a Mon Sep 17 00:00:00 2001 From: Hussein Awala Date: Sun, 16 Aug 2026 20:49:52 +0200 Subject: [PATCH 07/21] Drop deferrable support from AssetEventSensor The execution API calls backing asset event fetching (GetAssetEventByAsset and GetAssetEventByAssetAlias) are not available in the triggerer, so the deferrable path could not work in practice. Ship the synchronous sensor only; deferrable support can follow once the triggerer can fetch asset events and InletEventsAccessor exposes a native async interface. Removes AssetEventTrigger and its tests, folds the shared fetch/count/ serialize helpers into the sensor module, and drops the now-unused asset sensor exceptions. --- providers/standard/docs/sensors/asset.rst | 15 +- providers/standard/provider.yaml | 1 - .../example_dags/example_asset_sensor.py | 13 +- .../airflow/providers/standard/exceptions.py | 8 - .../providers/standard/get_provider_info.py | 1 - .../providers/standard/sensors/asset.py | 153 ++++----- .../providers/standard/triggers/asset.py | 206 ------------ .../standard/tests/unit/standard/conftest.py | 34 +- .../tests/unit/standard/sensors/test_asset.py | 166 ++------- .../unit/standard/triggers/test_asset.py | 316 ------------------ 10 files changed, 99 insertions(+), 814 deletions(-) delete mode 100644 providers/standard/src/airflow/providers/standard/triggers/asset.py delete mode 100644 providers/standard/tests/unit/standard/triggers/test_asset.py diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index c2e373cc8075..90b4d0658f0c 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -64,7 +64,8 @@ Post-processing results Pass a ``process_result`` callable (or a dotted import path to one) to transform, deduplicate or filter the fetched events **before** the count check. It receives the list of asset events and must -return a list; the processed events are pushed to XCom. +return a list; the processed events are pushed to XCom. It runs on every poke, so it should be +idempotent and free of side effects. .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python @@ -72,16 +73,8 @@ return a list; the processed events are pushed to XCom. :start-after: [START example_asset_event_process_result] :end-before: [END example_asset_event_process_result] -Deferrable mode ---------------- - -Set ``deferrable=True`` to run the sensor in :ref:`deferrable mode `. In this -mode ``process_result`` runs in the triggerer, so it must be a **top-level importable function** -(defined in an installed module, not a lambda, nested function, or bound method) and its return -value must be JSON-serializable. - .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python :dedent: 4 - :start-after: [START example_asset_event_sensor_async] - :end-before: [END example_asset_event_sensor_async] + :start-after: [START example_asset_event_sensor_process_result] + :end-before: [END example_asset_event_sensor_process_result] diff --git a/providers/standard/provider.yaml b/providers/standard/provider.yaml index 38524449e590..baee32f706a8 100644 --- a/providers/standard/provider.yaml +++ b/providers/standard/provider.yaml @@ -124,7 +124,6 @@ hooks: triggers: - integration-name: Standard python-modules: - - airflow.providers.standard.triggers.asset - airflow.providers.standard.triggers.external_task - airflow.providers.standard.triggers.file - airflow.providers.standard.triggers.temporal diff --git a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py index 175c9266d8f8..b140b36fabc8 100644 --- a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py +++ b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py @@ -36,7 +36,7 @@ # [START example_asset_event_process_result] def latest_event_only(events: list[Any]) -> list[Any]: - """Keep only the most recent event (must be a top-level importable function in deferrable mode).""" + """Keep only the most recent event.""" return events[-1:] @@ -66,13 +66,12 @@ def latest_event_only(events: list[Any]) -> list[Any]: ) # [END example_asset_event_sensor_filtered] - # [START example_asset_event_sensor_async] - wait_for_asset_event_async = AssetEventSensor( - task_id="wait_for_asset_event_async", + # [START example_asset_event_sensor_process_result] + wait_for_latest_asset_event = AssetEventSensor( + task_id="wait_for_latest_asset_event", asset=my_asset, process_result=latest_event_only, - deferrable=True, ) - # [END example_asset_event_sensor_async] + # [END example_asset_event_sensor_process_result] - [wait_for_asset_event, wait_for_partition_events, wait_for_asset_event_async] + [wait_for_asset_event, wait_for_partition_events, wait_for_latest_asset_event] diff --git a/providers/standard/src/airflow/providers/standard/exceptions.py b/providers/standard/src/airflow/providers/standard/exceptions.py index b3550f1a2e62..df13fd5040b2 100644 --- a/providers/standard/src/airflow/providers/standard/exceptions.py +++ b/providers/standard/src/airflow/providers/standard/exceptions.py @@ -57,14 +57,6 @@ class DuplicateStateError(AirflowExternalTaskSensorException): """Raised when duplicate states are provided across allowed, skipped and failed states.""" -class AssetEventSensorException(AirflowException): - """Base exception for all AssetEventSensor related errors.""" - - -class UnexpectedAssetEventTriggerEventError(AssetEventSensorException): - """Raised when the AssetEventTrigger returns an unexpected event to the sensor.""" - - class HITLTriggerEventError(Exception): """Raised when TriggerEvent contains error.""" diff --git a/providers/standard/src/airflow/providers/standard/get_provider_info.py b/providers/standard/src/airflow/providers/standard/get_provider_info.py index 13155d14f86e..b0980f9ad4fe 100644 --- a/providers/standard/src/airflow/providers/standard/get_provider_info.py +++ b/providers/standard/src/airflow/providers/standard/get_provider_info.py @@ -94,7 +94,6 @@ def get_provider_info(): { "integration-name": "Standard", "python-modules": [ - "airflow.providers.standard.triggers.asset", "airflow.providers.standard.triggers.external_task", "airflow.providers.standard.triggers.file", "airflow.providers.standard.triggers.temporal", diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index 393af347f7c4..b2565c8ee252 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -24,14 +24,6 @@ AssetAlias, BaseSensorOperator, PokeReturnValue, - conf, -) -from airflow.providers.standard.exceptions import UnexpectedAssetEventTriggerEventError -from airflow.providers.standard.triggers.asset import ( - AssetEventTrigger, - _count_satisfied, - _fetch_asset_events, - _serialize_events, ) from airflow.providers.standard.version_compat import AIRFLOW_V_3_4_PLUS @@ -42,6 +34,69 @@ from airflow.providers.common.compat.sdk import Context +def _count_satisfied(count: int, expected_count: int) -> bool: + """ + Return whether the number of (processed) asset events satisfies the expectation. + + ``expected_count == -1`` means "at least one" (``count >= 1``); any other value + requires an exact match (``count == expected_count``). + """ + if expected_count == -1: + return count >= 1 + return count == expected_count + + +def _fetch_asset_events( + *, + name: str | None, + uri: str | None, + alias_name: str | None, + after: datetime | str | None, + before: datetime | str | None, + ascending: bool, + limit: int | None, + partition_key: str | None, + partition_key_regexp_pattern: str | None, + extra: dict[str, str] | None, +) -> list[Any]: + """ + Fetch asset events matching the given filters. + + This uses the Task SDK :class:`InletEventsAccessor`, which lazily fetches events from + the supervisor, so it can only run where the execution API is available (i.e. on a worker). + """ + from airflow.sdk.execution_time.context import InletEventsAccessor + + accessor = InletEventsAccessor(asset_name=name, asset_uri=uri, alias_name=alias_name) + if after is not None: + accessor.after(after if isinstance(after, str) else after.isoformat()) + if before is not None: + accessor.before(before if isinstance(before, str) else before.isoformat()) + accessor.ascending(ascending) + if limit is not None: + accessor.limit(limit) + if partition_key is not None: + accessor.partition_key(partition_key) + if partition_key_regexp_pattern is not None: + accessor.partition_key_regexp_pattern(partition_key_regexp_pattern) + if extra: + for key, value in extra.items(): + accessor.extra(key, value) + return list(accessor) + + +def _serialize_events(events: list[Any]) -> list[Any]: + """Serialize a list of (processed) asset events to JSON-safe values.""" + serialized: list[Any] = [] + for event in events: + model_dump = getattr(event, "model_dump", None) + if callable(model_dump): + serialized.append(model_dump(mode="json")) + else: + serialized.append(event) + return serialized + + class AssetEventSensor(BaseSensorOperator): """ Wait for asset events matching the given filters to reach an expected count. @@ -71,14 +126,9 @@ class AssetEventSensor(BaseSensorOperator): the condition can never be satisfied (the sensor will wait until it times out). :param process_result: A callable (or a dotted import path to one) applied to the fetched events before the count check, to transform, deduplicate or filter them. It receives the - list of asset events and must return a list. In ``deferrable`` mode it must be a top-level - importable function (not a lambda, nested function, or bound method) that lives in a module - installed on the triggerer -- a function defined in a DAG file will import on the worker but - typically fail to import in the triggerer process. Its return value must be JSON-serializable, - because it runs in the triggerer and its result is returned via the trigger event. It should - be **idempotent / side-effect free**: in deferrable mode it runs once during the initial - synchronous poke and again on every fetch in the triggerer. - :param deferrable: Run the sensor in deferrable mode. + list of asset events and must return a list. It runs on every poke, so it should be + **idempotent / side-effect free**, and its return value must be JSON-serializable to be + pushed to XCom. """ template_fields: Sequence[str] = ( @@ -108,7 +158,6 @@ def __init__( extra: dict[str, str] | None = None, expected_count: int = -1, process_result: Callable[[list[Any]], list[Any]] | str | None = None, - deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), **kwargs, ) -> None: super().__init__(**kwargs) @@ -125,7 +174,7 @@ def __init__( uri = asset.uri else: raise TypeError(f"`asset` must be an Asset or AssetAlias, got {type(asset).__name__}") - if not (name or uri or alias_name): + if name is None and uri is None and alias_name is None: raise ValueError("One of `asset`, `name`, `uri`, or `alias_name` must be provided.") if expected_count < -1: raise ValueError( @@ -144,7 +193,6 @@ def __init__( self.extra = extra self.expected_count = expected_count self.process_result = process_result - self.deferrable = deferrable def _apply_process_result(self, events: list[Any]) -> list[Any]: if self.process_result is None: @@ -152,36 +200,6 @@ def _apply_process_result(self, events: list[Any]) -> list[Any]: func = self.process_result if callable(self.process_result) else import_string(self.process_result) return func(events) - def _resolve_process_result_path(self) -> str | None: - """Resolve ``process_result`` to a dotted import path for use in the trigger.""" - if self.process_result is None: - return None - if isinstance(self.process_result, str): - path = self.process_result - else: - func = self.process_result - module = getattr(func, "__module__", "") - qualname = getattr(func, "__qualname__", "") - if not module or not qualname or "<" in qualname: - raise ValueError( - "In deferrable mode, `process_result` must be a top-level importable function " - "(or a dotted import path string), not a lambda or a nested/local function." - ) - path = f"{module}.{qualname}" - # Fail fast at defer time rather than in the triggerer: e.g. a bound method resolves to - # ``module.Class.method`` which ``import_string`` cannot import. This validates importability - # on the *worker*; the callable must also live in a module installed on the triggerer (a - # function defined in a DAG file may import here yet fail there). - try: - import_string(path) - except Exception as exc: - raise ValueError( - "In deferrable mode, `process_result` must be importable by a dotted path, but the " - f"resolved path {path!r} is not importable ({exc}). Pass a top-level function " - "(defined in an installed module, not a DAG file) or an explicit import-path string." - ) from exc - return path - def poke(self, context: Context) -> PokeReturnValue: events = _fetch_asset_events( name=self.name, @@ -205,40 +223,3 @@ def poke(self, context: Context) -> PokeReturnValue: "condition met" if done else "still waiting", ) return PokeReturnValue(is_done=done, xcom_value=_serialize_events(processed) if done else None) - - def execute(self, context: Context) -> Any: - if not self.deferrable: - return super().execute(context=context) - - # Deferrable path: do an initial synchronous check to avoid deferring needlessly. - poke_result = self.poke(context) - if poke_result: - return poke_result.xcom_value if isinstance(poke_result, PokeReturnValue) else None - - self.defer( - trigger=AssetEventTrigger( - name=self.name, - uri=self.uri, - alias_name=self.alias_name, - after=self.after, - before=self.before, - ascending=self.ascending, - limit=self.limit, - partition_key=self.partition_key, - partition_key_regexp_pattern=self.partition_key_regexp_pattern, - extra=self.extra, - expected_count=self.expected_count, - process_result_path=self._resolve_process_result_path(), - poke_interval=self.poke_interval, - ), - method_name="execute_complete", - timeout=self.timeout, - ) - - def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> Any: - """Return the processed events once the trigger fires successfully.""" - if event and event.get("status") == "success": - return event.get("events") - raise UnexpectedAssetEventTriggerEventError( - f"AssetEventSensor received an unexpected trigger event: {event}" - ) diff --git a/providers/standard/src/airflow/providers/standard/triggers/asset.py b/providers/standard/src/airflow/providers/standard/triggers/asset.py deleted file mode 100644 index d8899e56293e..000000000000 --- a/providers/standard/src/airflow/providers/standard/triggers/asset.py +++ /dev/null @@ -1,206 +0,0 @@ -# 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 asyncio -from typing import TYPE_CHECKING, Any - -from asgiref.sync import sync_to_async - -from airflow.providers.common.compat.module_loading import import_string -from airflow.triggers.base import BaseTrigger, TriggerEvent - -if TYPE_CHECKING: - from collections.abc import AsyncIterator - from datetime import datetime - - -def _count_satisfied(count: int, expected_count: int) -> bool: - """ - Return whether the number of (processed) asset events satisfies the expectation. - - ``expected_count == -1`` means "at least one" (``count >= 1``); any other value - requires an exact match (``count == expected_count``). - """ - if expected_count == -1: - return count >= 1 - return count == expected_count - - -def _fetch_asset_events( - *, - name: str | None, - uri: str | None, - alias_name: str | None, - after: datetime | str | None, - before: datetime | str | None, - ascending: bool, - limit: int | None, - partition_key: str | None, - partition_key_regexp_pattern: str | None, - extra: dict[str, str] | None, -) -> list[Any]: - """ - Fetch asset events matching the given filters. - - This uses the Task SDK :class:`InletEventsAccessor`, which lazily fetches events - from the supervisor. It is a blocking call and must be wrapped with - ``sync_to_async`` when used from within the triggerer. - """ - from airflow.sdk.execution_time.context import InletEventsAccessor - - accessor = InletEventsAccessor(asset_name=name, asset_uri=uri, alias_name=alias_name) - if after is not None: - accessor.after(after if isinstance(after, str) else after.isoformat()) - if before is not None: - accessor.before(before if isinstance(before, str) else before.isoformat()) - accessor.ascending(ascending) - if limit is not None: - accessor.limit(limit) - if partition_key is not None: - accessor.partition_key(partition_key) - if partition_key_regexp_pattern is not None: - accessor.partition_key_regexp_pattern(partition_key_regexp_pattern) - if extra: - for key, value in extra.items(): - accessor.extra(key, value) - return list(accessor) - - -def _serialize_events(events: list[Any]) -> list[Any]: - """Serialize a list of (processed) asset events to JSON-safe values.""" - serialized: list[Any] = [] - for event in events: - model_dump = getattr(event, "model_dump", None) - if callable(model_dump): - serialized.append(model_dump(mode="json")) - else: - serialized.append(event) - return serialized - - -class AssetEventTrigger(BaseTrigger): - """ - A trigger that waits until asset events matching the given filters reach an expected count. - - The trigger periodically fetches asset events (by asset name/uri or alias) matching the - supplied filters, optionally applies a ``process_result`` callable to transform, deduplicate - or filter them, and fires once the resulting count satisfies ``expected_count``. - - :param name: The asset name to fetch events for. - :param uri: The asset uri to fetch events for. - :param alias_name: The asset alias name to fetch events for. - :param after: Only include events at or after this timestamp. - :param before: Only include events at or before this timestamp. - :param ascending: Whether events are returned in ascending timestamp order. - :param limit: Maximum number of events to fetch. - :param partition_key: Filter by exact partition key match. - :param partition_key_regexp_pattern: Filter by partition key regexp pattern. - :param extra: Filter by key/value pairs contained in the event ``extra`` field. - :param expected_count: The number of events required to succeed. ``-1`` means at least one. - :param process_result_path: Dotted import path to a callable applied to the fetched events - before the count check. Its return value must be JSON-serializable. - :param poke_interval: Number of seconds to wait between fetches. - """ - - def __init__( - self, - *, - name: str | None = None, - uri: str | None = None, - alias_name: str | None = None, - after: datetime | str | None = None, - before: datetime | str | None = None, - ascending: bool = True, - limit: int | None = None, - partition_key: str | None = None, - partition_key_regexp_pattern: str | None = None, - extra: dict[str, str] | None = None, - expected_count: int = -1, - process_result_path: str | None = None, - poke_interval: float = 60, - ) -> None: - super().__init__() - if expected_count < -1: - raise ValueError( - f"`expected_count` must be -1 (at least one) or a non-negative integer, got {expected_count}." - ) - self.name = name - self.uri = uri - self.alias_name = alias_name - self.after = after - self.before = before - self.ascending = ascending - self.limit = limit - self.partition_key = partition_key - self.partition_key_regexp_pattern = partition_key_regexp_pattern - self.extra = extra - self.expected_count = expected_count - self.process_result_path = process_result_path - self.poke_interval = poke_interval - - def serialize(self) -> tuple[str, dict[str, Any]]: - return ( - "airflow.providers.standard.triggers.asset.AssetEventTrigger", - { - "name": self.name, - "uri": self.uri, - "alias_name": self.alias_name, - "after": self.after, - "before": self.before, - "ascending": self.ascending, - "limit": self.limit, - "partition_key": self.partition_key, - "partition_key_regexp_pattern": self.partition_key_regexp_pattern, - "extra": self.extra, - "expected_count": self.expected_count, - "process_result_path": self.process_result_path, - "poke_interval": self.poke_interval, - }, - ) - - async def run(self) -> AsyncIterator[TriggerEvent]: - process_result = import_string(self.process_result_path) if self.process_result_path else None - while True: - events = await sync_to_async(_fetch_asset_events)( - name=self.name, - uri=self.uri, - alias_name=self.alias_name, - after=self.after, - before=self.before, - ascending=self.ascending, - limit=self.limit, - partition_key=self.partition_key, - partition_key_regexp_pattern=self.partition_key_regexp_pattern, - extra=self.extra, - ) - if process_result is not None: - # ``process_result`` may be an ordinary (non-async) callable, so run it in a - # separate thread to avoid blocking the triggerer event loop. - events = await sync_to_async(process_result, thread_sensitive=False)(events) - count = len(events) - if _count_satisfied(count, self.expected_count): - self.log.info("Found %d matching asset events; firing trigger.", count) - yield TriggerEvent({"status": "success", "events": _serialize_events(events)}) - return - self.log.info( - "Found %d matching asset events, expected %s; sleeping %s seconds.", - count, - self.expected_count, - self.poke_interval, - ) - await asyncio.sleep(self.poke_interval) diff --git a/providers/standard/tests/unit/standard/conftest.py b/providers/standard/tests/unit/standard/conftest.py index dbc1d2d453eb..6f5d962ac161 100644 --- a/providers/standard/tests/unit/standard/conftest.py +++ b/providers/standard/tests/unit/standard/conftest.py @@ -15,9 +15,9 @@ # specific language governing permissions and limitations # under the License. """ -Shared fixtures for the database-backed asset sensor/trigger tests. +Shared fixtures for the database-backed asset sensor tests. -The :class:`AssetEventSensor` / :class:`AssetEventTrigger` always fetch through the Task SDK +The :class:`AssetEventSensor` always fetches through the Task SDK :class:`~airflow.sdk.execution_time.context.InletEventsAccessor`, which talks to ``SUPERVISOR_COMMS`` (normally a socket to the supervisor, which calls the execution API, which queries the DB). There is no supervisor in a unit test, so :class:`_DBBackedComms` replaces only @@ -183,33 +183,3 @@ def asset_event_rows(session): yield events clear_db_assets() - - -@pytest.fixture -def add_asset_event(session): - """Return a helper that inserts (and commits) an extra asset event for ``asset_id=1``. - - Useful for exercising the trigger's polling loop: insert a new matching event "between" two - fetches (e.g. from a patched ``asyncio.sleep``) and watch the trigger fire. - """ - from airflow.models.asset import AssetEvent - from airflow.utils.session import create_session - - def _add(*, id: int, day: int, partition_key: str | None, extra: dict[str, str] | None = None) -> None: - with create_session() as new_session: - new_session.add( - AssetEvent( - id=id, - timestamp=event_timestamp(day), - partition_key=partition_key, - extra=extra or {}, - asset_id=1, - source_dag_id="producer", - source_task_id="emit", - source_run_id="run_1", - source_map_index=-1, - ) - ) - new_session.commit() - - return _add diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index fe342e567214..ebc8c21ba9a3 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -30,12 +30,9 @@ import pytest -from airflow.providers.common.compat.sdk import Asset, AssetAlias, PokeReturnValue, TaskDeferred -from airflow.providers.standard.exceptions import UnexpectedAssetEventTriggerEventError +from airflow.providers.common.compat.sdk import Asset, AssetAlias, PokeReturnValue from airflow.providers.standard.sensors.asset import AssetEventSensor -from airflow.providers.standard.triggers.asset import AssetEventTrigger -from tests_common.test_utils.config import conf_vars from tests_common.test_utils.version_compat import AIRFLOW_V_3_4_PLUS pytestmark = pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="AssetEventSensor requires Airflow 3.4+") @@ -51,7 +48,6 @@ def _ts(day: int) -> datetime: return datetime(2024, 1, day, tzinfo=timezone.utc) -# top-level (importable) process_result callables, so they also work in deferrable mode def only_us_partitions(events: list[Any]) -> list[Any]: """Keep only events whose partition key targets the ``us`` region.""" return [event for event in events if (event.partition_key or "").startswith("us|")] @@ -69,13 +65,6 @@ def dedup_by_partition_key(events: list[Any]) -> list[Any]: return out -class _Processor: - """A callable holder whose bound method cannot be serialized to an import path.""" - - def run(self, events: list[Any]) -> list[Any]: - return events - - def _partition_keys(result: Any) -> list[str | None]: """Extract partition keys from a poke result's (serialized) xcom value.""" assert isinstance(result, PokeReturnValue) @@ -127,50 +116,6 @@ def test_template_fields(self): "before", } - def test_deferrable_default_from_config(self): - # ``deferrable``'s default is bound to ``[operators] default_deferrable`` at import time, so - # the module has to be reloaded under the patched config to observe the new default. - import importlib - - from airflow.providers.standard.sensors import asset as asset_module - - try: - with conf_vars({("operators", "default_deferrable"): "True"}): - importlib.reload(asset_module) - sensor = asset_module.AssetEventSensor(task_id="s", name=ASSET_NAME) - assert sensor.deferrable is True - finally: - importlib.reload(asset_module) # restore the default-config version for other tests - - def test_non_deferrable_execute_delegates_to_base(self, mocker): - base_execute = mocker.patch( - "airflow.providers.standard.sensors.asset.BaseSensorOperator.execute", - return_value="delegated", - ) - sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, deferrable=False) - assert sensor.execute({"k": "v"}) == "delegated" - base_execute.assert_called_once() - - def test_execute_complete_success(self): - sensor = AssetEventSensor(task_id="s", name="my_asset") - events = [{"id": 1, "partition_key": "a"}] - assert sensor.execute_complete({}, {"status": "success", "events": events}) == events - - def test_execute_complete_failure(self): - sensor = AssetEventSensor(task_id="s", name="my_asset") - with pytest.raises(UnexpectedAssetEventTriggerEventError, match="unexpected trigger event"): - sensor.execute_complete({}, {"status": "boom"}) - - def test_execute_complete_none_event(self): - sensor = AssetEventSensor(task_id="s", name="my_asset") - with pytest.raises(UnexpectedAssetEventTriggerEventError, match="unexpected trigger event"): - sensor.execute_complete({}) - - def test_execute_complete_missing_status(self): - sensor = AssetEventSensor(task_id="s", name="my_asset") - with pytest.raises(UnexpectedAssetEventTriggerEventError, match="unexpected trigger event"): - sensor.execute_complete({}, {"events": []}) - @pytest.mark.db_test class TestPoke: @@ -326,87 +271,16 @@ def boom(events): sensor.poke({}) -@pytest.mark.db_test -class TestDeferrable: - def test_short_circuits_when_already_satisfied(self, asset_event_rows, db_supervisor_comms): - # Initial poke already satisfies expected_count, so execute() returns without deferring. - sensor = AssetEventSensor( - task_id="s", - name=ASSET_NAME, - process_result=only_us_partitions, - expected_count=3, - deferrable=True, - ) - events = sensor.execute({}) - assert [event["partition_key"] for event in events] == [ - "us|2024-01-01", - "us|2024-01-02", - "us|2024-01-01", - ] - - def test_defers_and_forwards_process_result_path(self, asset_event_rows, db_supervisor_comms): - # Ask for more events than exist so the initial poke fails and the sensor defers. - sensor = AssetEventSensor( - task_id="s", - name=ASSET_NAME, - partition_key="us|2024-01-01", - process_result=only_us_partitions, - expected_count=99, - deferrable=True, - ) - with pytest.raises(TaskDeferred) as exc: - sensor.execute({}) - trigger = exc.value.trigger - assert isinstance(trigger, AssetEventTrigger) - assert trigger.name == ASSET_NAME - assert trigger.partition_key == "us|2024-01-01" - assert trigger.expected_count == 99 - assert trigger.process_result_path.endswith("test_asset.only_us_partitions") - - def test_rejects_non_importable_callable(self, asset_event_rows, db_supervisor_comms): - # A lambda cannot be serialized to an import path for the trigger, so deferring must fail. - sensor = AssetEventSensor( - task_id="s", - name=ASSET_NAME, - expected_count=99, # force a defer past the initial poke - process_result=lambda events: events, - deferrable=True, - ) - with pytest.raises(ValueError, match="top-level importable function"): - sensor.execute({}) - - def test_rejects_bound_method_callable(self, asset_event_rows, db_supervisor_comms): - # A bound method resolves to ``module.Class.method`` which import_string cannot import; - # this must fail at defer time (not later in the triggerer). - sensor = AssetEventSensor( - task_id="s", - name=ASSET_NAME, - expected_count=99, - process_result=_Processor().run, - deferrable=True, - ) - with pytest.raises(ValueError, match="not importable"): - sensor.execute({}) - - def test_forwards_poke_interval_to_trigger(self, asset_event_rows, db_supervisor_comms): - sensor = AssetEventSensor( - task_id="s", name=ASSET_NAME, expected_count=99, deferrable=True, poke_interval=42 - ) - with pytest.raises(TaskDeferred) as exc: - sensor.execute({}) - assert exc.value.trigger.poke_interval == 42 - - -class TestDeferrableFilterForwarding: - """The regexp filter cannot run on SQLite, so verify filter -> trigger forwarding with a mock. +class TestFilterForwarding: + """The regexp filter cannot run on SQLite, so verify filter forwarding with a mock. This is the one place we still patch the fetch: it lets us assert that *all* filters (including - ``partition_key_regexp_pattern``) are forwarded to the trigger without executing a regexp query - that the local SQLite backend does not support. + ``partition_key_regexp_pattern``) reach the fetch layer without executing a regexp query that + the local SQLite backend does not support. """ - def test_forwards_all_filters_to_trigger(self, mocker): - mocker.patch(FETCH_PATH, return_value=[]) + def test_forwards_all_filters_to_fetch(self, mocker): + fetch = mocker.patch(FETCH_PATH, return_value=[]) sensor = AssetEventSensor( task_id="s", name=ASSET_NAME, @@ -419,17 +293,17 @@ def test_forwards_all_filters_to_trigger(self, mocker): partition_key_regexp_pattern="us.*", extra={"region": "us"}, expected_count=3, - deferrable=True, ) - with pytest.raises(TaskDeferred) as exc: - sensor.execute({}) - trigger = exc.value.trigger - assert isinstance(trigger, AssetEventTrigger) - assert (trigger.name, trigger.uri) == (ASSET_NAME, ASSET_URI) - assert (trigger.after, trigger.before) == (_ts(1), _ts(9)) - assert trigger.ascending is False - assert trigger.limit == 7 - assert trigger.partition_key == "us|2024-01-01" - assert trigger.partition_key_regexp_pattern == "us.*" - assert trigger.extra == {"region": "us"} - assert trigger.expected_count == 3 + sensor.poke({}) + assert fetch.call_args.kwargs == { + "name": ASSET_NAME, + "uri": ASSET_URI, + "alias_name": None, + "after": _ts(1), + "before": _ts(9), + "ascending": False, + "limit": 7, + "partition_key": "us|2024-01-01", + "partition_key_regexp_pattern": "us.*", + "extra": {"region": "us"}, + } diff --git a/providers/standard/tests/unit/standard/triggers/test_asset.py b/providers/standard/tests/unit/standard/triggers/test_asset.py deleted file mode 100644 index fe8b19ca59bb..000000000000 --- a/providers/standard/tests/unit/standard/triggers/test_asset.py +++ /dev/null @@ -1,316 +0,0 @@ -# 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. -""" -Tests for :class:`AssetEventTrigger`. - -The ``TestRun`` cases are database-backed (``db_test``): the trigger fetches from real -``AssetEvent`` rows via a DB-backed ``SUPERVISOR_COMMS`` (see the ``conftest.py`` one directory up), -imports the ``process_result`` callable by path, applies it, and fires once the count is satisfied. -Only the pure helpers and the serialization contract are tested without a DB. -""" - -from __future__ import annotations - -from typing import Any -from unittest import mock - -import pytest - -from airflow.providers.common.compat.sdk import TaskDeferred -from airflow.providers.standard.sensors.asset import AssetEventSensor -from airflow.providers.standard.triggers.asset import ( - AssetEventTrigger, - _count_satisfied, - _serialize_events, -) -from airflow.triggers.base import TriggerEvent - -from tests_common.test_utils.version_compat import AIRFLOW_V_3_4_PLUS - -pytestmark = pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="AssetEventTrigger requires Airflow 3.4+") - -ASSET_NAME = "my_asset" -ASSET_URI = "s3://bucket/key" -ALIAS_NAME = "my_alias" - - -# top-level (importable) process_result callables -def only_us_partitions(events: list[Any]) -> list[Any]: - """Keep only events whose partition key targets the ``us`` region.""" - return [event for event in events if (event.partition_key or "").startswith("us|")] - - -def dedup_by_partition_key(events: list[Any]) -> list[Any]: - """Keep the first event seen for each distinct partition key (order preserved).""" - seen: set[str | None] = set() - out: list[Any] = [] - for event in events: - if event.partition_key in seen: - continue - seen.add(event.partition_key) - out.append(event) - return out - - -def drop_all(events: list[Any]) -> list[Any]: - """A process_result that always yields nothing (keeps the trigger waiting).""" - return [] - - -def duplicate_all(events: list[Any]) -> list[Any]: - """A process_result that returns more events than it received.""" - return events + events - - -def boom(events: list[Any]) -> list[Any]: - raise RuntimeError("process_result exploded") - - -class _Stop(Exception): - """Sentinel raised from a patched ``asyncio.sleep`` to break the polling loop.""" - - -def _keys(event: TriggerEvent) -> list[str | None]: - return [e["partition_key"] for e in event.payload["events"]] - - -@pytest.mark.parametrize( - ("count", "expected_count", "result"), - [(0, -1, False), (1, -1, True), (5, -1, True), (2, 2, True), (1, 2, False), (3, 2, False)], -) -def test_count_satisfied(count, expected_count, result): - assert _count_satisfied(count, expected_count) is result - - -def test_serialize_events_uses_model_dump(): - class FakeEvent: - def model_dump(self, mode=None): - return {"dumped": mode} - - assert _serialize_events([FakeEvent(), {"plain": 1}]) == [{"dumped": "json"}, {"plain": 1}] - - -def test_serialize_round_trip(): - trigger = AssetEventTrigger( - name="my_asset", - uri="s3://bucket/key", - partition_key_regexp_pattern="da.*", - extra={"k": "v"}, - expected_count=2, - process_result_path="my.module.func", - poke_interval=30, - ) - classpath, kwargs = trigger.serialize() - assert classpath == "airflow.providers.standard.triggers.asset.AssetEventTrigger" - assert kwargs == { - "name": "my_asset", - "uri": "s3://bucket/key", - "alias_name": None, - "after": None, - "before": None, - "ascending": True, - "limit": None, - "partition_key": None, - "partition_key_regexp_pattern": "da.*", - "extra": {"k": "v"}, - "expected_count": 2, - "process_result_path": "my.module.func", - "poke_interval": 30, - } - # Re-instantiation from the serialized kwargs must work. - AssetEventTrigger(**kwargs) - - -def test_rejects_invalid_expected_count(): - with pytest.raises(ValueError, match="expected_count"): - AssetEventTrigger(name="my_asset", expected_count=-2) - - -def test_serialize_round_trip_with_datetimes(): - from datetime import datetime, timezone - - after = datetime(2024, 1, 1, tzinfo=timezone.utc) - before = datetime(2024, 1, 9, tzinfo=timezone.utc) - trigger = AssetEventTrigger(name="my_asset", after=after, before=before) - _, kwargs = trigger.serialize() - assert kwargs["after"] == after - assert kwargs["before"] == before - reborn = AssetEventTrigger(**kwargs) - assert reborn.after == after - assert reborn.before == before - - -@pytest.mark.db_test -class TestRun: - """run() against real ``AssetEvent`` rows (no patching of the fetch).""" - - @pytest.mark.asyncio - async def test_fires_at_least_one(self, asset_event_rows, db_supervisor_comms): - trigger = AssetEventTrigger(name=ASSET_NAME, poke_interval=0.01) # expected_count=-1 - event = await trigger.run().__anext__() - assert isinstance(event, TriggerEvent) - assert event.payload["status"] == "success" - assert len(event.payload["events"]) == 5 - - @pytest.mark.asyncio - async def test_fires_on_exact_count(self, asset_event_rows, db_supervisor_comms): - trigger = AssetEventTrigger(name=ASSET_NAME, expected_count=5, poke_interval=0.01) - event = await trigger.run().__anext__() - assert len(event.payload["events"]) == 5 - - @pytest.mark.asyncio - async def test_exact_partition_key_filter(self, asset_event_rows, db_supervisor_comms): - trigger = AssetEventTrigger(name=ASSET_NAME, partition_key="us|2024-01-01", poke_interval=0.01) - event = await trigger.run().__anext__() - assert _keys(event) == ["us|2024-01-01", "us|2024-01-01"] - - @pytest.mark.asyncio - async def test_extra_filter(self, asset_event_rows, db_supervisor_comms): - trigger = AssetEventTrigger(name=ASSET_NAME, extra={"region": "eu"}, poke_interval=0.01) - event = await trigger.run().__anext__() - assert _keys(event) == ["eu|2024-01-01"] - - @pytest.mark.asyncio - async def test_by_alias(self, asset_event_rows, db_supervisor_comms): - trigger = AssetEventTrigger(alias_name=ALIAS_NAME, poke_interval=0.01) - event = await trigger.run().__anext__() - assert len(event.payload["events"]) == 5 - - @pytest.mark.asyncio - async def test_applies_process_result_filter(self, asset_event_rows, db_supervisor_comms): - trigger = AssetEventTrigger( - name=ASSET_NAME, - expected_count=3, - process_result_path=f"{__name__}.only_us_partitions", - poke_interval=0.01, - ) - event = await trigger.run().__anext__() - assert _keys(event) == ["us|2024-01-01", "us|2024-01-02", "us|2024-01-01"] - - @pytest.mark.asyncio - async def test_applies_process_result_dedup(self, asset_event_rows, db_supervisor_comms): - trigger = AssetEventTrigger( - name=ASSET_NAME, - expected_count=4, - process_result_path=f"{__name__}.dedup_by_partition_key", - poke_interval=0.01, - ) - event = await trigger.run().__anext__() - assert _keys(event) == ["us|2024-01-01", "us|2024-01-02", "eu|2024-01-01", None] - - @pytest.mark.asyncio - async def test_sleeps_until_matching_event_appears( - self, asset_event_rows, db_supervisor_comms, add_asset_event, mocker - ): - # No event matches the filter yet; a new one is inserted "during" the first sleep, after - # which the next fetch finds it and the trigger fires. This exercises the real polling loop. - async def _insert(_seconds): - add_asset_event(id=100, day=9, partition_key="zz|only", extra={"region": "zz"}) - - sleep_mock = mocker.patch("asyncio.sleep", new=mock.AsyncMock(side_effect=_insert)) - trigger = AssetEventTrigger(name=ASSET_NAME, partition_key="zz|only", poke_interval=5) - event = await trigger.run().__anext__() - assert event.payload["status"] == "success" - assert _keys(event) == ["zz|only"] - sleep_mock.assert_awaited_once_with(5) - - @pytest.mark.asyncio - async def test_process_result_reduces_below_expected_keeps_waiting( - self, asset_event_rows, db_supervisor_comms, add_asset_event, mocker - ): - # only_us -> 3 events initially (< expected 4), so the trigger must sleep; a 4th "us" event - # is inserted during that sleep, after which the trigger fires. - async def _insert(_seconds): - add_asset_event(id=101, day=9, partition_key="us|2024-01-09", extra={"region": "us"}) - - sleep_mock = mocker.patch("asyncio.sleep", new=mock.AsyncMock(side_effect=_insert)) - trigger = AssetEventTrigger( - name=ASSET_NAME, - expected_count=4, - process_result_path=f"{__name__}.only_us_partitions", - poke_interval=5, - ) - event = await trigger.run().__anext__() - assert len(event.payload["events"]) == 4 - assert all((k or "").startswith("us|") for k in _keys(event)) - sleep_mock.assert_awaited_once_with(5) - - @pytest.mark.asyncio - async def test_callable_serialized_by_sensor_runs_in_trigger(self, asset_event_rows, db_supervisor_comms): - # End-to-end: pass a *real callable* to the sensor. The sensor's serialization util turns it - # into a dotted path and hands it to the trigger; we then run the exact trigger the sensor - # built and confirm the trigger imports and executes that callable against the DB. - sensor = AssetEventSensor( - task_id="s", - name=ASSET_NAME, - process_result=only_us_partitions, # a real function object, not an import path - expected_count=99, # force the initial poke to fail so the sensor defers - deferrable=True, - ) - with pytest.raises(TaskDeferred) as exc: - sensor.execute({}) - trigger = exc.value.trigger - assert isinstance(trigger, AssetEventTrigger) - assert trigger.process_result_path.endswith("test_asset.only_us_partitions") - - # Relax the (deliberately unreachable) expectation so the same trigger can fire, then run it. - trigger.expected_count = 3 - trigger.poke_interval = 0.01 - event = await trigger.run().__anext__() - assert event.payload["status"] == "success" - assert _keys(event) == ["us|2024-01-01", "us|2024-01-02", "us|2024-01-01"] - - @pytest.mark.asyncio - async def test_empty_extra_is_no_filter(self, asset_event_rows, db_supervisor_comms): - # An empty ``extra`` dict must be treated as "no filter", not as an impossible match. - trigger = AssetEventTrigger(name=ASSET_NAME, extra={}, poke_interval=0.01) - event = await trigger.run().__anext__() - assert len(event.payload["events"]) == 5 - - @pytest.mark.asyncio - async def test_process_result_returns_more_events(self, asset_event_rows, db_supervisor_comms): - trigger = AssetEventTrigger( - name=ASSET_NAME, - expected_count=10, - process_result_path=f"{__name__}.duplicate_all", - poke_interval=0.01, - ) - event = await trigger.run().__anext__() - assert len(event.payload["events"]) == 10 - - @pytest.mark.asyncio - async def test_process_result_exception_propagates(self, asset_event_rows, db_supervisor_comms): - trigger = AssetEventTrigger( - name=ASSET_NAME, process_result_path=f"{__name__}.boom", poke_interval=0.01 - ) - with pytest.raises(RuntimeError, match="process_result exploded"): - await trigger.run().__anext__() - - @pytest.mark.asyncio - async def test_empty_process_result_keeps_waiting(self, asset_event_rows, db_supervisor_comms, mocker): - # process_result drops everything -> count never satisfied -> the trigger must sleep. - # A patched sleep raises to break the otherwise-infinite polling loop after one iteration. - async def _stop(_seconds): - raise _Stop() - - sleep_mock = mocker.patch("asyncio.sleep", new=mock.AsyncMock(side_effect=_stop)) - trigger = AssetEventTrigger( - name=ASSET_NAME, process_result_path=f"{__name__}.drop_all", poke_interval=3 - ) - with pytest.raises(_Stop): - await trigger.run().__anext__() - sleep_mock.assert_awaited_once_with(3) From 6dc54751c6bc512c0558472c303e02eaa18697ed Mon Sep 17 00:00:00 2001 From: Hussein Awala Date: Thu, 1 Oct 2026 13:44:01 +0200 Subject: [PATCH 08/21] Declare asset sensor dependencies and support minimum event counts Task-level asset waits need visible lineage without changing the Dag schedule. Explicit count policies let consumers wait for a minimum number of events without missing the condition when several events arrive between pokes. --- providers/standard/docs/sensors/asset.rst | 31 +- .../example_dags/example_asset_sensor.py | 13 +- .../providers/standard/sensors/asset.py | 150 +++--- .../standard/tests/unit/standard/conftest.py | 185 ------- .../tests/unit/standard/sensors/test_asset.py | 477 ++++++++++-------- 5 files changed, 356 insertions(+), 500 deletions(-) delete mode 100644 providers/standard/tests/unit/standard/conftest.py diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index 90b4d0658f0c..edf806d2b298 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -25,6 +25,14 @@ AssetEventSensor Use the :class:`~airflow.providers.standard.sensors.asset.AssetEventSensor` to wait for asset events matching a set of filters to reach an expected count. +Use this sensor when an already-running Dag needs an asset between tasks. For example, a +daily consumer can run its preparation tasks immediately, then wait for another Dag to +produce the partition for its own data interval. Moving that dependency to an asset schedule +would change when the entire Dag starts and the data interval used by the consumer. + +The sensor declares its target as an inlet, so the dependency is visible in asset lineage +without changing the Dag's schedule. It reads events through ``context["inlet_events"]``. + .. note:: This sensor requires **Apache Airflow 3.4+**, because the ``partition_key``, @@ -34,9 +42,11 @@ asset events matching a set of filters to reach an expected count. Basic usage ----------- -Point the sensor at an :class:`~airflow.sdk.Asset` (or :class:`~airflow.sdk.AssetAlias`, or the raw -``name`` / ``uri`` / ``alias_name``). By default the sensor succeeds once **at least one** matching -event exists. +Pass an :class:`~airflow.sdk.Asset` or :class:`~airflow.sdk.AssetAlias` as ``obj``, or use the raw +``name`` / ``uri`` / ``alias_name`` arguments. A name-only or URI-only target is an asset reference +and must resolve to an existing asset when the task context is created. Target identifiers are +static so Airflow can record the inlet; use templated event filters to select a run's events. +By default the sensor succeeds once **at least one** matching event exists. .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python @@ -49,9 +59,18 @@ Filtering events and expected count Events can be narrowed with ``after`` / ``before`` (time range), ``ascending`` / ``limit`` (ordering and cap), ``partition_key`` / ``partition_key_regexp_pattern`` and ``extra`` (key/value -pairs contained in the event ``extra`` field). Use ``expected_count`` to control how many -(processed) events are required to succeed: ``-1`` (the default) means "at least one", ``0`` means -"exactly zero", and any other positive value requires an exact match. +pairs contained in the event ``extra`` field). Prefer a partition key for the event's partition +identity; ``extra`` can further filter metadata, such as a validation status. + +Use ``expected_count`` and ``count_policy`` to control how many processed events are required: + +* ``count_policy="minimum"`` (the default) succeeds at or above ``expected_count``, which defaults to one. +* ``count_policy="exact"`` succeeds only at ``expected_count``. Use this policy with zero to check + that no matching events exist. An exact count can be missed if several events arrive between pokes. + +Counts must be non-negative. With the minimum policy, zero always satisfies the count condition. +If no ``process_result`` callback is provided, a ``limit`` below ``expected_count`` is rejected +at construction instead of waiting until the sensor times out. .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python diff --git a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py index b140b36fabc8..a97534d8180a 100644 --- a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py +++ b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py @@ -14,7 +14,7 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -"""Example DAG demonstrating the usage of the ``AssetEventSensor``.""" +"""Example Dag demonstrating the usage of the ``AssetEventSensor``.""" from __future__ import annotations @@ -45,7 +45,7 @@ def latest_event_only(events: list[Any]) -> list[Any]: with DAG( dag_id="example_asset_sensor", - schedule=None, + schedule="@daily", start_date=pendulum.datetime(2021, 1, 1, tz="UTC"), catchup=False, tags=["example"], @@ -53,23 +53,24 @@ def latest_event_only(events: list[Any]) -> list[Any]: # [START example_asset_event_sensor] wait_for_asset_event = AssetEventSensor( task_id="wait_for_asset_event", - asset=my_asset, + obj=my_asset, ) # [END example_asset_event_sensor] # [START example_asset_event_sensor_filtered] wait_for_partition_events = AssetEventSensor( task_id="wait_for_partition_events", - asset=my_asset, - partition_key="2021-01-01", + obj=my_asset, + partition_key="{{ data_interval_start | ds }}", expected_count=3, + count_policy="minimum", ) # [END example_asset_event_sensor_filtered] # [START example_asset_event_sensor_process_result] wait_for_latest_asset_event = AssetEventSensor( task_id="wait_for_latest_asset_event", - asset=my_asset, + obj=my_asset, process_result=latest_event_only, ) # [END example_asset_event_sensor_process_result] diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index b2565c8ee252..c9482f405ac9 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -16,7 +16,7 @@ # under the License. from __future__ import annotations -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal from airflow.providers.common.compat.module_loading import import_string from airflow.providers.common.compat.sdk import ( @@ -32,57 +32,7 @@ from datetime import datetime from airflow.providers.common.compat.sdk import Context - - -def _count_satisfied(count: int, expected_count: int) -> bool: - """ - Return whether the number of (processed) asset events satisfies the expectation. - - ``expected_count == -1`` means "at least one" (``count >= 1``); any other value - requires an exact match (``count == expected_count``). - """ - if expected_count == -1: - return count >= 1 - return count == expected_count - - -def _fetch_asset_events( - *, - name: str | None, - uri: str | None, - alias_name: str | None, - after: datetime | str | None, - before: datetime | str | None, - ascending: bool, - limit: int | None, - partition_key: str | None, - partition_key_regexp_pattern: str | None, - extra: dict[str, str] | None, -) -> list[Any]: - """ - Fetch asset events matching the given filters. - - This uses the Task SDK :class:`InletEventsAccessor`, which lazily fetches events from - the supervisor, so it can only run where the execution API is available (i.e. on a worker). - """ - from airflow.sdk.execution_time.context import InletEventsAccessor - - accessor = InletEventsAccessor(asset_name=name, asset_uri=uri, alias_name=alias_name) - if after is not None: - accessor.after(after if isinstance(after, str) else after.isoformat()) - if before is not None: - accessor.before(before if isinstance(before, str) else before.isoformat()) - accessor.ascending(ascending) - if limit is not None: - accessor.limit(limit) - if partition_key is not None: - accessor.partition_key(partition_key) - if partition_key_regexp_pattern is not None: - accessor.partition_key_regexp_pattern(partition_key_regexp_pattern) - if extra: - for key, value in extra.items(): - accessor.extra(key, value) - return list(accessor) + from airflow.sdk.definitions.asset import AssetRef def _serialize_events(events: list[Any]) -> list[Any]: @@ -108,8 +58,9 @@ class AssetEventSensor(BaseSensorOperator): This sensor requires Apache Airflow 3.4+ because the ``partition_key``, ``partition_key_regexp_pattern`` and ``extra`` asset-event filters are only available there. - :param asset: The :class:`~airflow.sdk.Asset` or :class:`~airflow.sdk.AssetAlias` to wait on. - As an alternative, pass ``name``/``uri``/``alias_name`` directly. + :param obj: The :class:`~airflow.sdk.Asset` or :class:`~airflow.sdk.AssetAlias` to wait on. + The target is declared as an inlet. As an alternative, pass ``name``/``uri``/``alias_name`` + directly. Target identifiers are static; event filters can be templated. :param name: The asset name to fetch events for. :param uri: The asset uri to fetch events for. :param alias_name: The asset alias name to fetch events for. @@ -120,10 +71,10 @@ class AssetEventSensor(BaseSensorOperator): :param partition_key: Filter by exact partition key match. :param partition_key_regexp_pattern: Filter by partition key regexp pattern. :param extra: Filter by key/value pairs contained in the event ``extra`` field. - :param expected_count: The number of events required to succeed. ``-1`` (the default) means - "at least one" (``count >= 1``); ``0`` means "exactly zero"; any other positive value - requires an exact match. Note that if ``limit`` is set below an exact ``expected_count`` - the condition can never be satisfied (the sensor will wait until it times out). + :param expected_count: The non-negative number of processed events required to succeed. + Defaults to one. If ``process_result`` is omitted, ``limit`` must not be smaller. + :param count_policy: ``"minimum"`` (the default) waits for at least ``expected_count`` events; + ``"exact"`` requires exactly that number. To check for no events, use ``"exact"`` and zero. :param process_result: A callable (or a dotted import path to one) applied to the fetched events before the count check, to transform, deduplicate or filter them. It receives the list of asset events and must return a list. It runs on every poke, so it should be @@ -132,9 +83,6 @@ class AssetEventSensor(BaseSensorOperator): """ template_fields: Sequence[str] = ( - "name", - "uri", - "alias_name", "partition_key", "partition_key_regexp_pattern", "extra", @@ -145,7 +93,7 @@ class AssetEventSensor(BaseSensorOperator): def __init__( self, *, - asset: Asset | AssetAlias | None = None, + obj: Asset | AssetAlias | None = None, name: str | None = None, uri: str | None = None, alias_name: str | None = None, @@ -156,7 +104,8 @@ def __init__( partition_key: str | None = None, partition_key_regexp_pattern: str | None = None, extra: dict[str, str] | None = None, - expected_count: int = -1, + expected_count: int = 1, + count_policy: Literal["minimum", "exact"] = "minimum", process_result: Callable[[list[Any]], list[Any]] | str | None = None, **kwargs, ) -> None: @@ -166,24 +115,32 @@ def __init__( "AssetEventSensor requires Apache Airflow 3.4+ because the asset event filters " "it relies on are only available from 3.4 onwards." ) - if asset is not None: - if isinstance(asset, AssetAlias): - alias_name = asset.name - elif isinstance(asset, Asset): - name = asset.name - uri = asset.uri - else: - raise TypeError(f"`asset` must be an Asset or AssetAlias, got {type(asset).__name__}") - if name is None and uri is None and alias_name is None: - raise ValueError("One of `asset`, `name`, `uri`, or `alias_name` must be provided.") - if expected_count < -1: + self.obj: Asset | AssetAlias | AssetRef + if obj is not None: + if not isinstance(obj, (Asset, AssetAlias)): + raise TypeError(f"`obj` must be an Asset or AssetAlias, got {type(obj).__name__}") + self.obj = obj + elif alias_name is not None: + self.obj = AssetAlias(alias_name) + elif name is not None and uri is not None: + self.obj = Asset(name=name, uri=uri) + elif name is not None: + self.obj = Asset.ref(name=name) + elif uri is not None: + self.obj = Asset.ref(uri=uri) + else: + raise ValueError("One of `obj`, `name`, `uri`, or `alias_name` must be provided.") + if expected_count < 0: + raise ValueError(f"`expected_count` must be a non-negative integer, got {expected_count}.") + if count_policy not in {"minimum", "exact"}: + raise ValueError(f"`count_policy` must be 'minimum' or 'exact', got {count_policy!r}.") + if process_result is None and limit is not None and limit < expected_count: raise ValueError( - f"`expected_count` must be -1 (at least one) or a non-negative integer, got {expected_count}." + "`limit` must be at least `expected_count` when `process_result` is not provided." ) + if self.obj not in self.inlets: + self.inlets.append(self.obj) - self.name = name - self.uri = uri - self.alias_name = alias_name self.after = after self.before = before self.ascending = ascending @@ -192,6 +149,7 @@ def __init__( self.partition_key_regexp_pattern = partition_key_regexp_pattern self.extra = extra self.expected_count = expected_count + self.count_policy = count_policy self.process_result = process_result def _apply_process_result(self, events: list[Any]) -> list[Any]: @@ -201,25 +159,31 @@ def _apply_process_result(self, events: list[Any]) -> list[Any]: return func(events) def poke(self, context: Context) -> PokeReturnValue: - events = _fetch_asset_events( - name=self.name, - uri=self.uri, - alias_name=self.alias_name, - after=self.after, - before=self.before, - ascending=self.ascending, - limit=self.limit, - partition_key=self.partition_key, - partition_key_regexp_pattern=self.partition_key_regexp_pattern, - extra=self.extra, - ) - processed = self._apply_process_result(events) + accessor = context["inlet_events"][self.obj] + if self.after is not None: + accessor.after(self.after if isinstance(self.after, str) else self.after.isoformat()) + if self.before is not None: + accessor.before(self.before if isinstance(self.before, str) else self.before.isoformat()) + accessor.ascending(self.ascending) + if self.limit is not None: + accessor.limit(self.limit) + if self.partition_key is not None: + accessor.partition_key(self.partition_key) + if self.partition_key_regexp_pattern is not None: + accessor.partition_key_regexp_pattern(self.partition_key_regexp_pattern) + if self.extra: + for key, value in self.extra.items(): + accessor.extra(key, value) + processed = self._apply_process_result(list(accessor)) count = len(processed) - done = _count_satisfied(count, self.expected_count) + done = ( + count >= self.expected_count if self.count_policy == "minimum" else count == self.expected_count + ) self.log.info( - "Found %d matching asset events (expected %s): %s", + "Found %d matching asset events (expected %s, policy %s): %s", count, self.expected_count, + self.count_policy, "condition met" if done else "still waiting", ) return PokeReturnValue(is_done=done, xcom_value=_serialize_events(processed) if done else None) diff --git a/providers/standard/tests/unit/standard/conftest.py b/providers/standard/tests/unit/standard/conftest.py deleted file mode 100644 index 6f5d962ac161..000000000000 --- a/providers/standard/tests/unit/standard/conftest.py +++ /dev/null @@ -1,185 +0,0 @@ -# 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. -""" -Shared fixtures for the database-backed asset sensor tests. - -The :class:`AssetEventSensor` always fetches through the Task SDK -:class:`~airflow.sdk.execution_time.context.InletEventsAccessor`, which talks to -``SUPERVISOR_COMMS`` (normally a socket to the supervisor, which calls the execution API, which -queries the DB). There is no supervisor in a unit test, so :class:`_DBBackedComms` replaces only -that transport seam: it runs the *real* execution-API SQL against the test metadata DB, so the -partition-key / extra / time-range / limit filters execute for real. ``process_result`` and the -count check then run unmocked on the returned events. -""" - -from __future__ import annotations - -from datetime import datetime, timezone -from typing import Any - -import pytest - -ASSET_NAME = "my_asset" -ASSET_URI = "s3://bucket/key" -ALIAS_NAME = "my_alias" - - -def event_timestamp(day: int) -> datetime: - return datetime(2024, 1, day, tzinfo=timezone.utc) - - -class _DBBackedComms: - """A ``SUPERVISOR_COMMS`` stand-in that answers asset-event queries from the metadata DB. - - It mirrors what :class:`~airflow.sdk.execution_time.supervisor.ActivitySubprocess` does for - ``GetAssetEventByAsset`` / ``GetAssetEventByAssetAlias``, but instead of an HTTP round-trip it - calls the execution-API route function directly against a fresh session (so it is safe to use - from the triggerer's worker thread as well). - """ - - def send(self, msg: Any) -> Any: - from airflow.api_fastapi.common.parameters import FilterParam, _RegexParam - from airflow.api_fastapi.execution_api.routes.asset_events import ( - get_asset_event_by_asset_alias, - get_asset_event_by_asset_name_uri, - ) - from airflow.models.asset import AssetEvent - from airflow.sdk.execution_time.comms import ( - AssetEventsResult, - GetAssetEventByAsset, - GetAssetEventByAssetAlias, - ) - from airflow.utils.session import create_session - - def _extra_list(extra: dict[str, str] | None) -> list[str] | None: - return [f"{k}={v}" for k, v in extra.items()] if extra else None - - with create_session() as session: - partition_key = FilterParam(AssetEvent.partition_key, msg.partition_key) - partition_key_regexp = _RegexParam(AssetEvent.partition_key, msg.partition_key_regexp_pattern) - if isinstance(msg, GetAssetEventByAsset): - response = get_asset_event_by_asset_name_uri( - name=msg.name, - uri=msg.uri, - session=session, - partition_key=partition_key, - partition_key_regexp_pattern=partition_key_regexp, - after=msg.after, - before=msg.before, - ascending=msg.ascending, - limit=msg.limit, - extra=_extra_list(msg.extra), - ) - elif isinstance(msg, GetAssetEventByAssetAlias): - response = get_asset_event_by_asset_alias( - name=msg.alias_name, - session=session, - partition_key=partition_key, - partition_key_regexp_pattern=partition_key_regexp, - after=msg.after, - before=msg.before, - ascending=msg.ascending, - limit=msg.limit, - extra=_extra_list(msg.extra), - ) - else: # pragma: no cover - defensive - raise AssertionError(f"unexpected supervisor message: {msg!r}") - return AssetEventsResult.from_asset_events_response(response) - - -@pytest.fixture -def db_supervisor_comms(monkeypatch): - """Route the Task SDK ``SUPERVISOR_COMMS`` to the metadata DB for the duration of a test.""" - from airflow.sdk.execution_time import task_runner - - comms = _DBBackedComms() - monkeypatch.setattr(task_runner, "SUPERVISOR_COMMS", comms, raising=False) - return comms - - -@pytest.fixture -def asset_event_rows(session): - """Create one active asset with five events (varied partition keys / extras / timestamps). - - Layout (ascending by timestamp): - id=1 us|2024-01-01 {"region": "us"} - id=2 us|2024-01-02 {"region": "us"} - id=3 eu|2024-01-01 {"region": "eu"} - id=4 us|2024-01-01 {"region": "us"} # duplicate partition key of id=1 (exercises dedup) - id=5 None {} - Also links every event to an alias named ``my_alias``. - """ - from airflow.models.asset import AssetActive, AssetAliasModel, AssetEvent, AssetModel - - from tests_common.test_utils.db import clear_db_assets - - clear_db_assets() - - asset = AssetModel(id=1, name=ASSET_NAME, uri=ASSET_URI, group="asset", extra={}) - session.add_all([asset, AssetActive.for_asset(asset)]) - session.commit() - - common = { - "asset_id": 1, - "source_dag_id": "producer", - "source_task_id": "emit", - "source_run_id": "run_1", - "source_map_index": -1, - } - events = [ - AssetEvent( - id=1, - timestamp=event_timestamp(1), - partition_key="us|2024-01-01", - extra={"region": "us"}, - **common, - ), - AssetEvent( - id=2, - timestamp=event_timestamp(2), - partition_key="us|2024-01-02", - extra={"region": "us"}, - **common, - ), - AssetEvent( - id=3, - timestamp=event_timestamp(3), - partition_key="eu|2024-01-01", - extra={"region": "eu"}, - **common, - ), - AssetEvent( - id=4, - timestamp=event_timestamp(4), - partition_key="us|2024-01-01", - extra={"region": "us"}, - **common, - ), - AssetEvent(id=5, timestamp=event_timestamp(5), partition_key=None, extra={}, **common), - ] - session.add_all(events) - session.commit() - - alias = AssetAliasModel(id=1, name=ALIAS_NAME) - alias.asset_events = events - alias.assets.append(asset) - session.add(alias) - session.commit() - - yield events - - clear_db_assets() diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index ebc8c21ba9a3..1b4cf6b9ed05 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -14,19 +14,11 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -""" -Tests for :class:`AssetEventSensor`. - -Most tests are database-backed (``db_test``): they create real ``AssetEvent`` rows and exercise the -whole fetch path (real ``InletEventsAccessor`` -> DB-backed ``SUPERVISOR_COMMS`` -> real -execution-API SQL), rather than patching ``_fetch_asset_events``. The DB harness lives in the -``conftest.py`` one directory up (``db_supervisor_comms`` / ``asset_event_rows`` fixtures). -""" - from __future__ import annotations from datetime import datetime, timezone from typing import Any +from unittest.mock import call import pytest @@ -35,80 +27,119 @@ from tests_common.test_utils.version_compat import AIRFLOW_V_3_4_PLUS -pytestmark = pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="AssetEventSensor requires Airflow 3.4+") +if AIRFLOW_V_3_4_PLUS: + from airflow.sdk.api.datamodels._generated import AssetEventResponse, AssetResponse + from airflow.sdk.execution_time.comms import ( + AssetEventsResult, + AssetResult, + GetAssetByName, + GetAssetByUri, + GetAssetEventByAsset, + GetAssetEventByAssetAlias, + ) + from airflow.sdk.execution_time.context import InletEventsAccessors -FETCH_PATH = "airflow.providers.standard.sensors.asset._fetch_asset_events" +pytestmark = pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="AssetEventSensor requires Airflow 3.4+") ASSET_NAME = "my_asset" ASSET_URI = "s3://bucket/key" ALIAS_NAME = "my_alias" -def _ts(day: int) -> datetime: +def _get_timestamp(day: int) -> datetime: return datetime(2024, 1, day, tzinfo=timezone.utc) +def _get_context(sensor: AssetEventSensor) -> dict[str, Any]: + return {"inlet_events": InletEventsAccessors(sensor.inlets)} + + def only_us_partitions(events: list[Any]) -> list[Any]: - """Keep only events whose partition key targets the ``us`` region.""" return [event for event in events if (event.partition_key or "").startswith("us|")] def dedup_by_partition_key(events: list[Any]) -> list[Any]: - """Keep the first event seen for each distinct partition key (order preserved).""" seen: set[str | None] = set() - out: list[Any] = [] + result = [] for event in events: - if event.partition_key in seen: - continue - seen.add(event.partition_key) - out.append(event) - return out - - -def _partition_keys(result: Any) -> list[str | None]: - """Extract partition keys from a poke result's (serialized) xcom value.""" - assert isinstance(result, PokeReturnValue) - return [event["partition_key"] for event in (result.xcom_value or [])] + if event.partition_key not in seen: + seen.add(event.partition_key) + result.append(event) + return result + + +@pytest.fixture +def asset(): + return Asset(name=ASSET_NAME, uri=ASSET_URI) + + +@pytest.fixture +def events_response(): + partition_keys = ["us|2024-01-01", "us|2024-01-02", "eu|2024-01-01", "us|2024-01-01", None] + return AssetEventsResult( + asset_events=[ + AssetEventResponse( + id=index, + timestamp=_get_timestamp(index), + partition_key=key, + extra={"region": key.split("|")[0]} if key else {}, + asset=AssetResponse(name=ASSET_NAME, uri=ASSET_URI, group="asset", extra={}), + created_dagruns=[], + source_dag_id="producer", + source_task_id="emit", + source_run_id="run_1", + source_map_index=-1, + ) + for index, key in enumerate(partition_keys, start=1) + ] + ) class TestInit: - """Pure construction/validation logic (no DB access).""" - def test_requires_a_target(self): - with pytest.raises(ValueError, match="One of `asset`, `name`, `uri`, or `alias_name`"): + with pytest.raises(ValueError, match="obj.*name.*uri.*alias_name"): AssetEventSensor(task_id="s") - def test_target_from_asset(self): - sensor = AssetEventSensor(task_id="s", asset=Asset(name="my_asset", uri="s3://bucket/key")) - assert sensor.name == "my_asset" - assert sensor.uri == "s3://bucket/key" - assert sensor.alias_name is None - - def test_target_from_asset_alias(self): - sensor = AssetEventSensor(task_id="s", asset=AssetAlias(name="my_alias")) - assert sensor.alias_name == "my_alias" - assert sensor.name is None - assert sensor.uri is None + @pytest.mark.parametrize("use_alias", [False, True]) + def test_declares_target_as_inlet(self, asset, use_alias): + obj = AssetAlias(name=ALIAS_NAME) if use_alias else asset + sensor = AssetEventSensor(task_id="s", obj=obj) + assert sensor.obj == obj + assert sensor.inlets == [obj] + + @pytest.mark.parametrize("include_target", [False, True]) + def test_preserves_existing_inlets_without_duplicates(self, asset, include_target): + other_asset = Asset("s3://bucket/other") + inlets = [other_asset, asset] if include_target else [other_asset] + original_inlets = inlets.copy() + sensor = AssetEventSensor(task_id="s", obj=asset, inlets=inlets) + assert sensor.inlets == [other_asset, asset] + assert inlets == original_inlets def test_target_rejects_bad_type(self): - with pytest.raises(TypeError, match="must be an Asset or AssetAlias"): - AssetEventSensor(task_id="s", asset=object()) # type: ignore[arg-type] + with pytest.raises(TypeError, match="Asset.*AssetAlias"): + AssetEventSensor(task_id="s", obj=object()) - def test_rejects_invalid_expected_count(self): + def test_rejects_negative_expected_count(self, asset): with pytest.raises(ValueError, match="expected_count"): - AssetEventSensor(task_id="s", name=ASSET_NAME, expected_count=-2) + AssetEventSensor(task_id="s", obj=asset, expected_count=-1) + + def test_rejects_invalid_count_policy(self, asset): + with pytest.raises(ValueError, match="count_policy"): + AssetEventSensor(task_id="s", obj=asset, count_policy="unknown") + + @pytest.mark.parametrize("count_policy", ["minimum", "exact"]) + def test_rejects_limit_below_expected_count_without_processing(self, asset, count_policy): + with pytest.raises(ValueError, match="limit"): + AssetEventSensor(task_id="s", obj=asset, limit=1, expected_count=3, count_policy=count_policy) - def test_requires_airflow_3_4(self, mocker): - # The version guard is dead code in CI (the module is skipped below 3.4), so patch the flag. + def test_requires_airflow_3_4(self, mocker, asset): mocker.patch("airflow.providers.standard.sensors.asset.AIRFLOW_V_3_4_PLUS", False) with pytest.raises(RuntimeError, match="requires Apache Airflow 3.4"): - AssetEventSensor(task_id="s", name=ASSET_NAME) + AssetEventSensor(task_id="s", obj=asset) def test_template_fields(self): - assert set(AssetEventSensor.template_fields) >= { - "name", - "uri", - "alias_name", + assert set(AssetEventSensor.template_fields) == { "partition_key", "partition_key_regexp_pattern", "extra", @@ -116,194 +147,220 @@ def test_template_fields(self): "before", } - -@pytest.mark.db_test -class TestPoke: - """poke() against real ``AssetEvent`` rows (no patching of the fetch).""" - - def test_returns_all_events(self, asset_event_rows, db_supervisor_comms): - sensor = AssetEventSensor(task_id="s", name=ASSET_NAME) # expected_count=-1 (at least one) - result = sensor.poke({}) - assert bool(result) is True - assert _partition_keys(result) == [ - "us|2024-01-01", - "us|2024-01-02", - "eu|2024-01-01", - "us|2024-01-01", - None, - ] - - def test_no_match_is_not_done(self, asset_event_rows, db_supervisor_comms): - sensor = AssetEventSensor(task_id="s", name="does_not_exist") - result = sensor.poke({}) - assert bool(result) is False - assert result.xcom_value is None - - def test_exact_partition_key_filter(self, asset_event_rows, db_supervisor_comms): - sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, partition_key="us|2024-01-01") - assert _partition_keys(sensor.poke({})) == ["us|2024-01-01", "us|2024-01-01"] - - def test_extra_filter(self, asset_event_rows, db_supervisor_comms): - sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, extra={"region": "eu"}) - assert _partition_keys(sensor.poke({})) == ["eu|2024-01-01"] - - def test_time_range_limit_and_descending(self, asset_event_rows, db_supervisor_comms): + def test_renders_filters_without_changing_lineage(self, asset): sensor = AssetEventSensor( - task_id="s", name=ASSET_NAME, after=_ts(2), before=_ts(4), ascending=False, limit=2 + task_id="s", + obj=asset, + partition_key="{{ ds }}", + partition_key_regexp_pattern="{{ params.region }}.*", + extra={"region": "{{ params.region }}"}, + after="{{ ds }}T00:00:00+00:00", + before="{{ ds }}T23:59:59+00:00", ) - # events in [day2, day4] are ids 2,3,4; descending -> 4,3; limited to 2 - assert _partition_keys(sensor.poke({})) == ["us|2024-01-01", "eu|2024-01-01"] - - @pytest.mark.parametrize(("expected_count", "done"), [(5, True), (4, False), (1, False)]) - def test_exact_expected_count(self, asset_event_rows, db_supervisor_comms, expected_count, done): - sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, expected_count=expected_count) - assert bool(sensor.poke({})) is done + sensor.render_template_fields({"ds": "2024-01-01", "params": {"region": "us"}}) + assert sensor.partition_key == "2024-01-01" + assert sensor.partition_key_regexp_pattern == "us.*" + assert sensor.extra == {"region": "us"} + assert sensor.after == "2024-01-01T00:00:00+00:00" + assert sensor.before == "2024-01-01T23:59:59+00:00" + assert sensor.obj == asset + assert sensor.inlets == [asset] - def test_by_uri(self, asset_event_rows, db_supervisor_comms): - sensor = AssetEventSensor(task_id="s", uri=ASSET_URI) - assert len(sensor.poke({}).xcom_value) == 5 - def test_by_alias(self, asset_event_rows, db_supervisor_comms): - sensor = AssetEventSensor(task_id="s", asset=AssetAlias(name=ALIAS_NAME)) - assert len(sensor.poke({}).xcom_value) == 5 +class TestPoke: + def test_returns_serialized_events(self, asset, events_response, mock_supervisor_comms): + mock_supervisor_comms.send.return_value = events_response + sensor = AssetEventSensor(task_id="s", obj=asset) + result = sensor.poke(_get_context(sensor)) + assert isinstance(result, PokeReturnValue) + assert bool(result) is True + assert result.xcom_value == [event.model_dump(mode="json") for event in events_response.asset_events] + mock_supervisor_comms.send.assert_called_once_with( + GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI) + ) - def test_expected_count_zero_matches_none(self, asset_event_rows, db_supervisor_comms): - # expected_count=0 means "exactly zero events"; a filter matching nothing satisfies it. + @pytest.mark.parametrize( + ("count_policy", "expected_count", "actual_count", "done"), + [ + ("minimum", 1, 0, False), + ("minimum", 1, 1, True), + ("minimum", 3, 2, False), + ("minimum", 3, 3, True), + ("minimum", 3, 5, True), + ("minimum", 0, 0, True), + ("exact", 0, 0, True), + ("exact", 0, 1, False), + ("exact", 3, 2, False), + ("exact", 3, 3, True), + ("exact", 3, 5, False), + ], + ) + def test_count_policy( + self, asset, events_response, mock_supervisor_comms, count_policy, expected_count, actual_count, done + ): + events = events_response.asset_events[:actual_count] + mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=events) sensor = AssetEventSensor( - task_id="s", name=ASSET_NAME, partition_key="does-not-exist", expected_count=0 + task_id="s", obj=asset, count_policy=count_policy, expected_count=expected_count ) - result = sensor.poke({}) - assert bool(result) is True - assert result.xcom_value == [] - - def test_limit_below_exact_expected_count_never_satisfied(self, asset_event_rows, db_supervisor_comms): - # limit caps the DB result below the exact expected_count, so the condition can never be met. - sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, limit=1, expected_count=3) - assert bool(sensor.poke({})) is False - - def test_combined_filters(self, asset_event_rows, db_supervisor_comms): - # partition_key AND extra AND time-range together, resolved by real SQL -> only id=1. + result = sensor.poke(_get_context(sensor)) + assert bool(result) is done + assert result.xcom_value == ([event.model_dump(mode="json") for event in events] if done else None) + + @pytest.mark.parametrize("use_alias", [False, True]) + @pytest.mark.parametrize("string_bounds", [False, True]) + def test_forwards_all_filters(self, asset, mock_supervisor_comms, use_alias, string_bounds): + mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=[]) + obj = AssetAlias(name=ALIAS_NAME) if use_alias else asset sensor = AssetEventSensor( task_id="s", - name=ASSET_NAME, + obj=obj, + after=_get_timestamp(1).isoformat() if string_bounds else _get_timestamp(1), + before=_get_timestamp(9).isoformat() if string_bounds else _get_timestamp(9), + ascending=False, + limit=7, partition_key="us|2024-01-01", - extra={"region": "us"}, - after=_ts(1), - before=_ts(1), + partition_key_regexp_pattern="us.*", + extra={"region": "us", "status": "validated"}, ) - assert _partition_keys(sensor.poke({})) == ["us|2024-01-01"] - - def test_string_datetime_bounds(self, asset_event_rows, db_supervisor_comms): - # after/before accept ISO strings (coerced to datetime by the comms message model). - sensor = AssetEventSensor( - task_id="s", - name=ASSET_NAME, - after="2024-01-02T00:00:00+00:00", - before="2024-01-03T00:00:00+00:00", + sensor.poke(_get_context(sensor)) + filters = { + "after": _get_timestamp(1), + "before": _get_timestamp(9), + "ascending": False, + "limit": 7, + "partition_key": "us|2024-01-01", + "partition_key_regexp_pattern": "us.*", + "extra": {"region": "us", "status": "validated"}, + } + message = ( + GetAssetEventByAssetAlias(alias_name=ALIAS_NAME, **filters) + if use_alias + else GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, **filters) + ) + mock_supervisor_comms.send.assert_called_once_with(message) + + @pytest.mark.parametrize("selector", ["name", "uri"]) + def test_resolves_asset_reference(self, selector, events_response, mock_supervisor_comms): + target = {"name": ASSET_NAME} if selector == "name" else {"uri": ASSET_URI} + sensor = AssetEventSensor(task_id="s", **target) + assert sensor.obj == Asset.ref(**target) + assert sensor.inlets == [sensor.obj] + mock_supervisor_comms.send.side_effect = [ + AssetResult(name=ASSET_NAME, uri=ASSET_URI, group="asset", extra={}), + events_response, + ] + assert bool(sensor.poke(_get_context(sensor))) is True + resolution = GetAssetByName(name=ASSET_NAME) if selector == "name" else GetAssetByUri(uri=ASSET_URI) + query = GetAssetEventByAsset( + name=ASSET_NAME if selector == "name" else None, + uri=ASSET_URI if selector == "uri" else None, ) - assert _partition_keys(sensor.poke({})) == ["us|2024-01-02", "eu|2024-01-01"] + assert mock_supervisor_comms.send.call_args_list == [call(resolution), call(query)] + + @pytest.mark.parametrize("use_alias", [False, True]) + def test_raw_target(self, asset, events_response, mock_supervisor_comms, use_alias): + target = {"alias_name": ALIAS_NAME} if use_alias else {"name": ASSET_NAME, "uri": ASSET_URI} + sensor = AssetEventSensor(task_id="s", **target) + expected_obj = AssetAlias(name=ALIAS_NAME) if use_alias else asset + assert sensor.obj == expected_obj + assert sensor.inlets == [expected_obj] + mock_supervisor_comms.send.return_value = events_response + assert bool(sensor.poke(_get_context(sensor))) is True + query = ( + GetAssetEventByAssetAlias(alias_name=ALIAS_NAME) + if use_alias + else GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI) + ) + mock_supervisor_comms.send.assert_called_once_with(query) + def test_fetches_fresh_events_on_every_poke(self, asset, events_response, mock_supervisor_comms): + mock_supervisor_comms.send.side_effect = [AssetEventsResult(asset_events=[]), events_response] + sensor = AssetEventSensor(task_id="s", obj=asset) + context = _get_context(sensor) + assert bool(sensor.poke(context)) is False + assert bool(sensor.poke(context)) is True + query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI) + assert mock_supervisor_comms.send.call_args_list == [call(query), call(query)] -@pytest.mark.db_test -class TestProcessResult: - """process_result (filter / dedup) applied to real DB events before the count check.""" + def test_execute_returns_xcom_payload(self, asset, events_response, mock_supervisor_comms): + mock_supervisor_comms.send.return_value = events_response + sensor = AssetEventSensor(task_id="s", obj=asset) + result = sensor.execute(_get_context(sensor)) + assert result == [event.model_dump(mode="json") for event in events_response.asset_events] - def test_filters_out_events(self, asset_event_rows, db_supervisor_comms): - sensor = AssetEventSensor( - task_id="s", name=ASSET_NAME, process_result=only_us_partitions, expected_count=3 - ) - result = sensor.poke({}) - assert bool(result) is True - assert _partition_keys(result) == ["us|2024-01-01", "us|2024-01-02", "us|2024-01-01"] - def test_dedup(self, asset_event_rows, db_supervisor_comms): - sensor = AssetEventSensor( - task_id="s", name=ASSET_NAME, process_result=dedup_by_partition_key, expected_count=4 - ) - result = sensor.poke({}) - assert bool(result) is True - assert _partition_keys(result) == ["us|2024-01-01", "us|2024-01-02", "eu|2024-01-01", None] - - def test_by_import_path(self, asset_event_rows, db_supervisor_comms): +class TestProcessResult: + @pytest.mark.parametrize( + ("process_result", "expected_count", "expected_ids", "done"), + [ + (only_us_partitions, 3, [1, 2, 4], True), + (f"{__name__}.only_us_partitions", 3, [1, 2, 4], True), + (dedup_by_partition_key, 4, [1, 2, 3, 5], True), + (only_us_partitions, 5, None, False), + (lambda events: [], 1, None, False), + (lambda events: [], 0, [], True), + ], + ) + def test_processes_events_before_counting( + self, + asset, + events_response, + mock_supervisor_comms, + process_result, + expected_count, + expected_ids, + done, + ): + mock_supervisor_comms.send.return_value = events_response sensor = AssetEventSensor( task_id="s", - name=ASSET_NAME, - process_result=f"{__name__}.only_us_partitions", - expected_count=3, + obj=asset, + process_result=process_result, + expected_count=expected_count, + count_policy="exact", ) - assert bool(sensor.poke({})) is True - - def test_reduces_below_expected(self, asset_event_rows, db_supervisor_comms): - # only 3 "us" events remain after filtering, so an exact expectation of 5 is not met - sensor = AssetEventSensor( - task_id="s", name=ASSET_NAME, process_result=only_us_partitions, expected_count=5 + result = sensor.poke(_get_context(sensor)) + assert bool(result) is done + if done: + assert [event["id"] for event in result.xcom_value] == expected_ids + else: + assert result.xcom_value is None + + def test_processing_can_expand_limited_results(self, asset, events_response, mock_supervisor_comms): + mock_supervisor_comms.send.return_value = AssetEventsResult( + asset_events=events_response.asset_events[:1] ) - assert bool(sensor.poke({})) is False - - def test_returns_empty_list_not_done(self, asset_event_rows, db_supervisor_comms): - sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, process_result=lambda events: []) - result = sensor.poke({}) # expected_count=-1 -> "at least one" -> not satisfied by [] - assert bool(result) is False - assert result.xcom_value is None - - def test_returns_empty_list_with_expected_zero(self, asset_event_rows, db_supervisor_comms): sensor = AssetEventSensor( - task_id="s", name=ASSET_NAME, process_result=lambda events: [], expected_count=0 + task_id="s", + obj=asset, + limit=1, + expected_count=2, + count_policy="exact", + process_result=lambda events: events + events, ) - result = sensor.poke({}) + result = sensor.poke(_get_context(sensor)) assert bool(result) is True - assert result.xcom_value == [] + assert [event["id"] for event in result.xcom_value] == [1, 1] - def test_returns_more_events_than_fetched(self, asset_event_rows, db_supervisor_comms): + def test_processing_can_return_json_values(self, asset, events_response, mock_supervisor_comms): + mock_supervisor_comms.send.return_value = events_response sensor = AssetEventSensor( - task_id="s", name=ASSET_NAME, process_result=lambda events: events + events, expected_count=10 + task_id="s", + obj=asset, + process_result=lambda events: [{"partition": event.partition_key} for event in events], ) - result = sensor.poke({}) + result = sensor.poke(_get_context(sensor)) assert bool(result) is True - assert len(result.xcom_value) == 10 + assert result.xcom_value == [ + {"partition": event.partition_key} for event in events_response.asset_events + ] - def test_exception_propagates(self, asset_event_rows, db_supervisor_comms): + def test_exception_propagates(self, asset, events_response, mock_supervisor_comms): def boom(events): raise RuntimeError("process_result exploded") - sensor = AssetEventSensor(task_id="s", name=ASSET_NAME, process_result=boom) + mock_supervisor_comms.send.return_value = events_response + sensor = AssetEventSensor(task_id="s", obj=asset, process_result=boom) with pytest.raises(RuntimeError, match="process_result exploded"): - sensor.poke({}) - - -class TestFilterForwarding: - """The regexp filter cannot run on SQLite, so verify filter forwarding with a mock. - - This is the one place we still patch the fetch: it lets us assert that *all* filters (including - ``partition_key_regexp_pattern``) reach the fetch layer without executing a regexp query that - the local SQLite backend does not support. - """ - - def test_forwards_all_filters_to_fetch(self, mocker): - fetch = mocker.patch(FETCH_PATH, return_value=[]) - sensor = AssetEventSensor( - task_id="s", - name=ASSET_NAME, - uri=ASSET_URI, - after=_ts(1), - before=_ts(9), - ascending=False, - limit=7, - partition_key="us|2024-01-01", - partition_key_regexp_pattern="us.*", - extra={"region": "us"}, - expected_count=3, - ) - sensor.poke({}) - assert fetch.call_args.kwargs == { - "name": ASSET_NAME, - "uri": ASSET_URI, - "alias_name": None, - "after": _ts(1), - "before": _ts(9), - "ascending": False, - "limit": 7, - "partition_key": "us|2024-01-01", - "partition_key_regexp_pattern": "us.*", - "extra": {"region": "us"}, - } + sensor.poke(_get_context(sensor)) From 7d628bdec6061878f3cb9dab3f47ee9ea86a369f Mon Sep 17 00:00:00 2001 From: Hussein Awala Date: Thu, 1 Oct 2026 13:44:21 +0200 Subject: [PATCH 09/21] Reject ambiguous asset sensor targets and invalid event counts Conflicting selectors can silently wait for a different asset, while fractional counts and invalid limits can produce misleading waits. Result processing also needs clear limits so consumers know which events their callback can inspect. --- providers/standard/docs/sensors/asset.rst | 15 ++++- .../providers/standard/sensors/asset.py | 16 ++++- .../tests/unit/standard/sensors/test_asset.py | 64 +++++++++++++++++++ 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index edf806d2b298..5f40016efdf6 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -48,6 +48,9 @@ and must resolve to an existing asset when the task context is created. Target i static so Airflow can record the inlet; use templated event filters to select a run's events. By default the sensor succeeds once **at least one** matching event exists. +Choose one target form: ``obj``, ``alias_name``, or ``name`` / ``uri``. The name and URI may be +supplied together, but other combinations are rejected to avoid silently selecting a different asset. + .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python :dedent: 4 @@ -68,7 +71,8 @@ Use ``expected_count`` and ``count_policy`` to control how many processed events * ``count_policy="exact"`` succeeds only at ``expected_count``. Use this policy with zero to check that no matching events exist. An exact count can be missed if several events arrive between pokes. -Counts must be non-negative. With the minimum policy, zero always satisfies the count condition. +Counts must be non-negative integers, and ``limit`` must be a positive integer when supplied. +With the minimum policy, zero always satisfies the count condition. If no ``process_result`` callback is provided, a ``limit`` below ``expected_count`` is rejected at construction instead of waiting until the sensor times out. @@ -86,6 +90,15 @@ filter the fetched events **before** the count check. It receives the list of as return a list; the processed events are pushed to XCom. It runs on every poke, so it should be idempotent and free of side effects. +The query applies ``limit`` **before** processing. A callback may expand the fetched list, so +``limit < expected_count`` is allowed when a callback is supplied; the count is checked on its +output. Choose the limit with any filtering or deduplication in mind. + +With ascending order and a limit, each poke returns the same oldest matching events while those +events remain in the query range. If the callback rejects them, newer acceptable events beyond +the limit are never inspected. Prefer query filters such as ``partition_key``, ``extra`` and time +bounds where possible. For a check of recent events, use ``ascending=False`` with a suitable limit. + .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python :dedent: 0 diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index c9482f405ac9..3afd06536579 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -60,14 +60,15 @@ class AssetEventSensor(BaseSensorOperator): :param obj: The :class:`~airflow.sdk.Asset` or :class:`~airflow.sdk.AssetAlias` to wait on. The target is declared as an inlet. As an alternative, pass ``name``/``uri``/``alias_name`` - directly. Target identifiers are static; event filters can be templated. + directly. These alternatives cannot be combined with ``obj`` or with each other, except + for ``name`` and ``uri`` together. Target identifiers are static; event filters can be templated. :param name: The asset name to fetch events for. :param uri: The asset uri to fetch events for. :param alias_name: The asset alias name to fetch events for. :param after: Only include events at or after this timestamp. :param before: Only include events at or before this timestamp. :param ascending: Whether events are returned in ascending timestamp order. - :param limit: Maximum number of events to fetch. + :param limit: Positive maximum number of events to fetch, before applying ``process_result``. :param partition_key: Filter by exact partition key match. :param partition_key_regexp_pattern: Filter by partition key regexp pattern. :param extra: Filter by key/value pairs contained in the event ``extra`` field. @@ -115,6 +116,10 @@ def __init__( "AssetEventSensor requires Apache Airflow 3.4+ because the asset event filters " "it relies on are only available from 3.4 onwards." ) + if obj is not None and any(value is not None for value in (name, uri, alias_name)): + raise ValueError("`obj` cannot be combined with `name`, `uri`, or `alias_name`.") + if alias_name is not None and (name is not None or uri is not None): + raise ValueError("`alias_name` cannot be combined with `name` or `uri`.") self.obj: Asset | AssetAlias | AssetRef if obj is not None: if not isinstance(obj, (Asset, AssetAlias)): @@ -130,8 +135,15 @@ def __init__( self.obj = Asset.ref(uri=uri) else: raise ValueError("One of `obj`, `name`, `uri`, or `alias_name` must be provided.") + if not isinstance(expected_count, int) or isinstance(expected_count, bool): + raise TypeError("`expected_count` must be an integer.") if expected_count < 0: raise ValueError(f"`expected_count` must be a non-negative integer, got {expected_count}.") + if limit is not None: + if not isinstance(limit, int) or isinstance(limit, bool): + raise TypeError("`limit` must be an integer.") + if limit <= 0: + raise ValueError("`limit` must be positive.") if count_policy not in {"minimum", "exact"}: raise ValueError(f"`count_policy` must be 'minimum' or 'exact', got {count_policy!r}.") if process_result is None and limit is not None and limit < expected_count: diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index 1b4cf6b9ed05..fa9cacb718ec 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -120,10 +120,48 @@ def test_target_rejects_bad_type(self): with pytest.raises(TypeError, match="Asset.*AssetAlias"): AssetEventSensor(task_id="s", obj=object()) + @pytest.mark.parametrize( + "target", + [ + {"name": ASSET_NAME}, + {"uri": ASSET_URI}, + {"name": ASSET_NAME, "uri": ASSET_URI}, + {"alias_name": ALIAS_NAME}, + ], + ) + @pytest.mark.parametrize("use_alias", [False, True]) + def test_rejects_obj_with_raw_selector(self, asset, target, use_alias): + obj = AssetAlias(name=ALIAS_NAME) if use_alias else asset + with pytest.raises(ValueError, match="obj"): + AssetEventSensor(task_id="s", obj=obj, **target) + + @pytest.mark.parametrize( + "target", + [{"name": ASSET_NAME}, {"uri": ASSET_URI}, {"name": ASSET_NAME, "uri": ASSET_URI}], + ) + def test_rejects_alias_with_asset_selector(self, target): + with pytest.raises(ValueError, match="alias_name"): + AssetEventSensor(task_id="s", alias_name=ALIAS_NAME, **target) + + @pytest.mark.parametrize("expected_count", [1.5, "1", True, None]) + def test_rejects_noninteger_expected_count(self, asset, expected_count): + with pytest.raises(TypeError, match="expected_count"): + AssetEventSensor(task_id="s", obj=asset, expected_count=expected_count) + def test_rejects_negative_expected_count(self, asset): with pytest.raises(ValueError, match="expected_count"): AssetEventSensor(task_id="s", obj=asset, expected_count=-1) + @pytest.mark.parametrize("limit", [0.5, "1", True]) + def test_rejects_noninteger_limit(self, asset, limit): + with pytest.raises(TypeError, match="limit"): + AssetEventSensor(task_id="s", obj=asset, limit=limit) + + @pytest.mark.parametrize("limit", [0, -1]) + def test_rejects_nonpositive_limit(self, asset, limit): + with pytest.raises(ValueError, match="limit"): + AssetEventSensor(task_id="s", obj=asset, limit=limit, expected_count=0) + def test_rejects_invalid_count_policy(self, asset): with pytest.raises(ValueError, match="count_policy"): AssetEventSensor(task_id="s", obj=asset, count_policy="unknown") @@ -343,6 +381,32 @@ def test_processing_can_expand_limited_results(self, asset, events_response, moc assert bool(result) is True assert [event["id"] for event in result.xcom_value] == [1, 1] + def test_processing_receives_only_limited_results( + self, asset, events_response, mock_supervisor_comms, mocker + ): + mock_supervisor_comms.send.return_value = AssetEventsResult( + asset_events=[events_response.asset_events[2]] + ) + process_result = mocker.create_autospec(only_us_partitions, side_effect=only_us_partitions) + sensor = AssetEventSensor( + task_id="s", + obj=asset, + after=_get_timestamp(3), + ascending=True, + limit=1, + process_result=process_result, + ) + result = sensor.poke(_get_context(sensor)) + assert bool(result) is False + assert result.xcom_value is None + process_result.assert_called_once() + assert [event.id for event in process_result.call_args.args[0]] == [3] + mock_supervisor_comms.send.assert_called_once_with( + GetAssetEventByAsset( + name=ASSET_NAME, uri=ASSET_URI, after=_get_timestamp(3), ascending=True, limit=1 + ) + ) + def test_processing_can_return_json_values(self, asset, events_response, mock_supervisor_comms): mock_supervisor_comms.send.return_value = events_response sensor = AssetEventSensor( From 3997e6679637425ab5d46a5055651a7e5008c4b3 Mon Sep 17 00:00:00 2001 From: hussein-awala Date: Tue, 20 Oct 2026 23:58:27 +0200 Subject: [PATCH 10/21] Use UTC in asset sensor tests --- providers/standard/tests/unit/standard/sensors/test_asset.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index fa9cacb718ec..b6c3324e29fa 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -16,7 +16,7 @@ # under the License. from __future__ import annotations -from datetime import datetime, timezone +from datetime import UTC, datetime from typing import Any from unittest.mock import call @@ -47,7 +47,7 @@ def _get_timestamp(day: int) -> datetime: - return datetime(2024, 1, day, tzinfo=timezone.utc) + return datetime(2024, 1, day, tzinfo=UTC) def _get_context(sensor: AssetEventSensor) -> dict[str, Any]: From d8191b6f39f200e6e0341fede1b8edd54e8a79c1 Mon Sep 17 00:00:00 2001 From: Tzu-ping Chung Date: Tue, 27 Oct 2026 15:23:03 +0800 Subject: [PATCH 11/21] Unify sensor asset argument --- providers/standard/docs/sensors/asset.rst | 13 +-- .../example_dags/example_asset_sensor.py | 6 +- .../providers/standard/sensors/asset.py | 89 ++++++--------- .../tests/unit/standard/sensors/test_asset.py | 102 +++++------------- 4 files changed, 68 insertions(+), 142 deletions(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index 5f40016efdf6..df17f76417d9 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -42,14 +42,11 @@ without changing the Dag's schedule. It reads events through ``context["inlet_ev Basic usage ----------- -Pass an :class:`~airflow.sdk.Asset` or :class:`~airflow.sdk.AssetAlias` as ``obj``, or use the raw -``name`` / ``uri`` / ``alias_name`` arguments. A name-only or URI-only target is an asset reference -and must resolve to an existing asset when the task context is created. Target identifiers are -static so Airflow can record the inlet; use templated event filters to select a run's events. -By default the sensor succeeds once **at least one** matching event exists. - -Choose one target form: ``obj``, ``alias_name``, or ``name`` / ``uri``. The name and URI may be -supplied together, but other combinations are rejected to avoid silently selecting a different asset. +Pass an :class:`~airflow.sdk.Asset`, :meth:`~airflow.sdk.Asset.ref`, or +:class:`~airflow.sdk.AssetAlias` as ``asset``. A reference must resolve to an +existing asset when the task starts. The target is static so Airflow can record +the inlet; use templated event filters to select a run's events. By default the +sensor succeeds once **at least one** matching event exists. .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python diff --git a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py index a97534d8180a..56d2ac2ab502 100644 --- a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py +++ b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py @@ -53,14 +53,14 @@ def latest_event_only(events: list[Any]) -> list[Any]: # [START example_asset_event_sensor] wait_for_asset_event = AssetEventSensor( task_id="wait_for_asset_event", - obj=my_asset, + asset=my_asset, ) # [END example_asset_event_sensor] # [START example_asset_event_sensor_filtered] wait_for_partition_events = AssetEventSensor( task_id="wait_for_partition_events", - obj=my_asset, + asset=my_asset, partition_key="{{ data_interval_start | ds }}", expected_count=3, count_policy="minimum", @@ -70,7 +70,7 @@ def latest_event_only(events: list[Any]) -> list[Any]: # [START example_asset_event_sensor_process_result] wait_for_latest_asset_event = AssetEventSensor( task_id="wait_for_latest_asset_event", - obj=my_asset, + asset=my_asset, process_result=latest_event_only, ) # [END example_asset_event_sensor_process_result] diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index 3afd06536579..4138e97bbeee 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -19,12 +19,7 @@ from typing import TYPE_CHECKING, Any, Literal from airflow.providers.common.compat.module_loading import import_string -from airflow.providers.common.compat.sdk import ( - Asset, - AssetAlias, - BaseSensorOperator, - PokeReturnValue, -) +from airflow.providers.common.compat.sdk import BaseSensorOperator, PokeReturnValue from airflow.providers.standard.version_compat import AIRFLOW_V_3_4_PLUS if TYPE_CHECKING: @@ -32,7 +27,7 @@ from datetime import datetime from airflow.providers.common.compat.sdk import Context - from airflow.sdk.definitions.asset import AssetRef + from airflow.sdk.definitions.asset import Asset, AssetAlias, AssetRef def _serialize_events(events: list[Any]) -> list[Any]: @@ -51,36 +46,39 @@ class AssetEventSensor(BaseSensorOperator): """ Wait for asset events matching the given filters to reach an expected count. - The sensor fetches asset events (by asset or asset alias) matching the supplied filters, - optionally applies a ``process_result`` callable to transform, deduplicate or filter them, - and succeeds once the resulting number of events satisfies ``expected_count``. + The sensor fetches events of an asset, asset reference, or asset alias + matching the supplied filters, optionally applies a ``process_result`` + callable to transform, deduplicate or filter them, and succeeds once the + resulting number of events satisfies ``expected_count``. This sensor requires Apache Airflow 3.4+ because the ``partition_key``, - ``partition_key_regexp_pattern`` and ``extra`` asset-event filters are only available there. - - :param obj: The :class:`~airflow.sdk.Asset` or :class:`~airflow.sdk.AssetAlias` to wait on. - The target is declared as an inlet. As an alternative, pass ``name``/``uri``/``alias_name`` - directly. These alternatives cannot be combined with ``obj`` or with each other, except - for ``name`` and ``uri`` together. Target identifiers are static; event filters can be templated. - :param name: The asset name to fetch events for. - :param uri: The asset uri to fetch events for. - :param alias_name: The asset alias name to fetch events for. + ``partition_key_regexp_pattern`` and ``extra`` asset-event filters are only + available there. + + :param asset: The :class:`~airflow.sdk.Asset`, :meth:`~airflow.sdk.Asset.ref`, + or :class:`~airflow.sdk.AssetAlias` to wait on. It is declared as an + inlet. A reference must resolve to an existing asset when the task + starts. The target is static; event filters can be templated. :param after: Only include events at or after this timestamp. :param before: Only include events at or before this timestamp. :param ascending: Whether events are returned in ascending timestamp order. - :param limit: Positive maximum number of events to fetch, before applying ``process_result``. + :param limit: Positive maximum number of events to fetch, before applying + ``process_result``. :param partition_key: Filter by exact partition key match. :param partition_key_regexp_pattern: Filter by partition key regexp pattern. - :param extra: Filter by key/value pairs contained in the event ``extra`` field. - :param expected_count: The non-negative number of processed events required to succeed. - Defaults to one. If ``process_result`` is omitted, ``limit`` must not be smaller. - :param count_policy: ``"minimum"`` (the default) waits for at least ``expected_count`` events; - ``"exact"`` requires exactly that number. To check for no events, use ``"exact"`` and zero. - :param process_result: A callable (or a dotted import path to one) applied to the fetched - events before the count check, to transform, deduplicate or filter them. It receives the - list of asset events and must return a list. It runs on every poke, so it should be - **idempotent / side-effect free**, and its return value must be JSON-serializable to be - pushed to XCom. + :param extra: Filter by key/value pairs contained in the event ``extra``. + :param expected_count: The non-negative number of processed events required + to succeed. Defaults to 1. If ``process_result`` is omitted, ``limit`` + must not be smaller. + :param count_policy: ``"minimum"`` (the default) waits for at least + ``expected_count`` events; ``"exact"`` requires exactly that number. To + check for no events, use ``"exact"`` and zero. + :param process_result: A callable (or a dotted import path to one) applied + to the fetched events before the count check, to transform, deduplicate + or filter them. It receives the list of asset events and must return a + list. It runs on every poke, so it should be idempotent and free of + side-effects. Its return value must be JSON-serializable to be pushed + into XCom. """ template_fields: Sequence[str] = ( @@ -94,10 +92,7 @@ class AssetEventSensor(BaseSensorOperator): def __init__( self, *, - obj: Asset | AssetAlias | None = None, - name: str | None = None, - uri: str | None = None, - alias_name: str | None = None, + asset: Asset | AssetAlias | AssetRef, after: datetime | str | None = None, before: datetime | str | None = None, ascending: bool = True, @@ -116,25 +111,6 @@ def __init__( "AssetEventSensor requires Apache Airflow 3.4+ because the asset event filters " "it relies on are only available from 3.4 onwards." ) - if obj is not None and any(value is not None for value in (name, uri, alias_name)): - raise ValueError("`obj` cannot be combined with `name`, `uri`, or `alias_name`.") - if alias_name is not None and (name is not None or uri is not None): - raise ValueError("`alias_name` cannot be combined with `name` or `uri`.") - self.obj: Asset | AssetAlias | AssetRef - if obj is not None: - if not isinstance(obj, (Asset, AssetAlias)): - raise TypeError(f"`obj` must be an Asset or AssetAlias, got {type(obj).__name__}") - self.obj = obj - elif alias_name is not None: - self.obj = AssetAlias(alias_name) - elif name is not None and uri is not None: - self.obj = Asset(name=name, uri=uri) - elif name is not None: - self.obj = Asset.ref(name=name) - elif uri is not None: - self.obj = Asset.ref(uri=uri) - else: - raise ValueError("One of `obj`, `name`, `uri`, or `alias_name` must be provided.") if not isinstance(expected_count, int) or isinstance(expected_count, bool): raise TypeError("`expected_count` must be an integer.") if expected_count < 0: @@ -150,8 +126,9 @@ def __init__( raise ValueError( "`limit` must be at least `expected_count` when `process_result` is not provided." ) - if self.obj not in self.inlets: - self.inlets.append(self.obj) + self.asset = asset + if asset not in self.inlets: + self.inlets.append(asset) self.after = after self.before = before @@ -171,7 +148,7 @@ def _apply_process_result(self, events: list[Any]) -> list[Any]: return func(events) def poke(self, context: Context) -> PokeReturnValue: - accessor = context["inlet_events"][self.obj] + accessor = context["inlet_events"][self.asset] if self.after is not None: accessor.after(self.after if isinstance(self.after, str) else self.after.isoformat()) if self.before is not None: diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index b6c3324e29fa..12aefe23d5c9 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -96,85 +96,54 @@ def events_response(): class TestInit: - def test_requires_a_target(self): - with pytest.raises(ValueError, match="obj.*name.*uri.*alias_name"): - AssetEventSensor(task_id="s") - @pytest.mark.parametrize("use_alias", [False, True]) def test_declares_target_as_inlet(self, asset, use_alias): - obj = AssetAlias(name=ALIAS_NAME) if use_alias else asset - sensor = AssetEventSensor(task_id="s", obj=obj) - assert sensor.obj == obj - assert sensor.inlets == [obj] + target = AssetAlias(name=ALIAS_NAME) if use_alias else asset + sensor = AssetEventSensor(task_id="s", asset=target) + assert sensor.asset == target + assert sensor.inlets == [target] @pytest.mark.parametrize("include_target", [False, True]) def test_preserves_existing_inlets_without_duplicates(self, asset, include_target): other_asset = Asset("s3://bucket/other") inlets = [other_asset, asset] if include_target else [other_asset] original_inlets = inlets.copy() - sensor = AssetEventSensor(task_id="s", obj=asset, inlets=inlets) + sensor = AssetEventSensor(task_id="s", asset=asset, inlets=inlets) assert sensor.inlets == [other_asset, asset] assert inlets == original_inlets - def test_target_rejects_bad_type(self): - with pytest.raises(TypeError, match="Asset.*AssetAlias"): - AssetEventSensor(task_id="s", obj=object()) - - @pytest.mark.parametrize( - "target", - [ - {"name": ASSET_NAME}, - {"uri": ASSET_URI}, - {"name": ASSET_NAME, "uri": ASSET_URI}, - {"alias_name": ALIAS_NAME}, - ], - ) - @pytest.mark.parametrize("use_alias", [False, True]) - def test_rejects_obj_with_raw_selector(self, asset, target, use_alias): - obj = AssetAlias(name=ALIAS_NAME) if use_alias else asset - with pytest.raises(ValueError, match="obj"): - AssetEventSensor(task_id="s", obj=obj, **target) - - @pytest.mark.parametrize( - "target", - [{"name": ASSET_NAME}, {"uri": ASSET_URI}, {"name": ASSET_NAME, "uri": ASSET_URI}], - ) - def test_rejects_alias_with_asset_selector(self, target): - with pytest.raises(ValueError, match="alias_name"): - AssetEventSensor(task_id="s", alias_name=ALIAS_NAME, **target) - @pytest.mark.parametrize("expected_count", [1.5, "1", True, None]) def test_rejects_noninteger_expected_count(self, asset, expected_count): with pytest.raises(TypeError, match="expected_count"): - AssetEventSensor(task_id="s", obj=asset, expected_count=expected_count) + AssetEventSensor(task_id="s", asset=asset, expected_count=expected_count) def test_rejects_negative_expected_count(self, asset): with pytest.raises(ValueError, match="expected_count"): - AssetEventSensor(task_id="s", obj=asset, expected_count=-1) + AssetEventSensor(task_id="s", asset=asset, expected_count=-1) @pytest.mark.parametrize("limit", [0.5, "1", True]) def test_rejects_noninteger_limit(self, asset, limit): with pytest.raises(TypeError, match="limit"): - AssetEventSensor(task_id="s", obj=asset, limit=limit) + AssetEventSensor(task_id="s", asset=asset, limit=limit) @pytest.mark.parametrize("limit", [0, -1]) def test_rejects_nonpositive_limit(self, asset, limit): with pytest.raises(ValueError, match="limit"): - AssetEventSensor(task_id="s", obj=asset, limit=limit, expected_count=0) + AssetEventSensor(task_id="s", asset=asset, limit=limit, expected_count=0) def test_rejects_invalid_count_policy(self, asset): with pytest.raises(ValueError, match="count_policy"): - AssetEventSensor(task_id="s", obj=asset, count_policy="unknown") + AssetEventSensor(task_id="s", asset=asset, count_policy="unknown") @pytest.mark.parametrize("count_policy", ["minimum", "exact"]) def test_rejects_limit_below_expected_count_without_processing(self, asset, count_policy): with pytest.raises(ValueError, match="limit"): - AssetEventSensor(task_id="s", obj=asset, limit=1, expected_count=3, count_policy=count_policy) + AssetEventSensor(task_id="s", asset=asset, limit=1, expected_count=3, count_policy=count_policy) def test_requires_airflow_3_4(self, mocker, asset): mocker.patch("airflow.providers.standard.sensors.asset.AIRFLOW_V_3_4_PLUS", False) with pytest.raises(RuntimeError, match="requires Apache Airflow 3.4"): - AssetEventSensor(task_id="s", obj=asset) + AssetEventSensor(task_id="s", asset=asset) def test_template_fields(self): assert set(AssetEventSensor.template_fields) == { @@ -188,7 +157,7 @@ def test_template_fields(self): def test_renders_filters_without_changing_lineage(self, asset): sensor = AssetEventSensor( task_id="s", - obj=asset, + asset=asset, partition_key="{{ ds }}", partition_key_regexp_pattern="{{ params.region }}.*", extra={"region": "{{ params.region }}"}, @@ -201,14 +170,14 @@ def test_renders_filters_without_changing_lineage(self, asset): assert sensor.extra == {"region": "us"} assert sensor.after == "2024-01-01T00:00:00+00:00" assert sensor.before == "2024-01-01T23:59:59+00:00" - assert sensor.obj == asset + assert sensor.asset == asset assert sensor.inlets == [asset] class TestPoke: def test_returns_serialized_events(self, asset, events_response, mock_supervisor_comms): mock_supervisor_comms.send.return_value = events_response - sensor = AssetEventSensor(task_id="s", obj=asset) + sensor = AssetEventSensor(task_id="s", asset=asset) result = sensor.poke(_get_context(sensor)) assert isinstance(result, PokeReturnValue) assert bool(result) is True @@ -239,7 +208,7 @@ def test_count_policy( events = events_response.asset_events[:actual_count] mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=events) sensor = AssetEventSensor( - task_id="s", obj=asset, count_policy=count_policy, expected_count=expected_count + task_id="s", asset=asset, count_policy=count_policy, expected_count=expected_count ) result = sensor.poke(_get_context(sensor)) assert bool(result) is done @@ -249,10 +218,10 @@ def test_count_policy( @pytest.mark.parametrize("string_bounds", [False, True]) def test_forwards_all_filters(self, asset, mock_supervisor_comms, use_alias, string_bounds): mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=[]) - obj = AssetAlias(name=ALIAS_NAME) if use_alias else asset + target = AssetAlias(name=ALIAS_NAME) if use_alias else asset sensor = AssetEventSensor( task_id="s", - obj=obj, + asset=target, after=_get_timestamp(1).isoformat() if string_bounds else _get_timestamp(1), before=_get_timestamp(9).isoformat() if string_bounds else _get_timestamp(9), ascending=False, @@ -281,9 +250,8 @@ def test_forwards_all_filters(self, asset, mock_supervisor_comms, use_alias, str @pytest.mark.parametrize("selector", ["name", "uri"]) def test_resolves_asset_reference(self, selector, events_response, mock_supervisor_comms): target = {"name": ASSET_NAME} if selector == "name" else {"uri": ASSET_URI} - sensor = AssetEventSensor(task_id="s", **target) - assert sensor.obj == Asset.ref(**target) - assert sensor.inlets == [sensor.obj] + sensor = AssetEventSensor(task_id="s", asset=Asset.ref(**target)) + assert sensor.inlets == [Asset.ref(**target)] mock_supervisor_comms.send.side_effect = [ AssetResult(name=ASSET_NAME, uri=ASSET_URI, group="asset", extra={}), events_response, @@ -296,25 +264,9 @@ def test_resolves_asset_reference(self, selector, events_response, mock_supervis ) assert mock_supervisor_comms.send.call_args_list == [call(resolution), call(query)] - @pytest.mark.parametrize("use_alias", [False, True]) - def test_raw_target(self, asset, events_response, mock_supervisor_comms, use_alias): - target = {"alias_name": ALIAS_NAME} if use_alias else {"name": ASSET_NAME, "uri": ASSET_URI} - sensor = AssetEventSensor(task_id="s", **target) - expected_obj = AssetAlias(name=ALIAS_NAME) if use_alias else asset - assert sensor.obj == expected_obj - assert sensor.inlets == [expected_obj] - mock_supervisor_comms.send.return_value = events_response - assert bool(sensor.poke(_get_context(sensor))) is True - query = ( - GetAssetEventByAssetAlias(alias_name=ALIAS_NAME) - if use_alias - else GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI) - ) - mock_supervisor_comms.send.assert_called_once_with(query) - def test_fetches_fresh_events_on_every_poke(self, asset, events_response, mock_supervisor_comms): mock_supervisor_comms.send.side_effect = [AssetEventsResult(asset_events=[]), events_response] - sensor = AssetEventSensor(task_id="s", obj=asset) + sensor = AssetEventSensor(task_id="s", asset=asset) context = _get_context(sensor) assert bool(sensor.poke(context)) is False assert bool(sensor.poke(context)) is True @@ -323,7 +275,7 @@ def test_fetches_fresh_events_on_every_poke(self, asset, events_response, mock_s def test_execute_returns_xcom_payload(self, asset, events_response, mock_supervisor_comms): mock_supervisor_comms.send.return_value = events_response - sensor = AssetEventSensor(task_id="s", obj=asset) + sensor = AssetEventSensor(task_id="s", asset=asset) result = sensor.execute(_get_context(sensor)) assert result == [event.model_dump(mode="json") for event in events_response.asset_events] @@ -353,7 +305,7 @@ def test_processes_events_before_counting( mock_supervisor_comms.send.return_value = events_response sensor = AssetEventSensor( task_id="s", - obj=asset, + asset=asset, process_result=process_result, expected_count=expected_count, count_policy="exact", @@ -371,7 +323,7 @@ def test_processing_can_expand_limited_results(self, asset, events_response, moc ) sensor = AssetEventSensor( task_id="s", - obj=asset, + asset=asset, limit=1, expected_count=2, count_policy="exact", @@ -390,7 +342,7 @@ def test_processing_receives_only_limited_results( process_result = mocker.create_autospec(only_us_partitions, side_effect=only_us_partitions) sensor = AssetEventSensor( task_id="s", - obj=asset, + asset=asset, after=_get_timestamp(3), ascending=True, limit=1, @@ -411,7 +363,7 @@ def test_processing_can_return_json_values(self, asset, events_response, mock_su mock_supervisor_comms.send.return_value = events_response sensor = AssetEventSensor( task_id="s", - obj=asset, + asset=asset, process_result=lambda events: [{"partition": event.partition_key} for event in events], ) result = sensor.poke(_get_context(sensor)) @@ -425,6 +377,6 @@ def boom(events): raise RuntimeError("process_result exploded") mock_supervisor_comms.send.return_value = events_response - sensor = AssetEventSensor(task_id="s", obj=asset, process_result=boom) + sensor = AssetEventSensor(task_id="s", asset=asset, process_result=boom) with pytest.raises(RuntimeError, match="process_result exploded"): sensor.poke(_get_context(sensor)) From 50a4d23c4bbae268e4f0193722c9708cb4c806eb Mon Sep 17 00:00:00 2001 From: Tzu-ping Chung Date: Tue, 27 Oct 2026 15:47:03 +0800 Subject: [PATCH 12/21] Work around mapped inlet population bug --- .../airflow/providers/standard/sensors/asset.py | 13 ++++++++++++- .../tests/unit/standard/sensors/test_asset.py | 16 +++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index 4138e97bbeee..4fddc7cfba1e 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -16,6 +16,7 @@ # under the License. from __future__ import annotations +import contextlib from typing import TYPE_CHECKING, Any, Literal from airflow.providers.common.compat.module_loading import import_string @@ -28,6 +29,7 @@ from airflow.providers.common.compat.sdk import Context from airflow.sdk.definitions.asset import Asset, AssetAlias, AssetRef + from airflow.sdk.execution_time.context import InletEventsAccessor def _serialize_events(events: list[Any]) -> list[Any]: @@ -147,8 +149,17 @@ def _apply_process_result(self, events: list[Any]) -> list[Any]: func = self.process_result if callable(self.process_result) else import_string(self.process_result) return func(events) + def _get_accessor(self, context: Context) -> InletEventsAccessor: + # The mapped operator's inlets don't include the asset added in init. + # TODO: Remove this once the min Airflow refreshes after unmapping. + with contextlib.suppress(KeyError): + return context["inlet_events"][self.asset] + from airflow.sdk.execution_time.context import InletEventsAccessors + + return InletEventsAccessors([self.asset])[self.asset] + def poke(self, context: Context) -> PokeReturnValue: - accessor = context["inlet_events"][self.asset] + accessor = self._get_accessor(context) if self.after is not None: accessor.after(self.after if isinstance(self.after, str) else self.after.isoformat()) if self.before is not None: diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index 12aefe23d5c9..29b66b954c1a 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -22,7 +22,7 @@ import pytest -from airflow.providers.common.compat.sdk import Asset, AssetAlias, PokeReturnValue +from airflow.providers.common.compat.sdk import DAG, Asset, AssetAlias, PokeReturnValue from airflow.providers.standard.sensors.asset import AssetEventSensor from tests_common.test_utils.version_compat import AIRFLOW_V_3_4_PLUS @@ -279,6 +279,20 @@ def test_execute_returns_xcom_payload(self, asset, events_response, mock_supervi result = sensor.execute(_get_context(sensor)) assert result == [event.model_dump(mode="json") for event in events_response.asset_events] + def test_mapped_task(self, asset, events_response, create_runtime_ti, mock_supervisor_comms): + with DAG("test_dag"): + mapped = AssetEventSensor.partial(task_id="s", asset=asset).expand( + partition_key=["us|2024-01-01", "us|2024-01-02"] + ) + ti = create_runtime_ti(task=mapped, map_index=1) + context = ti.get_template_context() + ti.render_templates(context=context) + mock_supervisor_comms.send.return_value = events_response + assert bool(ti.task.poke(context)) is True + mock_supervisor_comms.send.assert_called_with( + GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, partition_key="us|2024-01-02") + ) + class TestProcessResult: @pytest.mark.parametrize( From 609529a20f604b1028052496b1b764948dc0f50c Mon Sep 17 00:00:00 2001 From: Tzu-ping Chung Date: Tue, 27 Oct 2026 16:06:22 +0800 Subject: [PATCH 13/21] Tighten limit and expected_count checks --- providers/standard/docs/sensors/asset.rst | 11 ++++++---- .../providers/standard/sensors/asset.py | 16 +++++++++----- .../tests/unit/standard/sensors/test_asset.py | 22 ++++++++++++++++--- 3 files changed, 37 insertions(+), 12 deletions(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index df17f76417d9..2aaa33e5714b 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -68,10 +68,13 @@ Use ``expected_count`` and ``count_policy`` to control how many processed events * ``count_policy="exact"`` succeeds only at ``expected_count``. Use this policy with zero to check that no matching events exist. An exact count can be missed if several events arrive between pokes. -Counts must be non-negative integers, and ``limit`` must be a positive integer when supplied. -With the minimum policy, zero always satisfies the count condition. -If no ``process_result`` callback is provided, a ``limit`` below ``expected_count`` is rejected -at construction instead of waiting until the sensor times out. +Counts must be non-negative integers, and ``limit`` must be a positive integer +when supplied. With the *minimum* policy, zero always satisfies the count +condition. + +If a ``process_result`` callback is not provided, the sensor raises *ValueError* +at construction if ``limit`` is less than ``expected_count`` with the *minimum* +policy, or not greater than ``expected_count`` with the *exact* policy. .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index 4fddc7cfba1e..e47ef0f5d9a4 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -71,7 +71,7 @@ class AssetEventSensor(BaseSensorOperator): :param extra: Filter by key/value pairs contained in the event ``extra``. :param expected_count: The non-negative number of processed events required to succeed. Defaults to 1. If ``process_result`` is omitted, ``limit`` - must not be smaller. + must not be smaller, or must be greater with the ``"exact"`` policy. :param count_policy: ``"minimum"`` (the default) waits for at least ``expected_count`` events; ``"exact"`` requires exactly that number. To check for no events, use ``"exact"`` and zero. @@ -124,10 +124,16 @@ def __init__( raise ValueError("`limit` must be positive.") if count_policy not in {"minimum", "exact"}: raise ValueError(f"`count_policy` must be 'minimum' or 'exact', got {count_policy!r}.") - if process_result is None and limit is not None and limit < expected_count: - raise ValueError( - "`limit` must be at least `expected_count` when `process_result` is not provided." - ) + if process_result is None and limit is not None: + if count_policy == "exact" and limit <= expected_count: + raise ValueError( + "`limit` must be greater than `expected_count` with the exact count policy, " + "otherwise extra events cannot be detected." + ) + if limit < expected_count: + raise ValueError( + "`limit` must be at least `expected_count` when `process_result` is not provided." + ) self.asset = asset if asset not in self.inlets: self.inlets.append(asset) diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index 29b66b954c1a..04332fb3b58d 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -135,10 +135,26 @@ def test_rejects_invalid_count_policy(self, asset): with pytest.raises(ValueError, match="count_policy"): AssetEventSensor(task_id="s", asset=asset, count_policy="unknown") - @pytest.mark.parametrize("count_policy", ["minimum", "exact"]) - def test_rejects_limit_below_expected_count_without_processing(self, asset, count_policy): + @pytest.mark.parametrize( + ("count_policy", "limit", "expected_count"), + [("minimum", 1, 3), ("exact", 1, 3), ("exact", 3, 3)], + ) + def test_rejects_insufficient_limit_without_processing(self, asset, count_policy, limit, expected_count): with pytest.raises(ValueError, match="limit"): - AssetEventSensor(task_id="s", asset=asset, limit=1, expected_count=3, count_policy=count_policy) + AssetEventSensor( + task_id="s", + asset=asset, + limit=limit, + expected_count=expected_count, + count_policy=count_policy, + ) + + @pytest.mark.parametrize(("count_policy", "limit"), [("minimum", 3), ("exact", 4)]) + def test_accepts_sufficient_limit_without_processing(self, asset, count_policy, limit): + sensor = AssetEventSensor( + task_id="s", asset=asset, limit=limit, expected_count=3, count_policy=count_policy + ) + assert sensor.limit == limit def test_requires_airflow_3_4(self, mocker, asset): mocker.patch("airflow.providers.standard.sensors.asset.AIRFLOW_V_3_4_PLUS", False) From d66327ce143ba34e941455e4df4262414cb6f4ae Mon Sep 17 00:00:00 2001 From: Tzu-ping Chung Date: Tue, 27 Oct 2026 16:32:25 +0800 Subject: [PATCH 14/21] Make sensor 3.2-compatible Specific arguments that only make sense in 3.4+ get additional checks at parse time to be rejected. Importing and using the sensor works on 3.2 and 3.3 as long as you do not use the 3.4+ parameters. --- providers/standard/docs/sensors/asset.rst | 6 +-- .../providers/standard/sensors/asset.py | 28 ++++++++----- .../tests/unit/standard/sensors/test_asset.py | 42 +++++++++++++------ 3 files changed, 51 insertions(+), 25 deletions(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index 2aaa33e5714b..b36b91d9ef82 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -35,9 +35,9 @@ without changing the Dag's schedule. It reads events through ``context["inlet_ev .. note:: - This sensor requires **Apache Airflow 3.4+**, because the ``partition_key``, - ``partition_key_regexp_pattern`` and ``extra`` asset-event filters it relies on are only - available in Airflow 3.4 and later. + This sensor requires **Apache Airflow 3.2+**. The ``partition_key``, + ``partition_key_regexp_pattern`` and ``extra`` filters require + **Apache Airflow 3.4+**. Basic usage ----------- diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index e47ef0f5d9a4..667f14699a57 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -20,8 +20,15 @@ from typing import TYPE_CHECKING, Any, Literal from airflow.providers.common.compat.module_loading import import_string -from airflow.providers.common.compat.sdk import BaseSensorOperator, PokeReturnValue -from airflow.providers.standard.version_compat import AIRFLOW_V_3_4_PLUS +from airflow.providers.common.compat.sdk import ( + AirflowOptionalProviderFeatureException, + BaseSensorOperator, + PokeReturnValue, +) +from airflow.providers.standard.version_compat import AIRFLOW_V_3_2_PLUS, AIRFLOW_V_3_4_PLUS + +if not AIRFLOW_V_3_2_PLUS: + raise AirflowOptionalProviderFeatureException("AssetEventSensor needs Airflow 3.2+.") if TYPE_CHECKING: from collections.abc import Callable, Sequence @@ -53,9 +60,8 @@ class AssetEventSensor(BaseSensorOperator): callable to transform, deduplicate or filter them, and succeeds once the resulting number of events satisfies ``expected_count``. - This sensor requires Apache Airflow 3.4+ because the ``partition_key``, - ``partition_key_regexp_pattern`` and ``extra`` asset-event filters are only - available there. + This sensor requires Apache Airflow 3.2+. The ``partition_key``, + ``partition_key_regexp_pattern`` and ``extra`` filters require Airflow 3.4+. :param asset: The :class:`~airflow.sdk.Asset`, :meth:`~airflow.sdk.Asset.ref`, or :class:`~airflow.sdk.AssetAlias` to wait on. It is declared as an @@ -107,12 +113,14 @@ def __init__( process_result: Callable[[list[Any]], list[Any]] | str | None = None, **kwargs, ) -> None: - super().__init__(**kwargs) - if not AIRFLOW_V_3_4_PLUS: - raise RuntimeError( - "AssetEventSensor requires Apache Airflow 3.4+ because the asset event filters " - "it relies on are only available from 3.4 onwards." + if not AIRFLOW_V_3_4_PLUS and ( + partition_key is not None or partition_key_regexp_pattern is not None or extra is not None + ): + raise AirflowOptionalProviderFeatureException( + "AssetEventSensor filters partition_key, partition_key_regexp_pattern and extra " + "need Airflow 3.4+." ) + super().__init__(**kwargs) if not isinstance(expected_count, int) or isinstance(expected_count, bool): raise TypeError("`expected_count` must be an integer.") if expected_count < 0: diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index 04332fb3b58d..00b9a46dc0bb 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -22,12 +22,18 @@ import pytest -from airflow.providers.common.compat.sdk import DAG, Asset, AssetAlias, PokeReturnValue -from airflow.providers.standard.sensors.asset import AssetEventSensor - -from tests_common.test_utils.version_compat import AIRFLOW_V_3_4_PLUS - -if AIRFLOW_V_3_4_PLUS: +from airflow.providers.common.compat.sdk import ( + DAG, + AirflowOptionalProviderFeatureException, + Asset, + AssetAlias, + PokeReturnValue, +) + +from tests_common.test_utils.version_compat import AIRFLOW_V_3_2_PLUS, AIRFLOW_V_3_4_PLUS + +if AIRFLOW_V_3_2_PLUS: + from airflow.providers.standard.sensors.asset import AssetEventSensor from airflow.sdk.api.datamodels._generated import AssetEventResponse, AssetResponse from airflow.sdk.execution_time.comms import ( AssetEventsResult, @@ -39,7 +45,8 @@ ) from airflow.sdk.execution_time.context import InletEventsAccessors -pytestmark = pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="AssetEventSensor requires Airflow 3.4+") +pytestmark = pytest.mark.skipif(not AIRFLOW_V_3_2_PLUS, reason="AssetEventSensor requires Airflow 3.2+") +requires_3_4 = pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="Filter requires Airflow 3.4+") ASSET_NAME = "my_asset" ASSET_URI = "s3://bucket/key" @@ -156,10 +163,19 @@ def test_accepts_sufficient_limit_without_processing(self, asset, count_policy, ) assert sensor.limit == limit - def test_requires_airflow_3_4(self, mocker, asset): + @pytest.mark.parametrize( + "filters", + [{"partition_key": "a"}, {"partition_key_regexp_pattern": "a.*"}, {"extra": {"k": "v"}}], + ) + def test_partition_and_extra_filters_require_airflow_3_4(self, mocker, asset, filters): + mocker.patch("airflow.providers.standard.sensors.asset.AIRFLOW_V_3_4_PLUS", False) + with pytest.raises(AirflowOptionalProviderFeatureException, match="need Airflow 3.4"): + AssetEventSensor(task_id="s", asset=asset, **filters) + + def test_other_filters_do_not_require_airflow_3_4(self, mocker, asset): mocker.patch("airflow.providers.standard.sensors.asset.AIRFLOW_V_3_4_PLUS", False) - with pytest.raises(RuntimeError, match="requires Apache Airflow 3.4"): - AssetEventSensor(task_id="s", asset=asset) + sensor = AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1), limit=1) + assert sensor.limit == 1 def test_template_fields(self): assert set(AssetEventSensor.template_fields) == { @@ -170,6 +186,7 @@ def test_template_fields(self): "before", } + @requires_3_4 def test_renders_filters_without_changing_lineage(self, asset): sensor = AssetEventSensor( task_id="s", @@ -230,6 +247,7 @@ def test_count_policy( assert bool(result) is done assert result.xcom_value == ([event.model_dump(mode="json") for event in events] if done else None) + @requires_3_4 @pytest.mark.parametrize("use_alias", [False, True]) @pytest.mark.parametrize("string_bounds", [False, True]) def test_forwards_all_filters(self, asset, mock_supervisor_comms, use_alias, string_bounds): @@ -298,7 +316,7 @@ def test_execute_returns_xcom_payload(self, asset, events_response, mock_supervi def test_mapped_task(self, asset, events_response, create_runtime_ti, mock_supervisor_comms): with DAG("test_dag"): mapped = AssetEventSensor.partial(task_id="s", asset=asset).expand( - partition_key=["us|2024-01-01", "us|2024-01-02"] + after=[_get_timestamp(1), _get_timestamp(2)] ) ti = create_runtime_ti(task=mapped, map_index=1) context = ti.get_template_context() @@ -306,7 +324,7 @@ def test_mapped_task(self, asset, events_response, create_runtime_ti, mock_super mock_supervisor_comms.send.return_value = events_response assert bool(ti.task.poke(context)) is True mock_supervisor_comms.send.assert_called_with( - GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, partition_key="us|2024-01-02") + GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=_get_timestamp(2)) ) From 7190fa8abcb4fc3e208adc152e5c8f1705fe4b36 Mon Sep 17 00:00:00 2001 From: Tzu-ping Chung Date: Tue, 27 Oct 2026 16:50:52 +0800 Subject: [PATCH 15/21] Remove dotted process_events format --- providers/standard/docs/sensors/asset.rst | 8 ++--- .../providers/standard/sensors/asset.py | 36 +++++++------------ .../tests/unit/standard/sensors/test_asset.py | 11 ------ 3 files changed, 17 insertions(+), 38 deletions(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index b36b91d9ef82..55f24c221fa6 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -85,10 +85,10 @@ policy, or not greater than ``expected_count`` with the *exact* policy. Post-processing results ----------------------- -Pass a ``process_result`` callable (or a dotted import path to one) to transform, deduplicate or -filter the fetched events **before** the count check. It receives the list of asset events and must -return a list; the processed events are pushed to XCom. It runs on every poke, so it should be -idempotent and free of side effects. +Pass a ``process_result`` callable to transform, deduplicate or filter the +fetched events before the count check. It receives the list of asset events and +must return a list; the processed events are pushed to XCom. It runs on every +poke, so it should be idempotent and free of side effects. The query applies ``limit`` **before** processing. A callback may expand the fetched list, so ``limit < expected_count`` is allowed when a callback is supplied; the count is checked on its diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index 667f14699a57..22650e90a673 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -19,7 +19,6 @@ import contextlib from typing import TYPE_CHECKING, Any, Literal -from airflow.providers.common.compat.module_loading import import_string from airflow.providers.common.compat.sdk import ( AirflowOptionalProviderFeatureException, BaseSensorOperator, @@ -36,6 +35,7 @@ from airflow.providers.common.compat.sdk import Context from airflow.sdk.definitions.asset import Asset, AssetAlias, AssetRef + from airflow.sdk.execution_time.comms import AssetEventResult from airflow.sdk.execution_time.context import InletEventsAccessor @@ -81,12 +81,11 @@ class AssetEventSensor(BaseSensorOperator): :param count_policy: ``"minimum"`` (the default) waits for at least ``expected_count`` events; ``"exact"`` requires exactly that number. To check for no events, use ``"exact"`` and zero. - :param process_result: A callable (or a dotted import path to one) applied - to the fetched events before the count check, to transform, deduplicate - or filter them. It receives the list of asset events and must return a - list. It runs on every poke, so it should be idempotent and free of - side-effects. Its return value must be JSON-serializable to be pushed - into XCom. + :param process_result: A callable applied to the fetched events before the + count check, to transform, deduplicate or filter them. It receives the + list of asset events and must return a list. It runs on every poke, so + it should be idempotent and free of side-effects. Its return value must + be JSON-serializable to be pushed into XCom. """ template_fields: Sequence[str] = ( @@ -110,7 +109,7 @@ def __init__( extra: dict[str, str] | None = None, expected_count: int = 1, count_policy: Literal["minimum", "exact"] = "minimum", - process_result: Callable[[list[Any]], list[Any]] | str | None = None, + process_result: Callable[[list[AssetEventResult]], list[Any]] | None = None, **kwargs, ) -> None: if not AIRFLOW_V_3_4_PLUS and ( @@ -121,15 +120,10 @@ def __init__( "need Airflow 3.4+." ) super().__init__(**kwargs) - if not isinstance(expected_count, int) or isinstance(expected_count, bool): - raise TypeError("`expected_count` must be an integer.") if expected_count < 0: raise ValueError(f"`expected_count` must be a non-negative integer, got {expected_count}.") - if limit is not None: - if not isinstance(limit, int) or isinstance(limit, bool): - raise TypeError("`limit` must be an integer.") - if limit <= 0: - raise ValueError("`limit` must be positive.") + if limit is not None and limit <= 0: + raise ValueError("`limit` must be positive.") if count_policy not in {"minimum", "exact"}: raise ValueError(f"`count_policy` must be 'minimum' or 'exact', got {count_policy!r}.") if process_result is None and limit is not None: @@ -157,12 +151,6 @@ def __init__( self.count_policy = count_policy self.process_result = process_result - def _apply_process_result(self, events: list[Any]) -> list[Any]: - if self.process_result is None: - return events - func = self.process_result if callable(self.process_result) else import_string(self.process_result) - return func(events) - def _get_accessor(self, context: Context) -> InletEventsAccessor: # The mapped operator's inlets don't include the asset added in init. # TODO: Remove this once the min Airflow refreshes after unmapping. @@ -185,10 +173,12 @@ def poke(self, context: Context) -> PokeReturnValue: accessor.partition_key(self.partition_key) if self.partition_key_regexp_pattern is not None: accessor.partition_key_regexp_pattern(self.partition_key_regexp_pattern) - if self.extra: + if self.extra is not None: for key, value in self.extra.items(): accessor.extra(key, value) - processed = self._apply_process_result(list(accessor)) + processed = list(accessor) + if self.process_result is not None: + processed = self.process_result(processed) count = len(processed) done = ( count >= self.expected_count if self.count_policy == "minimum" else count == self.expected_count diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index 00b9a46dc0bb..f4981f589010 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -119,20 +119,10 @@ def test_preserves_existing_inlets_without_duplicates(self, asset, include_targe assert sensor.inlets == [other_asset, asset] assert inlets == original_inlets - @pytest.mark.parametrize("expected_count", [1.5, "1", True, None]) - def test_rejects_noninteger_expected_count(self, asset, expected_count): - with pytest.raises(TypeError, match="expected_count"): - AssetEventSensor(task_id="s", asset=asset, expected_count=expected_count) - def test_rejects_negative_expected_count(self, asset): with pytest.raises(ValueError, match="expected_count"): AssetEventSensor(task_id="s", asset=asset, expected_count=-1) - @pytest.mark.parametrize("limit", [0.5, "1", True]) - def test_rejects_noninteger_limit(self, asset, limit): - with pytest.raises(TypeError, match="limit"): - AssetEventSensor(task_id="s", asset=asset, limit=limit) - @pytest.mark.parametrize("limit", [0, -1]) def test_rejects_nonpositive_limit(self, asset, limit): with pytest.raises(ValueError, match="limit"): @@ -333,7 +323,6 @@ class TestProcessResult: ("process_result", "expected_count", "expected_ids", "done"), [ (only_us_partitions, 3, [1, 2, 4], True), - (f"{__name__}.only_us_partitions", 3, [1, 2, 4], True), (dedup_by_partition_key, 4, [1, 2, 3, 5], True), (only_us_partitions, 5, None, False), (lambda events: [], 1, None, False), From aecfa16a1a98d85c635e007f2ff6d272da9b07b5 Mon Sep 17 00:00:00 2001 From: Tzu-ping Chung Date: Tue, 27 Oct 2026 16:56:49 +0800 Subject: [PATCH 16/21] Better BaseModel dump --- .../providers/standard/sensors/asset.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index 22650e90a673..7d3589d6c922 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -19,6 +19,8 @@ import contextlib from typing import TYPE_CHECKING, Any, Literal +from pydantic import BaseModel + from airflow.providers.common.compat.sdk import ( AirflowOptionalProviderFeatureException, BaseSensorOperator, @@ -40,15 +42,13 @@ def _serialize_events(events: list[Any]) -> list[Any]: - """Serialize a list of (processed) asset events to JSON-safe values.""" - serialized: list[Any] = [] - for event in events: - model_dump = getattr(event, "model_dump", None) - if callable(model_dump): - serialized.append(model_dump(mode="json")) - else: - serialized.append(event) - return serialized + """ + Convert asset events Pydantic models to JSON-compatible dicts. + + This keeps the XCom value plain JSON, rather than relying on how XCom + serializes pydantic models. + """ + return [e.model_dump(mode="json") if isinstance(e, BaseModel) else e for e in events] class AssetEventSensor(BaseSensorOperator): From 0da6176cd70080cdc66253e6213579e3d6faeada Mon Sep 17 00:00:00 2001 From: Tzu-ping Chung Date: Tue, 27 Oct 2026 17:22:08 +0800 Subject: [PATCH 17/21] Improve AssetEventSensor docs and example --- providers/standard/docs/sensors/asset.rst | 65 +++++++++++++++++-- .../example_dags/example_asset_sensor.py | 8 ++- 2 files changed, 65 insertions(+), 8 deletions(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index 55f24c221fa6..9da61b42d784 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -39,6 +39,30 @@ without changing the Dag's schedule. It reads events through ``context["inlet_ev ``partition_key_regexp_pattern`` and ``extra`` filters require **Apache Airflow 3.4+**. +When to use a schedule instead +------------------------------ + +If the dependency does not need to sit in the middle of a run, a schedule is +usually a better fit. See +:doc:`apache-airflow:authoring-and-scheduling/asset-scheduling` for details. + +* Schedule the Dag on the asset when the whole run can wait for it. +* Use ``AssetAndTimeSchedule`` (Airflow 3.4+) when a time-scheduled run needs + the asset before it starts. +* Use a partitioned asset timetable with ``RollupMapper`` to wait for every + partition in a window. + +Use this sensor when some tasks should run immediately and only later tasks +depend on the asset. Here, ``prepare`` starts as soon as the run does, and only +``process`` waits for the partition (``wait_for_partition_events`` is defined +:ref:`below `): + +.. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py + :language: python + :dedent: 4 + :start-after: [START example_asset_event_sensor_mid_run] + :end-before: [END example_asset_event_sensor_mid_run] + Basic usage ----------- @@ -48,25 +72,52 @@ existing asset when the task starts. The target is static so Airflow can record the inlet; use templated event filters to select a run's events. By default the sensor succeeds once **at least one** matching event exists. +.. warning:: + + Without ``after``, ``before`` or a partition filter, the sensor considers + the asset's entire event history, so it succeeds immediately if a matching + event ever existed. Bound the query, for example by time, as below. + .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python :dedent: 4 :start-after: [START example_asset_event_sensor] :end-before: [END example_asset_event_sensor] +.. note:: + + For asset-triggered runs, ``data_interval_end`` is the timestamp of the + newest triggering event, and ``after`` is inclusive. If the sensor waits on + the same asset that triggered the run, that event satisfies it immediately. + Use ``{{ dag_run.start_date | ts }}`` as the bound in that case. + +A mapped sensor works, but its asset is only recorded as an inlet in lineage if +it is also passed through ``partial(inlets=[...])``. + +.. _howto/sensor:AssetEventSensor:filtering: + Filtering events and expected count ----------------------------------- -Events can be narrowed with ``after`` / ``before`` (time range), ``ascending`` / ``limit`` -(ordering and cap), ``partition_key`` / ``partition_key_regexp_pattern`` and ``extra`` (key/value -pairs contained in the event ``extra`` field). Prefer a partition key for the event's partition +Events can be narrowed with ``after``, ``before`` (time range), ``ascending``, +``limit`` (ordering and cap), ``partition_key``, +``partition_key_regexp_pattern``, and ``extra`` (key/value pairs contained in +the event ``extra`` field). Prefer a partition key for the event's partition identity; ``extra`` can further filter metadata, such as a validation status. -Use ``expected_count`` and ``count_policy`` to control how many processed events are required: +``partition_key_regexp_pattern`` requires a positive +:ref:`[api] regexp_query_timeout `. +With the default ``0``, regexp filtering is disabled, the query is rejected, +and the task fails. + +Use ``expected_count`` and ``count_policy`` to control how many processed +events are required: -* ``count_policy="minimum"`` (the default) succeeds at or above ``expected_count``, which defaults to one. -* ``count_policy="exact"`` succeeds only at ``expected_count``. Use this policy with zero to check - that no matching events exist. An exact count can be missed if several events arrive between pokes. +* ``count_policy="minimum"`` (the default) succeeds at or above + ``expected_count``, which defaults to one. +* ``count_policy="exact"`` succeeds only at ``expected_count``. Use this policy + with zero to check that no matching events exist. An exact count can be + missed if several events arrive between pokes. Counts must be non-negative integers, and ``limit`` must be a positive integer when supplied. With the *minimum* policy, zero always satisfies the count diff --git a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py index 56d2ac2ab502..1ac8d989204b 100644 --- a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py +++ b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py @@ -28,6 +28,7 @@ import pendulum +from airflow.providers.standard.operators.empty import EmptyOperator from airflow.providers.standard.sensors.asset import AssetEventSensor from airflow.sdk import DAG, Asset @@ -54,6 +55,7 @@ def latest_event_only(events: list[Any]) -> list[Any]: wait_for_asset_event = AssetEventSensor( task_id="wait_for_asset_event", asset=my_asset, + after="{{ data_interval_end | ts }}", ) # [END example_asset_event_sensor] @@ -75,4 +77,8 @@ def latest_event_only(events: list[Any]) -> list[Any]: ) # [END example_asset_event_sensor_process_result] - [wait_for_asset_event, wait_for_partition_events, wait_for_latest_asset_event] + # [START example_asset_event_sensor_mid_run] + prepare = EmptyOperator(task_id="prepare") + process = EmptyOperator(task_id="process") + prepare >> wait_for_partition_events >> process + # [END example_asset_event_sensor_mid_run] From e8e0107bb4b90bbd569b326b545aa86ae20e8d3b Mon Sep 17 00:00:00 2001 From: hussein-awala Date: Tue, 27 Oct 2026 21:37:29 +0100 Subject: [PATCH 18/21] Support run-relative asset event bounds Asset waits need time bounds tied to a run without requiring Jinja expressions or limiting Dag authors to a fixed set of anchors. A runtime resolver contract lets authors derive custom bounds from task context. --- providers/standard/docs/sensors/asset.rst | 84 ++++++- .../example_dags/example_asset_sensor.py | 5 +- .../providers/standard/sensors/asset.py | 103 +++++++- .../tests/unit/standard/sensors/test_asset.py | 230 +++++++++++++++++- 4 files changed, 409 insertions(+), 13 deletions(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index 9da61b42d784..52ebdabdb471 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -86,14 +86,94 @@ sensor succeeds once **at least one** matching event exists. .. note:: - For asset-triggered runs, ``data_interval_end`` is the timestamp of the + For asset-triggered runs, ``dag_run.run_after`` can be the timestamp of the newest triggering event, and ``after`` is inclusive. If the sensor waits on the same asset that triggered the run, that event satisfies it immediately. - Use ``{{ dag_run.start_date | ts }}`` as the bound in that case. + Use ``RunStart()`` to wait for events at or after the actual run start. A mapped sensor works, but its asset is only recorded as an inlet in lineage if it is also passed through ``partial(inlets=[...])``. +Run-relative time bounds +----------------------- + +The ``after`` and ``before`` arguments accept datetime values, ISO strings, +Jinja templates, and these bound objects from +``airflow.providers.standard.sensors.asset``: + +* ``RunStart()`` uses ``dag_run.start_date``, the actual start of the Dag run. +* ``LogicalDate()`` uses ``logical_date``. +* ``DataIntervalStart()`` uses ``data_interval_start``. +* ``DataIntervalEnd()`` uses ``data_interval_end``. + +Each built-in object accepts a non-negative ``lookback`` duration, with zero as the +default. For example, ``RunStart(lookback=timedelta(hours=1))`` includes events +from one hour before the Dag run started. The basic example above uses this +bound, so an event from that hour can satisfy the sensor immediately. + +``RunStart`` uses the actual start even for a backfill. Select a logical date +or data interval explicitly when you need historical bounds. For example: + +.. code-block:: python + + from airflow.providers.standard.sensors.asset import ( + AssetEventSensor, + DataIntervalEnd, + DataIntervalStart, + ) + + wait_for_interval_events = AssetEventSensor( + task_id="wait_for_interval_events", + asset=my_asset, + after=DataIntervalStart(), + before=DataIntervalEnd(), + ) + +Both bounds are inclusive and filter the asset event's timestamp. An event at +an interval boundary can therefore match two adjacent intervals. These bounds +do not filter the event's partition key. + +A bound raises ``ValueError`` if its selected timestamp is missing. For example, +some runs do not have a logical date or data interval. The sensor does not +substitute another timestamp in that case. + +Airflow resolves the objects during template rendering, before polling. Their +run-relative values stay fixed while the sensor polls and after rescheduling. + +Custom resolvers +~~~~~~~~~~~~~~~~ + +Pass any object with a ``resolve(context)`` method that returns a datetime or +ISO string. :class:`~airflow.providers.standard.sensors.asset.AssetEventTimeBound` +defines this interface. Inheritance is optional. For example: + +.. code-block:: python + + from airflow.providers.standard.sensors.asset import AssetEventSensor, AssetEventTimeBound + + + class ParameterBound(AssetEventTimeBound): + def resolve(self, context): + return context["params"]["events_after"] + + + wait_for_custom_events = AssetEventSensor( + task_id="wait_for_custom_events", + asset=my_asset, + after=ParameterBound(), + params={"events_after": "2024-01-01T00:00:00+00:00"}, + ) + +The same example works with ``class ParameterBound:``. Custom resolvers need +only ``resolve(context)``. The ``lookback`` argument is a convenience provided +by the built-in helpers. + +Alternatively, pass a template callable that accepts the ``context`` and +``jinja_env`` keyword arguments and returns a datetime or ISO string. Airflow +evaluates the callable during template rendering. Custom resolvers and callables +must return the same bound after rescheduling. A bound based on the current clock +can move the query window and exclude events that arrived between pokes. + .. _howto/sensor:AssetEventSensor:filtering: Filtering events and expected count diff --git a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py index 1ac8d989204b..964e69713576 100644 --- a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py +++ b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py @@ -18,6 +18,7 @@ from __future__ import annotations +from datetime import timedelta from typing import Any from airflow.providers.common.compat.sdk import AirflowOptionalProviderFeatureException @@ -29,7 +30,7 @@ import pendulum from airflow.providers.standard.operators.empty import EmptyOperator -from airflow.providers.standard.sensors.asset import AssetEventSensor +from airflow.providers.standard.sensors.asset import AssetEventSensor, RunStart from airflow.sdk import DAG, Asset my_asset = Asset("s3://bucket/my-file.csv") @@ -55,7 +56,7 @@ def latest_event_only(events: list[Any]) -> list[Any]: wait_for_asset_event = AssetEventSensor( task_id="wait_for_asset_event", asset=my_asset, - after="{{ data_interval_end | ts }}", + after=RunStart(lookback=timedelta(hours=1)), ) # [END example_asset_event_sensor] diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index 7d3589d6c922..2468893f8099 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -17,7 +17,8 @@ from __future__ import annotations import contextlib -from typing import TYPE_CHECKING, Any, Literal +from datetime import timedelta +from typing import TYPE_CHECKING, Any, ClassVar, Literal, Protocol, cast from pydantic import BaseModel @@ -51,6 +52,86 @@ def _serialize_events(events: list[Any]) -> list[Any]: return [e.model_dump(mode="json") if isinstance(e, BaseModel) else e for e in events] +class AssetEventTimeBound(Protocol): + """ + A time bound that Airflow resolves during template rendering. + + Implement ``resolve(context)`` to return a datetime or ISO string. Custom + objects do not need to inherit this protocol. + The result must stay fixed across reschedules of the same Dag run. + """ + + def resolve(self, context: Context) -> datetime | str: + """Return the event timestamp bound for this task's runtime context.""" + ... + + +class _ContextTimeBound(AssetEventTimeBound): + _context_key: ClassVar[str] + + def __init__(self, *, lookback: timedelta = timedelta(0)) -> None: + if lookback < timedelta(0): + raise ValueError("`lookback` must be non-negative.") + self.lookback = lookback + + def __repr__(self) -> str: + return f"{type(self).__name__}(lookback={self.lookback!r})" + + def _get_timestamp(self, context: Context) -> datetime | None: + return cast("datetime | None", context.get(self._context_key)) + + def resolve(self, context: Context) -> datetime: + """Resolve the bound during template rendering, before the sensor polls.""" + timestamp = self._get_timestamp(context) + if timestamp is None: + raise ValueError(f"{type(self).__name__} requires {self._context_key!r} in the task context.") + return timestamp - self.lookback + + +class RunStart(_ContextTimeBound): + """ + Bound events by the Dag run's actual start time, including for backfills. + + :param lookback: Non-negative duration to subtract from ``dag_run.start_date``. + """ + + _context_key = "dag_run.start_date" + + def _get_timestamp(self, context: Context) -> datetime | None: + dag_run = context.get("dag_run") + return dag_run.start_date if dag_run is not None else None + + +class LogicalDate(_ContextTimeBound): + """ + Bound events by the Dag run's logical date. + + :param lookback: Non-negative duration to subtract from ``logical_date``. + """ + + _context_key = "logical_date" + + +class DataIntervalStart(_ContextTimeBound): + """ + Bound events by the start of the Dag run's data interval. + + :param lookback: Non-negative duration to subtract from ``data_interval_start``. + """ + + _context_key = "data_interval_start" + + +class DataIntervalEnd(_ContextTimeBound): + """ + Bound events by the end of the Dag run's data interval. + + :param lookback: Non-negative duration to subtract from ``data_interval_end``. + """ + + _context_key = "data_interval_end" + + class AssetEventSensor(BaseSensorOperator): """ Wait for asset events matching the given filters to reach an expected count. @@ -69,6 +150,11 @@ class AssetEventSensor(BaseSensorOperator): starts. The target is static; event filters can be templated. :param after: Only include events at or after this timestamp. :param before: Only include events at or before this timestamp. + Both bounds accept a datetime, ISO string, any object implementing + :class:`AssetEventTimeBound`, or a template callable accepting + ``context`` and ``jinja_env``. Airflow + resolves them before polling. Custom callables must return stable + bounds across reschedules. :param ascending: Whether events are returned in ascending timestamp order. :param limit: Positive maximum number of events to fetch, before applying ``process_result``. @@ -100,8 +186,8 @@ def __init__( self, *, asset: Asset | AssetAlias | AssetRef, - after: datetime | str | None = None, - before: datetime | str | None = None, + after: datetime | str | AssetEventTimeBound | Callable[..., datetime | str] | None = None, + before: datetime | str | AssetEventTimeBound | Callable[..., datetime | str] | None = None, ascending: bool = True, limit: int | None = None, partition_key: str | None = None, @@ -161,11 +247,14 @@ def _get_accessor(self, context: Context) -> InletEventsAccessor: return InletEventsAccessors([self.asset])[self.asset] def poke(self, context: Context) -> PokeReturnValue: + # Template rendering replaces bound objects and callables before polling. + after = cast("datetime | str | None", self.after) + before = cast("datetime | str | None", self.before) accessor = self._get_accessor(context) - if self.after is not None: - accessor.after(self.after if isinstance(self.after, str) else self.after.isoformat()) - if self.before is not None: - accessor.before(self.before if isinstance(self.before, str) else self.before.isoformat()) + if after is not None: + accessor.after(after if isinstance(after, str) else after.isoformat()) + if before is not None: + accessor.before(before if isinstance(before, str) else before.isoformat()) accessor.ascending(self.ascending) if self.limit is not None: accessor.limit(self.limit) diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index f4981f589010..ddfe24e5c036 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -16,7 +16,9 @@ # under the License. from __future__ import annotations -from datetime import UTC, datetime +import json +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace from typing import Any from unittest.mock import call @@ -33,7 +35,9 @@ from tests_common.test_utils.version_compat import AIRFLOW_V_3_2_PLUS, AIRFLOW_V_3_4_PLUS if AIRFLOW_V_3_2_PLUS: - from airflow.providers.standard.sensors.asset import AssetEventSensor + from airflow.exceptions import AirflowRescheduleException + from airflow.providers.standard.sensors import asset as asset_sensor + from airflow.providers.standard.sensors.asset import AssetEventSensor, AssetEventTimeBound, RunStart from airflow.sdk.api.datamodels._generated import AssetEventResponse, AssetResponse from airflow.sdk.execution_time.comms import ( AssetEventsResult, @@ -42,9 +46,21 @@ GetAssetByUri, GetAssetEventByAsset, GetAssetEventByAssetAlias, + TaskRescheduleStartDate, ) from airflow.sdk.execution_time.context import InletEventsAccessors + from tests_common.test_utils.compat import OperatorSerialization + + class _ParameterBound: + def resolve(self, context): + return context["params"]["events_after"] + + class _InheritedParameterBound(AssetEventTimeBound): + def resolve(self, context): + return context["params"]["events_after"] + + pytestmark = pytest.mark.skipif(not AIRFLOW_V_3_2_PLUS, reason="AssetEventSensor requires Airflow 3.2+") requires_3_4 = pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="Filter requires Airflow 3.4+") @@ -102,6 +118,30 @@ def events_response(): ) +@pytest.fixture( + params=[ + ("RunStart", "dag_run.start_date", 8), + ("LogicalDate", "logical_date", 1), + ("DataIntervalStart", "data_interval_start", 2), + ("DataIntervalEnd", "data_interval_end", 3), + ], + ids=lambda case: case[0], +) +def time_bound_case(request): + name, anchor, day = request.param + return getattr(asset_sensor, name), anchor, _get_timestamp(day) + + +@pytest.fixture +def time_bound_context(): + return { + "dag_run": SimpleNamespace(start_date=_get_timestamp(8)), + "logical_date": _get_timestamp(1), + "data_interval_start": _get_timestamp(2), + "data_interval_end": _get_timestamp(3), + } + + class TestInit: @pytest.mark.parametrize("use_alias", [False, True]) def test_declares_target_as_inlet(self, asset, use_alias): @@ -197,6 +237,192 @@ def test_renders_filters_without_changing_lineage(self, asset): assert sensor.inlets == [asset] +class TestTimeBounds: + @pytest.mark.parametrize("inherit_protocol", [False, True], ids=["plain", "subclass"]) + @pytest.mark.parametrize("as_string", [False, True], ids=["datetime", "iso"]) + def test_custom_resolver_needs_only_resolve( + self, asset, events_response, mock_supervisor_comms, inherit_protocol, as_string + ): + bound = _InheritedParameterBound() if inherit_protocol else _ParameterBound() + timestamp = _get_timestamp(8) + sensor = AssetEventSensor(task_id="s", asset=asset, after=bound) + context = { + **_get_context(sensor), + "params": {"events_after": timestamp.isoformat() if as_string else timestamp}, + } + sensor.render_template_fields(context) + mock_supervisor_comms.send.side_effect = [AssetEventsResult(asset_events=[]), events_response] + assert not sensor.poke(context) + assert sensor.poke(context) + query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=timestamp) + assert mock_supervisor_comms.send.call_args_list == [call(query), call(query)] + + def test_custom_resolver_serialization_is_optional(self, asset): + with DAG("test_custom_bound_serialization"): + sensor = AssetEventSensor(task_id="s", asset=asset, after=_ParameterBound()) + encoded = json.loads(json.dumps(OperatorSerialization.serialize_operator(sensor))) + assert isinstance(encoded["after"], str) + assert "_ParameterBound" in encoded["after"] + + @pytest.mark.parametrize("lookback", [timedelta(0), timedelta(hours=1, microseconds=7)]) + def test_resolves_selected_timestamp(self, time_bound_case, time_bound_context, lookback): + bound_type, _, timestamp = time_bound_case + assert bound_type(lookback=lookback).resolve(time_bound_context) == timestamp - lookback + + def test_rejects_negative_lookback(self): + with pytest.raises(ValueError, match="lookback.*non-negative"): + RunStart(lookback=timedelta(microseconds=-1)) + + @pytest.mark.parametrize("missing", [False, True], ids=["none", "absent"]) + def test_rejects_missing_timestamp(self, time_bound_case, time_bound_context, missing): + bound_type, anchor, _ = time_bound_case + if anchor == "dag_run.start_date": + time_bound_context["dag_run"].start_date = None + if missing: + del time_bound_context["dag_run"] + elif missing: + del time_bound_context[anchor] + else: + time_bound_context[anchor] = None + with pytest.raises(ValueError, match=rf"{bound_type.__name__} requires"): + bound_type().resolve(time_bound_context) + + def test_displays_bound_configuration_in_serialized_task(self, asset, time_bound_case): + bound_type, _, _ = time_bound_case + with DAG("test_bounds_serialization"): + first = AssetEventSensor( + task_id="first", asset=asset, after=bound_type(lookback=timedelta(hours=1)) + ) + second = AssetEventSensor( + task_id="second", asset=asset, after=bound_type(lookback=timedelta(hours=2)) + ) + first_encoded = json.loads(json.dumps(OperatorSerialization.serialize_operator(first))) + second_encoded = json.loads(json.dumps(OperatorSerialization.serialize_operator(second))) + assert first_encoded["after"] == f"{bound_type.__name__}(lookback=datetime.timedelta(seconds=3600))" + assert second_encoded["after"] == f"{bound_type.__name__}(lookback=datetime.timedelta(seconds=7200))" + + @pytest.mark.parametrize("field", ["after", "before"]) + def test_renders_and_queries_bound( + self, asset, time_bound_case, time_bound_context, field, mock_supervisor_comms + ): + bound_type, _, timestamp = time_bound_case + lookback = timedelta(hours=1) + bound = bound_type(lookback=lookback) + sensor = AssetEventSensor(task_id="s", asset=asset, **{field: bound}) + context = {**time_bound_context, **_get_context(sensor)} + sensor.render_template_fields(context) + mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=[]) + sensor.poke(context) + mock_supervisor_comms.send.assert_called_once_with( + GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, **{field: timestamp - lookback}) + ) + assert bound.lookback == lookback + + @pytest.mark.parametrize("as_string", [False, True]) + def test_custom_callable_resolves_before_polling( + self, asset, events_response, mock_supervisor_comms, mocker, as_string + ): + timestamp = _get_timestamp(8) + + def get_bound(*, context, jinja_env): + return timestamp.isoformat() if as_string else timestamp + + get_bound_spy = mocker.create_autospec(get_bound, side_effect=get_bound) + sensor = AssetEventSensor(task_id="s", asset=asset, after=get_bound_spy) + context = _get_context(sensor) + sensor.render_template_fields(context) + mock_supervisor_comms.send.side_effect = [AssetEventsResult(asset_events=[]), events_response] + assert not sensor.poke(context) + assert sensor.poke(context) + get_bound_spy.assert_called_once() + query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=timestamp) + assert mock_supervisor_comms.send.call_args_list == [call(query), call(query)] + + @pytest.mark.parametrize("mapped_bound", [False, True], ids=["partial", "expand"]) + def test_mapped_sensor( + self, asset, events_response, create_runtime_ti, mock_supervisor_comms, mapped_bound + ): + bound = RunStart(lookback=timedelta(hours=1)) + with DAG("test_mapped_bounds"): + if mapped_bound: + mapped = AssetEventSensor.partial(task_id="s", asset=asset).expand(after=[bound, bound]) + else: + mapped = AssetEventSensor.partial(task_id="s", asset=asset, after=bound).expand(limit=[1, 2]) + ti = create_runtime_ti(task=mapped, map_index=1, start_date=_get_timestamp(8), logical_date=None) + context = ti.get_template_context() + ti.render_templates(context=context) + mock_supervisor_comms.send.return_value = events_response + assert ti.task.poke(context) + mock_supervisor_comms.send.assert_called_with( + GetAssetEventByAsset( + name=ASSET_NAME, + uri=ASSET_URI, + after=_get_timestamp(8) - timedelta(hours=1), + limit=None if mapped_bound else 2, + ) + ) + + @pytest.mark.parametrize("mapped_bound", [False, True], ids=["partial", "expand"]) + def test_mapped_custom_resolver( + self, asset, events_response, create_runtime_ti, mock_supervisor_comms, mapped_bound + ): + bound = _ParameterBound() + timestamp = _get_timestamp(8) + with DAG("test_mapped_custom_bound"): + if mapped_bound: + mapped = AssetEventSensor.partial( + task_id="s", asset=asset, params={"events_after": timestamp.isoformat()} + ).expand(after=[bound, bound]) + else: + mapped = AssetEventSensor.partial( + task_id="s", + asset=asset, + after=bound, + params={"events_after": timestamp.isoformat()}, + ).expand(limit=[1, 2]) + ti = create_runtime_ti(task=mapped, map_index=1) + context = ti.get_template_context() + ti.render_templates(context=context) + mock_supervisor_comms.send.return_value = events_response + assert ti.task.poke(context) + mock_supervisor_comms.send.assert_called_with( + GetAssetEventByAsset( + name=ASSET_NAME, + uri=ASSET_URI, + after=timestamp, + limit=None if mapped_bound else 2, + ) + ) + + def test_reconstructed_sensor_keeps_bound_after_rescheduling( + self, asset, events_response, create_runtime_ti, mock_supervisor_comms, time_machine + ): + time_machine.move_to(_get_timestamp(10), tick=False) + first = AssetEventSensor(task_id="s", asset=asset, after=RunStart(), mode="reschedule") + ti = create_runtime_ti(task=first, start_date=_get_timestamp(8)) + context = ti.get_template_context() + ti.render_templates(context=context) + mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=[]) + with pytest.raises(AirflowRescheduleException): + ti.task.execute(context) + + time_machine.shift(timedelta(hours=1)) + resumed = AssetEventSensor(task_id="s", asset=asset, after=RunStart(), mode="reschedule") + resumed_ti = create_runtime_ti(task=resumed, start_date=_get_timestamp(8), task_reschedule_count=1) + resumed_context = resumed_ti.get_template_context() + resumed_ti.render_templates(context=resumed_context) + mock_supervisor_comms.send.side_effect = [ + TaskRescheduleStartDate(start_date=_get_timestamp(10)), + events_response, + ] + assert resumed_ti.task.execute(resumed_context) + query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=_get_timestamp(8)) + assert [c for c in mock_supervisor_comms.send.call_args_list if c == call(query)] == [ + call(query), + call(query), + ] + + class TestPoke: def test_returns_serialized_events(self, asset, events_response, mock_supervisor_comms): mock_supervisor_comms.send.return_value = events_response From cfd6a51d34121969f9c4ce989ce7a70ef056896e Mon Sep 17 00:00:00 2001 From: hussein-awala Date: Tue, 27 Oct 2026 22:47:37 +0100 Subject: [PATCH 19/21] Fix AssetEventSensor documentation heading --- providers/standard/docs/sensors/asset.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index 52ebdabdb471..ef63b73e5805 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -95,7 +95,7 @@ A mapped sensor works, but its asset is only recorded as an inlet in lineage if it is also passed through ``partial(inlets=[...])``. Run-relative time bounds ------------------------ +------------------------ The ``after`` and ``before`` arguments accept datetime values, ISO strings, Jinja templates, and these bound objects from From 1038a005024a62c6856154a52a3cd73d99c5c387 Mon Sep 17 00:00:00 2001 From: hussein-awala Date: Wed, 28 Oct 2026 23:44:35 +0100 Subject: [PATCH 20/21] Add explicit asset event filters and stable run bounds --- providers/standard/docs/sensors/asset.rst | 137 ++++++--- .../example_dags/example_asset_sensor.py | 6 +- .../providers/standard/sensors/asset.py | 85 ++++-- .../tests/unit/standard/sensors/test_asset.py | 267 ++++++++++++++---- 4 files changed, 377 insertions(+), 118 deletions(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index ef63b73e5805..345f3fcd4093 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -72,11 +72,16 @@ existing asset when the task starts. The target is static so Airflow can record the inlet; use templated event filters to select a run's events. By default the sensor succeeds once **at least one** matching event exists. -.. warning:: +Supply at least one query filter: ``after``, ``before``, ``partition_key``, +``partition_key_regexp_pattern``, or a non-empty ``extra`` dictionary. The sensor +raises ``ValueError`` at construction if no filter is supplied. It checks again +after template rendering, before querying events. An empty ``extra={}`` does +not count as a filter. - Without ``after``, ``before`` or a partition filter, the sensor considers - the asset's entire event history, so it succeeds immediately if a matching - event ever existed. Bound the query, for example by time, as below. +Time bounds are optional when another query filter is supplied. Ordering, +``limit``, and ``process_result`` do not replace query filters. + +This daily example waits for events at or after the data interval ends: .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python @@ -84,13 +89,6 @@ sensor succeeds once **at least one** matching event exists. :start-after: [START example_asset_event_sensor] :end-before: [END example_asset_event_sensor] -.. note:: - - For asset-triggered runs, ``dag_run.run_after`` can be the timestamp of the - newest triggering event, and ``after`` is inclusive. If the sensor waits on - the same asset that triggered the run, that event satisfies it immediately. - Use ``RunStart()`` to wait for events at or after the actual run start. - A mapped sensor works, but its asset is only recorded as an inlet in lineage if it is also passed through ``partial(inlets=[...])``. @@ -101,18 +99,59 @@ The ``after`` and ``before`` arguments accept datetime values, ISO strings, Jinja templates, and these bound objects from ``airflow.providers.standard.sensors.asset``: -* ``RunStart()`` uses ``dag_run.start_date``, the actual start of the Dag run. -* ``LogicalDate()`` uses ``logical_date``. -* ``DataIntervalStart()`` uses ``data_interval_start``. -* ``DataIntervalEnd()`` uses ``data_interval_end``. - -Each built-in object accepts a non-negative ``lookback`` duration, with zero as the -default. For example, ``RunStart(lookback=timedelta(hours=1))`` includes events -from one hour before the Dag run started. The basic example above uses this -bound, so an event from that hour can satisfy the sensor immediately. - -``RunStart`` uses the actual start even for a backfill. Select a logical date -or data interval explicitly when you need historical bounds. For example: +.. list-table:: Choosing a time bound + :header-rows: 1 + :widths: 20 25 25 30 + + * - Bound + - Available on + - When tasks are cleared + - Watch out for + * - ``RunStart()`` + - All runs, including asset-triggered runs and backfills. + - A finished run gets a new start time when it starts again. Clearing tasks + in a queued or running run preserves the existing start time. + - Uses ``dag_run.start_date``, the actual start even for a backfill. + With ``after``, a negative offset can include events from an earlier execution. + * - ``RunAfter()`` + - All runs, including asset-triggered runs and backfills. + - Stays fixed for the same run. + - Uses ``dag_run.run_after``. For some asset timetables, this equals a + triggering event's timestamp. Since ``after`` is inclusive, that event + can satisfy the sensor immediately. + * - ``LogicalDate()`` + - Runs with a logical date, including manual runs that supply one. + Asset-triggered runs have none. + - Stays fixed for the same run. + - Its meaning depends on the timetable or the value supplied for a manual + run. It does not necessarily represent when execution started. + * - ``DataIntervalStart()`` / ``DataIntervalEnd()`` + - Runs with a data interval. Availability depends on the timetable and + run type. Asset-triggered runs have none. + - Stay fixed for the same run. + - Use the interval represented by the run for historical work. + ``CronTriggerTimetable`` defaults to a zero-length interval, so both + bounds are equal. + +Use ``after=RunStart()`` when clearing a finished run should wait for new data. +Use ``after=RunAfter()`` to keep the same time boundary when an asset-triggered +run is cleared. Runs with logical dates or data intervals can also use those +fixed bounds. An open-ended query can still include new events that arrive +later, so fixed bounds do not freeze the result set. + +Each built-in object accepts a signed ``offset`` duration, with zero as the +default. A negative offset moves the bound earlier. A positive offset moves it +later. For example, ``after=DataIntervalEnd(offset=-timedelta(hours=1))`` includes +events from one hour before the interval ends onward. +``before=DataIntervalEnd(offset=timedelta(hours=1))`` includes events up to one +hour after the interval ends. Import ``timedelta`` from ``datetime`` to use these +examples. + +To exclude events exactly at ``dag_run.run_after``, use +``after=RunAfter(offset=timedelta(microseconds=1))``. Later events can still match, +including events seen during an earlier execution of the run. + +For example, use both interval bounds to select a historical window: .. code-block:: python @@ -133,9 +172,13 @@ Both bounds are inclusive and filter the asset event's timestamp. An event at an interval boundary can therefore match two adjacent intervals. These bounds do not filter the event's partition key. -A bound raises ``ValueError`` if its selected timestamp is missing. For example, -some runs do not have a logical date or data interval. The sensor does not -substitute another timestamp in that case. +To create a nonzero window with ``CronTriggerTimetable``, use an offset or +configure the timetable's ``interval``. + +A bound raises ``ValueError`` if its selected timestamp is missing; it does not +substitute another timestamp. Manual runs can have a data interval when a logical +date is supplied. Use ``after=RunStart()`` to wait for events at or after the actual +start of an asset-triggered run. Airflow resolves the objects during template rendering, before polling. Their run-relative values stay fixed while the sensor polls and after rescheduling. @@ -145,7 +188,14 @@ Custom resolvers Pass any object with a ``resolve(context)`` method that returns a datetime or ISO string. :class:`~airflow.providers.standard.sensors.asset.AssetEventTimeBound` -defines this interface. Inheritance is optional. For example: +defines this interface. Inheritance is optional. + +For stable Dag serialization, give custom objects a deterministic ``__repr__`` +that includes their configuration. Airflow currently uses this representation +for ``partial`` and ``expand`` arguments. Older versions, including Airflow 3.2.0, +also use it for unmapped template fields. The default object representation +contains a memory address and can create a new Dag version on each parse. +This example includes the parameter name in its representation: .. code-block:: python @@ -153,22 +203,28 @@ defines this interface. Inheritance is optional. For example: class ParameterBound(AssetEventTimeBound): + def __init__(self, name): + self.name = name + + def __repr__(self): + return f"ParameterBound(name={self.name!r})" + def resolve(self, context): - return context["params"]["events_after"] + return context["params"][self.name] - wait_for_custom_events = AssetEventSensor( + wait_for_custom_events = AssetEventSensor.partial( task_id="wait_for_custom_events", asset=my_asset, - after=ParameterBound(), + inlets=[my_asset], + after=ParameterBound("events_after"), params={"events_after": "2024-01-01T00:00:00+00:00"}, - ) + ).expand(limit=[1, 2]) -The same example works with ``class ParameterBound:``. Custom resolvers need -only ``resolve(context)``. The ``lookback`` argument is a convenience provided -by the built-in helpers. +Custom resolvers do not need ``serialize`` or ``deserialize`` methods. The +``offset`` argument is a convenience provided by the built-in helpers. -Alternatively, pass a template callable that accepts the ``context`` and +Alternatively, Airflow 3.2+ supports a template callable that accepts the ``context`` and ``jinja_env`` keyword arguments and returns a datetime or ISO string. Airflow evaluates the callable during template rendering. Custom resolvers and callables must return the same bound after rescheduling. A bound based on the current clock @@ -179,11 +235,12 @@ can move the query window and exclude events that arrived between pokes. Filtering events and expected count ----------------------------------- -Events can be narrowed with ``after``, ``before`` (time range), ``ascending``, -``limit`` (ordering and cap), ``partition_key``, -``partition_key_regexp_pattern``, and ``extra`` (key/value pairs contained in +Filter events with ``after``, ``before`` (time range), ``partition_key``, +``partition_key_regexp_pattern``, or ``extra`` (key/value pairs contained in the event ``extra`` field). Prefer a partition key for the event's partition identity; ``extra`` can further filter metadata, such as a validation status. +Use ``ascending`` to set the order and ``limit`` to cap the number of matching +events returned. ``partition_key_regexp_pattern`` requires a positive :ref:`[api] regexp_query_timeout `. @@ -230,6 +287,10 @@ events remain in the query range. If the callback rejects them, newer acceptable the limit are never inspected. Prefer query filters such as ``partition_key``, ``extra`` and time bounds where possible. For a check of recent events, use ``ascending=False`` with a suitable limit. +The example below keeps the latest event at or after the data interval ends. +If no post-processing is needed, use ``ascending=False, limit=1`` with the query +filter to fetch only its latest matching event. + .. exampleinclude:: /../src/airflow/providers/standard/example_dags/example_asset_sensor.py :language: python :dedent: 0 diff --git a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py index 964e69713576..105a91e3f66d 100644 --- a/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py +++ b/providers/standard/src/airflow/providers/standard/example_dags/example_asset_sensor.py @@ -18,7 +18,6 @@ from __future__ import annotations -from datetime import timedelta from typing import Any from airflow.providers.common.compat.sdk import AirflowOptionalProviderFeatureException @@ -30,7 +29,7 @@ import pendulum from airflow.providers.standard.operators.empty import EmptyOperator -from airflow.providers.standard.sensors.asset import AssetEventSensor, RunStart +from airflow.providers.standard.sensors.asset import AssetEventSensor, DataIntervalEnd from airflow.sdk import DAG, Asset my_asset = Asset("s3://bucket/my-file.csv") @@ -56,7 +55,7 @@ def latest_event_only(events: list[Any]) -> list[Any]: wait_for_asset_event = AssetEventSensor( task_id="wait_for_asset_event", asset=my_asset, - after=RunStart(lookback=timedelta(hours=1)), + after=DataIntervalEnd(), ) # [END example_asset_event_sensor] @@ -74,6 +73,7 @@ def latest_event_only(events: list[Any]) -> list[Any]: wait_for_latest_asset_event = AssetEventSensor( task_id="wait_for_latest_asset_event", asset=my_asset, + after=DataIntervalEnd(), process_result=latest_event_only, ) # [END example_asset_event_sensor_process_result] diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index 2468893f8099..9ec2eaff797d 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -17,6 +17,7 @@ from __future__ import annotations import contextlib +from abc import abstractmethod from datetime import timedelta from typing import TYPE_CHECKING, Any, ClassVar, Literal, Protocol, cast @@ -67,69 +68,97 @@ def resolve(self, context: Context) -> datetime | str: class _ContextTimeBound(AssetEventTimeBound): - _context_key: ClassVar[str] + _label: ClassVar[str] - def __init__(self, *, lookback: timedelta = timedelta(0)) -> None: - if lookback < timedelta(0): - raise ValueError("`lookback` must be non-negative.") - self.lookback = lookback + def __init__(self, *, offset: timedelta = timedelta(0)) -> None: + self.offset = offset def __repr__(self) -> str: - return f"{type(self).__name__}(lookback={self.lookback!r})" + return f"{type(self).__name__}(offset={self.offset!r})" - def _get_timestamp(self, context: Context) -> datetime | None: - return cast("datetime | None", context.get(self._context_key)) + def serialize(self) -> dict[str, str | float]: + """Return the bound configuration for serialized task metadata.""" + return {"anchor": self._label, "offset_seconds": self.offset.total_seconds()} + + @abstractmethod + def _get_timestamp(self, context: Context) -> datetime | None: ... def resolve(self, context: Context) -> datetime: """Resolve the bound during template rendering, before the sensor polls.""" timestamp = self._get_timestamp(context) if timestamp is None: - raise ValueError(f"{type(self).__name__} requires {self._context_key!r} in the task context.") - return timestamp - self.lookback + raise ValueError(f"{type(self).__name__} requires {self._label!r} in the task context.") + return timestamp + self.offset class RunStart(_ContextTimeBound): """ Bound events by the Dag run's actual start time, including for backfills. - :param lookback: Non-negative duration to subtract from ``dag_run.start_date``. + :param offset: Signed duration to add to ``dag_run.start_date``. """ - _context_key = "dag_run.start_date" + _label = "dag_run.start_date" def _get_timestamp(self, context: Context) -> datetime | None: dag_run = context.get("dag_run") return dag_run.start_date if dag_run is not None else None +class RunAfter(_ContextTimeBound): + """ + Bound events by the Dag run's earliest allowed start time. + + This timestamp stays fixed when tasks are cleared. With ``after``, an event + at this timestamp is included, even if it triggered the run. + + :param offset: Signed duration to add to ``dag_run.run_after``. + """ + + _label = "dag_run.run_after" + + def _get_timestamp(self, context: Context) -> datetime | None: + dag_run = context.get("dag_run") + return dag_run.run_after if dag_run is not None else None + + class LogicalDate(_ContextTimeBound): """ Bound events by the Dag run's logical date. - :param lookback: Non-negative duration to subtract from ``logical_date``. + :param offset: Signed duration to add to ``logical_date``. """ - _context_key = "logical_date" + _label = "logical_date" + + def _get_timestamp(self, context: Context) -> datetime | None: + return context.get("logical_date") class DataIntervalStart(_ContextTimeBound): """ Bound events by the start of the Dag run's data interval. - :param lookback: Non-negative duration to subtract from ``data_interval_start``. + :param offset: Signed duration to add to ``data_interval_start``. """ - _context_key = "data_interval_start" + _label = "data_interval_start" + + def _get_timestamp(self, context: Context) -> datetime | None: + return context.get("data_interval_start") class DataIntervalEnd(_ContextTimeBound): """ Bound events by the end of the Dag run's data interval. - :param lookback: Non-negative duration to subtract from ``data_interval_end``. + :param offset: Signed duration to add to ``data_interval_end``. """ - _context_key = "data_interval_end" + _label = "data_interval_end" + + def _get_timestamp(self, context: Context) -> datetime | None: + return context.get("data_interval_end") class AssetEventSensor(BaseSensorOperator): @@ -141,6 +170,9 @@ class AssetEventSensor(BaseSensorOperator): callable to transform, deduplicate or filter them, and succeeds once the resulting number of events satisfies ``expected_count``. + At least one of ``after``, ``before``, ``partition_key``, + ``partition_key_regexp_pattern``, or non-empty ``extra`` is required. + This sensor requires Apache Airflow 3.2+. The ``partition_key``, ``partition_key_regexp_pattern`` and ``extra`` filters require Airflow 3.4+. @@ -236,10 +268,24 @@ def __init__( self.expected_count = expected_count self.count_policy = count_policy self.process_result = process_result + self._validate_filters() + + def _validate_filters(self) -> None: + if ( + self.after is None + and self.before is None + and self.partition_key is None + and self.partition_key_regexp_pattern is None + and not self.extra + ): + raise ValueError( + "AssetEventSensor requires at least one filter: after, before, partition_key, " + "partition_key_regexp_pattern, or non-empty extra." + ) def _get_accessor(self, context: Context) -> InletEventsAccessor: # The mapped operator's inlets don't include the asset added in init. - # TODO: Remove this once the min Airflow refreshes after unmapping. + # Remove when the minimum Airflow includes https://github.com/apache/airflow/pull/75751. with contextlib.suppress(KeyError): return context["inlet_events"][self.asset] from airflow.sdk.execution_time.context import InletEventsAccessors @@ -247,6 +293,7 @@ def _get_accessor(self, context: Context) -> InletEventsAccessor: return InletEventsAccessors([self.asset])[self.asset] def poke(self, context: Context) -> PokeReturnValue: + self._validate_filters() # Template rendering replaces bound objects and callables before polling. after = cast("datetime | str | None", self.after) before = cast("datetime | str | None", self.before) diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index ddfe24e5c036..d25aae34d88a 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -37,7 +37,7 @@ if AIRFLOW_V_3_2_PLUS: from airflow.exceptions import AirflowRescheduleException from airflow.providers.standard.sensors import asset as asset_sensor - from airflow.providers.standard.sensors.asset import AssetEventSensor, AssetEventTimeBound, RunStart + from airflow.providers.standard.sensors.asset import AssetEventSensor, AssetEventTimeBound from airflow.sdk.api.datamodels._generated import AssetEventResponse, AssetResponse from airflow.sdk.execution_time.comms import ( AssetEventsResult, @@ -50,7 +50,7 @@ ) from airflow.sdk.execution_time.context import InletEventsAccessors - from tests_common.test_utils.compat import OperatorSerialization + from tests_common.test_utils.compat import DagSerialization, OperatorSerialization class _ParameterBound: def resolve(self, context): @@ -60,6 +60,16 @@ class _InheritedParameterBound(AssetEventTimeBound): def resolve(self, context): return context["params"]["events_after"] + class _MappedParameterBound: + def __init__(self, name): + self.name = name + + def __repr__(self): + return f"_MappedParameterBound(name={self.name!r})" + + def resolve(self, context): + return context["params"][self.name] + pytestmark = pytest.mark.skipif(not AIRFLOW_V_3_2_PLUS, reason="AssetEventSensor requires Airflow 3.2+") requires_3_4 = pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="Filter requires Airflow 3.4+") @@ -121,6 +131,7 @@ def events_response(): @pytest.fixture( params=[ ("RunStart", "dag_run.start_date", 8), + ("RunAfter", "dag_run.run_after", 7), ("LogicalDate", "logical_date", 1), ("DataIntervalStart", "data_interval_start", 2), ("DataIntervalEnd", "data_interval_end", 3), @@ -135,7 +146,7 @@ def time_bound_case(request): @pytest.fixture def time_bound_context(): return { - "dag_run": SimpleNamespace(start_date=_get_timestamp(8)), + "dag_run": SimpleNamespace(start_date=_get_timestamp(8), run_after=_get_timestamp(7)), "logical_date": _get_timestamp(1), "data_interval_start": _get_timestamp(2), "data_interval_end": _get_timestamp(3), @@ -143,10 +154,46 @@ def time_bound_context(): class TestInit: + @pytest.mark.parametrize( + "kwargs", + [ + {}, + {"after": None, "before": None}, + {"limit": 1}, + {"ascending": False}, + {"process_result": only_us_partitions}, + {"expected_count": 0, "count_policy": "exact"}, + pytest.param({"extra": {}}, marks=requires_3_4), + ], + ids=["none", "null-bounds", "limit", "order", "processing", "count", "empty-extra"], + ) + def test_requires_query_filter(self, asset, kwargs): + with pytest.raises(ValueError, match="requires at least one filter"): + AssetEventSensor(task_id="s", asset=asset, **kwargs) + + @pytest.mark.parametrize( + "filters", + [ + {"after": _get_timestamp(1)}, + {"before": _get_timestamp(2)}, + pytest.param({"partition_key": "a"}, marks=requires_3_4), + pytest.param({"partition_key_regexp_pattern": "a.*"}, marks=requires_3_4), + pytest.param({"extra": {"region": "us"}}, marks=requires_3_4), + ], + ids=["after", "before", "partition", "partition-regexp", "extra"], + ) + def test_accepts_each_query_filter_alone(self, asset, mock_supervisor_comms, filters): + sensor = AssetEventSensor(task_id="s", asset=asset, **filters) + mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=[]) + sensor.poke(_get_context(sensor)) + mock_supervisor_comms.send.assert_called_once_with( + GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, **filters) + ) + @pytest.mark.parametrize("use_alias", [False, True]) def test_declares_target_as_inlet(self, asset, use_alias): target = AssetAlias(name=ALIAS_NAME) if use_alias else asset - sensor = AssetEventSensor(task_id="s", asset=target) + sensor = AssetEventSensor(task_id="s", asset=target, after=_get_timestamp(1)) assert sensor.asset == target assert sensor.inlets == [target] @@ -155,22 +202,22 @@ def test_preserves_existing_inlets_without_duplicates(self, asset, include_targe other_asset = Asset("s3://bucket/other") inlets = [other_asset, asset] if include_target else [other_asset] original_inlets = inlets.copy() - sensor = AssetEventSensor(task_id="s", asset=asset, inlets=inlets) + sensor = AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1), inlets=inlets) assert sensor.inlets == [other_asset, asset] assert inlets == original_inlets def test_rejects_negative_expected_count(self, asset): with pytest.raises(ValueError, match="expected_count"): - AssetEventSensor(task_id="s", asset=asset, expected_count=-1) + AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1), expected_count=-1) @pytest.mark.parametrize("limit", [0, -1]) def test_rejects_nonpositive_limit(self, asset, limit): with pytest.raises(ValueError, match="limit"): - AssetEventSensor(task_id="s", asset=asset, limit=limit, expected_count=0) + AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1), limit=limit, expected_count=0) def test_rejects_invalid_count_policy(self, asset): with pytest.raises(ValueError, match="count_policy"): - AssetEventSensor(task_id="s", asset=asset, count_policy="unknown") + AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1), count_policy="unknown") @pytest.mark.parametrize( ("count_policy", "limit", "expected_count"), @@ -181,6 +228,7 @@ def test_rejects_insufficient_limit_without_processing(self, asset, count_policy AssetEventSensor( task_id="s", asset=asset, + after=_get_timestamp(1), limit=limit, expected_count=expected_count, count_policy=count_policy, @@ -189,7 +237,12 @@ def test_rejects_insufficient_limit_without_processing(self, asset, count_policy @pytest.mark.parametrize(("count_policy", "limit"), [("minimum", 3), ("exact", 4)]) def test_accepts_sufficient_limit_without_processing(self, asset, count_policy, limit): sensor = AssetEventSensor( - task_id="s", asset=asset, limit=limit, expected_count=3, count_policy=count_policy + task_id="s", + asset=asset, + after=_get_timestamp(1), + limit=limit, + expected_count=3, + count_policy=count_policy, ) assert sensor.limit == limit @@ -238,14 +291,15 @@ def test_renders_filters_without_changing_lineage(self, asset): class TestTimeBounds: + @pytest.mark.parametrize("field", ["after", "before"]) @pytest.mark.parametrize("inherit_protocol", [False, True], ids=["plain", "subclass"]) @pytest.mark.parametrize("as_string", [False, True], ids=["datetime", "iso"]) def test_custom_resolver_needs_only_resolve( - self, asset, events_response, mock_supervisor_comms, inherit_protocol, as_string + self, asset, events_response, mock_supervisor_comms, field, inherit_protocol, as_string ): bound = _InheritedParameterBound() if inherit_protocol else _ParameterBound() timestamp = _get_timestamp(8) - sensor = AssetEventSensor(task_id="s", asset=asset, after=bound) + sensor = AssetEventSensor(task_id="s", asset=asset, **{field: bound}) context = { **_get_context(sensor), "params": {"events_after": timestamp.isoformat() if as_string else timestamp}, @@ -254,7 +308,7 @@ def test_custom_resolver_needs_only_resolve( mock_supervisor_comms.send.side_effect = [AssetEventsResult(asset_events=[]), events_response] assert not sensor.poke(context) assert sensor.poke(context) - query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=timestamp) + query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, **{field: timestamp}) assert mock_supervisor_comms.send.call_args_list == [call(query), call(query)] def test_custom_resolver_serialization_is_optional(self, asset): @@ -264,20 +318,18 @@ def test_custom_resolver_serialization_is_optional(self, asset): assert isinstance(encoded["after"], str) assert "_ParameterBound" in encoded["after"] - @pytest.mark.parametrize("lookback", [timedelta(0), timedelta(hours=1, microseconds=7)]) - def test_resolves_selected_timestamp(self, time_bound_case, time_bound_context, lookback): + @pytest.mark.parametrize( + "offset", [timedelta(0), -timedelta(hours=1, microseconds=7), timedelta(hours=1, microseconds=7)] + ) + def test_resolves_selected_timestamp(self, time_bound_case, time_bound_context, offset): bound_type, _, timestamp = time_bound_case - assert bound_type(lookback=lookback).resolve(time_bound_context) == timestamp - lookback - - def test_rejects_negative_lookback(self): - with pytest.raises(ValueError, match="lookback.*non-negative"): - RunStart(lookback=timedelta(microseconds=-1)) + assert bound_type(offset=offset).resolve(time_bound_context) == timestamp + offset @pytest.mark.parametrize("missing", [False, True], ids=["none", "absent"]) def test_rejects_missing_timestamp(self, time_bound_case, time_bound_context, missing): bound_type, anchor, _ = time_bound_case - if anchor == "dag_run.start_date": - time_bound_context["dag_run"].start_date = None + if anchor.startswith("dag_run."): + setattr(time_bound_context["dag_run"], anchor.removeprefix("dag_run."), None) if missing: del time_bound_context["dag_run"] elif missing: @@ -287,40 +339,51 @@ def test_rejects_missing_timestamp(self, time_bound_case, time_bound_context, mi with pytest.raises(ValueError, match=rf"{bound_type.__name__} requires"): bound_type().resolve(time_bound_context) - def test_displays_bound_configuration_in_serialized_task(self, asset, time_bound_case): - bound_type, _, _ = time_bound_case + @pytest.mark.parametrize("offset", [-timedelta(hours=1, microseconds=7), timedelta(hours=2)]) + def test_displays_bound_configuration_in_serialized_task(self, asset, time_bound_case, offset): + bound_type, anchor, _ = time_bound_case + bound = bound_type(offset=offset) + metadata = {"anchor": anchor, "offset_seconds": offset.total_seconds()} + assert json.loads(json.dumps(bound.serialize())) == metadata with DAG("test_bounds_serialization"): - first = AssetEventSensor( - task_id="first", asset=asset, after=bound_type(lookback=timedelta(hours=1)) - ) - second = AssetEventSensor( - task_id="second", asset=asset, after=bound_type(lookback=timedelta(hours=2)) - ) - first_encoded = json.loads(json.dumps(OperatorSerialization.serialize_operator(first))) - second_encoded = json.loads(json.dumps(OperatorSerialization.serialize_operator(second))) - assert first_encoded["after"] == f"{bound_type.__name__}(lookback=datetime.timedelta(seconds=3600))" - assert second_encoded["after"] == f"{bound_type.__name__}(lookback=datetime.timedelta(seconds=7200))" + sensor = AssetEventSensor(task_id="s", asset=asset, after=bound) + encoded = json.loads(json.dumps(OperatorSerialization.serialize_operator(sensor))) + assert encoded["after"] in (metadata, repr(bound)) @pytest.mark.parametrize("field", ["after", "before"]) def test_renders_and_queries_bound( self, asset, time_bound_case, time_bound_context, field, mock_supervisor_comms ): bound_type, _, timestamp = time_bound_case - lookback = timedelta(hours=1) - bound = bound_type(lookback=lookback) + offset = -timedelta(hours=1) + bound = bound_type(offset=offset) sensor = AssetEventSensor(task_id="s", asset=asset, **{field: bound}) context = {**time_bound_context, **_get_context(sensor)} sensor.render_template_fields(context) mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=[]) sensor.poke(context) mock_supervisor_comms.send.assert_called_once_with( - GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, **{field: timestamp - lookback}) + GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, **{field: timestamp + offset}) ) - assert bound.lookback == lookback + assert bound.offset == offset + @pytest.mark.parametrize("offset", [timedelta(0), timedelta(microseconds=1)]) + def test_run_after_preserves_explicit_offset_in_query( + self, asset, time_bound_context, mock_supervisor_comms, offset + ): + sensor = AssetEventSensor(task_id="s", asset=asset, after=asset_sensor.RunAfter(offset=offset)) + context = {**time_bound_context, **_get_context(sensor)} + sensor.render_template_fields(context) + mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=[]) + sensor.poke(context) + mock_supervisor_comms.send.assert_called_once_with( + GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=_get_timestamp(7) + offset) + ) + + @pytest.mark.parametrize("field", ["after", "before"]) @pytest.mark.parametrize("as_string", [False, True]) def test_custom_callable_resolves_before_polling( - self, asset, events_response, mock_supervisor_comms, mocker, as_string + self, asset, events_response, mock_supervisor_comms, mocker, field, as_string ): timestamp = _get_timestamp(8) @@ -328,21 +391,29 @@ def get_bound(*, context, jinja_env): return timestamp.isoformat() if as_string else timestamp get_bound_spy = mocker.create_autospec(get_bound, side_effect=get_bound) - sensor = AssetEventSensor(task_id="s", asset=asset, after=get_bound_spy) + sensor = AssetEventSensor(task_id="s", asset=asset, **{field: get_bound_spy}) context = _get_context(sensor) sensor.render_template_fields(context) mock_supervisor_comms.send.side_effect = [AssetEventsResult(asset_events=[]), events_response] assert not sensor.poke(context) assert sensor.poke(context) get_bound_spy.assert_called_once() - query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=timestamp) + query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, **{field: timestamp}) assert mock_supervisor_comms.send.call_args_list == [call(query), call(query)] @pytest.mark.parametrize("mapped_bound", [False, True], ids=["partial", "expand"]) + @pytest.mark.parametrize(("bound_name", "anchor_day"), [("RunStart", 8), ("RunAfter", 7)]) def test_mapped_sensor( - self, asset, events_response, create_runtime_ti, mock_supervisor_comms, mapped_bound + self, + asset, + events_response, + create_runtime_ti, + mock_supervisor_comms, + mapped_bound, + bound_name, + anchor_day, ): - bound = RunStart(lookback=timedelta(hours=1)) + bound = getattr(asset_sensor, bound_name)(offset=-timedelta(hours=1)) with DAG("test_mapped_bounds"): if mapped_bound: mapped = AssetEventSensor.partial(task_id="s", asset=asset).expand(after=[bound, bound]) @@ -350,6 +421,7 @@ def test_mapped_sensor( mapped = AssetEventSensor.partial(task_id="s", asset=asset, after=bound).expand(limit=[1, 2]) ti = create_runtime_ti(task=mapped, map_index=1, start_date=_get_timestamp(8), logical_date=None) context = ti.get_template_context() + context["dag_run"].run_after = _get_timestamp(7) ti.render_templates(context=context) mock_supervisor_comms.send.return_value = events_response assert ti.task.poke(context) @@ -357,7 +429,7 @@ def test_mapped_sensor( GetAssetEventByAsset( name=ASSET_NAME, uri=ASSET_URI, - after=_get_timestamp(8) - timedelta(hours=1), + after=_get_timestamp(anchor_day) - timedelta(hours=1), limit=None if mapped_bound else 2, ) ) @@ -366,7 +438,7 @@ def test_mapped_sensor( def test_mapped_custom_resolver( self, asset, events_response, create_runtime_ti, mock_supervisor_comms, mapped_bound ): - bound = _ParameterBound() + bound = _MappedParameterBound("events_after") timestamp = _get_timestamp(8) with DAG("test_mapped_custom_bound"): if mapped_bound: @@ -394,29 +466,75 @@ def test_mapped_custom_resolver( ) ) + @pytest.mark.parametrize("mapped_bound", [False, True], ids=["partial", "expand"]) + @pytest.mark.parametrize( + "bound_name", + ["RunStart", "RunAfter", "LogicalDate", "DataIntervalStart", "DataIntervalEnd", "custom"], + ) + def test_mapped_bound_serialization_is_stable(self, asset, mapped_bound, bound_name): + def build_dag(configuration): + if bound_name == "custom": + bound = _MappedParameterBound(f"events_after_{configuration}") + else: + bound = getattr(asset_sensor, bound_name)(offset=timedelta(seconds=configuration)) + with DAG("test_mapped_bound_serialization") as dag: + if mapped_bound: + AssetEventSensor.partial(task_id="s", asset=asset).expand(after=[bound]) + else: + AssetEventSensor.partial(task_id="s", asset=asset, after=bound).expand(limit=[1]) + return dag + + first, second, changed = build_dag(1), build_dag(1), build_dag(2) + first_encoded = json.loads(json.dumps(DagSerialization.to_dict(first))) + assert first_encoded == json.loads(json.dumps(DagSerialization.to_dict(second))) + assert first_encoded != json.loads(json.dumps(DagSerialization.to_dict(changed))) + + def test_cleared_run_changes_only_start_time_bound(self, asset, time_bound_case, time_bound_context): + bound_type, anchor, timestamp = time_bound_case + first = AssetEventSensor(task_id="s", asset=asset, after=bound_type()) + first.render_template_fields(time_bound_context) + time_bound_context["dag_run"].start_date = _get_timestamp(9) + cleared = AssetEventSensor(task_id="s", asset=asset, after=bound_type()) + cleared.render_template_fields(time_bound_context) + assert first.after == timestamp + assert cleared.after == (_get_timestamp(9) if anchor == "dag_run.start_date" else timestamp) + + @pytest.mark.parametrize(("bound_name", "anchor_day"), [("RunStart", 8), ("RunAfter", 7)]) def test_reconstructed_sensor_keeps_bound_after_rescheduling( - self, asset, events_response, create_runtime_ti, mock_supervisor_comms, time_machine + self, + asset, + events_response, + create_runtime_ti, + mock_supervisor_comms, + time_machine, + bound_name, + anchor_day, ): time_machine.move_to(_get_timestamp(10), tick=False) - first = AssetEventSensor(task_id="s", asset=asset, after=RunStart(), mode="reschedule") - ti = create_runtime_ti(task=first, start_date=_get_timestamp(8)) + bound_type = getattr(asset_sensor, bound_name) + first = AssetEventSensor(task_id="s", asset=asset, after=bound_type(), mode="reschedule") + ti = create_runtime_ti(task=first, start_date=_get_timestamp(8), logical_date=None) context = ti.get_template_context() + context["dag_run"].run_after = _get_timestamp(7) ti.render_templates(context=context) mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=[]) with pytest.raises(AirflowRescheduleException): ti.task.execute(context) time_machine.shift(timedelta(hours=1)) - resumed = AssetEventSensor(task_id="s", asset=asset, after=RunStart(), mode="reschedule") - resumed_ti = create_runtime_ti(task=resumed, start_date=_get_timestamp(8), task_reschedule_count=1) + resumed = AssetEventSensor(task_id="s", asset=asset, after=bound_type(), mode="reschedule") + resumed_ti = create_runtime_ti( + task=resumed, start_date=_get_timestamp(8), logical_date=None, task_reschedule_count=1 + ) resumed_context = resumed_ti.get_template_context() + resumed_context["dag_run"].run_after = _get_timestamp(7) resumed_ti.render_templates(context=resumed_context) mock_supervisor_comms.send.side_effect = [ TaskRescheduleStartDate(start_date=_get_timestamp(10)), events_response, ] assert resumed_ti.task.execute(resumed_context) - query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=_get_timestamp(8)) + query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=_get_timestamp(anchor_day)) assert [c for c in mock_supervisor_comms.send.call_args_list if c == call(query)] == [ call(query), call(query), @@ -424,15 +542,40 @@ def test_reconstructed_sensor_keeps_bound_after_rescheduling( class TestPoke: + @pytest.mark.parametrize( + ("field", "rendered_value"), + [ + ("after", None), + ("before", None), + pytest.param("partition_key", None, marks=requires_3_4), + pytest.param("partition_key_regexp_pattern", None, marks=requires_3_4), + pytest.param("extra", None, marks=requires_3_4), + pytest.param("extra", {}, marks=requires_3_4), + ], + ids=["after", "before", "partition", "partition-regexp", "null-extra", "empty-extra"], + ) + def test_rejects_missing_filters_after_rendering( + self, asset, mock_supervisor_comms, field, rendered_value + ): + def get_filter(*, context, jinja_env): + return rendered_value + + sensor = AssetEventSensor(task_id="s", asset=asset, **{field: get_filter}) + context = _get_context(sensor) + sensor.render_template_fields(context) + with pytest.raises(ValueError, match="requires at least one filter"): + sensor.poke(context) + mock_supervisor_comms.send.assert_not_called() + def test_returns_serialized_events(self, asset, events_response, mock_supervisor_comms): mock_supervisor_comms.send.return_value = events_response - sensor = AssetEventSensor(task_id="s", asset=asset) + sensor = AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1)) result = sensor.poke(_get_context(sensor)) assert isinstance(result, PokeReturnValue) assert bool(result) is True assert result.xcom_value == [event.model_dump(mode="json") for event in events_response.asset_events] mock_supervisor_comms.send.assert_called_once_with( - GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI) + GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=_get_timestamp(1)) ) @pytest.mark.parametrize( @@ -457,7 +600,11 @@ def test_count_policy( events = events_response.asset_events[:actual_count] mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=events) sensor = AssetEventSensor( - task_id="s", asset=asset, count_policy=count_policy, expected_count=expected_count + task_id="s", + asset=asset, + after=_get_timestamp(1), + count_policy=count_policy, + expected_count=expected_count, ) result = sensor.poke(_get_context(sensor)) assert bool(result) is done @@ -500,7 +647,7 @@ def test_forwards_all_filters(self, asset, mock_supervisor_comms, use_alias, str @pytest.mark.parametrize("selector", ["name", "uri"]) def test_resolves_asset_reference(self, selector, events_response, mock_supervisor_comms): target = {"name": ASSET_NAME} if selector == "name" else {"uri": ASSET_URI} - sensor = AssetEventSensor(task_id="s", asset=Asset.ref(**target)) + sensor = AssetEventSensor(task_id="s", asset=Asset.ref(**target), after=_get_timestamp(1)) assert sensor.inlets == [Asset.ref(**target)] mock_supervisor_comms.send.side_effect = [ AssetResult(name=ASSET_NAME, uri=ASSET_URI, group="asset", extra={}), @@ -511,21 +658,22 @@ def test_resolves_asset_reference(self, selector, events_response, mock_supervis query = GetAssetEventByAsset( name=ASSET_NAME if selector == "name" else None, uri=ASSET_URI if selector == "uri" else None, + after=_get_timestamp(1), ) assert mock_supervisor_comms.send.call_args_list == [call(resolution), call(query)] def test_fetches_fresh_events_on_every_poke(self, asset, events_response, mock_supervisor_comms): mock_supervisor_comms.send.side_effect = [AssetEventsResult(asset_events=[]), events_response] - sensor = AssetEventSensor(task_id="s", asset=asset) + sensor = AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1)) context = _get_context(sensor) assert bool(sensor.poke(context)) is False assert bool(sensor.poke(context)) is True - query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI) + query = GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=_get_timestamp(1)) assert mock_supervisor_comms.send.call_args_list == [call(query), call(query)] def test_execute_returns_xcom_payload(self, asset, events_response, mock_supervisor_comms): mock_supervisor_comms.send.return_value = events_response - sensor = AssetEventSensor(task_id="s", asset=asset) + sensor = AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1)) result = sensor.execute(_get_context(sensor)) assert result == [event.model_dump(mode="json") for event in events_response.asset_events] @@ -569,6 +717,7 @@ def test_processes_events_before_counting( sensor = AssetEventSensor( task_id="s", asset=asset, + after=_get_timestamp(1), process_result=process_result, expected_count=expected_count, count_policy="exact", @@ -587,6 +736,7 @@ def test_processing_can_expand_limited_results(self, asset, events_response, moc sensor = AssetEventSensor( task_id="s", asset=asset, + after=_get_timestamp(1), limit=1, expected_count=2, count_policy="exact", @@ -627,6 +777,7 @@ def test_processing_can_return_json_values(self, asset, events_response, mock_su sensor = AssetEventSensor( task_id="s", asset=asset, + after=_get_timestamp(1), process_result=lambda events: [{"partition": event.partition_key} for event in events], ) result = sensor.poke(_get_context(sensor)) @@ -640,6 +791,6 @@ def boom(events): raise RuntimeError("process_result exploded") mock_supervisor_comms.send.return_value = events_response - sensor = AssetEventSensor(task_id="s", asset=asset, process_result=boom) + sensor = AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1), process_result=boom) with pytest.raises(RuntimeError, match="process_result exploded"): sensor.poke(_get_context(sensor)) From e29a7f2b94137b5ba7f86c5d254703d3d8f59ef5 Mon Sep 17 00:00:00 2001 From: hussein-awala Date: Tue, 3 Nov 2026 10:45:20 +0100 Subject: [PATCH 21/21] Allow empty extra filters on older Airflow versions An empty extra dictionary adds no query predicate, so it should not require Airflow 3.4 when another filter is present. --- providers/standard/docs/sensors/asset.rst | 4 +-- .../providers/standard/sensors/asset.py | 31 ++++++++++--------- .../tests/unit/standard/sensors/test_asset.py | 18 ++++++++--- 3 files changed, 32 insertions(+), 21 deletions(-) diff --git a/providers/standard/docs/sensors/asset.rst b/providers/standard/docs/sensors/asset.rst index 345f3fcd4093..6d57ffd5d4a0 100644 --- a/providers/standard/docs/sensors/asset.rst +++ b/providers/standard/docs/sensors/asset.rst @@ -177,8 +177,8 @@ configure the timetable's ``interval``. A bound raises ``ValueError`` if its selected timestamp is missing; it does not substitute another timestamp. Manual runs can have a data interval when a logical -date is supplied. Use ``after=RunStart()`` to wait for events at or after the actual -start of an asset-triggered run. +date is supplied. For asset-triggered runs, use ``RunStart()`` or ``RunAfter()`` +instead. See the table for how they differ when a run is cleared. Airflow resolves the objects during template rendering, before polling. Their run-relative values stay fixed while the sensor polls and after rescheduling. diff --git a/providers/standard/src/airflow/providers/standard/sensors/asset.py b/providers/standard/src/airflow/providers/standard/sensors/asset.py index 9ec2eaff797d..a092fb266955 100644 --- a/providers/standard/src/airflow/providers/standard/sensors/asset.py +++ b/providers/standard/src/airflow/providers/standard/sensors/asset.py @@ -68,7 +68,8 @@ def resolve(self, context: Context) -> datetime | str: class _ContextTimeBound(AssetEventTimeBound): - _label: ClassVar[str] + # This is a serialized identifier; changing its value changes the serialized Dag's hash. + _anchor: ClassVar[str] def __init__(self, *, offset: timedelta = timedelta(0)) -> None: self.offset = offset @@ -78,7 +79,7 @@ def __repr__(self) -> str: def serialize(self) -> dict[str, str | float]: """Return the bound configuration for serialized task metadata.""" - return {"anchor": self._label, "offset_seconds": self.offset.total_seconds()} + return {"anchor": self._anchor, "offset_seconds": self.offset.total_seconds()} @abstractmethod def _get_timestamp(self, context: Context) -> datetime | None: ... @@ -87,7 +88,7 @@ def resolve(self, context: Context) -> datetime: """Resolve the bound during template rendering, before the sensor polls.""" timestamp = self._get_timestamp(context) if timestamp is None: - raise ValueError(f"{type(self).__name__} requires {self._label!r} in the task context.") + raise ValueError(f"{type(self).__name__} requires {self._anchor!r} in the task context.") return timestamp + self.offset @@ -98,7 +99,7 @@ class RunStart(_ContextTimeBound): :param offset: Signed duration to add to ``dag_run.start_date``. """ - _label = "dag_run.start_date" + _anchor = "dag_run.start_date" def _get_timestamp(self, context: Context) -> datetime | None: dag_run = context.get("dag_run") @@ -115,7 +116,7 @@ class RunAfter(_ContextTimeBound): :param offset: Signed duration to add to ``dag_run.run_after``. """ - _label = "dag_run.run_after" + _anchor = "dag_run.run_after" def _get_timestamp(self, context: Context) -> datetime | None: dag_run = context.get("dag_run") @@ -129,7 +130,7 @@ class LogicalDate(_ContextTimeBound): :param offset: Signed duration to add to ``logical_date``. """ - _label = "logical_date" + _anchor = "logical_date" def _get_timestamp(self, context: Context) -> datetime | None: return context.get("logical_date") @@ -142,7 +143,7 @@ class DataIntervalStart(_ContextTimeBound): :param offset: Signed duration to add to ``data_interval_start``. """ - _label = "data_interval_start" + _anchor = "data_interval_start" def _get_timestamp(self, context: Context) -> datetime | None: return context.get("data_interval_start") @@ -155,7 +156,7 @@ class DataIntervalEnd(_ContextTimeBound): :param offset: Signed duration to add to ``data_interval_end``. """ - _label = "data_interval_end" + _anchor = "data_interval_end" def _get_timestamp(self, context: Context) -> datetime | None: return context.get("data_interval_end") @@ -230,13 +231,6 @@ def __init__( process_result: Callable[[list[AssetEventResult]], list[Any]] | None = None, **kwargs, ) -> None: - if not AIRFLOW_V_3_4_PLUS and ( - partition_key is not None or partition_key_regexp_pattern is not None or extra is not None - ): - raise AirflowOptionalProviderFeatureException( - "AssetEventSensor filters partition_key, partition_key_regexp_pattern and extra " - "need Airflow 3.4+." - ) super().__init__(**kwargs) if expected_count < 0: raise ValueError(f"`expected_count` must be a non-negative integer, got {expected_count}.") @@ -271,6 +265,13 @@ def __init__( self._validate_filters() def _validate_filters(self) -> None: + if not AIRFLOW_V_3_4_PLUS and ( + self.partition_key is not None or self.partition_key_regexp_pattern is not None or self.extra + ): + raise AirflowOptionalProviderFeatureException( + "AssetEventSensor filters partition_key, partition_key_regexp_pattern and extra " + "need Airflow 3.4+." + ) if ( self.after is None and self.before is None diff --git a/providers/standard/tests/unit/standard/sensors/test_asset.py b/providers/standard/tests/unit/standard/sensors/test_asset.py index d25aae34d88a..37f8f23b3a24 100644 --- a/providers/standard/tests/unit/standard/sensors/test_asset.py +++ b/providers/standard/tests/unit/standard/sensors/test_asset.py @@ -163,7 +163,7 @@ class TestInit: {"ascending": False}, {"process_result": only_us_partitions}, {"expected_count": 0, "count_policy": "exact"}, - pytest.param({"extra": {}}, marks=requires_3_4), + {"extra": {}}, ], ids=["none", "null-bounds", "limit", "order", "processing", "count", "empty-extra"], ) @@ -255,10 +255,20 @@ def test_partition_and_extra_filters_require_airflow_3_4(self, mocker, asset, fi with pytest.raises(AirflowOptionalProviderFeatureException, match="need Airflow 3.4"): AssetEventSensor(task_id="s", asset=asset, **filters) - def test_other_filters_do_not_require_airflow_3_4(self, mocker, asset): + @pytest.mark.parametrize("extra", [None, {}], ids=["no-extra", "empty-extra"]) + def test_other_filters_do_not_require_airflow_3_4(self, mocker, asset, mock_supervisor_comms, extra): mocker.patch("airflow.providers.standard.sensors.asset.AIRFLOW_V_3_4_PLUS", False) - sensor = AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1), limit=1) - assert sensor.limit == 1 + sensor = AssetEventSensor(task_id="s", asset=asset, after=_get_timestamp(1), limit=1, extra=extra) + mock_supervisor_comms.send.return_value = AssetEventsResult(asset_events=[]) + assert not sensor.poke(_get_context(sensor)) + mock_supervisor_comms.send.assert_called_once_with( + GetAssetEventByAsset(name=ASSET_NAME, uri=ASSET_URI, after=_get_timestamp(1), limit=1) + ) + + def test_empty_extra_requires_another_filter_before_airflow_3_4(self, mocker, asset): + mocker.patch("airflow.providers.standard.sensors.asset.AIRFLOW_V_3_4_PLUS", False) + with pytest.raises(ValueError, match="requires at least one filter"): + AssetEventSensor(task_id="s", asset=asset, extra={}) def test_template_fields(self): assert set(AssetEventSensor.template_fields) == {