kaxil commented on code in PR #74222:
URL: https://github.com/apache/airflow/pull/74222#discussion_r4182783987


##########
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:
+            batch.drop_constraint("task_instance_history_ti_fkey", 
type_="foreignkey")
+        with op.batch_alter_table("task_instance") as batch:
+            batch.add_column(sa.Column("working_set", sa.Boolean(), 
nullable=True, server_default=sa.true()))
+            batch.add_column(sa.Column("archived_reason", sa.String(50), 
nullable=True))
+            batch.drop_constraint("task_instance_composite_key", 
type_="unique")
+            batch.create_unique_constraint("task_instance_current_key", 
[*_COORDINATES, "working_set"])
+            batch.create_unique_constraint("task_instance_try_key", 
[*_COORDINATES, "try_number"])
+            batch.create_check_constraint(
+                "ti_working_set_true_or_null", "working_set IS NULL OR 
working_set = TRUE"
+            )
+        ti = sa.table(
+            "task_instance",
+            sa.column("id"),
+            *(sa.column(c) for c in _COPY_COLUMNS),
+            sa.column("working_set"),
+            sa.column("archived_reason"),
+            sa.column("dag_version_id"),
+        )
+        history = sa.table(
+            "task_instance_history",
+            sa.column("task_instance_id"),
+            *(sa.column(c) for c in _COPY_COLUMNS),
+            sa.column("dag_version_id"),
+        )
+        historical_max_tries = sa.func.coalesce(
+            history.c.max_tries,
+            sa.case((history.c.try_number > 0, history.c.try_number - 1), 
else_=0),
+        )
+        version = sa.table("dag_version", sa.column("id"))
+        history_rows = sa.select(
+            history.c.task_instance_id,
+            *(historical_max_tries if c == "max_tries" else history.c[c] for c 
in _COPY_COLUMNS),
+            sa.null(),
+            sa.literal("legacy"),
+            version.c.id,
+        ).select_from(history.outerjoin(version, history.c.dag_version_id == 
version.c.id))
+        dialect = op.get_bind().dialect.name
+        if dialect == "mysql":
+            existing = ti.alias("existing")
+            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()
+            )
+        columns = [
+            "id",
+            *_COPY_COLUMNS,
+            "working_set",
+            "archived_reason",
+            "dag_version_id",
+        ]
+        if dialect == "postgresql":
+            insert = (
+                postgresql.insert(ti)
+                .from_select(columns, history_rows)
+                .on_conflict_do_nothing(constraint="task_instance_try_key")

Review Comment:
   In 3.3, `clear_task_instances` writes try N to history but leaves the live 
row at try N (only `schedule_tis` bumps it). If that cleared TI then finishes 
without being scheduled (upstream fails again so it goes `upstream_failed`, a 
manual mark, or `removed`), the live row and the history row share try N, and 
0138 only bumps `up_for_retry` / `state IS NULL` rows. This `ON CONFLICT DO 
NOTHING` (and the MySQL `NOT EXISTS` above) then keeps the live row and drops 
the history row, which is the attempt that actually ran, along with its 
`hitl_detail_history`. Could the live row's `try_number` be bumped first when a 
same-try history row exists? 
`test_upgrade_discards_only_history_conflicting_with_live_try` covers the 
opposite shape (a running live row against a stale history row).



##########
airflow-core/src/airflow/api_fastapi/execution_api/security.py:
##########
@@ -205,9 +222,62 @@ async def require_auth(
                 detail="Token subject does not match callback ID",
             )
 
+    if (
+        request.method not in {"GET", "HEAD", "OPTIONS"}
+        and token_scope != "callback"
+        and "connection_test_id" not in request.path_params
+        and not request.scope.get(_IN_PROCESS_NON_TI_CALLER)
+        and not request.scope.get(_REQUEST_SCOPE_LIVE_ATTEMPT_KEY)
+        and not getattr(route, _SKIP_AUTO_TI_ATTEMPT_LIVE, False)
+    ):
+        # The versions package imports routes, which depend on this module.
+        from airflow.api_fastapi.execution_api.versions.v2026_10_30 import 
IdentifyRetiredTaskStateUpdates
+
+        await _require_live_attempt(
+            token,
+            allow_callback="task_instance_id" not in request.path_params,
+            identify_retired=IdentifyRetiredTaskStateUpdates.is_applied,

Review Comment:
   This check runs for every API version, so a task-sdk 1.3.x worker 
(`2026-06-30`) now gets 404 from `PUT /rtif` after it sends `RetryTask`. 3.3.2 
answered that with 410 for all clients, and the 1.3.2 supervisor only swallows 
410 there, so every retry of a task with `overwrite_rtif_after_execution` now 
logs an error. The extra-link XCom pushes in `finalize()` also run after 
`RetryTask` and now 404 where 3.3.2 accepted them. Should older clients keep 
getting 410 for RTIF, or skip the automatic check when 
`IdentifyRetiredTaskStateUpdates` isn't applied? The "preserving 404 for older 
clients" docstring in `v2026_10_30.py` doesn't match what 3.3 returned.



##########
airflow-core/src/airflow/utils/db_cleanup.py:
##########
@@ -831,6 +970,15 @@ def _get_archived_table_names(table_names: list[str] | 
None, session: Session) -
     inspector = inspect(session.bind)
     _, effective_config_dict = _effective_table_names(table_names=table_names)
     schemas = {config.schema_name for config in effective_config_dict.values()}
+    archive_sources = {config.bare_table_name for config in 
effective_config_dict.values()}
+    if "xcom_v2" in archive_sources:
+        archive_sources.add("xcom_v1")
+    if "xcom_v1" in archive_sources or "xcom_v2" in archive_sources:
+        archive_sources.add("xcom")
+    if "task_instance_history" in effective_config_dict or "task_instance" in 
archive_sources:
+        archive_sources.add("task_instance_history")
+    if archive_sources & {"task_instance", "dag_run"}:

Review Comment:
   With `--tables task_instance_history`, `_HISTORY_CONFIG` has 
`bare_table_name == "task_instance"`, so this branch adds every 
`_ATTEMPT_ARCHIVE_TABLES` name. `db drop-archived --tables 
task_instance_history` then also drops the `task_instance`, `xcom_v2`, 
`rtif_v2`, note and HITL archives, not just the old history archives the docs 
describe. A 3.3 script that only pruned history archives would lose the other 
recovery copies.



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_instances.py:
##########
@@ -983,7 +996,7 @@ def _collect_relatives(run_id: str, direction: 
Literal["upstream", "downstream"]
 
     if not dry_run:
         try:
-            clear_task_instances(
+            task_instances = clear_task_instances(

Review Comment:
   This now returns successors for most TIs, but for a RUNNING TI it returns 
the same attempt in RESTARTING, so the note patched below lands on that UUID. 
`complete_restart` then calls `prepare_db_for_next_try`, which creates the 
successor without copying `task_instance_note`, so the note drops out of the TI 
view once the restart finishes (`TaskInstanceHistoryResponse` has no `note` 
either). Non-running TIs in the same request do get it on their successor.



##########
airflow-core/src/airflow/models/taskinstance.py:
##########
@@ -2018,6 +2140,7 @@ def handle_failure(
 
         if not test_mode:
             TaskInstance.save_to_db(ti, session=session)
+        return ti

Review Comment:
   The `_log_state(task_instance=self)` just above runs after 
`fetch_handle_failure_context`, and on a retry `retire()` has already moved 
`self` to FAILED, so it logs "Marking task as FAILED" for every retry. Should 
it log the returned `ti` instead?



##########
airflow-core/src/airflow/providers_manager.py:
##########
@@ -52,6 +57,33 @@
     "apache-airflow-providers-celery": "2.1.0",
 }
 
+BLOCKED_PROVIDER_MIN_VERSIONS = {
+    "apache-airflow-providers-common-ai": "1.0.0",

Review Comment:
   Is 1.0.0 the intended floor? The comment below says the source-install 
exemption can go once a version > 0.10.0 exists, but a fixed 0.11.0 would still 
be skipped and users would be told to install a 1.0.0 that may not exist yet. 
Also, only `plugins/hitl_review.py` touches core models, yet this gate drops 
the whole provider from core discovery (connection types, hooks, `providers 
list`) as well as plugins. Could it be scoped to the plugin?



##########
providers/common/io/tests/unit/common/io/xcom/test_backend.py:
##########
@@ -300,20 +332,31 @@ def test_clear(self, task_instance, session, 
mock_supervisor_comms):
 
         if AIRFLOW_V_3_0_PLUS:
             mock_supervisor_comms.send.return_value = 
XComResult(key=XCOM_RETURN_KEY, value=path)
+            delete_kwargs = {"task_instance_id": task_instance.id} if 
AIRFLOW_V_3_4_PLUS else {}

Review Comment:
   `BaseXCom.delete` doesn't take `task_instance_id`, so on 3.4 this raises 
`TypeError` (it's the `test_clear` failure in the provider DB jobs).



##########
providers/common/ai/tests/unit/common/ai/plugins/test_hitl_review.py:
##########
@@ -612,6 +622,27 @@ def test_writes_and_reads_back_combinations(self, session, 
dag_maker, value, exp
             session, dag_id="d", run_id="r", task_id="t", map_index=-1, 
key=XCOM_AGENT_SESSION
         )
         assert result == expected
+
+    @pytest.mark.skipif(not AIRFLOW_V_3_4_PLUS, reason="Attempt ownership 
starts in Airflow 3.4")
+    def test_write_uses_current_attempt_after_retry(self, session, dag_maker):

Review Comment:
   This was inserted above the previous test's trailing `_clear_db()`, so 
`test_writes_and_reads_back_combinations` no longer cleans up after itself.



##########
airflow-core/src/airflow/models/taskinstance.py:
##########
@@ -639,7 +675,9 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
     duration: Mapped[float | None] = mapped_column(Float, nullable=True)
     state: Mapped[str | None] = mapped_column(String(20), nullable=True)
     try_number: Mapped[int] = mapped_column(Integer, default=0)
-    max_tries: Mapped[int] = mapped_column(Integer, server_default="-1")
+    max_tries: Mapped[int] = mapped_column(Integer, server_default="-1", 
nullable=False)
+    working_set: Mapped[bool | None] = mapped_column(Boolean, default=True, 
server_default=true())

Review Comment:
   `working_set IS TRUE` is now enforced by convention at a lot of call sites, 
and `filter_for_tis` already slipped through. XCom got a single read path plus 
a prek check; would something similar for TI (a current-attempts helper, a 
`with_loader_criteria` default with an explicit opt-out, or a prek check) be 
worth adding here so the next query that forgets it fails loudly instead of 
picking an arbitrary attempt?



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