ashb commented on code in PR #74222: URL: https://github.com/apache/airflow/pull/74222#discussion_r4193850194
########## airflow-core/src/airflow/migrations/versions/0142_3_4_0_unify_task_attempt_ownership.py: ########## @@ -0,0 +1,462 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Unify task attempt ownership without rewriting legacy XCom data. + +Revision ID: e7c2a91bd540 +Revises: 90e4d18ccadf +Create Date: 2026-09-29 12:00:00.000000 +""" + +from __future__ import annotations + +from contextlib import contextmanager + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import postgresql, sqlite + +from airflow.migrations.db_types import TIMESTAMP, StringID +from airflow.utils.sqlalchemy import ExecutorConfigType, ExtendedJSON, UtcDateTime + +revision = "e7c2a91bd540" +down_revision = "90e4d18ccadf" +branch_labels = None +depends_on = None +airflow_version = "3.4.0" + +_COORDINATES = ("dag_id", "task_id", "run_id", "map_index") +_LEGACY = ( + ("xcom", "xcom_v1", "xcom_task_instance_fkey", None), + ("rendered_task_instance_fields", "rtif_v1", "rtif_ti_fkey", None), +) +_COPY_COLUMNS = ( + "task_id", + "dag_id", + "run_id", + "map_index", + "try_number", + "start_date", + "end_date", + "duration", + "state", + "max_tries", + "hostname", + "unixname", + "pool", + "pool_slots", + "queue", + "priority_weight", + "operator", + "custom_operator_name", + "queued_dttm", + "scheduled_dttm", + "queued_by_job_id", + "pid", + "executor", + "executor_config", + "updated_at", + "rendered_map_index", + "context_carrier", + "external_executor_id", + "trigger_timeout", + "next_method", + "next_kwargs", + "task_display_name", + "retry_delay_override", + "retry_reason", +) +_HITL_COLUMNS = ( + "options", + "subject", + "body", + "defaults", + "multiple", + "params", + "assignees", + "created_at", + "responded_at", + "responded_by", + "chosen_options", + "params_input", +) + + +# Unlike disable_sqlite_fkeys, a failed SQLite upgrade rolls back atomically and foreign_keys is always restored. +@contextmanager +def _sqlite_rebuilds(): + if op.get_bind().dialect.name != "sqlite": + yield + return + if op.get_context().as_sql: + raise RuntimeError("SQLite offline SQL cannot render this migration's table rebuilds") + enabled = op.get_bind().exec_driver_sql("PRAGMA foreign_keys").scalar() + with op.get_context().autocommit_block(): + op.execute("PRAGMA foreign_keys=OFF") + try: + with op.get_bind().begin_nested(): + yield + finally: + with op.get_context().autocommit_block(): + op.execute(f"PRAGMA foreign_keys={int(enabled)}") + + +def _check_source(): + bind = op.get_bind() + if op.get_context().as_sql: + return + inspector = sa.inspect(bind) + for table, _, name, onupdate in ( + *_LEGACY, + ( + "task_instance_history", + None, + "task_instance_history_ti_fkey", + "CASCADE", + ), + ): + constraints = inspector.get_foreign_keys(table) + fk = next((fk for fk in constraints if fk["name"] == name), None) + if ( + fk is None + or fk["referred_table"] != "task_instance" + or fk["constrained_columns"] != list(_COORDINATES) + or fk["referred_columns"] != list(_COORDINATES) + or fk["options"].get("ondelete") != "CASCADE" + or fk["options"].get("onupdate") != onupdate + ): + raise RuntimeError(f"Unsupported attempt ownership source schema: {table}.{name}") + if bind.dialect.name == "postgresql": + validated = bind.scalar( + sa.text( + "SELECT convalidated FROM pg_constraint WHERE conrelid=to_regclass(:table) AND conname=:name" + ), + {"table": table, "name": name}, + ) + if not validated: + raise RuntimeError(f"Attempt ownership requires a validated source FK: {table}.{name}") + + +def _redirect_legacy(table, constraint, target, *, onupdate=None, not_valid=False): + if op.get_bind().dialect.name == "mysql": + quote = op.get_bind().dialect.identifier_preparer.quote + columns = ", ".join(quote(column) for column in _COORDINATES) + onupdate_sql = f" ON UPDATE {onupdate}" if onupdate else "" + op.execute("SET @ti141_foreign_key_checks = @@SESSION.foreign_key_checks") + op.execute("SET SESSION foreign_key_checks = 0") + try: + op.execute( + f"ALTER TABLE {quote(table)} DROP FOREIGN KEY {quote(constraint)}, " + "ALGORITHM=INPLACE, LOCK=NONE" + ) + op.execute( + f"ALTER TABLE {quote(table)} ADD CONSTRAINT {quote(constraint)} FOREIGN KEY ({columns}) " + f"REFERENCES {quote(target)} ({columns}) ON DELETE CASCADE{onupdate_sql}, " + "ALGORITHM=INPLACE, LOCK=NONE" + ) + finally: + op.execute("SET SESSION foreign_key_checks = @ti141_foreign_key_checks") + return + with op.batch_alter_table(table) as batch: + batch.drop_constraint(constraint, type_="foreignkey") + batch.create_foreign_key( + constraint, + target, + list(_COORDINATES), + list(_COORDINATES), + ondelete="CASCADE", + onupdate=onupdate, + postgresql_not_valid=not_valid, + ) + + +def upgrade(): + """Retain attempts and give legacy and new task data immutable UUID owners.""" + _check_source() + with _sqlite_rebuilds(): + owner = op.create_table( + "legacy_task_data_owner", + sa.Column("dag_id", StringID(), nullable=False), + sa.Column("task_id", StringID(), nullable=False), + sa.Column("run_id", StringID(), nullable=False), + sa.Column("map_index", sa.Integer(), nullable=False), + sa.Column("task_instance_id", sa.Uuid(), nullable=False), + sa.PrimaryKeyConstraint(*_COORDINATES, name="legacy_task_data_owner_pkey"), + sa.ForeignKeyConstraint( + ["task_instance_id"], + ["task_instance.id"], + name="legacy_task_data_owner_ti_fkey", + ondelete="CASCADE", + ), + ) + op.create_index("idx_legacy_task_data_owner_ti", "legacy_task_data_owner", ["task_instance_id"]) + op.add_column("log", sa.Column("task_instance_id", sa.Uuid(), nullable=True)) + source = sa.table("task_instance", sa.column("id"), *(sa.column(c) for c in _COORDINATES)) + op.execute( + owner.insert().from_select( + [*_COORDINATES, "task_instance_id"], + sa.select(*(source.c[c] for c in _COORDINATES), source.c.id), + ) + ) + for old_name, name, constraint, _ in _LEGACY: + op.rename_table(old_name, name) + # Validated source FKs plus the complete owner copy prove existing child ownership. + _redirect_legacy( + name, + constraint, + "legacy_task_data_owner", + not_valid=op.get_bind().dialect.name == "postgresql", + ) + with op.batch_alter_table("task_instance_history") as batch: Review Comment: Given we would allow at most a single row with a value of False (any more would hit uniq constraint), and by convention we search for `working_set = true` anyway (so false or null is fine as far as data query patterns are, even if it doesn't actually work for uniq constraint reasons) , I think I'm leaning towards removing the CHECK for all DBs, it doesn't seem worth while here. -- 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]
