wayblink opened a new issue, #77360:
URL: https://github.com/apache/airflow/issues/77360

   ### Summary
   
   Upgrading an existing metadata DB to 3.4.0 fails inside the task-attempt 
ownership migration
   (`0142_3_4_0_unify_task_attempt_ownership`, revision `e7c2a91bd540`) 
whenever a task had **more than one attempt before the upgrade**. The history 
rows are re-inserted into `task_instance` with a conflict target that cannot 
cover the primary key, so the second row for the same task raises 
`UniqueViolation` on `task_instance_pkey`. The upgrade is then blocked — 3.4.0 
does not start because the DB head never reaches `b4f1a7d2c903`.
   
   ### Environment
   
   - Apache Airflow **3.4.0** (upgrading from 3.3.1)
   - PostgreSQL **16.15**
   - Metadata DB with regular DAG history (tasks that were retried at least 
once)
   
   ### Steps to reproduce
   
   1. Run 3.3.x long enough that at least one task instance is retried, so 
`task_instance_history` holds more than one row for the same task (this is the 
normal state of any non-trivial deployment — retries are on by default for 
transient failures).
   2. Upgrade to 3.4.0 and let the migration run (`airflow db migrate`, or the 
chart's migration job).
   
   ### Actual behaviour
   
   ```
   sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate 
key value violates unique constraint "task_instance_pkey"
   DETAIL:  Key (id)=(01a1c931-0954-70c1-8c16-dc2c4052473f) already exists.
   
   [SQL: INSERT INTO task_instance (id, task_id, dag_id, run_id, map_index, 
try_number, ...)
         SELECT task_instance_history.task_instance_id, 
task_instance_history.task_id, ...
         FROM task_instance_history LEFT OUTER JOIN dag_version ON ...
         ON CONFLICT ON CONSTRAINT task_instance_try_key DO NOTHING]
   ```
   
   ### Expected behaviour
   
   The migration completes: rows that already exist as live `task_instance` 
rows are skipped and the upgrade proceeds.
   
   ### Root cause
   
   The insert is built as:
   
   ```python
   # 
airflow-core/src/airflow/migrations/versions/0142_3_4_0_unify_task_attempt_ownership.py
   if dialect == "postgresql":
       insert = (
           postgresql.insert(ti)
           .from_select(columns, history_rows)
           .on_conflict_do_nothing(constraint="task_instance_try_key")
       )
   ```
   
   Two facts collide here:
   
   1. In 3.3.x every attempt of a task shares one `task_instance` row, hence 
one `id`; `TaskInstanceHistory.record_ti()` stores that id in 
`task_instance_history.task_instance_id` for **every** archived attempt 
(`airflow-core/src/airflow/models/taskinstancehistory.py`). So N attempts of 
one task produce N history rows with the *same* `task_instance_id`.
   2. The migration copies `task_instance_history.task_instance_id` into 
`task_instance.id`, which is the **primary key**, while `ON CONFLICT` is scoped 
to `task_instance_try_key` (`dag_id, task_id, run_id, map_index, try_number` — 
i.e. *without* `id`).
   
   The first history row of a task either inserts cleanly or conflicts on 
`task_instance_try_key` (and is skipped). Every subsequent row of that same 
task conflicts on `task_instance_pkey`, which is not a conflict target of this 
statement, so PostgreSQL raises instead of skipping.
   
   Note the MySQL branch does not have this problem, because it pre-filters 
rows that already exist:
   
   ```python
   if dialect == "mysql":
       history_rows = history_rows.where(
           ~sa.select(1).select_from(existing)
           .where(*(existing.c[c] == history.c[c] for c in (*_COORDINATES, 
"try_number")))
           .exists()
       )
   ```
   
   It is only the PostgreSQL branch that relies on the conflict target to do 
that filtering.
   
   ### Suggested fix
   
   Drop the conflict target for the PostgreSQL branch so that any unique 
violation is skipped, which is the intended semantics ("insert the row unless 
it is already there"):
   
   ```python
   insert = (
       postgresql.insert(ti)
       .from_select(columns, history_rows)
       .on_conflict_do_nothing()
   )
   ```
   
   (Alternatively, apply the same pre-filter the MySQL branch uses.) I verified 
locally that with the target removed the migration completes on a 3.3.1 
database that has retried tasks, and that the resulting `task_instance` rows 
are consistent with what the migration produces on a retry-free database.
   
   ### Additional context
   
   - A silently truncated alternative would be worse than failing: dropping the 
retried attempts is acceptable for the *rows that already exist live*, but the 
migration currently cannot proceed at all.
   - We did not find an existing report of this. Related work: #74222 (retried 
attempts under the attempt UUID) and #74407 (downgrading past this migration) 
touch the same area but not this conflict handling.
   - If useful, I can open a PR with the one-line change plus a regression test 
— a test would need a fixture DB whose `task_instance_history` holds two rows 
with the same `task_instance_id` and different `try_number`, which mirrors any 
deployment that retried a task.
   
   ---
   Drafted-by: pi coding agent (DeepSeek v4.1) (no human review before posting)
   


-- 
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]

Reply via email to