Repository navigation
Fix airflow db clean IntegrityError when a dag_version is referenced by a task_instance - #66350
Conversation
|
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
|
6447ea9 to
3f2d216
Compare
3f2d216 to
b2bf70b
Compare
Vamsi-klu
left a comment
There was a problem hiding this comment.
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_dictand asserts eachdag_id_column_nameis 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_namemeans--dag-ids/--exclude-dag-idsnow silently ignores the filter fordeadlineandtask_reschedule(they get cleaned across all dags by timestamp), since_build_querygates ondag_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.
b2bf70b to
4141407
Compare
|
@Vamsi-klu added tests and addressed your 2nd point in the PR body. |
|
@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 #71732 fixes that part properly. It adds Your PR also has two things #71732 doesn't, so combining them together beats either one alone. Re-applying So the actual request: Could you cherry-pick @Arose26's changes into this PR, and give co-author credit in the commit message? Please bring their newsfragment across as well, and add |
ferruzzi
left a comment
There was a problem hiding this comment.
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.
bcae162 to
213dbe2
Compare
Consolidated. |
ferruzzi
left a comment
There was a problem hiding this comment.
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.
daf8760 to
6df7461
Compare
|
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. |
|
The newsfragment test failing is expected, the others look legit. Can you have a look when you get time? |
ferruzzi
left a comment
There was a problem hiding this comment.
Retracting my change request. Thanks for getting that so quick
3d0b37a to
7028b57
Compare
|
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.
Keep 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. |
|
@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. |
3d1a0db to
aa33a41
Compare
ramitkataria
left a comment
There was a problem hiding this comment.
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
… 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]>
aa33a41 to
fef5bea
Compare
|
Awesome work, congrats on your first merged pull request! You are invited to check our Issue Tracker for additional contributions. |
|
#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 👍 |
|
@vatsrahul1001 - any chance we can get this one backported as well? Sorry I didn't have the label on it |
|
Thanks @ferruzzi for your assistance on this one. Happy it got merged! |
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.
airflow db cleanfails onasset_event,deadlineandtask_reschedulewhenever--dag-idsor--exclude-dag-idsis passed, while the same command without a dag filter succeeds:Cause
All three are configured with
dag_id_column_name="dag_id", and none of them has adag_idcolumn:asset_eventsource_dag_idtask_rescheduleti_id→task_instance.iddeadlinedagrun_id→dag_run.id_build_queryonly readsdag_id_columnwhen a dag filter is requested, which is why the failure appears solely with those two flags.Fix
asset_eventfilters onsource_dag_id.task_rescheduleanddeadlinehave no dag id of their own, so_TableConfiggainsdag_id_via=(fk_column, parent_table, parent_pk_column)and filters through the parent'sdag_idvia a correlatedEXISTSsubquery — matching theskip_if_referencedguard already in the same function.EXISTSrather thanIN/NOT INbecausedeadline.dagrun_idis nullable: a deadline with no dag run belongs to no dag, so it is kept under--dag-idsand removed under--exclude-dag-ids; withNOT IN, the NULL would swallow the comparison and the row would survive a filter that does not name it.Setting both
dag_id_column_nameanddag_id_viaraises rather than silently ANDing two filters.Dry-run output prints the resolved path (
ti_id -> task_instance.dag_id) instead ofNone.Also fixes a race between the archive INSERT and DELETE by re-applying
skip_if_referencedon the DELETE.Tests
--dag-idsand--exclude-dag-ids— reproduces the reportedRuntimeErrorverbatim.task_rescheduleandasset_event, cleaned with--dag-ids dag1: onlydag2's rows survive. Parametrized to also run withtask_instanceanddag_runin the table list, covering the cascade path as well as the child's own filter.test_dag_id_column_name_matches_schemaregression test ensuring alldag_id_column_nameentries match the actual schema._TableConfigguard rejecting both filter styles at once.Was generative AI tooling used to co-author this PR?
Generated-by: Claude Code (claude-sonnet-4-6) following the guidelines