Skip to content

Fix tasks clear --dag-regex AttributeError on SDK DAG - #66884

Closed
jni-bot wants to merge 2 commits into
apache:mainfrom
jni-bot:fix-tasks-clear-regex
Closed

jni-bot wants to merge 2 commits into
apache:mainfrom
jni-bot:fix-tasks-clear-regex

Conversation

@jni-bot

@jni-bot jni-bot commented May 13, 2026 •

Copy link
Copy Markdown

airflow tasks clear --dag-regex <pattern> crashes with AttributeError: 'DAG' object has no attribute 'clear' whenever the regex matches one or more Dags. The non-regex form works.

Reproduction

$ airflow tasks clear -R "example_python_operator" -y
...
File "airflow-core/src/airflow/cli/commands/task_command.py", line 530, in task_clear
    SerializedDAG.clear_dags(
File "airflow-core/src/airflow/serialization/definitions/dag.py", line 1121, in <genexpr>
    dag.clear(
AttributeError: 'DAG' object has no attribute 'clear'

Root cause

task_clear calls get_dags(..., from_db=True) expecting SerializedDAG instances, because that's the type SerializedDAG.clear_dags iterates over (it calls .clear() on each, which only exists on SerializedDAG, not on the SDK DAG returned by BundleDagBag). See the existing comment at task_command.py:504:

# Reading from_db because clear method still not implemented in Task SDK DAG
dags = get_dags(args.bundle_name, args.dag_id, use_regex=args.dag_regex, from_db=True)

But in utils/cli.py, get_dags only honors from_db in the non-regex branch:

if not use_regex:
    if from_db:
        return [get_db_dag(...)]    # SerializedDAG ✓
    return [get_bagged_dag(...)]
# regex branch ignored from_db entirely → BundleDagBag → SDK DAG → no .clear()

The from_db parameter was added in #48471 (closes #48430), which only plumbed it through the non-regex branch. Issue #63817 reported this same AttributeError for the non-regex path; #63827 fixed it by swapping get_dag_by_file_location → get_db_dag. The regex path was left in the original broken state, and no test guarded it.

Fix

In get_dags, when use_regex=True and from_db=True, query SerializedDagModel.read_all_dags() and regex-filter the Dag IDs. The non-regex path is unchanged. The original bundle-walking path is preserved for callers that don't pass from_db (e.g. dags trigger -R, dags pause -R).

Also switches the "not found" raise from the generic AirflowException to DagNotFound per the coding standards (prefer specific exceptions).

Side benefit: the previous bundle-walking path breaks out of the loop after the first bundle with any matches (utils/cli.py:343-344), so regex matches spanning multiple bundles were silently truncated. Querying the serialized Dag table sees all Dags regardless of bundle.

Tests

  • test_task_clear_with_dag_regex_returns_serialized_dags — unit-level: asserts get_dags(use_regex=True, from_db=True) returns objects with .clear().
  • test_task_clear_dag_regex_does_not_attribute_error — end-to-end regression test: invokes task_command.task_clear with -R and asserts it completes without the original AttributeError. Verified to fail with the exact pre-fix traceback when the cli.py change is reverted.

related: #63817


Was generative AI tooling used to co-author this PR?
  • Yes — Claude Code (Opus 4.7)

Generated-by: Claude Code (Opus 4.7) following the guidelines


Important

🛠️ Maintainer triage note for @jni-bot · by @potiuk · 2026-06-18 13:57 UTC

Paused pending your next update — this PR has been inactive for ~30 days, so it's been moved to draft to keep the review queue clear:

  • Rebase on the latest main, address any new failures, and mark it Ready for review when you pick it back up — no rush.
  • See the Pull Request quality criteria.

The ball is in your court — you've been assigned to this PR.

Automated triage — may be imperfect; a maintainer takes the next look.

@boring-cyborg

boring-cyborg Bot commented May 13, 2026

Copy link
Copy Markdown

Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide
Here are some useful points:

  • Pay attention to the quality of your code (ruff, mypy and type annotations). Our prek-hooks will help you with that.
  • In case of a new feature add useful documentation (in docstrings or in docs/ directory). Adding a new operator? Check this short guide Consider adding an example Dag that shows how users should use it.
  • Consider using Breeze environment for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
  • Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
  • Please follow ASF Code of Conduct for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
  • Be sure to read the Airflow Coding style.
  • Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
    Apache Airflow is a community-driven project and together we are making it better 🚀.
    In case of doubts contact the developers at:
    Mailing List: [email protected]
    Slack: https://s.apache.org/airflow-slack

@jni-bot
jni-bot force-pushed the fix-tasks-clear-regex branch from e68ed8b to b1638fa Compare May 13, 2026 18:40

@SameerMesiah97 SameerMesiah97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would want a maintainer to weigh in here but it looks fine to me. Just one nit. And CI needs to be triggered.

@jni-bot
jni-bot force-pushed the fix-tasks-clear-regex branch 3 times, most recently from e84a967 to c7d9ab0 Compare May 18, 2026 18:52
@potiuk potiuk added the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label May 19, 2026
@potiuk
potiuk marked this pull request as draft June 18, 2026 13:59
@jni-bot
jni-bot force-pushed the fix-tasks-clear-regex branch from c7d9ab0 to 5b30edd Compare June 19, 2026 03:33
@jni-bot
jni-bot marked this pull request as ready for review June 19, 2026 03:35
@jni-bot
jni-bot requested a review from SameerMesiah97 June 19, 2026 03:36
@SameerMesiah97

Copy link
Copy Markdown
Contributor

@jni-bot

CI still needs to be triggered. I can't sign off on this until it is green.

@potiuk

Could you trigger CI?

@jni-bot

jni-bot commented Jun 19, 2026

Copy link
Copy Markdown
Author

@SameerMesiah97 Thank you, I didn't know who to ask!

The regex branch of `get_dags` ignored `from_db=True` and built a
`BundleDagBag` off disk, returning SDK `DAG` objects. `task_clear` then
calls `SerializedDAG.clear_dags`, which calls `.clear()` on each — a
method that only exists on `SerializedDAG`. Result:

    AttributeError: 'DAG' object has no attribute 'clear'

The non-regex branch was fixed in apache#63827 (closes apache#63817) but the regex
path was left untouched and untested.

This change honors `from_db=True` in the regex branch too, querying
`SerializedDagModel.read_all_dags()` and regex-filtering DAG IDs in
Python. The previous bundle-walking path is preserved for callers that
don't pass `from_db`. Also switches the "not found" raise from the
generic `AirflowException` to `DagNotFound`.

related: apache#63817
@jni-bot
jni-bot force-pushed the fix-tasks-clear-regex branch from 5b30edd to c261fef Compare July 1, 2026 18:47
@jni-bot

jni-bot commented Jul 1, 2026

Copy link
Copy Markdown
Author

@potiuk I rebased since it's been 2 weeks, which unfortunately resets the CI tag

@jni-bot

jni-bot commented Jul 7, 2026

Copy link
Copy Markdown
Author

@potiuk Rebased in the hope that whatever was failing CI (it was a static check complaining about a file I hadn't touched) has been addressed in the interim :)

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for chasing this down — the diagnosis is right: the regex branch was handing back SDK DAG objects while SerializedDAG.clear_dags needs .clear(), and DagNotFound is the correct exception to raise here rather than AirflowException.

One blocking issue though: the new branch drops the bundle_names filter entirely, which for a destructive command like tasks clear widens the blast radius silently. Details inline, plus a note on loading every serialized Dag into memory and one on the test assertions.


Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting

return [get_db_dag(bundle_names=bundle_names, dag_id=dag_id)]
return [get_bagged_dag(bundle_names=bundle_names, dag_id=dag_id)]

if from_db:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This branch returns before bundle_names is ever consulted, so --bundle-name is silently ignored on the regex path.

Both other paths honour it: the non-regex from_db branch passes it to get_db_dag(bundle_names=..., dag_id=...), and the existing regex branch below iterates bundle_names first and only falls back to all bundles when nothing matched. As written, airflow tasks clear --bundle-name X -R <pattern> would clear matching Dags from every bundle — a silent widening on a destructive command.

Please filter by bundle here too, mirroring the fallback behaviour of the branch below.


Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting


matched_dags = [
dag
for dag_id_key, dag in SerializedDagModel.read_all_dags().items()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

read_all_dags() deserializes every Dag in the deployment to then regex-filter them in Python. On a large instance that is a lot of memory and CPU for a CLI call that usually matches a handful of Dags.

Since the filter is a plain re.search against dag_id, this could be pushed into SQL — or at minimum select the ids first and only deserialize the matches.


Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting

dags = get_dags(bundle_names=None, dag_id="example_python_operator", use_regex=True, from_db=True)
assert dags
for dag in dags:
assert hasattr(dag, "clear"), f"{type(dag).__name__} is missing .clear()"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hasattr(dag, "clear") is a weak assertion — it passes for anything that happens to expose a clear attribute, including a plain dict. Since the whole point is the concrete type, assert isinstance(dag, SerializedDAG) states the actual contract.

Separately, test_task_clear_dag_regex_does_not_attribute_error below runs a real tasks clear -y against example_python_operator — worth confirming it's covered by the DB-test markers so it isn't mutating state shared with other tests.


Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed in 5 days if no further activity occurs. Thank you for your contributions.

@github-actions github-actions Bot added the stale Stale PRs per the .github/workflows/stale.yml policy file label Oct 28, 2026
@github-actions github-actions Bot closed this Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:CLI ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. stale Stale PRs per the .github/workflows/stale.yml policy file

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Not able to clear a task instance using CLI command

3 participants