kaxil commented on code in PR #65314:
URL: https://github.com/apache/airflow/pull/65314#discussion_r3706945021
##########
airflow-core/src/airflow/serialization/definitions/dag.py:
##########
@@ -1104,6 +1124,106 @@ 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:
+ if (ti_key := ti.key.primary) 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
+
+ if rendered :=
RenderedTaskInstanceFields.get_templated_fields(ti, session=session):
+ 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)
Review Comment:
This resolves the child Dag from its latest version, but the code being
restored used the run-pinned one: `dag_bag.get_dag_for_run(tii.dag_run,
session=session)`, at `dag.py:1029` before #54383 removed it. This route
already calls `get_dag_for_run` in two other spots (lines 335 and 882), so the
helper is right there.
Why it matters: the `partial_subset(include_downstream=True)` just below
becomes the `task_id.in_(...)` filter for the child's TI query. With bundle
versioning on, that means we work out the downstream closure from a graph the
historical child run may never have had. Say child v1 is `wait >> transform >>
load` and v2 drops `transform`: clearing the parent reruns `load` and leaves
`transform` sitting at SUCCESS in the v1 run.
`get_dag_for_run(...) or get_latest_version_of_dag(...)` keeps a fallback
for a missing serialized row, and still routes through `_get_dag`, so the
deserialize-once behaviour you added earlier holds.
##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_instances.py:
##########
@@ -933,30 +938,69 @@ def _collect_relatives(run_id: str, direction:
Literal["upstream", "downstream"]
*((t, m) for t, m in mapped_tasks_tuples if t not in
normal_task_ids),
]
+ # Follow ExternalTaskMarker connections when explicitly requested via
include_downstream_dags, or
+ # automatically whenever downstream clearing is selected (restoring
Airflow 2 behavior)
+ include_dependent_dags = body.include_downstream_dags or downstream
Review Comment:
Coming back to the flag overlap I asked about in
https://github.com/apache/airflow/pull/65314#discussion_r3482222489, now that
I've read the code this restores.
`include_downstream_dags: false` can't actually turn the cascade off,
because `or downstream` only ever reacts to `true`. And the comment doesn't
quite line up with what was there before: the pre-removal `clear()` hard-coded
`include_dependent_dags=True` (`dag.py:1404`), it wasn't keyed off the same-Dag
downstream flag at all.
The UI side is what bothers me more. `ClearTaskInstanceDialog` seeds
`selectedOptions` with `["downstream"]` (line 80, and the group dialog does the
same at 54), so a default single-task clear from the grid now walks into other
Dags and the caller has no way to say no.
`run_on_latest_version` in this same body model is already `bool | None`.
Same treatment here gets you the opt-out and keeps the current UI default:
```python
include_downstream_dags: bool | None = None
...
downstream if body.include_downstream_dags is None else
body.include_downstream_dags
```
##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_instances.py:
##########
@@ -933,30 +938,69 @@ def _collect_relatives(run_id: str, direction:
Literal["upstream", "downstream"]
*((t, m) for t, m in mapped_tasks_tuples if t not in
normal_task_ids),
]
+ # Follow ExternalTaskMarker connections when explicitly requested via
include_downstream_dags, or
+ # automatically whenever downstream clearing is selected (restoring
Airflow 2 behavior)
+ include_dependent_dags = body.include_downstream_dags or downstream
+
task_instances: Sequence[TI]
- if dag_run_id is not None and not (past or future):
- # Use run_id-based clearing when we have a specific dag_run_id and not
using past/future
- task_instances = dag.clear(
- dry_run=True,
- task_ids=task_markers_to_clear,
- run_id=dag_run_id,
- session=session,
- run_on_latest_version=resolved_run_on_latest,
- only_failed=body.only_failed,
- only_running=body.only_running,
- )
- else:
- # Use date-based clearing when no dag_run_id or when past/future is
specified
- task_instances = dag.clear(
- dry_run=True,
- task_ids=task_markers_to_clear,
- start_date=body.start_date,
- end_date=body.end_date,
- session=session,
- run_on_latest_version=resolved_run_on_latest,
- only_failed=body.only_failed,
- only_running=body.only_running,
- )
+ try:
+ if dag_run_id is not None and not (past or future):
+ # Use run_id-based clearing when we have a specific dag_run_id and
not using past/future
+ task_instances = dag.clear(
+ dry_run=True,
+ task_ids=task_markers_to_clear,
+ run_id=dag_run_id,
+ session=session,
+ run_on_latest_version=resolved_run_on_latest,
+ only_failed=body.only_failed,
+ only_running=body.only_running,
+ include_dependent_dags=include_dependent_dags,
+ dag_bag=dag_bag,
+ )
+ else:
+ # Use date-based clearing when no dag_run_id or when past/future
is specified
+ task_instances = dag.clear(
+ dry_run=True,
+ task_ids=task_markers_to_clear,
+ start_date=body.start_date,
+ end_date=body.end_date,
+ session=session,
+ run_on_latest_version=resolved_run_on_latest,
+ only_failed=body.only_failed,
+ only_running=body.only_running,
+ include_dependent_dags=include_dependent_dags,
+ dag_bag=dag_bag,
+ )
+
+ except MaxRecursionDepthError as e:
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, str(e)) from e
+ except ParserError as e:
Review Comment:
Still `ParserError`-only, so this misses the inputs that raise `ValueError`
directly. Same point as
https://github.com/apache/airflow/pull/65314#discussion_r3625072184, which got
resolved without the change.
Two shapes reach it on the pinned pendulum 3.2.0. `pendulum.parse("")`
raises `ValueError: year 0 is out of range`, which isn't a `ParserError`. And
`pendulum.parse("P1D")` returns a `Duration`, which then goes into
`DagRun.logical_date == <Duration>` and comes back as a `StatementError`. Both
end up as a 500. A marker with `logical_date="{{ dag_run.conf.get('x', '') }}"`
rendering empty gets you the first one.
Catching `ValueError` picks up the bare case plus the `ParserError` ones,
since it's the parent. The `Duration` shape needs a check on what `parse`
actually returned.
One thing to flag:
`test_invalid_external_task_marker_logical_date_returns_400` can't catch either
of these. It sets `side_effect=ParserError(...)` on a fully mocked `clear()`,
so it only proves the except clause catches what the test hands it, not what
the real call site raises.
##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_instances.py:
##########
@@ -933,30 +938,69 @@ def _collect_relatives(run_id: str, direction:
Literal["upstream", "downstream"]
*((t, m) for t, m in mapped_tasks_tuples if t not in
normal_task_ids),
]
+ # Follow ExternalTaskMarker connections when explicitly requested via
include_downstream_dags, or
+ # automatically whenever downstream clearing is selected (restoring
Airflow 2 behavior)
+ include_dependent_dags = body.include_downstream_dags or downstream
+
task_instances: Sequence[TI]
- if dag_run_id is not None and not (past or future):
- # Use run_id-based clearing when we have a specific dag_run_id and not
using past/future
- task_instances = dag.clear(
- dry_run=True,
- task_ids=task_markers_to_clear,
- run_id=dag_run_id,
- session=session,
- run_on_latest_version=resolved_run_on_latest,
- only_failed=body.only_failed,
- only_running=body.only_running,
- )
- else:
- # Use date-based clearing when no dag_run_id or when past/future is
specified
- task_instances = dag.clear(
- dry_run=True,
- task_ids=task_markers_to_clear,
- start_date=body.start_date,
- end_date=body.end_date,
- session=session,
- run_on_latest_version=resolved_run_on_latest,
- only_failed=body.only_failed,
- only_running=body.only_running,
- )
+ try:
+ if dag_run_id is not None and not (past or future):
+ # Use run_id-based clearing when we have a specific dag_run_id and
not using past/future
+ task_instances = dag.clear(
+ dry_run=True,
+ task_ids=task_markers_to_clear,
+ run_id=dag_run_id,
+ session=session,
+ run_on_latest_version=resolved_run_on_latest,
+ only_failed=body.only_failed,
+ only_running=body.only_running,
+ include_dependent_dags=include_dependent_dags,
+ dag_bag=dag_bag,
+ )
+ else:
+ # Use date-based clearing when no dag_run_id or when past/future
is specified
+ task_instances = dag.clear(
+ dry_run=True,
+ task_ids=task_markers_to_clear,
+ start_date=body.start_date,
+ end_date=body.end_date,
+ session=session,
+ run_on_latest_version=resolved_run_on_latest,
+ only_failed=body.only_failed,
+ only_running=body.only_running,
+ include_dependent_dags=include_dependent_dags,
+ dag_bag=dag_bag,
+ )
+
+ except MaxRecursionDepthError as e:
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, str(e)) from e
+ except ParserError as e:
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, f"Invalid
logical_date: {e}") from e
+ except DagNotFound as e:
+ raise HTTPException(status.HTTP_404_NOT_FOUND, str(e)) from e
+
+ if include_dependent_dags:
+ # Ensure proper access to downstream Dags/tasks with dag.clear and
include_dependent_dags
+ auth_manager = get_auth_manager()
+ all_dag_ids = {ti.dag_id for ti in task_instances} # Retrieve all Dag
ID's from task instances
+
+ # Used to find a team name from a Dag ID
+ dag_id_to_team =
DagModel.get_dag_id_to_team_name_mapping(list(all_dag_ids), session=session)
+
+ # set of Dag ID's that can be cleared
+ editable_dag_ids = {
+ dependent_dag_id
+ for dependent_dag_id in all_dag_ids
+ if auth_manager.is_authorized_dag(
+ method="PUT",
+ access_entity=DagAccessEntity.TASK_INSTANCE,
+ details=DagDetails(id=dependent_dag_id,
team_name=dag_id_to_team.get(dependent_dag_id)),
+ user=user,
+ )
+ }
+
+ # list of all TI's that can be cleared (TI's within the Dags from
above)
+ task_instances = [ti for ti in task_instances if ti.dag_id in
editable_dag_ids]
Review Comment:
Now that this list can span Dags, the single `resolved_run_on_latest`
computed up at line 863 from the path `dag_id` gets applied to child Dag runs
too. `resolve_run_on_latest_version` only takes one `dag_id` and reads the
*parent's* Dag-level setting; `clear_task_instances` then rewrites each run's
`created_dag_version_id` and calls `verify_integrity()`, which can add or drop
TIs in that run.
Since the clear dialog always sends the field, the `explicit_value is not
None` short-circuit means a child Dag with `rerun_with_latest_version=False`
gets upgraded regardless of its own setting.
Grouping the TIs by `dag_id` and resolving per Dag when
`body.run_on_latest_version is None` would respect each Dag's policy, with an
explicit value from the caller still winning everywhere.
--
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]