Lee-W commented on code in PR #65314:
URL: https://github.com/apache/airflow/pull/65314#discussion_r3702835105
##########
airflow-core/src/airflow/serialization/definitions/dag.py:
##########
@@ -1104,6 +1124,111 @@ def apply_state_filter(query):
else:
tis_full = apply_state_filter(tis_full)
+ if include_dependent_dags:
+ # Recursively find external tasks indicated by ExternalTaskMarker
+ from airflow.providers.standard.sensors.external_task import
ExternalTaskMarker
+
+ # Build a full-object query for identifying ExternalTaskMarker TIs
in the current set
+ if as_pk_tuple:
+ all_ti_rows = session.execute(tis_pk).all()
+ condition = TaskInstance.filter_for_tis(
+ TaskInstanceKey(**cols._mapping) for cols in all_ti_rows
+ )
+ marker_query = select(TaskInstance).where(condition) if
condition is not None else None
+ else:
+ marker_query = tis_full
+
+ if marker_query is not None:
+ if visited_external_tis is None:
+ visited_external_tis = set()
+
+ external_marker_tis = session.scalars(
+ marker_query.where(TaskInstance.operator ==
ExternalTaskMarker.__name__)
+ )
+
+ for ti in external_marker_tis:
+ ti_key = ti.key.primary
+
+ if ti_key in visited_external_tis:
+ continue
+
+ visited_external_tis.add(ti_key)
+ task: ExternalTaskMarker = cast("ExternalTaskMarker",
self.get_task(ti.task_id))
+
+ if max_recursion_depth is None:
+ # Maximum recursion depth is set from the first
ExternalTaskMarker encountered
+ max_recursion_depth = task.recursion_depth
+
+ if recursion_depth + 1 > max_recursion_depth:
+ raise MaxRecursionDepthError(
+ f"Maximum recursion depth {max_recursion_depth}
reached for "
+ f"{ExternalTaskMarker.__name__} {ti.task_id}. "
+ f"Attempted to clear too many tasks or there may
be a cyclic dependency."
+ )
+
+ if ti.dag_run.logical_date is None:
+ continue
+
+ # Retrieve the logical date from the TI, Dag/task ID's
from the task
+ logical_date_str: str = ti.dag_run.logical_date.isoformat()
+ external_dag_id = task.external_dag_id
+ external_task_id = task.external_task_id
+
+ rendered =
RenderedTaskInstanceFields.get_templated_fields(ti, session=session)
+
+ if rendered:
+ external_dag_id = rendered.get("external_dag_id",
external_dag_id)
+ external_task_id = rendered.get("external_task_id",
external_task_id)
+
+ if "logical_date" in rendered:
+ logical_date_str = rendered["logical_date"]
+
+ external_logical_date = pendulum.parse(logical_date_str)
+ external_tis = session.scalars(
+ select(TaskInstance)
+ .join(TaskInstance.dag_run)
+ .where(
+ TaskInstance.dag_id == external_dag_id,
+ TaskInstance.task_id == external_task_id,
+ DagRun.logical_date == external_logical_date,
+ )
+ )
+
+ # Load the DagBag such that Dags can be extracted from it
+ if not dag_bag:
+ dag_bag = DBDagBag(load_op_links=False)
+
+ for tii in external_tis:
+ external_dag =
dag_bag.get_latest_version_of_dag(tii.dag_id, session=session)
+
+ if not external_dag:
Review Comment:
```suggestion
external_dag =
dag_bag.get_latest_version_of_dag(tii.dag_id, session=session)
if not external_dag:
```
##########
airflow-core/src/airflow/serialization/definitions/dag.py:
##########
@@ -1277,6 +1414,12 @@ def clear(
:param exclude_task_ids: A set of ``task_id`` or (``task_id``,
``map_index``)
tuples that should not be cleared
:param exclude_run_ids: A set of ``run_id`` or (``run_id``)
+ :param include_dependent_dags: If True, also clear tasks in downstream
DAGs that are
Review Comment:
```suggestion
:param include_dependent_dags: If True, also clear tasks in
downstream Dags that are
```
##########
airflow-core/src/airflow/serialization/definitions/dag.py:
##########
@@ -1104,6 +1124,111 @@ def apply_state_filter(query):
else:
tis_full = apply_state_filter(tis_full)
+ if include_dependent_dags:
+ # Recursively find external tasks indicated by ExternalTaskMarker
+ from airflow.providers.standard.sensors.external_task import
ExternalTaskMarker
+
+ # Build a full-object query for identifying ExternalTaskMarker TIs
in the current set
+ if as_pk_tuple:
+ all_ti_rows = session.execute(tis_pk).all()
+ condition = TaskInstance.filter_for_tis(
+ TaskInstanceKey(**cols._mapping) for cols in all_ti_rows
+ )
+ marker_query = select(TaskInstance).where(condition) if
condition is not None else None
+ else:
+ marker_query = tis_full
+
+ if marker_query is not None:
+ if visited_external_tis is None:
+ visited_external_tis = set()
+
+ external_marker_tis = session.scalars(
+ marker_query.where(TaskInstance.operator ==
ExternalTaskMarker.__name__)
+ )
+
+ for ti in external_marker_tis:
+ ti_key = ti.key.primary
+
+ if ti_key in visited_external_tis:
+ continue
Review Comment:
```suggestion
if (ti_key := ti.ket.primary) in visited_external_tis:
continue
```
##########
airflow-core/tests/unit/serialization/definitions/test_dag.py:
##########
@@ -0,0 +1,387 @@
+#
+# 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 unittest import mock
+
+import pendulum
+import pytest
+
+from airflow.exceptions import AirflowException
+from airflow.models.dagbag import DBDagBag
+from airflow.models.renderedtifields import RenderedTaskInstanceFields
+from airflow.providers.standard.sensors.external_task import
ExternalTaskMarker, ExternalTaskSensor
+
+from tests_common.test_utils import db
+from tests_common.test_utils.db import clear_rendered_ti_fields
+
+pytestmark = pytest.mark.db_test
+
+EXTERNAL_LOGICAL_DATE = pendulum.datetime(2024, 1, 1, tz="UTC")
+
+
[email protected](autouse=True)
+def reset_db():
+ db.clear_db_dags()
+ db.clear_db_runs()
+ db.clear_db_serialized_dags()
+ clear_rendered_ti_fields()
+
+
+def test_clear_does_not_follow_external_marker_by_default(dag_maker, session):
+ """Without include_dependent_dags, ExternalTaskMarker links are not
followed."""
+ with dag_maker("parent_dag", session=session, schedule=None):
+ ExternalTaskMarker(
+ task_id="trigger_child",
+ external_dag_id="child_dag",
+ external_task_id="wait_for_parent",
+ recursion_depth=3,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ serialized_parent = dag_maker.serialized_dag
+
+ with dag_maker("child_dag", session=session, schedule=None):
+ ExternalTaskSensor(
+ task_id="wait_for_parent",
+ external_dag_id="parent_dag",
+ external_task_id="trigger_child",
+ poke_interval=5,
+ )
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ session.flush()
+
+ result = serialized_parent.clear(dry_run=True, only_failed=False,
session=session)
+
+ dag_ids = {ti.dag_id for ti in result}
+ assert "parent_dag" in dag_ids
+ assert "child_dag" not in dag_ids
+
+
+def
test_clear_follows_external_marker_when_include_dependent_dags_enabled(dag_maker,
session):
+ """With include_dependent_dags=True, clear() follows ExternalTaskMarker
links into child Dags."""
+ with dag_maker("parent_dag", session=session, schedule=None):
+ ExternalTaskMarker(
+ task_id="trigger_child",
+ external_dag_id="child_dag",
+ external_task_id="wait_for_parent",
+ recursion_depth=3,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ serialized_parent = dag_maker.serialized_dag
+
+ with dag_maker("child_dag", session=session, schedule=None):
+ ExternalTaskSensor(
+ task_id="wait_for_parent",
+ external_dag_id="parent_dag",
+ external_task_id="trigger_child",
+ poke_interval=5,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ session.flush()
+
+ result = serialized_parent.clear(
+ dry_run=True, only_failed=False, include_dependent_dags=True,
session=session
+ )
+
+ dag_ids = {ti.dag_id for ti in result}
+ task_ids = {ti.task_id for ti in result}
+
+ assert "parent_dag" in dag_ids
+ assert "child_dag" in dag_ids
+ assert "wait_for_parent" in task_ids
+
+
+def test_clear_reuses_provided_dag_bag_for_external_dags(dag_maker, session):
+ """Passing an existing dag_bag into clear() reuses it instead of creating
an uncached, un-configured one."""
+ with dag_maker("parent_dag", session=session, schedule=None):
+ ExternalTaskMarker(
+ task_id="trigger_child",
+ external_dag_id="child_dag",
+ external_task_id="wait_for_parent",
+ recursion_depth=3,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ serialized_parent = dag_maker.serialized_dag
+
+ with dag_maker("child_dag", session=session, schedule=None):
+ ExternalTaskSensor(
+ task_id="wait_for_parent",
+ external_dag_id="parent_dag",
+ external_task_id="trigger_child",
+ poke_interval=5,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ session.flush()
+
+ provided_dag_bag = DBDagBag()
+
+ with mock.patch("airflow.serialization.definitions.dag.DBDagBag",
wraps=DBDagBag) as mock_dbdagbag_cls:
+ result = serialized_parent.clear(
+ dry_run=True,
+ only_failed=False,
+ include_dependent_dags=True,
+ session=session,
+ dag_bag=provided_dag_bag,
+ )
+
+ mock_dbdagbag_cls.assert_not_called()
+ dag_ids = {ti.dag_id for ti in result}
+ assert "child_dag" in dag_ids
+
+
+def test_clear_creates_dag_bag_when_none_provided(dag_maker, session):
+ """Without a caller-provided dag_bag, clear() falls back to creating its
own."""
+ with dag_maker("parent_dag", session=session, schedule=None):
+ ExternalTaskMarker(
+ task_id="trigger_child",
+ external_dag_id="child_dag",
+ external_task_id="wait_for_parent",
+ recursion_depth=3,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ serialized_parent = dag_maker.serialized_dag
+
+ with dag_maker("child_dag", session=session, schedule=None):
+ ExternalTaskSensor(
+ task_id="wait_for_parent",
+ external_dag_id="parent_dag",
+ external_task_id="trigger_child",
+ poke_interval=5,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ session.flush()
+
+ with mock.patch("airflow.serialization.definitions.dag.DBDagBag",
wraps=DBDagBag) as mock_dbdagbag_cls:
+ serialized_parent.clear(dry_run=True, only_failed=False,
include_dependent_dags=True, session=session)
+
+ mock_dbdagbag_cls.assert_called_once_with(load_op_links=False)
+
+
+def
test_clear_dependent_dags_deserializes_child_dag_once_across_multiple_markers(dag_maker,
session):
+ """Multiple ExternalTaskMarkers into the same child dag must not each
re-deserialize it."""
+ with dag_maker("parent_dag", session=session, schedule=None):
+ ExternalTaskMarker(
+ task_id="trigger_child_a",
+ external_dag_id="child_dag",
+ external_task_id="wait_for_parent_a",
+ recursion_depth=3,
+ )
+ ExternalTaskMarker(
+ task_id="trigger_child_b",
+ external_dag_id="child_dag",
+ external_task_id="wait_for_parent_b",
+ recursion_depth=3,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ serialized_parent = dag_maker.serialized_dag
+
+ with dag_maker("child_dag", session=session, schedule=None):
+ ExternalTaskSensor(
+ task_id="wait_for_parent_a",
+ external_dag_id="parent_dag",
+ external_task_id="trigger_child_a",
+ poke_interval=5,
+ )
+ ExternalTaskSensor(
+ task_id="wait_for_parent_b",
+ external_dag_id="parent_dag",
+ external_task_id="trigger_child_b",
+ poke_interval=5,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ session.flush()
+
+ with mock.patch.object(
+ DBDagBag, "_read_dag", autospec=True, side_effect=DBDagBag._read_dag
+ ) as mock_read_dag:
+ result = serialized_parent.clear(
+ dry_run=True, only_failed=False, include_dependent_dags=True,
session=session
+ )
+
+ dag_ids = {ti.dag_id for ti in result}
+ assert "child_dag" in dag_ids
+ # Only the first ExternalTaskMarker into child_dag triggers an actual
deserialize; the
+ # second is served from the shared DBDagBag cache instead of
re-reading/re-deserializing.
+ child_dag_reads = [call for call in mock_read_dag.call_args_list if
call.args[1].dag_id == "child_dag"]
+ assert len(child_dag_reads) == 1
+
+
+def test_clear_raises_when_recursion_depth_exceeded(dag_maker, session):
+ """MaxRecursionDepthError is raised when the dependency chain depth
exceeds recursion_depth."""
+ with dag_maker("parent_dag", session=session, schedule=None):
+ ExternalTaskMarker(
+ task_id="trigger_child",
+ external_dag_id="child_dag",
+ external_task_id="wait_for_parent",
+ recursion_depth=1,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ serialized_parent = dag_maker.serialized_dag
+
+ with dag_maker("child_dag", session=session, schedule=None):
+ wait_for_parent = ExternalTaskSensor(
+ task_id="wait_for_parent",
+ external_dag_id="parent_dag",
+ external_task_id="trigger_child",
+ poke_interval=5,
+ )
+
+ trigger_grandchild = ExternalTaskMarker(
+ task_id="trigger_grandchild",
+ external_dag_id="grandchild_dag",
+ external_task_id="wait_for_child",
+ recursion_depth=1,
+ )
+
+ wait_for_parent >> trigger_grandchild
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+
+ with dag_maker("grandchild_dag", session=session, schedule=None):
+ ExternalTaskSensor(
+ task_id="wait_for_child",
+ external_dag_id="child_dag",
+ external_task_id="trigger_grandchild",
+ poke_interval=5,
+ )
+
+ dag_maker.create_dagrun(logical_date=EXTERNAL_LOGICAL_DATE)
+ session.flush()
+
+ with pytest.raises(AirflowException, match="Maximum recursion depth"):
Review Comment:
Shouldn't it be `MaxRecursionDepthError` instead?
##########
airflow-core/src/airflow/serialization/definitions/dag.py:
##########
@@ -1104,6 +1124,111 @@ def apply_state_filter(query):
else:
tis_full = apply_state_filter(tis_full)
+ if include_dependent_dags:
+ # Recursively find external tasks indicated by ExternalTaskMarker
+ from airflow.providers.standard.sensors.external_task import
ExternalTaskMarker
+
+ # Build a full-object query for identifying ExternalTaskMarker TIs
in the current set
+ if as_pk_tuple:
+ all_ti_rows = session.execute(tis_pk).all()
+ condition = TaskInstance.filter_for_tis(
+ TaskInstanceKey(**cols._mapping) for cols in all_ti_rows
+ )
+ marker_query = select(TaskInstance).where(condition) if
condition is not None else None
+ else:
+ marker_query = tis_full
+
+ if marker_query is not None:
+ if visited_external_tis is None:
+ visited_external_tis = set()
+
+ external_marker_tis = session.scalars(
+ marker_query.where(TaskInstance.operator ==
ExternalTaskMarker.__name__)
+ )
+
+ for ti in external_marker_tis:
+ ti_key = ti.key.primary
+
+ if ti_key in visited_external_tis:
+ continue
+
+ visited_external_tis.add(ti_key)
+ task: ExternalTaskMarker = cast("ExternalTaskMarker",
self.get_task(ti.task_id))
+
+ if max_recursion_depth is None:
+ # Maximum recursion depth is set from the first
ExternalTaskMarker encountered
+ max_recursion_depth = task.recursion_depth
+
+ if recursion_depth + 1 > max_recursion_depth:
+ raise MaxRecursionDepthError(
+ f"Maximum recursion depth {max_recursion_depth}
reached for "
+ f"{ExternalTaskMarker.__name__} {ti.task_id}. "
+ f"Attempted to clear too many tasks or there may
be a cyclic dependency."
+ )
+
+ if ti.dag_run.logical_date is None:
+ continue
+
+ # Retrieve the logical date from the TI, Dag/task ID's
from the task
+ logical_date_str: str = ti.dag_run.logical_date.isoformat()
+ external_dag_id = task.external_dag_id
+ external_task_id = task.external_task_id
+
+ rendered =
RenderedTaskInstanceFields.get_templated_fields(ti, session=session)
+
+ if rendered:
Review Comment:
```suggestion
if (rendered :=
RenderedTaskInstanceFields.get_templated_fields(ti, session=session)):
```
##########
airflow-core/tests/unit/serialization/definitions/test_dag.py:
##########
@@ -0,0 +1,387 @@
+#
+# 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 unittest import mock
+
+import pendulum
+import pytest
+
+from airflow.exceptions import AirflowException
+from airflow.models.dagbag import DBDagBag
+from airflow.models.renderedtifields import RenderedTaskInstanceFields
+from airflow.providers.standard.sensors.external_task import
ExternalTaskMarker, ExternalTaskSensor
+
+from tests_common.test_utils import db
+from tests_common.test_utils.db import clear_rendered_ti_fields
+
+pytestmark = pytest.mark.db_test
+
+EXTERNAL_LOGICAL_DATE = pendulum.datetime(2024, 1, 1, tz="UTC")
+
+
[email protected](autouse=True)
+def reset_db():
+ db.clear_db_dags()
+ db.clear_db_runs()
+ db.clear_db_serialized_dags()
+ clear_rendered_ti_fields()
Review Comment:
```suggestion
from tests_common.test_utils.db import (
clear_db_dags,
clear_db_runs,
clear_db_serialized_dags,
clear_rendered_ti_fields,
)
pytestmark = pytest.mark.db_test
EXTERNAL_LOGICAL_DATE = pendulum.datetime(2024, 1, 1, tz="UTC")
@pytest.fixture(autouse=True)
def reset_db():
clear_db_dags()
clear_db_runs()
clear_db_serialized_dags()
clear_rendered_ti_fields()
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]