Skip to content

Fix airflow db clean IntegrityError when a dag_version is referenced by a task_instance - #66350

Merged
ferruzzi merged 6 commits into
apache:mainfrom
jakubmatyszewski:fix_db_cleanup_dag_id
Sep 22, 2026
Merged

ferruzzi merged 6 commits into
apache:mainfrom
jakubmatyszewski:fix_db_cleanup_dag_id

Conversation

@jakubmatyszewski

@jakubmatyszewski jakubmatyszewski commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

airflow db clean fails on asset_event, deadline and task_reschedule whenever --dag-ids or --exclude-dag-ids is passed, while the same command without a dag filter succeeds:

RuntimeError: airflow db clean encountered errors on the following tables and
did not clean them: ['asset_event', 'deadline', 'task_reschedule']

Cause

All three are configured with dag_id_column_name="dag_id", and none of them has a dag_id column:

table actual column
asset_event source_dag_id
task_reschedule ti_id → task_instance.id
deadline dagrun_id → dag_run.id

_build_query only reads dag_id_column when a dag filter is requested, which is why the failure appears solely with those two flags.

Fix

asset_event filters on source_dag_id.

task_reschedule and deadline have no dag id of their own, so _TableConfig gains dag_id_via=(fk_column, parent_table, parent_pk_column) and filters through the parent's dag_id via a correlated EXISTS subquery — matching the skip_if_referenced guard already in the same function.

EXISTS rather than IN / NOT IN because deadline.dagrun_id is nullable: a deadline with no dag run belongs to no dag, so it is kept under --dag-ids and removed under --exclude-dag-ids; with NOT IN, the NULL would swallow the comparison and the row would survive a filter that does not name it.

Setting both dag_id_column_name and dag_id_via raises rather than silently ANDing two filters.

Dry-run output prints the resolved path (ti_id -> task_instance.dag_id) instead of None.

Also fixes a race between the archive INSERT and DELETE by re-applying skip_if_referenced on the DELETE.

Tests

  • Cleanup of the three tables under --dag-ids and --exclude-dag-ids — reproduces the reported RuntimeError verbatim.
  • Rows for two dags in task_reschedule and asset_event, cleaned with --dag-ids dag1: only dag2's rows survive. Parametrized to also run with task_instance and dag_run in the table list, covering the cascade path as well as the child's own filter.
  • test_dag_id_column_name_matches_schema regression test ensuring all dag_id_column_name entries match the actual schema.
  • _TableConfig guard rejecting both filter styles at once.

Was generative AI tooling used to co-author this PR?
  • Yes — Claude Code (claude-sonnet-4-6)

Generated-by: Claude Code (claude-sonnet-4-6) following the guidelines

@boring-cyborg

boring-cyborg Bot commented May 4, 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

@jakubmatyszewski
jakubmatyszewski force-pushed the fix_db_cleanup_dag_id branch from 6447ea9 to 3f2d216 Compare May 5, 2026 19:31
@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 11, 2026
@potiuk
potiuk marked this pull request as draft June 18, 2026 13:58
@jakubmatyszewski
jakubmatyszewski marked this pull request as ready for review June 30, 2026 09:07

@Vamsi-klu Vamsi-klu left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nice catch, and the migration table in the description makes this easy to trust — I confirmed all three against the models at HEAD: AssetEvent has source_dag_id (not dag_id), task_reschedule collapsed to a single ti_id, and deadline only carries dagrun_id. So the rename and the two drops are each correct.

Two small things before LGTM:

  • Could you add a regression test? The cheapest guard is a db_test that iterates config_dict and asserts each dag_id_column_name is an actual reflected column of its table — that fails today for all three and stops this config/schema drift from recurring.
  • Dropping dag_id_column_name means --dag-ids/--exclude-dag-ids now silently ignores the filter for deadline and task_reschedule (they get cleaned across all dags by timestamp), since _build_query gates on dag_id_column is not None. That matches how other dag-less tables (import_error, trigger) already behave, so I think it's fine — just want to confirm it's intentional and worth a note in the PR body.

@jakubmatyszewski

Copy link
Copy Markdown
Contributor Author

@Vamsi-klu added tests and addressed your 2nd point in the PR body.

@ferruzzi ferruzzi added this to the Airflow 3.3.2 milestone Aug 28, 2026
@ferruzzi

ferruzzi commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

@jakubmatyszewski - I think this is half of the fix. #71732 (@Arose26) is the other half and I'd be more comfortable merging them as one PR so they don't somehow get split accidentally if one gets backported without the other or something.

Your asset_event change here is right: source_dag_id is the right column name. My concern is deadline and task_reschedule, where this drops dag_id_column_name altogether. _build_query only applies the filter when the column is present so after this change airflow db clean --dag-ids one_dag stops crashing on those two tables and instead cleans them for every dag. For a destructive command going into 3.3.2, I'd rather not trade a loud failure for a silent delete.

#71732 fixes that part properly. It adds dag_id_via=(fk_column, parent_table, parent_pk_column) and filters through the parent's dag_id. The EXISTS that arose26 put there is worth keeping. deadline.dagrun_id is nullable, and with NOT IN the NULL would swallow the comparison, so a row would survive the filter.

Your PR also has two things #71732 doesn't, so combining them together beats either one alone. Re-applying skip_if_referenced on the DELETE closes the race between the archive INSERT and the DELETE, and test_dag_id_column_name_matches_schema is a great regression test.

So the actual request: Could you cherry-pick @Arose26's changes into this PR, and give co-author credit in the commit message?

Co-authored-by: arose26 <[email protected]>

Please bring their newsfragment across as well, and add closes: #69030, which is the issue #71732 closes. Then we can land one complete fix rather than half of one, close #71732 as folded in, and never have to worry about only half of the fix getting picked up.

@Arose26 and @potiuk - are you both alright with this plan?

@ferruzzi ferruzzi 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.

Requesting changes as a merge guardrail rather than a code objection; see my comment above.

Maintainers: please don't merge this independently. It is half of a fix. It stops airflow db clean --dag-ids crashing on deadline and task_reschedule by dropping their dag_id_column_name, and because _build_query only applies the filter when that column is present, those two tables would then be cleaned for every dag rather than the ones named. #71732 supplies the missing half via dag_id_via and should land in the same PR.

I'll clear this as soon as the two are consolidated.

@jakubmatyszewski

Copy link
Copy Markdown
Contributor Author

Requesting changes as a merge guardrail rather than a code objection; see my comment above.

Maintainers: please don't merge this independently. It is half of a fix. It stops airflow db clean --dag-ids crashing on deadline and task_reschedule by dropping their dag_id_column_name, and because _build_query only applies the filter when that column is present, those two tables would then be cleaned for every dag rather than the ones named. #71732 supplies the missing half via dag_id_via and should land in the same PR.

I'll clear this as soon as the two are consolidated.

Consolidated.

@ferruzzi ferruzzi 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.

Thanks for doing that so quick! Just need to update the file name on the newsfragment to refer to your PR number and we can merge it.

@ferruzzi ferruzzi added the skip newsfragment check Skip the newsfragment PR number check label Sep 10, 2026
@ferruzzi

ferruzzi commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Added the "skip newsfragments" tag so arose26's fragment gets retained. It'll point to the old PR, but that one redirect back here so nothing is lost and both fixes get their release note.

EDIT: It doesn't seem to be working, that check is still running and failing... it looks like "re-run jobs" triggers the same batch as before, so it won't start skipping that test now that it has run.

@ferruzzi

Copy link
Copy Markdown
Contributor

The newsfragment test failing is expected, the others look legit. Can you have a look when you get time?

@ferruzzi ferruzzi 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.

Retracting my change request. Thanks for getting that so quick

@ferruzzi
ferruzzi dismissed their stale review September 11, 2026 23:38

Addressed

@Vamsi-klu Vamsi-klu left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

​

@jakubmatyszewski
jakubmatyszewski force-pushed the fix_db_cleanup_dag_id branch 2 times, most recently from 3d0b37a to 7028b57 Compare September 16, 2026 08:07
@ferruzzi

ferruzzi commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Jakub, you've been great about working with my change requests and this is a bit frustrating, but #73173 merged a couple of hours ago and it fixes the same three tables this PR does. It came in from the #70923 angle and they didn't see this existing work. I've left a message over there pointing it out, but it's already merged.

The DELETE race fix is still a real bug that #73173 doesn't touch, so yours is still the only fix for it. If you are still up for getting this merged, here's the last list. Four mechanical bits and two actual code changes.

  1. Drop dag_id_via, the three _TableConfig entries, and 71732.bugfix.rst. (( I know, that's the code from arose26 I asked you to pull into this one in the first place.))
  2. Remove closes: #69030 from your description
  3. Change the PR title to reflect the new scope, something like "Fix airflow db clean IntegrityError when a dag_version is referenced by a task_instance" since that's pretty close to your original commit message and that's what you'll have left.
  4. Rebase on main.

Keep 66350.bugfix.rst, your _do_delete changes, and test_dag_id_column_name_matches_schema. Kaxil's test parametrizes filter combinations and yours reads the schema directly, so both are worth having. Also keep the two lines in _cleanup_table that pass skip_if_referenced and referenced_pk_column through to _do_delete.

It should rebase pretty cleanly after that. Then two actual code changes.

And honestly, if you've had enough after four months of this, say so. I'll cherry-pick your work over and get it over the line with your author credit intact. I'm sorry that this was your first introduction to the project, it's been a rough one.

EDIT: Broke the wall of text into a couple of smaller comments.

@kaxil

kaxil commented Sep 17, 2026

Copy link
Copy Markdown
Member

@jakubmatyszewski Apologies Jakub, I didn't see this PR. As Dennis pointed out this work is still important and catches one thing that isn't yet merged, so please rebase on main.

@ramitkataria ramitkataria 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.

Thanks for working through all the changes! I noticed some things after the rebase. Also I would suggest updating the PR title and body with the updated state of the PR

@ferruzzi ferruzzi changed the title Fix airflow db clean --dag-ids crashing with UndefinedColumn on deadline, task_reschedule, and asset_event Fix airflow db clean IntegrityError when a dag_version is referenced by a task_instance Sep 19, 2026
jakubmatyszewski and others added 6 commits September 21, 2026 10:23
… by task_instance

The ON DELETE RESTRICT FK from task_instance.dag_version_id means that a
dag_version row cannot be deleted while any task instance still references it.
The skip_if_referenced filter in _build_query correctly excluded such rows from
the archive (SELECT) step, but _do_delete issued the DELETE using only a PK
join against the archive table — with no re-check of the FK constraint.

In production Airflow (running while db clean executes) a new task_instance can
be created referencing a dag_version between the archive INSERT commit and the
DELETE, causing a psycopg2 ForeignKeyViolation (IntegrityError) and aborting
the cleanup command.

Re-apply the same NOT EXISTS guard on the DELETE WHERE clause so rows that have
become referenced since the archive was created are silently skipped instead of
failing the FK.

Also add:
- test_do_delete_skip_if_referenced_guards_against_race: directly exercises the
  _do_delete FK guard by inserting a TI after the archive is created.
- test_dag_id_column_name_matches_schema: regression guard that reflects every
  configured table and asserts dag_id_column_name is an actual DB column,
  addressing reviewer feedback requesting protection against config/schema drift.
asset_event, task_reschedule and deadline were configured to filter on a
dag_id column that none of them has, so passing --dag-ids or
--exclude-dag-ids made the cleanup fail on exactly those tables while the
same command without a dag filter succeeded.
The regression test called _do_delete with a raw select(archive_table),
bypassing the NOT EXISTS guard that _build_query embeds in every SELECT.
That made continue on deleted == 0 loop forever: the unguarded SELECT
kept counting the archive row even though the DELETE kept refusing it.

Rewrite the test to build the query via _build_query, as _cleanup_table
does. The TI reference then keeps the SELECT count at zero from the start
so the loop exits without issuing any DELETE, which is the correct
invariant: referenced rows are excluded by the SELECT, not just the DELETE.
When skip_if_referenced causes the DELETE to skip rows, log a warning
so users can tell their dag_version rows were left behind due to live
task_instance references, rather than silently continuing.

The race regression test was not actually reproducing the race: it
inserted the TI before building the query, so the NOT EXISTS guard in
the SELECT returned zero rows immediately and _do_delete never reached
the DELETE at all.  Rewrite the test using a patched reflect_tables to
inject the TI in the exact window between the archive CTAS commit and
the DELETE, which is the real race scenario.  Add a ``raced`` sentinel
so the test fails fast if the injection point ever moves rather than
passing without testing anything.  Also add a second DagVersion so
raced_old is actually eligible for deletion (dag_version is keep_last
per dag_id, so a lone version is always the survivor).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@ferruzzi ferruzzi removed the skip newsfragment check Skip the newsfragment PR number check label Sep 21, 2026
@ferruzzi
ferruzzi dismissed stale reviews from Vamsi-klu September 21, 2026 20:18

AI spam

@ferruzzi
ferruzzi merged commit b68ea78 into apache:main Sep 22, 2026
155 checks passed
@boring-cyborg

boring-cyborg Bot commented Sep 22, 2026

Copy link
Copy Markdown

Awesome work, congrats on your first merged pull request! You are invited to check our Issue Tracker for additional contributions.

@ferruzzi

ferruzzi commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

#rookie_protm #protm candidate here. That was a long slog to get merged with a bunch of rewrites which were not at all the author's fault. 10/10 new contributor 👍

@ferruzzi

Copy link
Copy Markdown
Contributor

@vatsrahul1001 - any chance we can get this one backported as well? Sorry I didn't have the label on it

@jakubmatyszewski

Copy link
Copy Markdown
Contributor Author

Thanks @ferruzzi for your assistance on this one. Happy it got merged!

vincbeck pushed a commit that referenced this pull request Oct 5, 2026
The guarded DELETE added in #66350 logged a warning only when ``deleted == 0``, which fires when an entire batch is skipped by the skip_if_referenced guard.  The partial case is both the likely one and the harmful one: the archive has already committed a copy of every row the SELECT found, so a row the guard skips is archived and still live, and export-archived will emit a phantom copy of it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants