You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by as...@apache.org on 2026/10/05 07:32:48 UTC
(airflow) 01/01: Keep retired task attempts and their data under the attempt UUID
This is an automated email from the ASF dual-hosted git repository.
ashb pushed a commit to branch store-historic-ti-ownership-data
in repository https://gitbox.apache.org/repos/asf/airflow.git
commit 30853155b7f1b490f8e415054bf7964d9fa3b4de
Author: Ash Berlin-Taylor <as...@apache.org>
AuthorDate: Sat Oct 3 10:23:19 2026 +0100
Keep retired task attempts and their data under the attempt UUID
---
.pre-commit-config.yaml | 7 +
airflow-core/.pre-commit-config.yaml | 10 -
airflow-core/docs/howto/usage-cli.rst | 10 +-
airflow-core/docs/migrations-ref.rst | 5 +-
airflow-core/src/airflow/api/common/delete_dag.py | 13 +-
airflow-core/src/airflow/api/common/mark_tasks.py | 3 +
.../src/airflow/api_fastapi/common/db/dag_runs.py | 33 +-
.../api_fastapi/common/db/task_instances.py | 35 +-
.../airflow/api_fastapi/common/parameters/misc.py | 1 +
.../airflow/api_fastapi/common/parameters/sort.py | 3 +-
.../core_api/routes/public/extra_links.py | 28 +-
.../api_fastapi/core_api/routes/public/hitl.py | 61 +-
.../api_fastapi/core_api/routes/public/log.py | 16 -
.../core_api/routes/public/task_instances.py | 130 ++--
.../core_api/routes/public/task_state_store.py | 1 +
.../api_fastapi/core_api/routes/public/xcom.py | 166 +++---
.../airflow/api_fastapi/core_api/routes/ui/dags.py | 5 +-
.../api_fastapi/core_api/routes/ui/dashboard.py | 2 +-
.../api_fastapi/core_api/routes/ui/gantt.py | 23 +-
.../airflow/api_fastapi/core_api/routes/ui/grid.py | 8 +-
.../src/airflow/api_fastapi/core_api/security.py | 6 +-
.../core_api/services/public/dag_run.py | 25 +-
.../core_api/services/public/task_instances.py | 30 +-
.../src/airflow/api_fastapi/execution_api/app.py | 11 +-
.../execution_api/routes/task_instances.py | 122 ++--
.../api_fastapi/execution_api/routes/xcoms.py | 146 +++--
.../airflow/api_fastapi/execution_api/security.py | 78 ++-
.../execution_api/versions/v2026_10_30.py | 2 +-
.../src/airflow/cli/commands/dag_command.py | 2 +
.../src/airflow/jobs/scheduler_job_runner.py | 46 +-
.../0142_3_4_0_unify_task_attempt_ownership.py | 462 +++++++++++++++
airflow-core/src/airflow/models/__init__.py | 3 -
airflow-core/src/airflow/models/asset.py | 1 +
airflow-core/src/airflow/models/dagrun.py | 68 ++-
airflow-core/src/airflow/models/hitl_history.py | 91 ---
airflow-core/src/airflow/models/log.py | 10 +-
airflow-core/src/airflow/models/pool.py | 14 +-
.../src/airflow/models/renderedtifields.py | 304 ++++++----
airflow-core/src/airflow/models/taskinstance.py | 300 +++++++---
.../src/airflow/models/taskinstancehistory.py | 225 -------
airflow-core/src/airflow/models/trigger.py | 23 +-
airflow-core/src/airflow/models/xcom.py | 485 ++++++++++-----
airflow-core/src/airflow/plugins_manager.py | 3 +-
airflow-core/src/airflow/providers_manager.py | 36 +-
.../src/airflow/serialization/definitions/dag.py | 7 +-
.../serialization/definitions/operatorlink.py | 23 +-
.../airflow/serialization/definitions/xcom_arg.py | 28 +-
.../ti_deps/deps/mapped_task_upstream_dep.py | 1 +
.../src/airflow/ti_deps/deps/prev_dagrun_dep.py | 4 +
.../src/airflow/ti_deps/deps/trigger_rule_dep.py | 18 +-
airflow-core/src/airflow/utils/db.py | 4 +-
airflow-core/src/airflow/utils/db_cleanup.py | 171 +++++-
.../src/airflow/utils/log/file_task_handler.py | 21 +-
airflow-core/src/airflow/utils/log/log_reader.py | 7 +-
.../tests/unit/always/test_providers_manager.py | 68 ++-
.../tests/unit/api/common/test_delete_dag.py | 47 +-
.../unit/api_fastapi/common/test_parameters.py | 11 +
.../core_api/routes/public/test_dag_run.py | 1 +
.../core_api/routes/public/test_extra_links.py | 8 +-
.../core_api/routes/public/test_hitl.py | 74 ++-
.../core_api/routes/public/test_task_instances.py | 251 +++++---
.../core_api/routes/public/test_xcom.py | 20 +-
.../api_fastapi/core_api/routes/ui/test_dags.py | 18 +
.../core_api/routes/ui/test_dashboard.py | 20 +
.../unit/api_fastapi/execution_api/test_app.py | 18 +-
.../api_fastapi/execution_api/test_security.py | 369 +++++++++++-
.../versions/head/test_task_instances.py | 221 ++++---
.../execution_api/versions/head/test_xcoms.py | 281 ++++-----
.../versions/v2025_04_28/test_xcom.py | 10 +-
.../versions/v2026_10_30/test_task_instances.py | 6 +-
.../unit/cli/commands/test_partition_command.py | 7 +-
airflow-core/tests/unit/jobs/test_scheduler_job.py | 277 ++++++---
airflow-core/tests/unit/jobs/test_triggerer_job.py | 5 +-
.../test_0142_unify_task_attempt_ownership.py | 653 +++++++++++++++++++++
airflow-core/tests/unit/models/test_asset.py | 32 +
airflow-core/tests/unit/models/test_cleartasks.py | 247 +++++---
airflow-core/tests/unit/models/test_dag.py | 23 +-
airflow-core/tests/unit/models/test_dagrun.py | 68 ++-
airflow-core/tests/unit/models/test_log.py | 48 ++
.../tests/unit/models/test_mappedoperator.py | 141 ++++-
airflow-core/tests/unit/models/test_pool.py | 19 +-
.../tests/unit/models/test_renderedtifields.py | 114 ++--
airflow-core/tests/unit/models/test_task_data.py | 588 +++++++++++++++++++
.../tests/unit/models/test_taskinstance.py | 404 +++++++++++--
airflow-core/tests/unit/models/test_trigger.py | 52 +-
airflow-core/tests/unit/models/test_xcom.py | 97 +--
.../tests/unit/plugins/test_plugins_manager.py | 75 +++
airflow-core/tests/unit/utils/test_db_cleanup.py | 293 ++++++++-
airflow-core/tests/unit/utils/test_log_handlers.py | 36 +-
devel-common/src/tests_common/pytest_plugin.py | 16 +-
.../src/tests_common/test_utils/asserts.py | 2 +-
.../tests_common/test_utils/attempt_ownership.py | 159 +++++
devel-common/src/tests_common/test_utils/db.py | 12 +-
.../src/tests_common/test_utils/mapping.py | 24 +-
.../tests/unit/tests_common/test_dag_maker.py | 13 +-
.../kubernetes/executors/kubernetes_executor.py | 22 +-
.../cncf/kubernetes/kubernetes_helper_functions.py | 6 +-
.../providers/common/ai/plugins/hitl_review.py | 83 ++-
.../unit/common/ai/plugins/test_hitl_review.py | 70 ++-
.../providers/common/compat/version_compat.py | 2 +
.../io/tests/unit/common/io/xcom/test_backend.py | 64 +-
.../providers/edge3/executors/edge_executor.py | 7 +-
.../unit/edge3/executors/test_edge_executor.py | 2 +-
scripts/ci/prek/check_ti_vs_tis_attributes.py | 77 ---
scripts/ci/prek/check_xcom_model_columns.py | 141 +++++
.../plugins_manager/plugins_manager.py | 8 +-
.../providers_discovery/providers_discovery.py | 5 +
task-sdk/src/airflow/sdk/bases/xcom.py | 2 +-
.../src/airflow/sdk/execution_time/supervisor.py | 17 +-
task-sdk/tests/task_sdk/bases/test_xcom.py | 16 +
.../task_sdk/execution_time/test_supervisor.py | 26 +-
111 files changed, 6651 insertions(+), 2062 deletions(-)
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 54b29e9cdd6..e7745d4240b 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1460,6 +1460,13 @@ repos:
language: python
pass_filenames: true
files: \.py$
+ - id: check-xcom-model-columns
+ name: Check XComModel columns are read through xcom_entity, not directly in SQLAlchemy queries
+ entry: ./scripts/ci/prek/check_xcom_model_columns.py
+ language: python
+ pass_filenames: true
+ files: ^(airflow-core|providers/.*)/src/airflow/.*\.py$
+ exclude: ^airflow-core/src/airflow/(models/xcom\.py|api_fastapi/common/parameters/xcom\.py)$
- id: check-no-new-airflow-exceptions
name: Check that no new raise AirflowException usages are added
entry: ./scripts/ci/prek/check_new_airflow_exception_usage.py
diff --git a/airflow-core/.pre-commit-config.yaml b/airflow-core/.pre-commit-config.yaml
index 11e70570598..a16401bf481 100644
--- a/airflow-core/.pre-commit-config.yaml
+++ b/airflow-core/.pre-commit-config.yaml
@@ -30,16 +30,6 @@ repos:
language: python
files: ^src/airflow/.*\.py$
pass_filenames: true
- - id: check-taskinstance-tis-attrs
- name: Check that TI and TIS have the same attributes
- entry: ../scripts/ci/prek/check_ti_vs_tis_attributes.py
- language: python
- files:
- (?x)
- ^src/airflow/models/taskinstance\.py$|
- ^src/airflow/models/taskinstancehistory\.py$
- pass_filenames: false
- require_serial: true
- id: check-airflow-k8s-not-used
name: Check airflow.kubernetes imports are not used
language: python
diff --git a/airflow-core/docs/howto/usage-cli.rst b/airflow-core/docs/howto/usage-cli.rst
index 00647ff9f33..fdb40c82836 100644
--- a/airflow-core/docs/howto/usage-cli.rst
+++ b/airflow-core/docs/howto/usage-cli.rst
@@ -230,7 +230,11 @@ You can optionally provide a list of tables to perform deletes on with ``--table
``--tables`` sets where cleanup starts, not the full list of tables it touches. Each table has a
configured list of dependent tables, and those are cleaned first, so that their rows are archived
too. Asking for ``--tables trigger`` therefore also cleans ``task_instance``,
- ``task_instance_history`` and ``xcom``, all of which the ``--dry-run`` output lists.
+ ``xcom_v1`` and ``xcom_v2``, all of which the ``--dry-run`` output lists.
+
+ ``--tables xcom`` selects both XCom stores. ``--tables task_instance_history`` selects only
+ retired attempts from ``task_instance``. Selecting ``xcom_v2`` also removes legacy values
+ shadowed by the selected v2 rows, so those values cannot reappear after cleanup.
That list is maintained per table rather than derived from the schema, so it does not cover every
foreign key. A table left off it can still lose rows to a cascading delete when its parent is
@@ -255,9 +259,9 @@ You can filter cleanup to specific DAGs using ``--dag-ids`` (comma-separated lis
The ``--dry-run`` output shows a ``dag_id_column`` for each table it would clean. Where that column is
``None``, the DAG filters do not apply to that table.
-By default, ``db clean`` will archive purged rows in tables of the form ``_airflow_deleted__<table>__<timestamp>``. If you don't want the data preserved in this way, you may supply argument ``--skip-archive``.
+By default, ``db clean`` will archive purged rows in tables of the form ``_airflow_deleted__<table>__<timestamp>``. Cascading attempt data may use a unique suffix instead of a timestamp. If you don't want the data preserved in this way, you may supply argument ``--skip-archive``.
-When you encounter an error without using ``--skip-archive``, ``_airflow_deleted__<table>__<timestamp>`` would still exist in the DB. You can use ``db drop-archived`` command to manually drop these tables.
+When you encounter an error without using ``--skip-archive``, an archive table may remain in the DB. You can use ``db drop-archived`` to remove it. ``db export-archived`` and ``db drop-archived`` also accept the pre-upgrade names ``xcom`` and ``task_instance_history`` to find older archives.
Detecting cleanup failures
^^^^^^^^^^^^^^^^^^^^^^^^^^
diff --git a/airflow-core/docs/migrations-ref.rst b/airflow-core/docs/migrations-ref.rst
index afd3ed01e8c..513d0089dcb 100644
--- a/airflow-core/docs/migrations-ref.rst
+++ b/airflow-core/docs/migrations-ref.rst
@@ -39,7 +39,10 @@ Here's the list of all the Database Migrations that are executed via when you ru
+-------------------------+------------------+-------------------+--------------------------------------------------------------+
| Revision ID | Revises ID | Airflow Version | Description |
+=========================+==================+===================+==============================================================+
-| ``90e4d18ccadf`` (head) | ``e5a91c7f42b3`` | ``3.4.0`` | Add timetable_asset_gated to DagModel. |
+| ``e7c2a91bd540`` (head) | ``90e4d18ccadf`` | ``3.4.0`` | Unify task attempt ownership without rewriting legacy XCom |
+| | | | data. |
++-------------------------+------------------+-------------------+--------------------------------------------------------------+
+| ``90e4d18ccadf`` | ``e5a91c7f42b3`` | ``3.4.0`` | Add timetable_asset_gated to DagModel. |
+-------------------------+------------------+-------------------+--------------------------------------------------------------+
| ``e5a91c7f42b3`` | ``ca8499dc1004`` | ``3.4.0`` | Add language column to dag_code. |
+-------------------------+------------------+-------------------+--------------------------------------------------------------+
diff --git a/airflow-core/src/airflow/api/common/delete_dag.py b/airflow-core/src/airflow/api/common/delete_dag.py
index 4dc753fa945..6473d7dfaba 100644
--- a/airflow-core/src/airflow/api/common/delete_dag.py
+++ b/airflow-core/src/airflow/api/common/delete_dag.py
@@ -22,7 +22,7 @@ from __future__ import annotations
import logging
from typing import TYPE_CHECKING, cast
-from sqlalchemy import delete, or_, select
+from sqlalchemy import Table, delete, or_, select
from airflow import models
from airflow.exceptions import AirflowException, DagNotFound
@@ -55,8 +55,11 @@ def delete_dag(dag_id: str, keep_records_in_log: bool = True, *, session: Sessio
log.info("Deleting Dag: %s", dag_id)
running_tis = session.scalar(
select(models.TaskInstance.state)
- .where(models.TaskInstance.dag_id == dag_id)
- .where(models.TaskInstance.state == TaskInstanceState.RUNNING)
+ .where(
+ models.TaskInstance.dag_id == dag_id,
+ models.TaskInstance.working_set.is_(True),
+ models.TaskInstance.state == TaskInstanceState.RUNNING,
+ )
.limit(1)
)
if running_tis:
@@ -68,7 +71,9 @@ def delete_dag(dag_id: str, keep_records_in_log: bool = True, *, session: Sessio
# To ensure the TaskInstance and DagRun model is deleted before
# each of the model DagVersion and BackFill respectively.
models_for_deletion = [TaskInstance, DagRun] + [
- model for model in get_sqla_model_classes() if model.__name__ not in ["TaskInstance", "DagRun"]
+ model
+ for model in get_sqla_model_classes()
+ if model.__name__ not in ["TaskInstance", "DagRun"] and isinstance(model.__table__, Table)
]
count: int = 0
diff --git a/airflow-core/src/airflow/api/common/mark_tasks.py b/airflow-core/src/airflow/api/common/mark_tasks.py
index 31c81db0864..6ba61686aec 100644
--- a/airflow-core/src/airflow/api/common/mark_tasks.py
+++ b/airflow-core/src/airflow/api/common/mark_tasks.py
@@ -113,6 +113,7 @@ def get_all_dag_task_query(
):
"""Get all tasks of the main dag that will be affected by a state change."""
qry_dag = select(TaskInstance).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == dag.dag_id,
TaskInstance.run_id.in_(run_ids),
)
@@ -261,6 +262,7 @@ def _set_dag_run_terminal_state(
running_tis: list[TaskInstance] = list(
session.scalars(
select(TaskInstance).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == dag.dag_id,
TaskInstance.run_id == run_id,
TaskInstance.task_id.in_(task_ids),
@@ -283,6 +285,7 @@ def _set_dag_run_terminal_state(
pending_tis: list[TaskInstance] = list(
session.scalars(
select(TaskInstance).filter(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == dag.dag_id,
TaskInstance.run_id == run_id,
TaskInstance.task_id.in_(task_ids),
diff --git a/airflow-core/src/airflow/api_fastapi/common/db/dag_runs.py b/airflow-core/src/airflow/api_fastapi/common/db/dag_runs.py
index 09779b17dd0..ed559e30225 100644
--- a/airflow-core/src/airflow/api_fastapi/common/db/dag_runs.py
+++ b/airflow-core/src/airflow/api_fastapi/common/db/dag_runs.py
@@ -22,7 +22,7 @@ from collections.abc import Sequence
from typing import TYPE_CHECKING
from uuid import UUID
-from sqlalchemy import func, select, tuple_, union_all
+from sqlalchemy import func, select, tuple_
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.interfaces import LoaderOption
@@ -31,7 +31,6 @@ from airflow.models.dag import DagModel
from airflow.models.dag_version import DagVersion
from airflow.models.dagrun import DagRun
from airflow.models.taskinstance import TaskInstance
-from airflow.models.taskinstancehistory import TaskInstanceHistory
if TYPE_CHECKING:
from sqlalchemy.orm import Session
@@ -58,7 +57,7 @@ def eager_load_dag_run_for_list() -> tuple[LoaderOption, ...]:
Only loads the direct relationships needed for serialization (dag_model,
dag_run_note, created_dag_version, and the owning team). The dag_versions
- property — which requires iterating every TI and TIH — is populated separately by
+ property — which requires iterating every attempt — is populated separately by
:func:`attach_dag_versions_to_runs` using a single DISTINCT query.
"""
return (
@@ -73,21 +72,21 @@ def attach_dag_versions_to_runs(dag_runs: Sequence[DagRun], *, session: Session)
"""
Prefetch distinct dag_version_ids for each DagRun via a lightweight query.
- Instead of loading all TI and TIH rows (potentially thousands per run)
+ Instead of loading all attempt rows (potentially thousands per run)
through the ORM relationship just to extract distinct dag_version_ids,
this issues a single query that returns only the distinct
(dag_id, run_id, dag_version_id) tuples for the given runs.
The result is attached to each DagRun as ``_prefetched_dag_version_ids``
(a dict mapping version_id -> DagVersion), which the ``dag_versions``
- property reads as an optimized substitute for traversing TI/TIH
+ property reads as an optimized substitute for traversing attempt
relationships. All business logic (bundle_version shortcut, sorting,
deduplication) remains solely in ``DagRun.dag_versions``.
"""
if not dag_runs:
return
- # Only runs without a bundle_version need TI/TIH traversal;
+ # Only runs without a bundle_version need attempt traversal;
# runs with bundle_version use created_dag_version directly
# (handled by the dag_versions property).
runs_needing_versions = [dr for dr in dag_runs if not dr.bundle_version]
@@ -96,29 +95,17 @@ def attach_dag_versions_to_runs(dag_runs: Sequence[DagRun], *, session: Session)
run_key_values = [(dr.dag_id, dr.run_id) for dr in runs_needing_versions]
- ti_sub = (
+ rows = session.execute(
select(
TaskInstance.dag_id,
TaskInstance.run_id,
- TaskInstance.dag_version_id,
+ TaskInstance.dag_version_id.label("dag_version_id"),
)
- .where(TaskInstance.dag_version_id.isnot(None))
- .where(tuple_(TaskInstance.dag_id, TaskInstance.run_id).in_(run_key_values))
- .distinct()
- )
- tih_sub = (
- select(
- TaskInstanceHistory.dag_id,
- TaskInstanceHistory.run_id,
- TaskInstanceHistory.dag_version_id,
+ .where(
+ TaskInstance.dag_version_id.is_not(None),
+ tuple_(TaskInstance.dag_id, TaskInstance.run_id).in_(run_key_values),
)
- .where(TaskInstanceHistory.dag_version_id.isnot(None))
- .where(tuple_(TaskInstanceHistory.dag_id, TaskInstanceHistory.run_id).in_(run_key_values))
.distinct()
- )
- combined = union_all(ti_sub, tih_sub).subquery()
- rows = session.execute(
- select(combined.c.dag_id, combined.c.run_id, combined.c.dag_version_id).distinct()
).all()
all_version_ids = {r.dag_version_id for r in rows}
diff --git a/airflow-core/src/airflow/api_fastapi/common/db/task_instances.py b/airflow-core/src/airflow/api_fastapi/common/db/task_instances.py
index 9d93baf2530..58d2e61b4a8 100644
--- a/airflow-core/src/airflow/api_fastapi/common/db/task_instances.py
+++ b/airflow-core/src/airflow/api_fastapi/common/db/task_instances.py
@@ -21,18 +21,14 @@ from sqlalchemy import Select
from sqlalchemy.orm import contains_eager, joinedload
from airflow.api_fastapi.common.db.dags import eager_load_teams
-from airflow.models import Base
from airflow.models.dag_version import DagVersion
from airflow.models.dagrun import DagRun
from airflow.models.taskinstance import TaskInstance
-def eager_load_TI_and_TIH_for_validation(
- query: Select,
- orm_model: Base | None = None,
-) -> Select:
+def eager_load_task_instance_for_validation(query: Select) -> Select:
"""
- Add JOINs and eager-loading options for TaskInstanceResponse and TaskInstanceHistoryResponse.
+ Add JOINs and eager-loading options for TaskInstanceResponse.
Adds ``join(dag_run)`` and ``outerjoin(dag_version)`` to the query and
configures ``contains_eager`` so SQLAlchemy reuses those joins for
@@ -42,21 +38,16 @@ def eager_load_TI_and_TIH_for_validation(
ensures ORDER BY / WHERE clauses on DagRun columns resolve correctly.
:param query: The SELECT statement to augment.
- :param orm_model: The ORM model to load options for (defaults to TaskInstance).
"""
- if orm_model is None:
- orm_model = TaskInstance
-
- query = query.join(orm_model.dag_run).outerjoin(orm_model.dag_version)
- query = query.options(
- contains_eager(orm_model.dag_run).options(
- joinedload(DagRun.dag_model).options(*eager_load_teams()),
- ),
- contains_eager(orm_model.dag_version).options(joinedload(DagVersion.bundle)),
- )
- if orm_model is TaskInstance:
- query = query.options(
- joinedload(orm_model.task_instance_note),
- joinedload(orm_model.rendered_task_instance_fields),
+ return (
+ query.join(TaskInstance.dag_run)
+ .outerjoin(TaskInstance.dag_version)
+ .options(
+ contains_eager(TaskInstance.dag_run).options(
+ joinedload(DagRun.dag_model).options(*eager_load_teams()),
+ ),
+ contains_eager(TaskInstance.dag_version).options(joinedload(DagVersion.bundle)),
+ joinedload(TaskInstance.task_instance_note),
+ joinedload(TaskInstance.rendered_task_instance_fields),
)
- return query
+ )
diff --git a/airflow-core/src/airflow/api_fastapi/common/parameters/misc.py b/airflow-core/src/airflow/api_fastapi/common/parameters/misc.py
index 6a5b2a44bdc..be10b0d1fa5 100644
--- a/airflow-core/src/airflow/api_fastapi/common/parameters/misc.py
+++ b/airflow-core/src/airflow/api_fastapi/common/parameters/misc.py
@@ -63,6 +63,7 @@ class _PendingActionsFilter(BaseParam[bool]):
.join(TaskInstance, HITLDetail.ti_id == TaskInstance.id)
.where(
HITLDetail.responded_at.is_(None),
+ TaskInstance.working_set.is_(True),
TaskInstance.state.in_((TaskInstanceState.DEFERRED, TaskInstanceState.AWAITING_INPUT)),
)
.where(TaskInstance.dag_id == DagModel.dag_id)
diff --git a/airflow-core/src/airflow/api_fastapi/common/parameters/sort.py b/airflow-core/src/airflow/api_fastapi/common/parameters/sort.py
index 2e01e695422..d138b1a4456 100644
--- a/airflow-core/src/airflow/api_fastapi/common/parameters/sort.py
+++ b/airflow-core/src/airflow/api_fastapi/common/parameters/sort.py
@@ -168,7 +168,8 @@ class SortParam(BaseParam[list[str]]):
def get_primary_key_column(self) -> Column:
"""Get the primary key column of the model of SortParam object."""
- return inspect(self.model).primary_key[0]
+ inspection = inspect(self.model)
+ return inspection.selectable.corresponding_column(inspection.mapper.primary_key[0])
def get_primary_key_string(self) -> str:
"""Get the primary key string of the model of SortParam object."""
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/extra_links.py b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/extra_links.py
index a855689e27a..3b0ef365f05 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/extra_links.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/extra_links.py
@@ -70,7 +70,6 @@ def get_extra_links(
) -> ExtraLinkCollectionResponse:
"""Get extra links for task instance."""
from airflow.models.taskinstance import TaskInstance
- from airflow.models.taskinstancehistory import TaskInstanceHistory
dag_run = session.scalar(select(DagRun).where(DagRun.dag_id == dag_id, DagRun.run_id == dag_run_id))
@@ -80,6 +79,9 @@ def get_extra_links(
TaskInstance.run_id == dag_run_id,
TaskInstance.task_id == task_id,
TaskInstance.map_index == map_index,
+ TaskInstance.working_set.is_(True)
+ if try_number is None
+ else TaskInstance.try_number == try_number,
)
)
@@ -96,28 +98,6 @@ def get_extra_links(
except TaskNotFound:
raise HTTPException(status.HTTP_404_NOT_FOUND, f"Task with ID = {task_id} not found")
- # Resolve which object to use for link generation. For the current try we use
- # the live TI; for past tries we fetch the immutable TaskInstanceHistory record,
- # which also validates that the requested try_number actually exists.
- if try_number is not None and try_number != ti.try_number:
- tih = session.scalar(
- select(TaskInstanceHistory).where(
- TaskInstanceHistory.dag_id == dag_id,
- TaskInstanceHistory.task_id == task_id,
- TaskInstanceHistory.run_id == dag_run_id,
- TaskInstanceHistory.map_index == map_index,
- TaskInstanceHistory.try_number == try_number,
- )
- )
- if not tih:
- raise HTTPException(
- status.HTTP_404_NOT_FOUND,
- f"TaskInstanceHistory not found for try_number={try_number}",
- )
- ti_for_links = tih
- else:
- ti_for_links = ti
-
link_names: list[str] = task.extra_links
if conf.getboolean("core", "multi_team"):
dag_team_name = DagModel.get_team_name(dag_id)
@@ -130,7 +110,7 @@ def get_extra_links(
]
all_extra_link_pairs = (
- (link_name, task.get_extra_links(ti_for_links, link_name))
+ (link_name, task.get_extra_links(ti, link_name))
for link_name in link_names # type: ignore[arg-type]
)
all_extra_links = {link_name: link_url or None for link_name, link_url in sorted(all_extra_link_pairs)}
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/hitl.py b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/hitl.py
index 4771d1de934..abf4c497506 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/hitl.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/hitl.py
@@ -63,12 +63,11 @@ from airflow.api_fastapi.core_api.security import (
requires_access_dag,
)
from airflow.api_fastapi.logging.decorators import action_logging
-from airflow.models.base import Base
from airflow.models.dag_version import DagVersion
from airflow.models.dagrun import DagRun
from airflow.models.hitl import HITLDetail as HITLDetailModel, HITLUser
+from airflow.models.renderedtifields import load_legacy_rendered_fields
from airflow.models.taskinstance import TaskInstance as TI
-from airflow.models.taskinstancehistory import TaskInstanceHistory as TIH
from airflow.models.trigger import handle_event_submit
from airflow.triggers.base import TriggerEvent
from airflow.utils.state import TaskInstanceState
@@ -89,34 +88,21 @@ def _get_task_instance_with_hitl_detail(
session: SessionDep,
map_index: int,
try_number: int | None = None,
-) -> TI | TIH:
- def _query(orm_object: Base) -> TI | TIH | None:
- options = [joinedload(orm_object.hitl_detail)]
- if orm_object is TI:
- options.append(joinedload(TI.rendered_task_instance_fields))
- query = (
- select(orm_object)
- .where(
- orm_object.dag_id == dag_id,
- orm_object.run_id == dag_run_id,
- orm_object.task_id == task_id,
- orm_object.map_index == map_index,
- )
- .options(*options)
+) -> TI:
+ query = (
+ select(TI)
+ .where(
+ TI.dag_id == dag_id,
+ TI.run_id == dag_run_id,
+ TI.task_id == task_id,
+ TI.map_index == map_index,
)
+ .options(joinedload(TI.hitl_detail), joinedload(TI.rendered_task_instance_fields))
+ )
+ query = query.where(TI.working_set.is_(True) if try_number is None else TI.try_number == try_number)
+ ti = session.scalar(query)
- if try_number is not None:
- query = query.where(orm_object.try_number == try_number)
-
- ti_or_tih = session.scalar(query)
- return ti_or_tih
-
- if try_number is None:
- ti_or_tih = _query(TI)
- else:
- ti_or_tih = _query(TIH) or _query(TI)
-
- if ti_or_tih is None:
+ if ti is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=(
@@ -125,13 +111,14 @@ def _get_task_instance_with_hitl_detail(
),
)
- if not ti_or_tih.hitl_detail:
+ if not ti.hitl_detail:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Human-in-the-loop detail does not exist for Task Instance with id {ti_or_tih.id}",
+ detail=f"Human-in-the-loop detail does not exist for Task Instance with id {ti.id}",
)
- return ti_or_tih
+ load_legacy_rendered_fields([ti], session=session)
+ return ti
@task_instances_hitl_router.patch(
@@ -175,17 +162,21 @@ def update_hitl_detail(
if isinstance(task_instance, TI)
else None
)
+ if locked_ti is None or locked_ti.working_set is not True:
+ raise HTTPException(status.HTTP_409_CONFLICT, "The Task Instance is no longer current")
# Lock the hitl_detail row (FOR UPDATE OF hitl_detail). of= scopes the lock to hitl_detail, which
# eager-joins task_instance (lazy="joined"); a bare with_for_update() would emit FOR UPDATE against
# the nullable side of that outer join, which Postgres rejects. populate_existing re-reads the
# joinedloaded row under the lock, so assignees and options are validated against the request committed
# by a concurrent upsert from the re-run, not the snapshot taken before locking.
- hitl_detail_model = session.scalars(
+ hitl_detail_model = session.scalar(
select(HITLDetailModel)
.where(HITLDetailModel.ti_id == task_instance.id)
.with_for_update(of=HITLDetailModel)
.execution_options(populate_existing=True)
- ).one()
+ )
+ if hitl_detail_model is None:
+ raise HTTPException(status.HTTP_404_NOT_FOUND, "Human-in-the-loop detail does not exist")
if hitl_detail_model.response_received:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
@@ -360,6 +351,7 @@ def get_hitl_details(
query = (
select(HITLDetailModel)
.join(TI, HITLDetailModel.ti_id == TI.id)
+ .where(TI.working_set.is_(True))
.join(TI.dag_run)
.options(
joinedload(HITLDetailModel.task_instance).options(
@@ -402,7 +394,8 @@ def get_hitl_details(
session=session,
)
- hitl_details = session.scalars(hitl_detail_select)
+ hitl_details = session.scalars(hitl_detail_select).all()
+ load_legacy_rendered_fields([detail.task_instance for detail in hitl_details], session=session)
return HITLDetailCollection(
hitl_details=hitl_details,
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/log.py b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/log.py
index da8a47dbe50..58927314410 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/log.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/log.py
@@ -39,7 +39,6 @@ from airflow.api_fastapi.core_api.security import DagAccessEntity, requires_acce
from airflow.configuration import conf
from airflow.exceptions import TaskNotFound
from airflow.models import TaskInstance, Trigger
-from airflow.models.taskinstancehistory import TaskInstanceHistory
from airflow.utils.log.log_reader import TaskLogReader
_NDJSON_BATCH_SIZE = conf.getint("api", "log_stream_buffer_size")
@@ -137,21 +136,6 @@ def get_log(
.options(joinedload(TaskInstance.dag_model))
)
ti = session.scalar(query)
- if ti is None:
- query = (
- select(TaskInstanceHistory)
- .where(
- TaskInstanceHistory.task_id == task_id,
- TaskInstanceHistory.dag_id == dag_id,
- TaskInstanceHistory.run_id == dag_run_id,
- TaskInstanceHistory.map_index == map_index,
- TaskInstanceHistory.try_number == try_number,
- )
- .options(joinedload(TaskInstanceHistory.dag_run))
- # we need to joinedload the dag_run, since FileTaskHandler._render_filename needs ti.dag_run
- )
- ti = session.scalar(query)
-
if ti is None:
metadata["end_of_log"] = True
raise HTTPException(status.HTTP_404_NOT_FOUND, "TaskInstance not found")
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_instances.py b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_instances.py
index 65f8b57ec8e..a6c0940ec42 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_instances.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_instances.py
@@ -24,7 +24,6 @@ import structlog
from fastapi import Depends, HTTPException, Query, status
from sqlalchemy import select
from sqlalchemy.orm import joinedload
-from sqlalchemy.sql.selectable import Select
from airflow.api_fastapi.auth.managers.models.resource_details import DagAccessEntity
from airflow.api_fastapi.common.cursors import (
@@ -47,7 +46,7 @@ from airflow.api_fastapi.common.db.common import (
paginated_select,
)
from airflow.api_fastapi.common.db.dags import eager_load_teams
-from airflow.api_fastapi.common.db.task_instances import eager_load_TI_and_TIH_for_validation
+from airflow.api_fastapi.common.db.task_instances import eager_load_task_instance_for_validation
from airflow.api_fastapi.common.parameters import (
FilterOptionEnum,
FilterParam,
@@ -119,9 +118,9 @@ from airflow.api_fastapi.core_api.services.public.task_instances import (
)
from airflow.api_fastapi.logging.decorators import action_logging
from airflow.exceptions import AirflowClearRunningTaskException, TaskNotFound
-from airflow.models import Base, DagRun
+from airflow.models import DagRun
+from airflow.models.renderedtifields import load_legacy_rendered_fields
from airflow.models.taskinstance import TaskInstance as TI, clear_task_instances
-from airflow.models.taskinstancehistory import TaskInstanceHistory as TIH
from airflow.ti_deps.dep_context import DepContext
from airflow.ti_deps.dependencies_deps import SCHEDULER_QUEUED_DEPS
from airflow.utils.db import get_query_count
@@ -147,7 +146,7 @@ def get_task_instance(
"""Get task instance."""
query = (
select(TI)
- .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == task_id)
+ .where(TI.working_set.is_(True), TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == task_id)
.options(joinedload(TI.rendered_task_instance_fields))
.options(joinedload(TI.dag_version))
.options(joinedload(TI.dag_run).options(joinedload(DagRun.dag_model)))
@@ -164,6 +163,7 @@ def get_task_instance(
raise HTTPException(
status.HTTP_404_NOT_FOUND, "Task instance is mapped, add the map_index value to the URL"
)
+ load_legacy_rendered_fields([task_instance], session=session)
return task_instance
@@ -241,9 +241,13 @@ def get_mapped_task_instances(
session: SessionDep,
) -> TaskInstanceCollectionResponse:
"""Get list of mapped task instances."""
- query = eager_load_TI_and_TIH_for_validation(
+ query = eager_load_task_instance_for_validation(
select(TI).where(
- TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == task_id, TI.map_index >= 0
+ TI.working_set.is_(True),
+ TI.dag_id == dag_id,
+ TI.run_id == dag_run_id,
+ TI.task_id == task_id,
+ TI.map_index >= 0,
)
)
# 0 can mean a mapped TI that expanded to an empty list, so it is not an automatic 404
@@ -291,7 +295,8 @@ def get_mapped_task_instances(
limit=limit,
session=session,
)
- task_instances = session.scalars(task_instance_select)
+ task_instances = list(session.scalars(task_instance_select))
+ load_legacy_rendered_fields(task_instances, session=session)
return TaskInstanceCollectionResponse(
task_instances=task_instances,
@@ -320,7 +325,9 @@ def get_task_instance_dependencies(
map_index: int = -1,
) -> TaskDependencyCollectionResponse:
"""Get dependencies blocking task from getting scheduled."""
- query = select(TI).where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == task_id)
+ query = select(TI).where(
+ TI.working_set.is_(True), TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == task_id
+ )
query = query.where(TI.map_index == map_index)
result = session.execute(query).one_or_none()
@@ -372,27 +379,26 @@ def get_task_instance_tries(
map_index: int = -1,
) -> TaskInstanceHistoryCollectionResponse:
"""Get list of task instances history."""
-
- def _query(orm_object: Base) -> Select:
- query = eager_load_TI_and_TIH_for_validation(
- select(orm_object).where(
- orm_object.dag_id == dag_id,
- orm_object.run_id == dag_run_id,
- orm_object.task_id == task_id,
- orm_object.map_index == map_index,
- ),
- orm_model=orm_object,
- ).options(joinedload(orm_object.hitl_detail))
- return query
-
- tis = session.scalars(_query(TI)).all()
- task_instances = list(session.scalars(_query(TIH)).all()) + list(tis)
+ query = (
+ eager_load_task_instance_for_validation(
+ select(TI).where(
+ TI.dag_id == dag_id,
+ TI.run_id == dag_run_id,
+ TI.task_id == task_id,
+ TI.map_index == map_index,
+ )
+ )
+ .options(joinedload(TI.hitl_detail))
+ .order_by(TI.try_number)
+ )
+ task_instances = list(session.scalars(query))
if not task_instances:
raise HTTPException(
status.HTTP_404_NOT_FOUND,
f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, task_id: `{task_id}` and map_index: `{map_index}` was not found",
)
+ load_legacy_rendered_fields(task_instances, session=session)
return TaskInstanceHistoryCollectionResponse(
task_instances=cast("list[TaskInstanceHistoryResponse]", task_instances),
total_entries=len(task_instances),
@@ -435,7 +441,13 @@ def get_mapped_task_instance(
"""Get task instance."""
query = (
select(TI)
- .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == task_id, TI.map_index == map_index)
+ .where(
+ TI.working_set.is_(True),
+ TI.dag_id == dag_id,
+ TI.run_id == dag_run_id,
+ TI.task_id == task_id,
+ TI.map_index == map_index,
+ )
.options(joinedload(TI.rendered_task_instance_fields))
.options(joinedload(TI.dag_version))
.options(joinedload(TI.dag_run).options(joinedload(DagRun.dag_model)))
@@ -449,6 +461,7 @@ def get_mapped_task_instance(
f"The Mapped Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, task_id: `{task_id}`, and map_index: `{map_index}` was not found",
)
+ load_legacy_rendered_fields([task_instance], session=session)
return task_instance
@@ -558,7 +571,7 @@ def get_task_instances(
"""
use_cursor = cursor is not None
dag_run = None
- query = eager_load_TI_and_TIH_for_validation(select(TI))
+ query = eager_load_task_instance_for_validation(select(TI).where(TI.working_set.is_(True)))
if dag_run_id != "~":
if dag_id == "~":
raise HTTPException(
@@ -650,6 +663,7 @@ def get_task_instances(
total_entries, total_entries_limit = bounded_total_entries(
statement=query, filters=filters, session=session
)
+ load_legacy_rendered_fields(task_instances, session=session)
return TaskInstanceCollectionResponse(
task_instances=task_instances,
total_entries=total_entries,
@@ -673,6 +687,7 @@ def get_task_instances(
session=session,
)
task_instances = list(session.scalars(task_instance_select))
+ load_legacy_rendered_fields(task_instances, session=session)
return TaskInstanceCollectionResponse(
task_instances=task_instances,
total_entries=total_entries,
@@ -756,7 +771,7 @@ def get_task_instances_batch(
TI,
).set_value([body.order_by] if body.order_by else None)
- query = eager_load_TI_and_TIH_for_validation(select(TI))
+ query = eager_load_task_instance_for_validation(select(TI).where(TI.working_set.is_(True)))
task_instance_select, total_entries = paginated_select(
statement=query,
filters=[
@@ -779,7 +794,8 @@ def get_task_instances_batch(
limit=limit,
session=session,
)
- task_instances = session.scalars(task_instance_select)
+ task_instances = list(session.scalars(task_instance_select))
+ load_legacy_rendered_fields(task_instances, session=session)
return TaskInstanceCollectionResponse(
task_instances=task_instances,
@@ -801,26 +817,23 @@ def get_task_instance_try_details(
map_index: int = -1,
) -> TaskInstanceHistoryResponse:
"""Get task instance details by try number."""
-
- def _query(orm_object: Base) -> TI | TIH | None:
- query = select(orm_object).where(
- orm_object.dag_id == dag_id,
- orm_object.run_id == dag_run_id,
- orm_object.task_id == task_id,
- orm_object.try_number == task_try_number,
- orm_object.map_index == map_index,
+ query = eager_load_task_instance_for_validation(
+ select(TI).where(
+ TI.dag_id == dag_id,
+ TI.run_id == dag_run_id,
+ TI.task_id == task_id,
+ TI.try_number == task_try_number,
+ TI.map_index == map_index,
)
-
- ti_or_tih = session.scalar(query)
- return ti_or_tih
-
- ti_or_tih = _query(TI) or _query(TIH)
- if ti_or_tih is None:
+ )
+ ti = session.scalar(query)
+ if ti is None:
raise HTTPException(
status.HTTP_404_NOT_FOUND,
f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, task_id: `{task_id}`, try_number: `{task_try_number}` and map_index: `{map_index}` was not found",
)
- return ti_or_tih
+ load_legacy_rendered_fields([ti], session=session)
+ return ti
@task_instances_router.get(
@@ -983,7 +996,7 @@ def post_clear_task_instances(
if not dry_run:
try:
- clear_task_instances(
+ task_instances = clear_task_instances(
task_instances,
session,
DagRunState.QUEUED if reset_dag_runs else False,
@@ -1007,16 +1020,7 @@ def post_clear_task_instances(
user=user,
)
- # Eagerly load rendered_task_instance_fields for serialization (lazy='raise' prevents lazy access).
- # dag.clear() returns TIs without this relationship loaded; re-query with joinedload.
- # populate_existing=True ensures the joinedload updates TIs already in the identity map.
- if task_instances:
- task_instances = session.scalars(
- select(TI)
- .options(joinedload(TI.rendered_task_instance_fields))
- .where(TI.id.in_([ti.id for ti in task_instances]))
- .execution_options(populate_existing=True)
- ).all()
+ task_instances = _reload_tis_with_rendered_fields(task_instances, session)
return TaskInstanceCollectionResponse(
task_instances=[TaskInstanceResponse.model_validate(ti) for ti in task_instances],
@@ -1170,16 +1174,7 @@ def patch_task_instance_dry_run(
or []
)
- # Eagerly load rendered_task_instance_fields for serialization (lazy='raise' prevents lazy access).
- # set_task_instance_state() returns TIs without this relationship loaded; re-query with joinedload.
- # populate_existing=True ensures the joinedload updates TIs already in the identity map.
- if tis:
- tis = session.scalars(
- select(TI)
- .options(joinedload(TI.rendered_task_instance_fields))
- .where(TI.id.in_([ti.id for ti in tis]))
- .execution_options(populate_existing=True)
- ).all()
+ tis = _reload_tis_with_rendered_fields(tis, session)
return TaskInstanceCollectionResponse(
task_instances=[
@@ -1277,6 +1272,8 @@ def patch_task_instance(
session=session,
)
+ load_legacy_rendered_fields(tis, session=session)
+
return TaskInstanceCollectionResponse(
task_instances=[
TaskInstanceResponse.model_validate(
@@ -1302,6 +1299,7 @@ def delete_task_instance(
) -> None:
"""Delete a task instance."""
query = select(TI).where(
+ TI.working_set.is_(True),
TI.dag_id == dag_id,
TI.run_id == dag_run_id,
TI.task_id == task_id,
@@ -1315,4 +1313,6 @@ def delete_task_instance(
f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, task_id: `{task_id}` and map_index: `{map_index}` was not found",
)
- session.delete(task_instance)
+ TI.delete_attempts(
+ dag_id=dag_id, run_id=dag_run_id, task_id=task_id, map_index=map_index, session=session
+ )
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_state_store.py b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_state_store.py
index 8c0e5be5ef3..df6a8b9daab 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_state_store.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/task_state_store.py
@@ -59,6 +59,7 @@ def _require_task_instance(
) -> None:
"""Raise 404 unless the task instance exists. ``map_index=None`` matches any map index."""
statement = select(TI.task_id).where(
+ TI.working_set.is_(True),
TI.dag_id == dag_id,
TI.run_id == dag_run_id,
TI.task_id == task_id,
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/xcom.py b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/xcom.py
index 28304390c82..53e23555e05 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/xcom.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/xcom.py
@@ -16,11 +16,10 @@
# under the License.
from __future__ import annotations
-import copy
from typing import Annotated
from fastapi import Depends, HTTPException, Query, status
-from sqlalchemy import and_, delete, select
+from sqlalchemy import and_, select
from sqlalchemy.orm import joinedload
from airflow.api_fastapi.auth.managers.models.resource_details import DagAccessEntity
@@ -60,7 +59,8 @@ from airflow.api_fastapi.logging.decorators import action_logging
from airflow.exceptions import TaskNotFound
from airflow.models import DagRun as DR
from airflow.models.dag import DagModel
-from airflow.models.xcom import XComModel
+from airflow.models.taskinstance import TaskInstance
+from airflow.models.xcom import XComModel, build_xcom_read_query, select_producers, xcom_entity
xcom_router = AirflowRouter(
tags=["XCom"], prefix="/dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances/{task_id}/xcomEntries"
@@ -88,16 +88,18 @@ def get_xcom_entry(
stringify: Annotated[bool, Query()] = False,
) -> XComResponseNative | XComResponseString:
"""Get an XCom entry."""
- xcom_query = XComModel.get_many(
+ xcom_read = XComModel.get_many(
run_id=dag_run_id,
key=xcom_key,
task_ids=task_id,
dag_ids=dag_id,
map_indexes=map_index,
- ).options(
- joinedload(XComModel.task),
- joinedload(XComModel.dag_run).joinedload(DR.dag_model),
- *eager_load_teams(XComModel.dag_run, DR.dag_model),
+ )
+ entity = xcom_entity(xcom_read)
+ xcom_query = xcom_read.options(
+ joinedload(entity.task),
+ joinedload(entity.dag_run).joinedload(DR.dag_model),
+ *eager_load_teams(entity.dag_run, DR.dag_model),
)
# We use `BaseXCom.get_many` to fetch XComs directly from the database, bypassing the XCom Backend.
@@ -109,7 +111,7 @@ def get_xcom_entry(
raise HTTPException(status.HTTP_404_NOT_FOUND, f"XCom entry with key: `{xcom_key}` not found")
result = raw_result[0] if isinstance(raw_result, tuple) else raw_result
- item = copy.copy(result)
+ value = result.value
if deserialize:
# Custom XCom backends may store references (eg: object storage paths) in the database.
@@ -131,17 +133,19 @@ def get_xcom_entry(
parsed_value = result.value
try:
- item.value = stringify_xcom(parsed_value)
+ value = stringify_xcom(parsed_value)
except StringifyNotSupportedError:
- item.value = XComModel.deserialize_value(result)
+ value = XComModel.deserialize_value(result)
else:
# For native format, return the raw serialized value from the database
# This preserves the JSON string format that the API expects
- item.value = result.value
+ value = result.value
+ data = XComResponseNative.model_validate(result).model_dump()
+ data["value"] = value
if stringify:
- return XComResponseString.model_validate(item)
- return XComResponseNative.model_validate(item)
+ return XComResponseString.model_validate(data)
+ return XComResponseNative.model_validate(data)
@xcom_router.get(
@@ -172,11 +176,20 @@ def get_xcom_entries(
task_id_prefix_pattern: QueryXComTaskIdPrefixPatternSearch,
map_index_filter: Annotated[
FilterParam[int | None],
- Depends(filter_param_factory(XComModel.map_index, int | None, filter_name="map_index_filter")),
+ Depends(
+ filter_param_factory(
+ XComModel.map_index, # xcom-model-column: allow
+ int | None,
+ filter_name="map_index_filter",
+ )
+ ),
],
logical_date_range: Annotated[RangeFilter, Depends(datetime_range_filter_factory("logical_date", DR))],
run_after_range: Annotated[RangeFilter, Depends(datetime_range_filter_factory("run_after", DR))],
- teams: Annotated[_DagIdTeamsFilter, Depends(teams_filter_factory(XComModel.dag_id))],
+ teams: Annotated[
+ _DagIdTeamsFilter,
+ Depends(teams_filter_factory(XComModel.dag_id)), # xcom-model-column: allow
+ ],
order_by: Annotated[
SortParam,
Depends(
@@ -195,27 +208,49 @@ def get_xcom_entries(
This endpoint allows specifying `~` as the dag_id, dag_run_id, task_id to retrieve XCom entries for all Dags.
"""
- query = select(XComModel)
+ xcom_read = build_xcom_read_query(
+ producer_ids=select_producers(
+ dag_ids=None if dag_id == "~" else dag_id,
+ run_id=None if dag_run_id == "~" else dag_run_id,
+ task_ids=None if task_id == "~" else task_id,
+ map_indexes=map_index,
+ ),
+ key=xcom_key,
+ )
+ query, entity = xcom_read, xcom_entity(xcom_read)
+ readable_xcom_filter.entity = entity
+ for parameter, name in (
+ (xcom_key_pattern, "key"),
+ (xcom_key_prefix_pattern, "key"),
+ (run_id_pattern, "run_id"),
+ (run_id_prefix_pattern, "run_id"),
+ (task_id_pattern, "task_id"),
+ (task_id_prefix_pattern, "task_id"),
+ (map_index_filter, "map_index"),
+ ):
+ parameter.attribute = getattr(entity, name)
+ teams.dag_id_attribute = entity.dag_id
+ order_by.model = entity
if dag_id != "~":
- query = query.where(XComModel.dag_id == dag_id)
+ query = query.where(entity.dag_id == dag_id)
query = (
- query.join(DR, and_(XComModel.dag_id == DR.dag_id, XComModel.run_id == DR.run_id))
+ query.join(DR, and_(entity.dag_id == DR.dag_id, entity.run_id == DR.run_id))
.join(DagModel, DR.dag_id == DagModel.dag_id)
.options(
- joinedload(XComModel.task),
- joinedload(XComModel.dag_run).joinedload(DR.dag_model),
- *eager_load_teams(XComModel.dag_run, DR.dag_model),
+ joinedload(entity.task),
+ joinedload(entity.dag_run).joinedload(DR.dag_model),
+ *eager_load_teams(entity.dag_run, DR.dag_model),
)
)
if task_id != "~":
- query = query.where(XComModel.task_id == task_id)
+ query = query.where(entity.task_id == task_id)
if dag_run_id != "~":
query = query.where(DR.run_id == dag_run_id)
if map_index is not None:
- query = query.where(XComModel.map_index == map_index)
+ query = query.where(entity.map_index == map_index)
if xcom_key is not None:
- query = query.where(XComModel.key == xcom_key)
+ query = query.where(entity.key == xcom_key)
query, total_entries = paginated_select(
statement=query,
@@ -287,14 +322,14 @@ def create_xcom_entry(
)
# Check existing XCom
- already_existing_query = XComModel.get_many(
+ xcom_read = XComModel.get_many(
key=request_body.key,
task_ids=task_id,
dag_ids=dag_id,
run_id=dag_run_id,
map_indexes=request_body.map_index,
)
- result = session.execute(already_existing_query.with_only_columns(XComModel.value).limit(1)).first()
+ result = session.execute(xcom_read.with_only_columns(xcom_entity(xcom_read).value).limit(1)).first()
if result:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
@@ -317,20 +352,12 @@ def create_xcom_entry(
status.HTTP_400_BAD_REQUEST, f"Couldn't serialise the XCom with key: `{request_body.key}`"
) from e
+ entity = xcom_entity(xcom_read)
xcom = session.scalar(
- select(XComModel)
- .where(
- XComModel.dag_id == dag_id,
- XComModel.task_id == task_id,
- XComModel.run_id == dag_run_id,
- XComModel.key == request_body.key,
- XComModel.map_index == request_body.map_index,
- )
- .limit(1)
- .options(
- joinedload(XComModel.task),
- joinedload(XComModel.dag_run).joinedload(DR.dag_model),
- *eager_load_teams(XComModel.dag_run, DR.dag_model),
+ xcom_read.limit(1).options(
+ joinedload(entity.task),
+ joinedload(entity.dag_run).joinedload(DR.dag_model),
+ *eager_load_teams(entity.dag_run, DR.dag_model),
)
)
@@ -361,22 +388,18 @@ def update_xcom_entry(
session: SessionDep,
) -> XComResponseNative:
"""Update an existing XCom entry."""
- # Check if XCom entry exists
- xcom_query = (
- select(XComModel)
- .where(
- XComModel.dag_id == dag_id,
- XComModel.task_id == task_id,
- XComModel.run_id == dag_run_id,
- XComModel.key == xcom_key,
- XComModel.map_index == patch_body.map_index,
- )
- .limit(1)
- .options(
- joinedload(XComModel.task),
- joinedload(XComModel.dag_run).joinedload(DR.dag_model),
- *eager_load_teams(XComModel.dag_run, DR.dag_model),
- )
+ xcom_read = XComModel.get_many(
+ dag_ids=dag_id,
+ task_ids=task_id,
+ run_id=dag_run_id,
+ key=xcom_key,
+ map_indexes=patch_body.map_index,
+ )
+ entity = xcom_entity(xcom_read)
+ xcom_query = xcom_read.options(
+ joinedload(entity.task),
+ joinedload(entity.dag_run).joinedload(DR.dag_model),
+ *eager_load_teams(entity.dag_run, DR.dag_model),
)
xcom_entry = session.scalar(xcom_query)
@@ -387,13 +410,10 @@ def update_xcom_entry(
)
try:
- XComModel.set(
+ XComModel.set_for_attempt(
key=xcom_key,
value=patch_body.value,
- dag_id=dag_id,
- task_id=task_id,
- run_id=dag_run_id,
- map_index=patch_body.map_index,
+ task_instance_id=xcom_entry.task_instance_id,
serialize=False,
# Not recomputed from the new value: a custom XCom backend stores only a reference.
mapped_length=xcom_entry.mapped_length,
@@ -432,19 +452,21 @@ def delete_xcom_entry(
map_index: Annotated[int, Query(ge=-1)] = -1,
):
"""Delete an XCom entry."""
- # Delete XCom entry
- result = session.execute(
- delete(XComModel).where(
- XComModel.dag_id == dag_id,
- XComModel.task_id == task_id,
- XComModel.run_id == dag_run_id,
- XComModel.key == xcom_key,
- XComModel.map_index == map_index,
- )
+ read = XComModel.get_many(
+ dag_ids=dag_id,
+ task_ids=task_id,
+ run_id=dag_run_id,
+ key=xcom_key,
+ map_indexes=map_index,
)
-
- if getattr(result, "rowcount", 0) == 0:
+ owner = session.scalar(read.with_only_columns(xcom_entity(read).task_instance_id))
+ if owner is None:
raise HTTPException(
status.HTTP_404_NOT_FOUND,
f"The XCom with key: `{xcom_key}` with mentioned task instance doesn't exist.",
)
+ XComModel.delete_for_attempts(
+ producer_ids=select(TaskInstance.id).where(TaskInstance.id == owner),
+ key=xcom_key,
+ session=session,
+ )
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py b/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py
index 55b1202cbc8..b23bbcfc426 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py
@@ -82,6 +82,7 @@ from airflow.configuration import conf
from airflow.models import DagModel, DagRun
from airflow.models.dag_favorite import DagFavorite
from airflow.models.hitl import HITLDetail
+from airflow.models.renderedtifields import load_legacy_rendered_fields
from airflow.models.taskinstance import TaskInstance
from airflow.utils.state import DagRunState, State, TaskInstanceState
@@ -260,6 +261,7 @@ def get_dags(
defaultload(HITLDetail.task_instance).joinedload(TaskInstance.rendered_task_instance_fields)
)
.where(
+ TaskInstance.working_set.is_(True),
HITLDetail.responded_at.is_(None),
TaskInstance.state.in_((TaskInstanceState.DEFERRED, TaskInstanceState.AWAITING_INPUT)),
)
@@ -267,7 +269,8 @@ def get_dags(
.order_by(TaskInstance.dag_id)
)
- pending_actions = session.execute(pending_actions_select)
+ pending_actions = list(session.execute(pending_actions_select))
+ load_legacy_rendered_fields([detail.task_instance for _, detail in pending_actions], session=session)
# Group pending actions by dag_id
for dag_id, hitl_detail in pending_actions:
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dashboard.py b/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dashboard.py
index 97b2589c76e..f962916313c 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dashboard.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dashboard.py
@@ -108,7 +108,7 @@ def historical_metrics(
)
task_instance_states, task_instances_are_lower_bounds = _compute_state_counts(
TaskInstance,
- dag_run_filters,
+ [*dag_run_filters, TaskInstance.working_set.is_(True)],
session=session,
join=TaskInstance.dag_run,
null_label="no_status",
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/gantt.py b/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/gantt.py
index 7807e3fd6bc..119fb208038 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/gantt.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/gantt.py
@@ -18,7 +18,7 @@
from __future__ import annotations
from fastapi import Depends, HTTPException, status
-from sqlalchemy import or_, select, union_all
+from sqlalchemy import or_, select
from airflow.api_fastapi.auth.managers.models.resource_details import DagAccessEntity
from airflow.api_fastapi.common.db.common import SessionDep
@@ -27,7 +27,6 @@ from airflow.api_fastapi.core_api.datamodels.ui.gantt import GanttResponse, Gant
from airflow.api_fastapi.core_api.openapi.exceptions import create_openapi_http_exception_doc
from airflow.api_fastapi.core_api.security import requires_access_dag
from airflow.models.taskinstance import TaskInstance
-from airflow.models.taskinstancehistory import TaskInstanceHistory
from airflow.utils.state import TaskInstanceState
gantt_router = AirflowRouter(prefix="/gantt", tags=["Gantt"])
@@ -61,7 +60,7 @@ def get_gantt_data(
session: SessionDep,
) -> GanttResponse:
"""Get all task instance tries for Gantt chart."""
- # Exclude mapped tasks (use grid summaries) and UP_FOR_RETRY (already in history)
+ # Pending retries retain timing for backoff; only the retired attempt belongs on the chart.
current_tis = select(
TaskInstance.task_id.label("task_id"),
TaskInstance.task_display_name.label("task_display_name"), # type: ignore[attr-defined]
@@ -78,23 +77,7 @@ def get_gantt_data(
or_(TaskInstance.state != TaskInstanceState.UP_FOR_RETRY, TaskInstance.state.is_(None)),
)
- history_tis = select(
- TaskInstanceHistory.task_id.label("task_id"),
- TaskInstanceHistory.task_display_name.label("task_display_name"),
- TaskInstanceHistory.try_number.label("try_number"),
- TaskInstanceHistory.state.label("state"),
- TaskInstanceHistory.scheduled_dttm.label("scheduled_dttm"),
- TaskInstanceHistory.queued_dttm.label("queued_dttm"),
- TaskInstanceHistory.start_date.label("start_date"),
- TaskInstanceHistory.end_date.label("end_date"),
- ).where(
- TaskInstanceHistory.dag_id == dag_id,
- TaskInstanceHistory.run_id == run_id,
- TaskInstanceHistory.map_index == -1,
- )
-
- combined = union_all(current_tis, history_tis).subquery()
- query = select(combined).order_by(combined.c.task_id, combined.c.try_number)
+ query = current_tis.order_by(TaskInstance.task_id, TaskInstance.try_number)
results = session.execute(query).fetchall()
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/grid.py b/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/grid.py
index e4f9b02f7d1..fbfd20b70e6 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/grid.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/grid.py
@@ -226,6 +226,7 @@ def get_dag_structure(
select(TaskInstance.dag_version_id)
.join(TaskInstance.dag_run)
.where(
+ TaskInstance.working_set.is_(True),
DagRun.id.in_(run_ids),
)
.distinct()
@@ -538,8 +539,11 @@ def get_grid_ti_summaries_stream(
has_note_subq,
)
.outerjoin(DagVersion, TaskInstance.dag_version_id == DagVersion.id)
- .where(TaskInstance.dag_id == dag_id)
- .where(TaskInstance.run_id == run_id)
+ .where(
+ TaskInstance.working_set.is_(True),
+ TaskInstance.dag_id == dag_id,
+ TaskInstance.run_id == run_id,
+ )
.order_by(TaskInstance.task_id)
.execution_options(yield_per=1000)
)
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/security.py b/airflow-core/src/airflow/api_fastapi/core_api/security.py
index 1937cf1e7cc..52d2be28b97 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/security.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/security.py
@@ -366,8 +366,12 @@ class PermittedTIFilter(PermittedDagFilter):
class PermittedXComFilter(PermittedDagFilter):
"""A parameter that filters the permitted XComs for the user."""
+ def __init__(self, value: set[str] | None = None, *, entity=XComModel):
+ super().__init__(value)
+ self.entity = entity
+
def to_orm(self, select: Select) -> Select:
- return select.where(XComModel.dag_id.in_(self.value or set()))
+ return select.where(self.entity.dag_id.in_(self.value or set()))
class PermittedTagFilter(PermittedDagFilter):
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/services/public/dag_run.py b/airflow-core/src/airflow/api_fastapi/core_api/services/public/dag_run.py
index ebd149e05dd..84803c27e21 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/services/public/dag_run.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/services/public/dag_run.py
@@ -41,7 +41,7 @@ from airflow.api_fastapi.common.dagbag import (
get_latest_version_of_dag,
resolve_run_on_latest_version,
)
-from airflow.api_fastapi.common.db.task_instances import eager_load_TI_and_TIH_for_validation
+from airflow.api_fastapi.common.db.task_instances import eager_load_task_instance_for_validation
from airflow.api_fastapi.core_api.datamodels.common import (
BulkActionNotOnExistence,
BulkActionResponse,
@@ -60,8 +60,9 @@ from airflow.api_fastapi.core_api.services.public.common import BulkService
from airflow.api_fastapi.core_api.services.public.task_instances import _emit_state_listener_hooks
from airflow.listeners.listener import get_listener_manager
from airflow.models.dagrun import DagRun, clear_partition_runs
+from airflow.models.renderedtifields import load_legacy_rendered_fields
from airflow.models.taskinstance import TaskInstance
-from airflow.models.xcom import XCOM_RETURN_KEY, XComModel
+from airflow.models.xcom import XCOM_RETURN_KEY, XComModel, xcom_entity
from airflow.utils.session import create_session_async
from airflow.utils.state import State, TaskInstanceState
@@ -111,6 +112,7 @@ def dry_run_clear_dag_run(
existing_task_ids = set(
session.scalars(
select(TaskInstance.task_id).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == dag_id,
TaskInstance.run_id == dag_run_id,
)
@@ -119,7 +121,9 @@ def dry_run_clear_dag_run(
new_task_ids = sorted(set(latest_dag.task_ids) - existing_task_ids)
return [NewTaskResponse(task_id=task_id, task_display_name=task_id) for task_id in new_task_ids]
- ti_query = eager_load_TI_and_TIH_for_validation(select(TaskInstance))
+ ti_query = eager_load_task_instance_for_validation(
+ select(TaskInstance).where(TaskInstance.working_set.is_(True))
+ )
ti_query = ti_query.where(
TaskInstance.dag_id == dag_id,
TaskInstance.run_id == dag_run_id,
@@ -128,7 +132,9 @@ def dry_run_clear_dag_run(
ti_query = ti_query.where(
TaskInstance.state.in_([TaskInstanceState.FAILED, TaskInstanceState.UPSTREAM_FAILED])
)
- return list(session.scalars(ti_query))
+ task_instances = list(session.scalars(ti_query))
+ load_legacy_rendered_fields(task_instances, session=session)
+ return task_instances
def perform_clear_dag_run(
@@ -259,22 +265,25 @@ class DagRunWaiter:
async def _serialize_xcoms(self) -> dict[str, Any]:
if self.result_task_ids is None: # Return dag-author-specified results.
- xcom_query = XComModel.get_many(
+ xcom_read = XComModel.get_many(
run_id=self.run_id,
key=XCOM_RETURN_KEY,
dag_ids=self.dag_id,
)
- xcom_query = xcom_query.where(XComModel.dag_result.is_(True))
+ entity = xcom_entity(xcom_read)
+ xcom_query = xcom_read.where(entity.dag_result.is_(True))
else: # Explicitly API user-specified results.
- xcom_query = XComModel.get_many(
+ xcom_read = XComModel.get_many(
run_id=self.run_id,
key=XCOM_RETURN_KEY,
task_ids=self.result_task_ids,
dag_ids=self.dag_id,
)
+ xcom_query = xcom_read
+ entity = xcom_entity(xcom_read)
# XComModel.get_many() orders XCom by timestamp. Reset this to make
# mapped task results stable since execution order is not guaranteed.
- xcom_query = xcom_query.order_by(None).order_by(XComModel.task_id, XComModel.map_index)
+ xcom_query = xcom_query.order_by(None).order_by(entity.task_id, entity.map_index)
async with create_session_async() as session:
xcom_results = (await session.scalars(xcom_query)).all()
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py b/airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py
index 1c9a92768c0..b8a443e4a66 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py
@@ -51,6 +51,7 @@ from airflow.api_fastapi.core_api.services.public.common import BulkService
from airflow.configuration import conf
from airflow.listeners.listener import get_listener_manager
from airflow.models.dag import DagModel
+from airflow.models.renderedtifields import load_legacy_rendered_fields
from airflow.models.taskinstance import TaskInstance as TI
from airflow.serialization.definitions.dag import SerializedDAG
from airflow.state.metastore import _get_db_backend
@@ -175,7 +176,7 @@ def _reload_tis_with_rendered_fields(tis: list[TI], session: Session) -> list[TI
"""
if not tis:
return tis
- return list(
+ reloaded = list(
session.scalars(
select(TI)
.options(joinedload(TI.rendered_task_instance_fields))
@@ -183,6 +184,8 @@ def _reload_tis_with_rendered_fields(tis: list[TI], session: Session) -> list[TI
.execution_options(populate_existing=True)
).all()
)
+ load_legacy_rendered_fields(reloaded, session=session)
+ return reloaded
def _patch_ti_validate_request(
@@ -201,7 +204,7 @@ def _patch_ti_validate_request(
query = (
select(TI)
- .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == task_id)
+ .where(TI.working_set.is_(True), TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == task_id)
.options(joinedload(TI.rendered_task_instance_fields))
)
if map_index is not None:
@@ -244,6 +247,7 @@ def _get_task_group_task_instances(
query = (
select(TI)
.where(
+ TI.working_set.is_(True),
TI.dag_id == dag_id,
TI.run_id == dag_run_id,
TI.task_id.in_(task_ids),
@@ -481,7 +485,10 @@ class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
# Filter at database level using exact tuple matching instead of fetching all combinations
# and filtering in Python
task_keys_list = list(task_keys)
- query = select(TI).where(tuple_(TI.dag_id, TI.run_id, TI.task_id, TI.map_index).in_(task_keys_list))
+ query = select(TI).where(
+ TI.working_set.is_(True),
+ tuple_(TI.dag_id, TI.run_id, TI.task_id, TI.map_index).in_(task_keys_list),
+ )
task_instances = self.session.scalars(query).all()
task_instances_map = {
@@ -601,6 +608,7 @@ class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
batch_task_instances = self.session.scalars(
select(TI).where(
+ TI.working_set.is_(True),
TI.dag_id.in_(all_dag_ids),
TI.run_id.in_(all_run_ids),
TI.task_id.in_(all_task_ids),
@@ -656,7 +664,7 @@ class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
try:
# Handle deletion of specific (dag_id, dag_run_id, task_id, map_index) tuples
if delete_specific_map_index_task_keys:
- task_instances_map, matched_task_keys, not_found_task_keys = self._categorize_task_instances(
+ _, matched_task_keys, not_found_task_keys = self._categorize_task_instances(
delete_specific_map_index_task_keys
)
not_found_task_ids = [
@@ -672,7 +680,13 @@ class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
for task_key in matched_task_keys:
dag_id, run_id, task_id, map_index = task_key
- self.session.delete(task_instances_map[task_key])
+ TI.delete_attempts(
+ dag_id=dag_id,
+ run_id=run_id,
+ task_id=task_id,
+ map_index=map_index,
+ session=self.session,
+ )
results.success.append(f"{dag_id}.{run_id}.{task_id}[{map_index}]")
# Handle deletion of all map indexes for certain (dag_id, dag_run_id, task_id) tuples
@@ -683,6 +697,7 @@ class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
batch_task_instances = self.session.scalars(
select(TI).where(
+ TI.working_set.is_(True),
TI.dag_id.in_(all_dag_ids),
TI.run_id.in_(all_run_ids),
TI.task_id.in_(all_task_ids),
@@ -707,8 +722,11 @@ class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]):
detail=f"No task instances found for dag_id: {dag_id}, run_id: {run_id}, task_id: {task_id}",
)
+ if all_task_instances:
+ TI.delete_attempts(
+ dag_id=dag_id, run_id=run_id, task_id=task_id, session=self.session
+ )
for ti in all_task_instances:
- self.session.delete(ti)
results.success.append(f"{dag_id}.{run_id}.{task_id}[{ti.map_index}]")
except HTTPException as e:
diff --git a/airflow-core/src/airflow/api_fastapi/execution_api/app.py b/airflow-core/src/airflow/api_fastapi/execution_api/app.py
index 4b881cda03c..29b6793c6da 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/app.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/app.py
@@ -392,7 +392,7 @@ class InProcessExecutionAPI:
from airflow.api_fastapi.execution_api.routes.connections import has_connection_access
from airflow.api_fastapi.execution_api.routes.variables import has_variable_access
from airflow.api_fastapi.execution_api.routes.xcoms import has_xcom_access
- from airflow.api_fastapi.execution_api.security import _jwt_bearer
+ from airflow.api_fastapi.execution_api.security import _IN_PROCESS_NON_TI_CALLER, _jwt_bearer
# Give this app its own lifespan + services registry so that stubbing services
# (e.g. JWTValidator) doesn't affect the module-level ``lifespan.registry``.
@@ -411,7 +411,14 @@ class InProcessExecutionAPI:
from uuid import UUID
ti_id = UUID(
- request.path_params.get("task_instance_id", "00000000-0000-0000-0000-000000000000")
+ request.path_params.get("task_instance_id")
+ or request.headers.get("X-Airflow-In-Process-Attempt-Id")
+ or "00000000-0000-0000-0000-000000000000"
+ )
+ # Watchers and other trusted in-process callers may have no task identity.
+ request.scope[_IN_PROCESS_NON_TI_CALLER] = (
+ "task_instance_id" not in request.path_params
+ and "X-Airflow-In-Process-Attempt-Id" not in request.headers
)
claims = TIClaims(scope="execution")
return TIToken(id=ti_id, claims=claims)
diff --git a/airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py b/airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py
index 4b5402d2342..cf7ecdcfadd 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py
@@ -35,7 +35,7 @@ from opentelemetry import trace
from opentelemetry.trace import StatusCode
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from pydantic import JsonValue, ValidationError
-from sqlalchemy import and_, exists, func, or_, tuple_, update
+from sqlalchemy import and_, func, or_, tuple_, update
from sqlalchemy.engine import CursorResult
from sqlalchemy.exc import DataError, NoResultFound, SQLAlchemyError
from sqlalchemy.orm import contains_eager, joinedload
@@ -82,6 +82,7 @@ from airflow.api_fastapi.execution_api.security import (
get_team_name_for_ti,
issue_execution_token,
require_auth,
+ skip_auto_ti_attempt_live,
)
from airflow.api_fastapi.execution_api.services.task_instances import (
client_supports_arg_bindings,
@@ -97,10 +98,9 @@ from airflow.models.dagrun import DagRun as DR
from airflow.models.hitl import HITLDetail
from airflow.models.log import Log
from airflow.models.taskinstance import TaskInstance as TI, _stop_remaining_tasks
-from airflow.models.taskinstancehistory import TaskInstanceHistory as TIH
from airflow.models.taskreschedule import TaskReschedule
from airflow.models.trigger import Trigger, handle_event_submit
-from airflow.models.xcom import XComModel
+from airflow.models.xcom import build_xcom_read_query, xcom_entity
from airflow.serialization.definitions.assets import SerializedAsset, SerializedAssetUniqueKey
from airflow.state import get_state_backend
from airflow.triggers.base import TriggerEvent
@@ -187,7 +187,7 @@ def ti_run(
.select_from(TI)
.join(DR, and_(TI.dag_id == DR.dag_id, TI.run_id == DR.run_id))
.join(DagModel, TI.dag_id == DagModel.dag_id)
- .where(TI.id == task_instance_id)
+ .where(TI.id == task_instance_id, TI.working_set.is_(True))
.with_for_update(of=TI)
)
try:
@@ -252,6 +252,7 @@ def ti_run(
session.add(
Log(
event=TaskInstanceState.RUNNING.value,
+ task_instance_id=task_instance_id,
task_id=ti.task_id,
dag_id=ti.dag_id,
run_id=ti.run_id,
@@ -306,16 +307,9 @@ def ti_run(
# However, do not clear it for deferral
xcom_keys = []
if not ti.next_method:
- map_index = None if ti.map_index < 0 else ti.map_index
- xcom_query = select(XComModel.key).where(
- XComModel.dag_id == ti.dag_id,
- XComModel.task_id == ti.task_id,
- XComModel.run_id == ti.run_id,
- )
- if map_index is not None:
- xcom_query = xcom_query.where(XComModel.map_index == map_index)
-
- xcom_keys = list(session.scalars(xcom_query))
+ read = build_xcom_read_query(producer_ids=select(TI.id).where(TI.id == task_instance_id))
+ entity = xcom_entity(read)
+ xcom_keys = list(session.scalars(read.with_only_columns(entity.key)))
task_reschedule_count = (
session.scalar(
select(func.count(TaskReschedule.id)).where(TaskReschedule.ti_id == task_instance_id)
@@ -387,6 +381,7 @@ def ti_run(
HTTP_422_UNPROCESSABLE_CONTENT: {"description": "Invalid payload for the state transition"},
},
)
+@skip_auto_ti_attempt_live
def ti_update_state(
task_instance_id: UUID,
ti_patch_payload: Annotated[TIStateUpdate, Body()],
@@ -412,9 +407,9 @@ def ti_update_state(
.execution_options(populate_existing=True)
)
if ti is None:
- if session.scalar(select(TIH.task_instance_id).where(TIH.task_instance_id == task_instance_id)):
- return Response(status_code=status.HTTP_204_NO_CONTENT)
raise HTTPException(status_code=404, detail={"reason": "not_found"})
+ if ti.working_set is None:
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
if (ti.hostname, ti.pid) != (ti_patch_payload.hostname, ti_patch_payload.pid) or (
ti_patch_payload.hostname is None or ti_patch_payload.pid is None
):
@@ -444,6 +439,7 @@ def ti_update_state(
TI.hostname,
DR.logical_date,
DagModel.owners,
+ TI.working_set,
)
.select_from(TI)
.join(DR, and_(TI.dag_id == DR.dag_id, TI.run_id == DR.run_id))
@@ -463,6 +459,7 @@ def ti_update_state(
hostname,
logical_date,
owners,
+ working_set,
) = session.execute(old).one()
log.debug(
"Retrieved current task instance state",
@@ -471,18 +468,10 @@ def ti_update_state(
max_tries=max_tries,
)
except NoResultFound:
- if IdentifyRetiredTaskStateUpdates.is_applied:
- archived_in_history = bool(
- session.scalar(select(exists().where(TIH.task_instance_id == task_instance_id)))
- )
- _raise_ti_not_in_live_table(task_instance_id, archived_in_history=archived_in_history)
- log.error("Task Instance not found")
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail={
- "reason": "not_found",
- "message": "Task Instance not found",
- },
+ _raise_ti_not_in_live_table(task_instance_id, archived_in_history=False)
+ if working_set is None:
+ _raise_ti_not_in_live_table(
+ task_instance_id, archived_in_history=IdentifyRetiredTaskStateUpdates.is_applied
)
# TIStateUpdate can include terminal and intermediate states. This idempotency check handles
@@ -529,7 +518,7 @@ def ti_update_state(
)
if "rendered_map_index" in data:
data["_rendered_map_index"] = data.pop("rendered_map_index")
- query = update(TI).where(TI.id == task_instance_id).values(data)
+ query = update(TI).where(TI.working_set.is_(True), TI.id == task_instance_id).values(data)
asset_callbacks: Sequence[Callable[[], None]] = ()
try:
@@ -551,7 +540,9 @@ def ti_update_state(
payload=ti_patch_payload,
)
session.rollback()
- ti = session.get(TI, task_instance_id, with_for_update={"of": TI})
+ ti = session.scalar(
+ select(TI).where(TI.id == task_instance_id, TI.working_set.is_(True)).with_for_update(of=TI)
+ )
if session.bind is not None:
query = TI.duration_expression_update(timezone.utcnow(), query, session.bind)
query = query.values(state=(updated_state := TaskInstanceState.FAILED))
@@ -562,6 +553,13 @@ def ti_update_state(
# https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers
try:
result = session.execute(query)
+ if (
+ isinstance(ti_patch_payload, TIRetryStatePayload)
+ and updated_state == TaskInstanceState.UP_FOR_RETRY
+ ):
+ ti = session.scalar(select(TI).where(TI.id == task_instance_id))
+ if ti is not None:
+ ti = ti.prepare_db_for_next_try(session)
log.info(
"Task instance state updated",
new_state=updated_state,
@@ -570,6 +568,7 @@ def ti_update_state(
session.add(
Log(
event=updated_state.value,
+ task_instance_id=task_instance_id,
task_id=task_id,
dag_id=dag_id,
run_id=run_id,
@@ -718,7 +717,7 @@ def _create_ti_state_update_query_and_update_state(
) -> tuple[Update, TaskInstanceState, Sequence[Callable[[], None]]]:
asset_callbacks: Sequence[Callable[[], None]] = ()
if isinstance(ti_patch_payload, (TITerminalStatePayload, TIRetryStatePayload, TISuccessStatePayload)):
- ti = session.get(TI, task_instance_id, with_for_update={"of": TI})
+ ti = session.scalar(select(TI).where(TI.id == task_instance_id).with_for_update(of=TI))
updated_state = TaskInstanceState(ti_patch_payload.state.value)
if session.bind is not None:
query = TI.duration_expression_update(ti_patch_payload.end_date, query, session.bind)
@@ -734,9 +733,6 @@ def _create_ti_state_update_query_and_update_state(
retry_delay_override = ti_patch_payload.retry_delay_seconds
retry_reason = ti_patch_payload.retry_reason[:500] if ti_patch_payload.retry_reason else None
if ti is not None:
- # Snapshot the finished try onto the TI *before* archiving so record_ti()
- # copies the values into task_instance_history (it reads attrs off the
- # ti object and cannot see the live-row UPDATE built below).
ti.retry_delay_override = retry_delay_override
ti.retry_reason = retry_reason
ti.end_date = ti_patch_payload.end_date
@@ -758,8 +754,6 @@ def _create_ti_state_update_query_and_update_state(
_emit_task_span(ti, state=updated_state)
except Exception:
log.warning("Failed to emit task span", exc_info=True)
- if isinstance(ti_patch_payload, TIRetryStatePayload) and ti is not None:
- ti.prepare_db_for_next_try(session=session)
elif isinstance(ti_patch_payload, TIDeferredStatePayload):
# Calculate timeout if it was passed
timeout = None
@@ -803,7 +797,7 @@ def _create_ti_state_update_query_and_update_state(
#
# Fixed lock order (TaskInstance -> HITLDetail), matching the Core API response path, so a
# human response racing this park transition cannot deadlock.
- ti = session.get(TI, task_instance_id, with_for_update={"of": TI})
+ ti = session.scalar(select(TI).where(TI.id == task_instance_id).with_for_update(of=TI))
# Lock only the hitl_detail row (of=...): HITLDetail eager-joins task_instance (lazy="joined"),
# and Postgres rejects FOR UPDATE against the nullable side of that outer join.
hitl_detail = session.scalar(
@@ -858,7 +852,7 @@ def _create_ti_state_update_query_and_update_state(
if session.bind is not None:
query = TI.duration_expression_update(timezone.utcnow(), query, session.bind)
query = query.values(state=TaskInstanceState.FAILED)
- ti = session.get(TI, task_instance_id, with_for_update={"of": TI})
+ ti = session.scalar(select(TI).where(TI.id == task_instance_id).with_for_update(of=TI))
if ti is not None:
_handle_fail_fast_for_dag(ti=ti, dag_id=dag_id, session=session, dag_bag=dag_bag)
return query, TaskInstanceState.FAILED, ()
@@ -907,7 +901,9 @@ def ti_skip_downstream(
now = timezone.utcnow()
tasks = ti_patch_payload.tasks
- query_result = session.execute(select(TI.dag_id, TI.run_id).where(TI.id == task_instance_id))
+ query_result = session.execute(
+ select(TI.dag_id, TI.run_id).where(TI.working_set.is_(True), TI.id == task_instance_id)
+ )
row_result = query_result.fetchone()
if row_result is None:
raise HTTPException(
@@ -939,6 +935,7 @@ def ti_skip_downstream(
query = (
update(TI)
.where(
+ TI.working_set.is_(True),
TI.dag_id == dag_id,
TI.run_id == run_id,
or_(TI.task_id.in_(task_ids), tuple_(TI.task_id, TI.map_index).in_(ti_keys)),
@@ -1044,6 +1041,7 @@ def update_dag_run_note(
]
),
)
+@skip_auto_ti_attempt_live
async def ti_heartbeat(
task_instance_id: UUID,
ti_payload: TIHeartbeatInfo,
@@ -1060,6 +1058,7 @@ async def ti_heartbeat(
await session.execute(
update(TI)
.where(
+ TI.working_set.is_(True),
TI.id == task_instance_id,
TI.state == TaskInstanceState.RUNNING,
TI.hostname == ti_payload.hostname,
@@ -1075,21 +1074,25 @@ async def ti_heartbeat(
log.debug("Heartbeat fast path missed; falling back to diagnostic checks")
- old = select(TI.state, TI.hostname, TI.pid).where(TI.id == task_instance_id).with_for_update()
+ old = (
+ select(TI.state, TI.hostname, TI.pid, TI.working_set)
+ .where(TI.id == task_instance_id)
+ .with_for_update()
+ )
try:
- (previous_state, hostname, pid) = (await session.execute(old)).one()
+ (previous_state, hostname, pid, working_set) = (await session.execute(old)).one()
log.debug(
"Retrieved current task state", state=previous_state, current_hostname=hostname, current_pid=pid
)
except NoResultFound:
- # Check if the TI exists in the Task Instance History table.
- # If it does, it was likely cleared while running, so return 410 Gone
+ _raise_ti_not_in_live_table(task_instance_id, archived_in_history=False)
+ if working_set is None:
+ # A retired attempt was likely cleared while running, so return 410 Gone
# instead of 404 Not Found to give the client a more specific signal.
- archived_in_history = bool(
- await session.scalar(select(exists().where(TIH.task_instance_id == task_instance_id)))
+ _raise_ti_not_in_live_table(
+ task_instance_id, archived_in_history=IdentifyRetiredTaskStateUpdates.is_applied
)
- _raise_ti_not_in_live_table(task_instance_id, archived_in_history=archived_in_history)
if hostname != ti_payload.hostname or pid != ti_payload.pid:
log.warning(
@@ -1122,7 +1125,9 @@ async def ti_heartbeat(
# Update the last heartbeat time!
await session.execute(
- update(TI).where(TI.id == task_instance_id).values(last_heartbeat_at=timezone.utcnow())
+ update(TI)
+ .where(TI.working_set.is_(True), TI.id == task_instance_id)
+ .values(last_heartbeat_at=timezone.utcnow())
)
log.debug("Heartbeat updated", state=previous_state)
@@ -1159,12 +1164,9 @@ def ti_put_rtif(
log.info("Updating RenderedTaskInstanceFields", field_count=len(put_rtif_payload))
task_instance = session.scalar(select(TI).where(TI.id == task_instance_id))
- if not task_instance:
+ if task_instance is None or task_instance.working_set is None:
# On retry/clear, the server regenerates the TI id. Return 410 for the stale id.
- archived_in_history = bool(
- session.scalar(select(exists().where(TIH.task_instance_id == task_instance_id)))
- )
- _raise_ti_not_in_live_table(task_instance_id, archived_in_history=archived_in_history)
+ _raise_ti_not_in_live_table(task_instance_id, archived_in_history=task_instance is not None)
task_instance.update_rtif(put_rtif_payload, session=session)
log.debug("RenderedTaskInstanceFields updated successfully")
@@ -1274,7 +1276,7 @@ def get_task_instance_count(
states: Annotated[list[str] | None, Query()] = None,
) -> int:
"""Get the count of task instances matching the given criteria."""
- query = select(func.count()).select_from(TI).where(TI.dag_id == dag_id)
+ query = select(func.count()).select_from(TI).where(TI.dag_id == dag_id, TI.working_set.is_(True))
if task_ids:
query = query.where(TI.task_id.in_(task_ids))
@@ -1340,7 +1342,9 @@ async def get_previous_task_instance(
select(TI)
.join(DR, (TI.dag_id == DR.dag_id) & (TI.run_id == DR.run_id))
.options(contains_eager(TI.dag_run).load_only(DR.logical_date))
- .where(TI.dag_id == dag_id, TI.task_id == task_id, TI.map_index == map_index)
+ .where(
+ TI.dag_id == dag_id, TI.task_id == task_id, TI.map_index == map_index, TI.working_set.is_(True)
+ )
.order_by(DR.logical_date.desc())
)
@@ -1384,7 +1388,7 @@ def get_task_instance_states(
"""Get the states for Task Instances with the given criteria."""
run_id_task_state_map: dict[str, dict[str, Any]] = defaultdict(dict)
- query = select(TI).where(TI.dag_id == dag_id)
+ query = select(TI).where(TI.working_set.is_(True), TI.dag_id == dag_id)
if task_ids:
query = query.where(TI.task_id.in_(task_ids))
@@ -1426,7 +1430,12 @@ async def get_task_instance_breadcrumbs(
result = (
await session.execute(
select(TI.task_id, TI.map_index, TI.state, TI.operator, TI.duration)
- .where(TI.dag_id == dag_id, TI.run_id == run_id, TI.state.in_(TerminalTIState))
+ .where(
+ TI.working_set.is_(True),
+ TI.dag_id == dag_id,
+ TI.run_id == run_id,
+ TI.state.in_(TerminalTIState),
+ )
.order_by(TI.task_id, TI.map_index)
)
).mappings()
@@ -1474,6 +1483,7 @@ def _get_group_tasks(
# First get all task instances to get the task_id, map_index pairs
group_tasks = session.scalars(
select(TI).where(
+ TI.working_set.is_(True),
TI.dag_id == dag_id,
TI.task_id.in_(task.task_id for task in task_group.iter_tasks()),
*([TI.logical_date.in_(logical_dates)] if logical_dates else []),
diff --git a/airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py b/airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py
index 08b773076eb..d0444a392b8 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py
@@ -19,10 +19,11 @@ from __future__ import annotations
import logging
from typing import Annotated
+from uuid import UUID
from fastapi import APIRouter, Body, Depends, HTTPException, Path, Query, Request, Response, status
from pydantic import JsonValue
-from sqlalchemy import delete
+from sqlalchemy import select
from sqlalchemy.sql.selectable import Select
from airflow.api_fastapi.common.db.common import SessionDep
@@ -33,8 +34,10 @@ from airflow.api_fastapi.execution_api.datamodels.xcom import (
XComSequenceIndexResponse,
XComSequenceSliceResponse,
)
-from airflow.api_fastapi.execution_api.security import CurrentTIToken
-from airflow.models.xcom import XCOM_RETURN_KEY, XComModel
+from airflow.api_fastapi.execution_api.security import _IN_PROCESS_NON_TI_CALLER, CurrentTIToken
+from airflow.api_fastapi.execution_api.versions.v2026_10_30 import IdentifyRetiredTaskStateUpdates
+from airflow.models.taskinstance import TaskInstance
+from airflow.models.xcom import XCOM_RETURN_KEY, XComModel, xcom_entity
from airflow.utils.db import get_query_count
@@ -123,14 +126,14 @@ async def xcom_query(
key: str,
map_index: Annotated[int | None, Query()] = None,
) -> Select:
- query = XComModel.get_many(
+ xcom_read = XComModel.get_many(
run_id=run_id,
key=key,
task_ids=task_id,
dag_ids=dag_id,
map_indexes=map_index,
)
- return query
+ return xcom_read
@router.get(
@@ -145,17 +148,19 @@ def get_mapped_xcom_by_index(
offset: int,
session: SessionDep,
) -> XComSequenceIndexResponse:
- xcom_query = XComModel.get_many(
+ xcom_read = XComModel.get_many(
run_id=run_id,
key=key,
task_ids=task_id,
dag_ids=dag_id,
)
+ entity = xcom_entity(xcom_read)
+ xcom_query = xcom_read
xcom_query = xcom_query.order_by(None)
if offset >= 0:
- xcom_query = xcom_query.order_by(XComModel.map_index.asc()).offset(offset)
+ xcom_query = xcom_query.order_by(entity.map_index.asc()).offset(offset)
else:
- xcom_query = xcom_query.order_by(XComModel.map_index.desc()).offset(-1 - offset)
+ xcom_query = xcom_query.order_by(entity.map_index.desc()).offset(-1 - offset)
result: tuple[XComModel] | None
if (result := session.scalars(xcom_query.limit(1)).first()) is None:
@@ -196,13 +201,15 @@ def get_mapped_xcom_by_slice(
params: Annotated[GetXComSliceFilterParams, Query()],
session: SessionDep,
) -> XComSequenceSliceResponse:
- query = XComModel.get_many(
+ xcom_read = XComModel.get_many(
run_id=run_id,
key=key,
task_ids=task_id,
dag_ids=dag_id,
include_prior_dates=params.include_prior_dates,
)
+ entity = xcom_entity(xcom_read)
+ query = xcom_read
query = query.order_by(None)
step = params.step or 1
@@ -213,25 +220,25 @@ def get_mapped_xcom_by_slice(
if (start := params.start) is None:
if (stop := params.stop) is None:
if step >= 0:
- query = query.order_by(XComModel.map_index.asc())
+ query = query.order_by(entity.map_index.asc())
else:
- query = query.order_by(XComModel.map_index.desc())
+ query = query.order_by(entity.map_index.desc())
step = -step
elif stop >= 0:
- query = query.order_by(XComModel.map_index.asc())
+ query = query.order_by(entity.map_index.asc())
if step >= 0:
query = query.limit(stop)
else:
query = query.offset(stop + 1)
else:
- query = query.order_by(XComModel.map_index.desc())
+ query = query.order_by(entity.map_index.desc())
step = -step
if step > 0:
query = query.limit(-stop - 1)
else:
query = query.offset(-stop)
elif start >= 0:
- query = query.order_by(XComModel.map_index.asc())
+ query = query.order_by(entity.map_index.asc())
if (stop := params.stop) is None:
if step >= 0:
query = query.offset(start)
@@ -245,7 +252,7 @@ def get_mapped_xcom_by_slice(
else:
query = _get_sliced_query_or_empty(query, stop + 1, start + 1)
else:
- query = query.order_by(XComModel.map_index.desc())
+ query = query.order_by(entity.map_index.desc())
step = -step
if (stop := params.stop) is None:
if step > 0:
@@ -260,7 +267,7 @@ def get_mapped_xcom_by_slice(
else:
query = _get_sliced_query_or_empty(query, -stop, -start)
- values = [row.value for row in session.execute(query.with_only_columns(XComModel.value)).all()]
+ values = [row.value for row in session.execute(query.with_only_columns(entity.value)).all()]
if step != 1:
values = values[::step]
return XComSequenceSliceResponse(values)
@@ -322,23 +329,55 @@ def get_xcom(
key: Annotated[str, Path(min_length=1)],
session: SessionDep,
params: Annotated[GetXcomFilterParams, Query()],
+ token=CurrentTIToken,
) -> XComResponse:
"""Get an Airflow XCom from database - not other XCom Backends."""
- xcom_query = XComModel.get_many(
+ owner = session.execute(
+ select(TaskInstance.id, TaskInstance.working_set)
+ .where(
+ TaskInstance.id == token.id,
+ TaskInstance.dag_id == dag_id,
+ TaskInstance.run_id == run_id,
+ TaskInstance.task_id == task_id,
+ TaskInstance.map_index == params.map_index,
+ )
+ .limit(1)
+ ).first()
+ if (
+ owner is not None
+ and owner.working_set is None
+ and not params.include_prior_dates
+ and params.offset is None
+ ):
+ identify_retired = IdentifyRetiredTaskStateUpdates.is_applied
+ raise HTTPException(
+ status_code=status.HTTP_410_GONE if identify_retired else status.HTTP_404_NOT_FOUND,
+ detail={
+ "reason": "not_found",
+ "message": (
+ "Task Instance not found in the working set; its attempt has been archived"
+ if identify_retired
+ else "Task Instance not found"
+ ),
+ },
+ )
+ xcom_read = XComModel.get_many(
run_id=run_id,
key=key,
task_ids=task_id,
dag_ids=dag_id,
include_prior_dates=params.include_prior_dates,
)
+ entity = xcom_entity(xcom_read)
+ xcom_query = xcom_read
if params.offset is not None:
- xcom_query = xcom_query.where(XComModel.value.is_not(None)).order_by(None)
+ xcom_query = xcom_query.where(entity.value.is_not(None)).order_by(None)
if params.offset >= 0:
- xcom_query = xcom_query.order_by(XComModel.map_index.asc()).offset(params.offset)
+ xcom_query = xcom_query.order_by(entity.map_index.asc()).offset(params.offset)
else:
- xcom_query = xcom_query.order_by(XComModel.map_index.desc()).offset(-1 - params.offset)
+ xcom_query = xcom_query.order_by(entity.map_index.desc()).offset(-1 - params.offset)
else:
- xcom_query = xcom_query.where(XComModel.map_index == params.map_index)
+ xcom_query = xcom_query.where(entity.map_index == params.map_index)
# We use `BaseXCom.get_many` to fetch XComs directly from the database, bypassing the XCom Backend.
# This avoids deserialization via the backend (e.g., from a remote storage like S3) and instead
@@ -385,6 +424,7 @@ def set_xcom(
task_id: str,
key: Annotated[str, Path(min_length=1)],
session: SessionDep,
+ request: Request,
value: Annotated[
JsonValue,
Body(
@@ -410,6 +450,7 @@ def set_xcom(
mapped_length: Annotated[
int | None, Query(ge=0, description="Number of mapped tasks this value expands into")
] = None,
+ token=CurrentTIToken,
):
"""Set an Airflow XCom."""
from airflow.configuration import conf
@@ -451,13 +492,18 @@ def set_xcom(
# (the mapped task would fail in a moment as it can't be expanded anyway.)
try:
# We expect serialised value from the caller - sdk, do not serialise in here
- XComModel.set(
+ XComModel.set_for_attempt(
key=key,
value=value,
- run_id=run_id,
- task_id=task_id,
- dag_id=dag_id,
- map_index=map_index,
+ task_instance_id=_writer_id(
+ token.id,
+ dag_id=dag_id,
+ run_id=run_id,
+ task_id=task_id,
+ map_index=map_index,
+ request=request,
+ session=session,
+ ),
serialize=False,
dag_result=dag_result,
mapped_length=mapped_length,
@@ -488,15 +534,49 @@ def delete_xcom(
run_id: str,
task_id: str,
key: Annotated[str, Path(min_length=1)],
+ request: Request,
map_index: Annotated[int, Query()] = -1,
+ token=CurrentTIToken,
):
"""Delete a single XCom Value."""
- query = delete(XComModel).where(
- XComModel.key == key,
- XComModel.run_id == run_id,
- XComModel.task_id == task_id,
- XComModel.dag_id == dag_id,
- XComModel.map_index == map_index,
+ owner = _writer_id(
+ token.id,
+ dag_id=dag_id,
+ run_id=run_id,
+ task_id=task_id,
+ map_index=map_index,
+ request=request,
+ session=session,
+ )
+ XComModel.delete_for_attempts(
+ producer_ids=select(TaskInstance.id).where(TaskInstance.id == owner),
+ key=key,
+ session=session,
)
- session.execute(query)
return {"message": f"XCom with key: {key} successfully deleted."}
+
+
+def _writer_id(
+ attempt_id: UUID,
+ *,
+ dag_id: str,
+ run_id: str,
+ task_id: str,
+ map_index: int,
+ request: Request,
+ session: SessionDep,
+) -> UUID:
+ query = select(TaskInstance.id).where(
+ TaskInstance.dag_id == dag_id,
+ TaskInstance.run_id == run_id,
+ TaskInstance.task_id == task_id,
+ TaskInstance.map_index == map_index,
+ )
+ if request.scope.get(_IN_PROCESS_NON_TI_CALLER):
+ query = query.where(TaskInstance.working_set.is_(True))
+ else:
+ query = query.where(TaskInstance.id == attempt_id)
+ owner = session.scalar(query)
+ if owner is None:
+ raise HTTPException(status.HTTP_403_FORBIDDEN, detail={"reason": "attempt_coordinates_mismatch"})
+ return owner
diff --git a/airflow-core/src/airflow/api_fastapi/execution_api/security.py b/airflow-core/src/airflow/api_fastapi/execution_api/security.py
index c85980db08b..040467ce34f 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/security.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/security.py
@@ -42,6 +42,8 @@ Enforcement flow:
by ``ExecutionAPIRoute`` from ``token:*`` Security scopes).
- ``ti:self`` scope — checks that the JWT ``sub`` matches the
``{task_instance_id}`` path parameter.
+ - Mutating task requests — checks that the attempt UUID still exists
+ in the live TI table. Already-admitted requests may finish after retirement.
3. ``ExecutionAPIRoute`` precomputes ``allowed_token_types`` from
``token:*`` Security scopes at route registration time. Routes
without explicit ``token:*`` scopes default to execution-only.
@@ -67,7 +69,8 @@ Why ``ExecutionAPIRoute`` is needed:
# Disable future annotations in this file to work around https://github.com/fastapi/fastapi/issues/13056
# ruff: noqa: I002
-from typing import Any, get_args
+from collections.abc import Callable
+from typing import Any, ParamSpec, TypeVar, get_args
import structlog
import svcs
@@ -81,12 +84,26 @@ from sqlalchemy import select
from airflow.api_fastapi.auth.tokens import JWTGenerator, JWTValidator
from airflow.api_fastapi.execution_api.datamodels.token import TIClaims, TIToken, TokenScope
from airflow.api_fastapi.execution_api.deps import DepContainer
+from airflow.models.callback import Callback
+from airflow.models.taskinstance import TaskInstance
+from airflow.utils.session import create_session_async
log = structlog.get_logger(logger_name=__name__)
VALID_TOKEN_TYPES: frozenset[str] = frozenset(get_args(TokenScope))
_REQUEST_SCOPE_TOKEN_KEY = "ti_token"
+_REQUEST_SCOPE_LIVE_ATTEMPT_KEY = "live_attempt_checked"
+_IN_PROCESS_NON_TI_CALLER = "airflow_in_process_non_ti_caller"
+_SKIP_AUTO_TI_ATTEMPT_LIVE = "skip_auto_ti_attempt_live"
+_P = ParamSpec("_P")
+_R = TypeVar("_R")
+
+
+def skip_auto_ti_attempt_live(endpoint: Callable[_P, _R]) -> Callable[_P, _R]:
+ """Mark a route that checks attempt liveness itself, so ``require_auth`` skips its automatic check."""
+ setattr(endpoint, _SKIP_AUTO_TI_ATTEMPT_LIVE, True)
+ return endpoint
class JWTBearer(HTTPBearer):
@@ -150,7 +167,7 @@ async def require_auth(
token: TIToken = Depends(_jwt_bearer),
) -> TIToken:
"""
- Security dependency that enforces token type and ``ti:self`` scope.
+ Enforce token type, self scopes, and live attempt identity for mutations.
Used via ``Security(require_auth)`` on routers. ``SecurityScopes`` are
accumulated by FastAPI from all parent ``Security()`` declarations.
@@ -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,
+ )
+ request.scope[_REQUEST_SCOPE_LIVE_ATTEMPT_KEY] = True
+
return token
+async def _require_live_attempt(token: TIToken, *, allow_callback: bool, identify_retired: bool) -> None:
+ """
+ Reject mutations from an attempt whose UUID is no longer in the working set.
+
+ This is an admission check, not a lock: retirement may race with an already
+ admitted request. Use a fresh session so a prior transaction's snapshot
+ cannot keep a retired UUID visible. Historical attempts never grant access.
+ """
+ async with create_session_async() as session:
+ attempt = (
+ await session.execute(select(TaskInstance.working_set).where(TaskInstance.id == token.id))
+ ).one_or_none()
+ if attempt is not None and attempt.working_set:
+ return
+ # Callback token exchange issues an execution token with the callback UUID.
+ if (
+ attempt is None
+ and allow_callback
+ and await session.scalar(select(Callback.id).where(Callback.id == token.id))
+ ):
+ return
+ archived = identify_retired and attempt is not None
+ raise HTTPException(
+ status_code=status.HTTP_410_GONE if archived else status.HTTP_404_NOT_FOUND,
+ detail={
+ "reason": "not_found",
+ "message": (
+ "Task Instance not found in the working set; its attempt has been archived"
+ if archived
+ else "Task Instance not found"
+ ),
+ },
+ )
+
+
CurrentTIToken: TIToken = Depends(require_auth)
@@ -229,9 +299,11 @@ class ExecutionAPIRoute(APIRoute):
"""
allowed_token_types: frozenset[str]
+ skip_auto_ti_attempt_live: bool
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
+ self.skip_auto_ti_attempt_live = bool(getattr(self.endpoint, _SKIP_AUTO_TI_ATTEMPT_LIVE, False))
all_scopes: set[str] = set()
for dep in self.dependencies:
@@ -254,8 +326,6 @@ async def get_team_name_dep(token=CurrentTIToken) -> str | None:
if not conf.getboolean("core", "multi_team"):
return None
- from airflow.utils.session import create_session_async
-
async with create_session_async() as session:
return await session.scalar(_team_name_for_ti_stmt(token.id))
diff --git a/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2026_10_30.py b/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2026_10_30.py
index 050018f45a3..aef90d41506 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2026_10_30.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/versions/v2026_10_30.py
@@ -46,7 +46,7 @@ class AddStoppedTaskReport(VersionChange):
class IdentifyRetiredTaskStateUpdates(VersionChangeWithSideEffects):
- """Return 410 for state reports from archived attempts, preserving 404 for unknown attempts."""
+ """Return 410 for requests from archived attempts, preserving 404 for older clients and unknown attempts."""
description = __doc__
instructions_to_migrate_to_previous_version = ()
diff --git a/airflow-core/src/airflow/cli/commands/dag_command.py b/airflow-core/src/airflow/cli/commands/dag_command.py
index bd42dadf925..96459bc8a15 100644
--- a/airflow-core/src/airflow/cli/commands/dag_command.py
+++ b/airflow-core/src/airflow/cli/commands/dag_command.py
@@ -225,6 +225,7 @@ def _bulk_clear_runs(
cleared = 0
for chunk_run_ids in chunks(run_ids, _RUN_CHUNK_SIZE):
ti_query = select(TaskInstance).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == dag_id,
TaskInstance.run_id.in_(chunk_run_ids),
)
@@ -858,6 +859,7 @@ def dag_test(args, dag: DAG | None = None, *, session: Session = NEW_SESSION) ->
if show_dagrun or imgcat or filename:
tis = session.scalars(
select(TaskInstance).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == dag.dag_id,
TaskInstance.run_id == dr.run_id,
)
diff --git a/airflow-core/src/airflow/jobs/scheduler_job_runner.py b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
index 5e07bf3cf70..293b3dba175 100644
--- a/airflow-core/src/airflow/jobs/scheduler_job_runner.py
+++ b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
@@ -277,7 +277,7 @@ class ConcurrencyMap:
self.task_dagrun_concurrency_map.clear()
query = session.execute(
select(TI.dag_id, TI.task_id, TI.run_id, TI.state, func.count("*"))
- .where(TI.state.in_(ACTIVE_STATES))
+ .where(TI.working_set.is_(True), TI.state.in_(ACTIVE_STATES))
.group_by(TI.dag_id, TI.task_id, TI.run_id, TI.state)
)
for dag_id, task_id, run_id, state, count in query:
@@ -306,7 +306,7 @@ def _get_current_dr_task_concurrency(states: Iterable[TaskInstanceState]) -> Sub
"""Get the dag_run IDs and how many tasks are in the provided states for each one."""
return (
select(TI.dag_id, TI.run_id, func.count("*").label("task_per_dr_count"))
- .where(TI.state.in_(states))
+ .where(TI.working_set.is_(True), TI.state.in_(states))
.group_by(TI.dag_id, TI.run_id)
.subquery()
)
@@ -610,7 +610,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
session.execute(
update(TI)
- .where(TI.dag_id == dag_id, TI.state == TaskInstanceState.SCHEDULED)
+ .where(TI.working_set.is_(True), TI.dag_id == dag_id, TI.state == TaskInstanceState.SCHEDULED)
.values(state=TaskInstanceState.FAILED)
.execution_options(synchronize_session="fetch")
)
@@ -1020,7 +1020,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
select(TI)
.with_hint(TI, "USE INDEX (ti_state)", dialect_name="mysql")
.join(TI.dag_run)
- .where(DR.state == DagRunState.RUNNING)
+ .where(DR.state == DagRunState.RUNNING, TI.working_set.is_(True))
.join(TI.dag_model)
.where(~DM.is_paused)
.where(TI.state == TaskInstanceState.SCHEDULED)
@@ -1084,7 +1084,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
& (TI.run_id == ranked_query.c.run_id)
& (TI.map_index == ranked_query.c.map_index),
)
- .where(ranked_query.c.row_num <= ranked_query.c.dr_max_active_tasks)
+ .where(ranked_query.c.row_num <= ranked_query.c.dr_max_active_tasks, TI.working_set.is_(True))
# Add the order_by columns from the ranked query for sqlite.
.order_by(
-ranked_query.c.priority_weight_for_ordering,
@@ -1170,7 +1170,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
queued_update = (
update(TI)
- .where(filter_for_tis)
+ .where(TI.working_set.is_(True), filter_for_tis)
.values(**queued_values)
.execution_options(synchronize_session=False)
)
@@ -1187,7 +1187,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
else:
session.execute(queued_update)
id_rows = session.execute(
- select(TI.id, TI.external_executor_id).where(filter_for_tis)
+ select(TI.id, TI.external_executor_id).where(TI.working_set.is_(True), filter_for_tis)
).all()
id_map = {row[0]: row[1] for row in id_rows}
for ti in executable_tis:
@@ -1530,7 +1530,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
asset_loader, alias_loader = _eager_load_dag_run_for_validation()
query = (
select(TI)
- .where(TI.id.in_([key.id for key in tis_with_right_state]))
+ .where(TI.working_set.is_(True), TI.id.in_([key.id for key in tis_with_right_state]))
.options(selectinload(TI.dag_model))
.options(asset_loader)
.options(alias_loader)
@@ -3142,7 +3142,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
dag_run.set_state(DagRunState.FAILED)
unfinished_task_instances = session.scalars(
select(TI)
- .where(TI.dag_id == dag_run.dag_id)
+ .where(TI.working_set.is_(True), TI.dag_id == dag_run.dag_id)
.where(TI.run_id == dag_run.run_id)
.where(TI.state.in_(State.unfinished) | (TI.state.is_(None)))
).all()
@@ -3274,6 +3274,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
session.execute(
update(TI)
.where(
+ TI.working_set.is_(True),
TI.dag_id == dag_run.dag_id,
TI.run_id == dag_run.run_id,
TI.state.in_(State.unfinished),
@@ -3328,6 +3329,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
"""Query db for TIs that are stuck in queued."""
return session.scalars(
select(TI).where(
+ TI.working_set.is_(True),
TI.state == TaskInstanceState.QUEUED,
TI.queued_dttm < (timezone.utcnow() - timedelta(seconds=self._task_queued_timeout)),
TI.queued_by_job_id == self.job.id,
@@ -3423,7 +3425,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
return
session.execute(
update(TI)
- .where(filter_for_tis)
+ .where(TI.working_set.is_(True), filter_for_tis)
.values(
state=TaskInstanceState.SCHEDULED,
queued_dttm=None,
@@ -3486,7 +3488,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
TaskInstance.queue,
func.count(TaskInstance.task_id).label("count"),
)
- .filter(TaskInstance.state.in_(metric_states))
+ .filter(TaskInstance.state.in_(metric_states), TaskInstance.working_set.is_(True))
.group_by(TaskInstance.state, TaskInstance.dag_id, TaskInstance.task_id, TaskInstance.queue)
)
all_states_metric = session.execute(stmt).all()
@@ -3625,7 +3627,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
query = (
select(TI)
.options(lazyload(TI.dag_run)) # avoids double join to dag_run
- .where(TI.state.in_(State.adoptable_states))
+ .where(TI.state.in_(State.adoptable_states), TI.working_set.is_(True))
.join(TI.queued_by_job)
.where(Job.state.is_distinct_from(JobState.RUNNING))
.join(TI.dag_run)
@@ -3660,12 +3662,11 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
reset_tis_message = []
for ti in to_reset:
reset_tis_message.append(repr(ti))
- ti.prepare_db_for_next_try(session=session)
-
- ti.state = None
- ti.queued_by_job_id = None
- ti.external_executor_id = None
- ti.clear_next_method_args()
+ successor = ti.prepare_db_for_next_try(session=session)
+ successor.state = None
+ successor.queued_by_job_id = None
+ successor.external_executor_id = None
+ successor.clear_next_method_args()
for ti in set(tis_to_adopt_or_reset) - set(to_reset):
ti.queued_by_job_id = self.job.id
@@ -3705,6 +3706,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
result = session.execute(
update(TI)
.where(
+ TI.working_set.is_(True),
TI.state == TaskInstanceState.DEFERRED,
TI.trigger_timeout < timezone.utcnow(),
)
@@ -3738,6 +3740,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
query = (
select(TI)
.where(
+ TI.working_set.is_(True),
TI.state == TaskInstanceState.AWAITING_INPUT,
TI.trigger_timeout < now,
)
@@ -3860,6 +3863,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
.with_hint(TI, "USE INDEX (ti_state)", dialect_name="mysql")
.join(DM, TI.dag_id == DM.dag_id)
.where(
+ TI.working_set.is_(True),
TI.state.in_((TaskInstanceState.RUNNING, TaskInstanceState.RESTARTING)),
TI.last_heartbeat_at < limit_dttm,
)
@@ -4054,7 +4058,11 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
select(AssetWatcherModel.trigger_id).where(AssetWatcherModel.trigger_id == Trigger.id)
),
~exists(select(Callback.trigger_id).where(Callback.trigger_id == Trigger.id)),
- ~exists(select(TaskInstance.trigger_id).where(TaskInstance.trigger_id == Trigger.id)),
+ ~exists(
+ select(TaskInstance.trigger_id).where(
+ TaskInstance.working_set.is_(True), TaskInstance.trigger_id == Trigger.id
+ )
+ ),
)
.execution_options(synchronize_session="fetch")
)
diff --git a/airflow-core/src/airflow/migrations/versions/0142_3_4_0_unify_task_attempt_ownership.py b/airflow-core/src/airflow/migrations/versions/0142_3_4_0_unify_task_attempt_ownership.py
new file mode 100644
index 00000000000..afec6189a54
--- /dev/null
+++ b/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")
+ )
+ elif dialect == "sqlite":
+ insert = (
+ sqlite.insert(ti)
+ .from_select(columns, history_rows.where(sa.true()))
+ .on_conflict_do_nothing(index_elements=[*_COORDINATES, "try_number"])
+ )
+ else:
+ insert = ti.insert().from_select(columns, history_rows)
+ op.execute(insert)
+ hitl = sa.table("hitl_detail", sa.column("ti_id"), *(sa.column(c) for c in _HITL_COLUMNS))
+ hitl_history = sa.table(
+ "hitl_detail_history", sa.column("ti_history_id"), *(sa.column(c) for c in _HITL_COLUMNS)
+ )
+ op.execute(
+ hitl.insert().from_select(
+ ["ti_id", *_HITL_COLUMNS],
+ sa.select(hitl_history.c.ti_history_id, *(hitl_history.c[c] for c in _HITL_COLUMNS)).join(
+ ti,
+ sa.and_(ti.c.id == hitl_history.c.ti_history_id, ti.c.working_set.is_(None)),
+ ),
+ )
+ )
+ op.drop_table("hitl_detail_history")
+ op.drop_table("task_instance_history")
+ for name, columns in (
+ ("ti_current_state", ["working_set", "state"]),
+ ("ti_current_dag_run", ["working_set", "dag_id", "run_id", "state"]),
+ ):
+ op.create_index(
+ name,
+ "task_instance",
+ columns,
+ postgresql_where=sa.text("working_set IS TRUE"),
+ sqlite_where=sa.text("working_set IS TRUE"),
+ )
+ op.create_table(
+ "xcom_v2",
+ sa.Column("id", sa.Uuid(), nullable=False),
+ sa.Column("task_instance_id", sa.Uuid(), nullable=False),
+ sa.Column("key", StringID(length=512), nullable=False),
+ sa.Column("value", sa.JSON().with_variant(postgresql.JSONB(), "postgresql")),
+ sa.Column("timestamp", TIMESTAMP(), nullable=False),
+ sa.Column("dag_result", sa.Boolean(), nullable=True),
+ sa.Column("mapped_length", sa.Integer(), nullable=True),
+ sa.PrimaryKeyConstraint("id", name="xcom_v2_pkey"),
+ sa.UniqueConstraint("task_instance_id", "key", name="xcom_v2_ti_key_uq"),
+ sa.ForeignKeyConstraint(
+ ["task_instance_id"], ["task_instance.id"], name="xcom_v2_ti_fkey", ondelete="CASCADE"
+ ),
+ sa.CheckConstraint("mapped_length >= 0", name="xcom_v2_mapped_length_not_negative"),
+ )
+ op.create_table(
+ "rtif_v2",
+ sa.Column("id", sa.Uuid(), nullable=False),
+ sa.Column("task_instance_id", sa.Uuid(), nullable=False),
+ sa.Column("rendered_fields", sa.JSON(), nullable=False),
+ sa.Column("k8s_pod_yaml", sa.JSON(), nullable=True),
+ sa.PrimaryKeyConstraint("id", name="rtif_v2_pkey"),
+ sa.UniqueConstraint("task_instance_id", name="rtif_v2_ti_uq"),
+ sa.ForeignKeyConstraint(
+ ["task_instance_id"], ["task_instance.id"], name="rtif_v2_ti_fkey", ondelete="CASCADE"
+ ),
+ )
+
+
+def downgrade():
+ """Refuse downgrade when the predecessor cannot represent retained ownership."""
+ if op.get_context().as_sql:
+ raise RuntimeError("Offline downgrade cannot verify retained attempt ownership")
+ bind = op.get_bind()
+ if bind.scalar(sa.text("SELECT 1 FROM task_instance WHERE working_set IS NULL LIMIT 1")):
+ raise RuntimeError("Cannot downgrade attempt ownership with historical attempts")
+ for name in ("xcom_v2", "rtif_v2"):
+ if bind.scalar(sa.text(f"SELECT 1 FROM {name} LIMIT 1")):
+ raise RuntimeError(f"Cannot downgrade attempt ownership with data in {name}")
+ if bind.scalar(
+ sa.text(
+ "SELECT 1 FROM legacy_task_data_owner o JOIN task_instance t ON t.id=o.task_instance_id "
+ "WHERE o.dag_id<>t.dag_id OR o.task_id<>t.task_id OR o.run_id<>t.run_id OR o.map_index<>t.map_index LIMIT 1"
+ )
+ ):
+ raise RuntimeError("Cannot downgrade attempt ownership after legacy owners changed coordinates")
+ with _sqlite_rebuilds():
+ op.drop_table("rtif_v2")
+ op.drop_table("xcom_v2")
+ op.drop_index("ti_current_state", table_name="task_instance")
+ op.drop_index("ti_current_dag_run", table_name="task_instance")
+ with op.batch_alter_table("task_instance") as batch:
+ batch.drop_constraint("task_instance_current_key", type_="unique")
+ batch.drop_constraint("task_instance_try_key", type_="unique")
+ batch.drop_constraint("ti_working_set_true_or_null", type_="check")
+ batch.create_unique_constraint("task_instance_composite_key", list(_COORDINATES))
+ for column in ("working_set", "archived_reason"):
+ batch.drop_column(column)
+ for old_name, name, constraint, onupdate in _LEGACY:
+ _redirect_legacy(name, constraint, "task_instance", onupdate=onupdate)
+ op.rename_table(name, old_name)
+ op.drop_table("legacy_task_data_owner")
+ with op.batch_alter_table("log") as batch:
+ batch.drop_column("task_instance_id")
+ _restore_history_tables()
+
+
+def _restore_history_tables():
+ op.create_table(
+ "task_instance_history",
+ sa.Column("task_instance_id", sa.Uuid(), nullable=False),
+ sa.Column("task_id", StringID(), nullable=False),
+ sa.Column("dag_id", StringID(), nullable=False),
+ sa.Column("run_id", StringID(), nullable=False),
+ sa.Column("map_index", sa.Integer(), nullable=False, server_default="-1"),
+ sa.Column("try_number", sa.Integer(), nullable=False),
+ sa.Column("start_date", UtcDateTime(), nullable=True),
+ sa.Column("end_date", UtcDateTime(), nullable=True),
+ sa.Column("duration", sa.Float(), nullable=True),
+ sa.Column("state", sa.String(20), nullable=True),
+ sa.Column("max_tries", sa.Integer(), nullable=True, server_default="-1"),
+ sa.Column("hostname", sa.String(1000), nullable=True),
+ sa.Column("unixname", sa.String(1000), nullable=True),
+ sa.Column("pool", sa.String(256), nullable=False),
+ sa.Column("pool_slots", sa.Integer(), nullable=False),
+ sa.Column("queue", sa.String(256), nullable=True),
+ sa.Column("priority_weight", sa.Integer(), nullable=True),
+ sa.Column("operator", sa.String(1000), nullable=True),
+ sa.Column("custom_operator_name", sa.String(1000), nullable=True),
+ sa.Column("queued_dttm", UtcDateTime(), nullable=True),
+ sa.Column("scheduled_dttm", UtcDateTime(), nullable=True),
+ sa.Column("queued_by_job_id", sa.Integer(), nullable=True),
+ sa.Column("pid", sa.Integer(), nullable=True),
+ sa.Column("executor", sa.String(1000), nullable=True),
+ sa.Column("executor_config", ExecutorConfigType(), nullable=True),
+ sa.Column("updated_at", UtcDateTime(), nullable=True),
+ sa.Column("rendered_map_index", sa.String(250), nullable=True),
+ sa.Column("context_carrier", ExtendedJSON(), nullable=True),
+ sa.Column("external_executor_id", sa.Text(), nullable=True),
+ sa.Column("trigger_id", sa.Integer(), nullable=True),
+ sa.Column("trigger_timeout", sa.DateTime(), nullable=True),
+ sa.Column("next_method", sa.String(1000), nullable=True),
+ sa.Column("next_kwargs", ExtendedJSON(), nullable=True),
+ sa.Column("task_display_name", sa.String(2000), nullable=True),
+ sa.Column("dag_version_id", sa.Uuid(), nullable=True),
+ sa.Column("retry_delay_override", sa.Float(), nullable=True),
+ sa.Column("retry_reason", sa.String(500), nullable=True),
+ sa.PrimaryKeyConstraint("task_instance_id", name="task_instance_history_pkey"),
+ sa.UniqueConstraint(*_COORDINATES, "try_number", name="task_instance_history_dtrt_uq"),
+ sa.ForeignKeyConstraint(
+ list(_COORDINATES),
+ [f"task_instance.{c}" for c in _COORDINATES],
+ name="task_instance_history_ti_fkey",
+ ondelete="CASCADE",
+ onupdate="CASCADE",
+ ),
+ )
+ op.create_index("idx_tih_dag_run", "task_instance_history", ["dag_id", "run_id"])
+ op.create_table(
+ "hitl_detail_history",
+ sa.Column("ti_history_id", sa.Uuid(), nullable=False),
+ sa.Column("options", sa.JSON(), nullable=False),
+ sa.Column("subject", sa.Text(), nullable=False),
+ sa.Column("body", sa.Text(), nullable=True),
+ sa.Column("defaults", sa.JSON(), nullable=True),
+ sa.Column("multiple", sa.Boolean(), nullable=True),
+ sa.Column("params", sa.JSON(), nullable=False),
+ sa.Column("assignees", sa.JSON(), nullable=True),
+ sa.Column("created_at", UtcDateTime(), nullable=False),
+ sa.Column("responded_at", UtcDateTime(), nullable=True),
+ sa.Column("responded_by", sa.JSON(), nullable=True),
+ sa.Column("chosen_options", sa.JSON(), nullable=True),
+ sa.Column("params_input", sa.JSON(), nullable=False),
+ sa.PrimaryKeyConstraint("ti_history_id", name="hitl_detail_history_pkey"),
+ sa.ForeignKeyConstraint(
+ ["ti_history_id"],
+ ["task_instance_history.task_instance_id"],
+ name="hitl_detail_history_tih_fkey",
+ ondelete="CASCADE",
+ onupdate="CASCADE",
+ ),
+ )
diff --git a/airflow-core/src/airflow/models/__init__.py b/airflow-core/src/airflow/models/__init__.py
index f5bffb4e571..c88209f37d3 100644
--- a/airflow-core/src/airflow/models/__init__.py
+++ b/airflow-core/src/airflow/models/__init__.py
@@ -45,7 +45,6 @@ __all__ = [
"RenderedTaskInstanceFields",
"SkipMixin",
"TaskInstance",
- "TaskInstanceHistory",
"TaskReschedule",
"Trigger",
"Variable",
@@ -74,7 +73,6 @@ def import_all_models():
import airflow.models.revoked_token
import airflow.models.serialized_dag
import airflow.models.task_state_store
- import airflow.models.taskinstancehistory
import airflow.models.tasklog
import airflow.models.team
import airflow.models.xcom
@@ -146,7 +144,6 @@ if TYPE_CHECKING:
from airflow.models.pool import Pool
from airflow.models.renderedtifields import RenderedTaskInstanceFields
from airflow.models.taskinstance import TaskInstance, clear_task_instances
- from airflow.models.taskinstancehistory import TaskInstanceHistory
from airflow.models.taskreschedule import TaskReschedule
from airflow.models.trigger import Trigger
from airflow.models.variable import Variable
diff --git a/airflow-core/src/airflow/models/asset.py b/airflow-core/src/airflow/models/asset.py
index aee173590cc..ddac396f182 100644
--- a/airflow-core/src/airflow/models/asset.py
+++ b/airflow-core/src/airflow/models/asset.py
@@ -884,6 +884,7 @@ class AssetEvent(Base):
AssetEvent.source_run_id == foreign(TaskInstance.run_id),
AssetEvent.source_task_id == foreign(TaskInstance.task_id),
AssetEvent.source_map_index == foreign(TaskInstance.map_index),
+ TaskInstance.working_set.is_(True),
)""",
viewonly=True,
lazy="select",
diff --git a/airflow-core/src/airflow/models/dagrun.py b/airflow-core/src/airflow/models/dagrun.py
index fc26cbccd16..12d967a0f21 100644
--- a/airflow-core/src/airflow/models/dagrun.py
+++ b/airflow-core/src/airflow/models/dagrun.py
@@ -89,7 +89,6 @@ from airflow.models.backfill import Backfill
from airflow.models.base import Base, StringID
from airflow.models.deadline_alert import DeadlineAlert as DeadlineAlertModel
from airflow.models.taskinstance import TaskInstance as TI, _add_and_prime_mapped_ti, clear_task_instances
-from airflow.models.taskinstancehistory import TaskInstanceHistory as TIH
from airflow.models.tasklog import LogTemplate
from airflow.serialization.definitions.deadline import SerializedReferenceModels
from airflow.serialization.definitions.notset import NOTSET, ArgNotSet, is_arg_set
@@ -356,13 +355,13 @@ class DagRun(Base, LoggingMixin):
task_instances = relationship(
TI,
back_populates="dag_run",
+ primaryjoin="and_(DagRun.dag_id == TaskInstance.dag_id, DagRun.run_id == TaskInstance.run_id, TaskInstance.working_set.is_(True))",
cascade="save-update, merge, delete, delete-orphan",
+ passive_deletes=True,
)
- task_instances_histories = relationship(
- TIH,
- primaryjoin="and_(DagRun.dag_id == TaskInstanceHistory.dag_id, DagRun.run_id == TaskInstanceHistory.run_id)",
- foreign_keys="TaskInstanceHistory.dag_id, TaskInstanceHistory.run_id",
- order_by=TIH.dag_version_id,
+ historical_task_instances = relationship(
+ TI,
+ primaryjoin="and_(DagRun.dag_id == TaskInstance.dag_id, DagRun.run_id == TaskInstance.run_id, TaskInstance.working_set.is_(None))",
viewonly=True,
)
dag_model = relationship(
@@ -412,10 +411,10 @@ class DagRun(Base, LoggingMixin):
fallback=20,
)
_ti_dag_versions = association_proxy("task_instances", "dag_version")
- _tih_dag_versions = association_proxy("task_instances_histories", "dag_version")
+ _historical_dag_versions = association_proxy("historical_task_instances", "dag_version")
# Can be set by manual prefetch, such as attach_dag_versions_to_runs()
- # as an alternative to traversing all TI/TIH ORM relationships. Maps version_id -> DagVersion.
+ # as an alternative to traversing all current and historical attempts. Maps version_id -> DagVersion.
_prefetched_dag_version_ids: dict[UUID, DagVersion] | None = None
def __init__(
@@ -543,7 +542,7 @@ class DagRun(Base, LoggingMixin):
else:
dag_version_objects = [
dv
- for dv in dict.fromkeys(list(self._tih_dag_versions) + list(self._ti_dag_versions))
+ for dv in dict.fromkeys(list(self._historical_dag_versions) + list(self._ti_dag_versions))
if dv is not None
]
return sorted(dag_version_objects, key=lambda dv: dv.id)
@@ -586,12 +585,12 @@ class DagRun(Base, LoggingMixin):
def check_version_id_exists_in_dr(self, dag_version_id: UUID, *, session: Session = NEW_SESSION):
select_stmt = (
select(TI.dag_version_id)
- .where(TI.dag_id == self.dag_id, TI.dag_version_id == dag_version_id, TI.run_id == self.run_id)
- .union(
- select(TIH.dag_version_id).where(
- TIH.dag_id == self.dag_id, TIH.dag_version_id == dag_version_id, TIH.run_id == self.run_id
- )
+ .where(
+ TI.dag_id == self.dag_id,
+ TI.dag_version_id == dag_version_id,
+ TI.run_id == self.run_id,
)
+ .limit(1)
)
return session.scalar(select_stmt)
@@ -974,6 +973,7 @@ class DagRun(Base, LoggingMixin):
select(TI)
.options(joinedload(TI.dag_run))
.where(
+ TI.working_set.is_(True),
TI.dag_id == dag_id,
TI.run_id == run_id,
)
@@ -1102,7 +1102,9 @@ class DagRun(Base, LoggingMixin):
:param session: Sqlalchemy ORM Session
"""
return session.scalars(
- select(TI).filter_by(dag_id=dag_id, run_id=dag_run_id, task_id=task_id, map_index=map_index)
+ select(TI)
+ .where(TI.working_set.is_(True))
+ .filter_by(dag_id=dag_id, run_id=dag_run_id, task_id=task_id, map_index=map_index)
).one_or_none()
def get_dag(self) -> SerializedDAG:
@@ -1786,7 +1788,7 @@ class DagRun(Base, LoggingMixin):
# Check if any ti changed state
tis_filter = TI.filter_for_tis(old_states)
if tis_filter is not None:
- fresh_tis = session.scalars(select(TI).where(tis_filter)).all()
+ fresh_tis = session.scalars(select(TI).where(TI.working_set.is_(True), tis_filter)).all()
changed_tis = any(ti.state != old_states[ti.key] for ti in fresh_tis)
return ready_tis, changed_tis, expansion_happened
@@ -2007,9 +2009,8 @@ class DagRun(Base, LoggingMixin):
"task_restored_to_dag",
tags={**self.stats_tags, "dag_id": dag.dag_id},
)
- if ti.try_number > 0:
- ti.prepare_db_for_next_try(session)
- ti.state = None
+ restored = ti.prepare_db_for_next_try(session) if ti.try_number > 0 else ti
+ restored.state = None
return task_ids
@@ -2180,6 +2181,7 @@ class DagRun(Base, LoggingMixin):
query = session.scalars(
select(TI.map_index).where(
+ TI.working_set.is_(True),
TI.dag_id == self.dag_id,
TI.task_id == task.task_id,
TI.run_id == self.run_id,
@@ -2192,6 +2194,7 @@ class DagRun(Base, LoggingMixin):
session.execute(
update(TI)
.where(
+ TI.working_set.is_(True),
TI.dag_id == self.dag_id,
TI.task_id == task.task_id,
TI.run_id == self.run_id,
@@ -2201,11 +2204,22 @@ class DagRun(Base, LoggingMixin):
)
session.flush()
+ missing_indexes = [index for index in range(total_length) if index not in existing_indexes]
+ if not missing_indexes:
+ return []
+ last_tries = TI.get_last_try_numbers(
+ dag_id=self.dag_id,
+ task_id=task.task_id,
+ run_id=self.run_id,
+ map_indexes=missing_indexes,
+ session=session,
+ )
+
new_tis: list[TI] = []
- for index in range(total_length):
- if index in existing_indexes:
- continue
+ for index in missing_indexes:
ti = TI(task, run_id=self.run_id, map_index=index, state=None, dag_version_id=dag_version_id)
+ ti.try_number = last_tries.get(index, -1) + 1
+ ti.max_tries += ti.try_number
self.log.debug("Expanding TIs upserted %s", ti)
_add_and_prime_mapped_ti(ti, task, self, session=session)
new_tis.append(ti)
@@ -2295,7 +2309,7 @@ class DagRun(Base, LoggingMixin):
for id_chunk in schedulable_ti_ids_chunks:
result = session.execute(
update(TI)
- .where(TI.id.in_(id_chunk), schedulable_state_clause)
+ .where(TI.working_set.is_(True), TI.id.in_(id_chunk), schedulable_state_clause)
.values(
state=TaskInstanceState.SCHEDULED,
scheduled_dttm=timezone.utcnow(),
@@ -2306,7 +2320,9 @@ class DagRun(Base, LoggingMixin):
count += getattr(result, "rowcount", 0)
if debug_try_number_check:
rows = session.execute(
- select(TI.id, TI.try_number, TI.state).where(TI.id.in_(id_chunk))
+ select(TI.id, TI.try_number, TI.state).where(
+ TI.working_set.is_(True), TI.id.in_(id_chunk)
+ )
).all()
rows_by_ti_id = {
ti_id: (db_try_number, db_state) for ti_id, db_try_number, db_state in rows
@@ -2343,7 +2359,7 @@ class DagRun(Base, LoggingMixin):
for id_chunk in dummy_ti_ids_chunks:
result = session.execute(
update(TI)
- .where(TI.id.in_(id_chunk), schedulable_state_clause)
+ .where(TI.working_set.is_(True), TI.id.in_(id_chunk), schedulable_state_clause)
.values(
state=TaskInstanceState.SUCCESS,
start_date=timezone.utcnow(),
@@ -2512,6 +2528,7 @@ def clear_partition_runs(
chunk_tis = list(
session.scalars(
select(TI).where(
+ TI.working_set.is_(True),
TI.dag_id == dag_id,
TI.run_id.in_(ti_buffer_run_ids),
)
@@ -2560,6 +2577,7 @@ def clear_partition_runs(
select(func.count())
.select_from(TI)
.where(
+ TI.working_set.is_(True),
TI.dag_id == dag_id,
TI.run_id.in_(chunk),
)
diff --git a/airflow-core/src/airflow/models/hitl_history.py b/airflow-core/src/airflow/models/hitl_history.py
deleted file mode 100644
index 79741438140..00000000000
--- a/airflow-core/src/airflow/models/hitl_history.py
+++ /dev/null
@@ -1,91 +0,0 @@
-# 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.
-from __future__ import annotations
-
-from datetime import datetime
-from typing import TYPE_CHECKING
-from uuid import UUID
-
-import sqlalchemy as sa
-from sqlalchemy import Boolean, ForeignKeyConstraint, Text, Uuid
-from sqlalchemy.orm import Mapped, mapped_column, relationship
-
-from airflow._shared.timezones import timezone
-from airflow.models.base import Base
-from airflow.models.hitl import HITLDetailPropertyMixin
-from airflow.utils.sqlalchemy import UtcDateTime
-
-if TYPE_CHECKING:
- from airflow.models.hitl import HITLDetail
-
-
-class HITLDetailHistory(Base, HITLDetailPropertyMixin):
- """
- Store HITLDetail for old tries of TaskInstances.
-
- :meta private:
- """
-
- __tablename__ = "hitl_detail_history"
- ti_history_id: Mapped[UUID] = mapped_column(
- Uuid(),
- primary_key=True,
- nullable=False,
- )
-
- # User Request Detail
- options: Mapped[dict] = mapped_column(sa.JSON(), nullable=False)
- subject: Mapped[str] = mapped_column(Text, nullable=False)
- body: Mapped[str | None] = mapped_column(Text, nullable=True)
- defaults: Mapped[dict | None] = mapped_column(sa.JSON(), nullable=True)
- multiple: Mapped[bool | None] = mapped_column(Boolean, unique=False, default=False, nullable=True)
- params: Mapped[dict] = mapped_column(sa.JSON(), nullable=False, default={})
- assignees: Mapped[list[dict[str, str]] | None] = mapped_column(sa.JSON(), nullable=True)
- created_at: Mapped[datetime] = mapped_column(UtcDateTime, default=timezone.utcnow, nullable=False)
-
- # Response Content Detail
- responded_at: Mapped[datetime | None] = mapped_column(UtcDateTime, nullable=True)
- responded_by: Mapped[dict | None] = mapped_column(sa.JSON(), nullable=True)
- chosen_options: Mapped[dict | None] = mapped_column(
- sa.JSON(),
- nullable=True,
- default=None,
- )
- params_input: Mapped[dict] = mapped_column(sa.JSON(), nullable=False, default={})
- task_instance = relationship(
- "TaskInstanceHistory",
- lazy="joined",
- back_populates="hitl_detail",
- )
-
- def __init__(self, hitl_detail: HITLDetail):
- super().__init__()
- for column in self.__table__.columns:
- if column.name == "ti_history_id":
- setattr(self, column.name, hitl_detail.ti_id)
- continue
- setattr(self, column.name, getattr(hitl_detail, column.name))
-
- __table_args__ = (
- ForeignKeyConstraint(
- (ti_history_id,),
- ["task_instance_history.task_instance_id"],
- name="hitl_detail_history_tih_fkey",
- ondelete="CASCADE",
- onupdate="CASCADE",
- ),
- )
diff --git a/airflow-core/src/airflow/models/log.py b/airflow-core/src/airflow/models/log.py
index c966694ca05..220ab2b0b91 100644
--- a/airflow-core/src/airflow/models/log.py
+++ b/airflow-core/src/airflow/models/log.py
@@ -19,8 +19,9 @@ from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
+from uuid import UUID
-from sqlalchemy import Index, Integer, String, Text, event
+from sqlalchemy import Index, Integer, String, Text, Uuid, event
from sqlalchemy.orm import Mapped, Session, mapped_column, relationship
from airflow._shared.timezones import timezone
@@ -51,6 +52,8 @@ class Log(Base):
owner_display_name: Mapped[str | None] = mapped_column(String(500), nullable=True)
extra: Mapped[str | None] = mapped_column(Text, nullable=True)
try_number: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ # The attempt that wrote the event. Not a foreign key, so the event outlives its attempt.
+ task_instance_id: Mapped[UUID | None] = mapped_column(Uuid(), nullable=True)
# Team this event belongs to, recorded when the row is written: either passed in by a caller
# acting on a team-scoped resource that owns no Dag (a triggerer started with ``--team-name``,
# a team-scoped pool, the ``teams`` commands), or resolved from ``dag_id`` on insert. Stamped
@@ -71,7 +74,7 @@ class Log(Base):
"TaskInstance",
viewonly=True,
foreign_keys=[dag_id, task_id, run_id, map_index],
- primaryjoin="and_(Log.dag_id == TaskInstance.dag_id, Log.task_id == TaskInstance.task_id, Log.run_id == TaskInstance.run_id, Log.map_index == TaskInstance.map_index)",
+ primaryjoin="and_(Log.dag_id == TaskInstance.dag_id, Log.task_id == TaskInstance.task_id, Log.run_id == TaskInstance.run_id, Log.map_index == TaskInstance.map_index, TaskInstance.working_set.is_(True))",
lazy="raise",
)
@@ -106,6 +109,7 @@ class Log(Base):
self.logical_date = logical_date
self.try_number = task_instance.try_number
self.map_index = task_instance.map_index
+ self.task_instance_id = getattr(task_instance, "id", None)
if task := getattr(task_instance, "task", None):
task_owner = task.owner
@@ -121,6 +125,8 @@ class Log(Base):
self.map_index = kwargs["map_index"]
if "try_number" in kwargs:
self.try_number = kwargs["try_number"]
+ if "task_instance_id" in kwargs:
+ self.task_instance_id = kwargs["task_instance_id"]
if "team_name" in kwargs:
self.team_name = kwargs["team_name"]
diff --git a/airflow-core/src/airflow/models/pool.py b/airflow-core/src/airflow/models/pool.py
index 339abaddf5d..c5b4d8dc428 100644
--- a/airflow-core/src/airflow/models/pool.py
+++ b/airflow-core/src/airflow/models/pool.py
@@ -222,7 +222,7 @@ class Pool(Base):
}
state_count_by_pool = session.execute(
select(TaskInstance.pool, TaskInstance.state, func.sum(TaskInstance.pool_slots))
- .filter(TaskInstance.state.in_(allowed_execution_states))
+ .filter(TaskInstance.state.in_(allowed_execution_states), TaskInstance.working_set.is_(True))
.group_by(TaskInstance.pool, TaskInstance.state)
)
@@ -284,7 +284,7 @@ class Pool(Base):
return int(
session.scalar(
select(func.sum(TaskInstance.pool_slots))
- .filter(TaskInstance.pool == self.pool)
+ .filter(TaskInstance.pool == self.pool, TaskInstance.working_set.is_(True))
.filter(TaskInstance.state.in_(occupied_states))
)
or 0
@@ -310,7 +310,7 @@ class Pool(Base):
return int(
session.scalar(
select(func.sum(TaskInstance.pool_slots))
- .filter(TaskInstance.pool == self.pool)
+ .filter(TaskInstance.pool == self.pool, TaskInstance.working_set.is_(True))
.filter(TaskInstance.state == TaskInstanceState.RUNNING)
)
or 0
@@ -329,7 +329,7 @@ class Pool(Base):
return int(
session.scalar(
select(func.sum(TaskInstance.pool_slots))
- .filter(TaskInstance.pool == self.pool)
+ .filter(TaskInstance.pool == self.pool, TaskInstance.working_set.is_(True))
.filter(TaskInstance.state == TaskInstanceState.QUEUED)
)
or 0
@@ -348,7 +348,7 @@ class Pool(Base):
return int(
session.scalar(
select(func.sum(TaskInstance.pool_slots))
- .filter(TaskInstance.pool == self.pool)
+ .filter(TaskInstance.pool == self.pool, TaskInstance.working_set.is_(True))
.filter(TaskInstance.state == TaskInstanceState.SCHEDULED)
)
or 0
@@ -367,7 +367,9 @@ class Pool(Base):
return int(
session.scalar(
select(func.sum(TaskInstance.pool_slots)).where(
- TaskInstance.pool == self.pool, TaskInstance.state == TaskInstanceState.DEFERRED
+ TaskInstance.working_set.is_(True),
+ TaskInstance.pool == self.pool,
+ TaskInstance.state == TaskInstanceState.DEFERRED,
)
)
or 0
diff --git a/airflow-core/src/airflow/models/renderedtifields.py b/airflow-core/src/airflow/models/renderedtifields.py
index 01e68849d05..220d1bc78ae 100644
--- a/airflow-core/src/airflow/models/renderedtifields.py
+++ b/airflow-core/src/airflow/models/renderedtifields.py
@@ -20,21 +20,27 @@
from __future__ import annotations
import os
+from collections.abc import Collection, Sequence
from typing import TYPE_CHECKING, Any
+from uuid import UUID
import sqlalchemy as sa
+import uuid6
from sqlalchemy import (
ForeignKeyConstraint,
Integer,
PrimaryKeyConstraint,
+ UniqueConstraint,
delete,
select,
)
-from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import Mapped, mapped_column, relationship
+from sqlalchemy.orm.attributes import NO_VALUE, set_committed_value
from airflow.configuration import conf
-from airflow.models.base import StringID, TaskInstanceDependencies
+from airflow.models.base import Base, StringID, TaskInstanceDependencies
+from airflow.models.taskinstance import LegacyTaskDataOwner
+from airflow.models.taskinstancekey import TaskInstanceKey
from airflow.serialization.helpers import serialize_template_field
from airflow.utils.retries import retry_db_transaction
from airflow.utils.session import NEW_SESSION, provide_session
@@ -44,7 +50,7 @@ if TYPE_CHECKING:
from sqlalchemy.orm import Session
from sqlalchemy.sql.selectable import ScalarSelect
- from airflow.models.taskinstance import TaskInstance, TaskInstanceKey
+ from airflow.models.taskinstance import TaskInstance
from airflow.serialization.definitions.baseoperator import SerializedBaseOperator
@@ -100,10 +106,10 @@ def get_serialized_template_fields(task: SerializedBaseOperator):
return rendered_fields
-class RenderedTaskInstanceFields(TaskInstanceDependencies):
- """Save Rendered Template Fields."""
+class LegacyRenderedTaskInstanceFields(TaskInstanceDependencies):
+ """Rendered template fields stored before Airflow 3.4, keyed by dag, task, run and map index."""
- __tablename__ = "rendered_task_instance_fields"
+ __tablename__ = "rtif_v1"
dag_id: Mapped[str] = mapped_column(StringID(), primary_key=True)
task_id: Mapped[str] = mapped_column(StringID(), primary_key=True)
@@ -123,39 +129,110 @@ class RenderedTaskInstanceFields(TaskInstanceDependencies):
ForeignKeyConstraint(
[dag_id, task_id, run_id, map_index],
[
- "task_instance.dag_id",
- "task_instance.task_id",
- "task_instance.run_id",
- "task_instance.map_index",
+ "legacy_task_data_owner.dag_id",
+ "legacy_task_data_owner.task_id",
+ "legacy_task_data_owner.run_id",
+ "legacy_task_data_owner.map_index",
],
name="rtif_ti_fkey",
ondelete="CASCADE",
),
)
- task_instance = relationship(
- "TaskInstance",
- lazy="joined",
- back_populates="rendered_task_instance_fields",
- )
- # We don't need a DB level FK here, as we already have that to TI (which has one to DR) but by defining
- # the relationship we can more easily find the logical date for these rows
- dag_run = relationship(
- "DagRun",
- primaryjoin="""and_(
- RenderedTaskInstanceFields.dag_id == foreign(DagRun.dag_id),
- RenderedTaskInstanceFields.run_id == foreign(DagRun.run_id),
- )""",
- viewonly=True,
+
+class RenderedTaskInstanceFields(Base):
+ """Rendered template fields stored per task attempt, keyed by the attempt UUID."""
+
+ __tablename__ = "rtif_v2"
+ id: Mapped[UUID] = mapped_column(sa.Uuid(), primary_key=True, default=uuid6.uuid7)
+ task_instance_id: Mapped[UUID] = mapped_column(sa.Uuid(), nullable=False)
+ rendered_fields: Mapped[dict] = mapped_column(sa.JSON(), nullable=False)
+ k8s_pod_yaml: Mapped[dict | None] = mapped_column(sa.JSON(), nullable=True)
+ __table_args__ = (
+ PrimaryKeyConstraint("id", name="rtif_v2_pkey"),
+ UniqueConstraint("task_instance_id", name="rtif_v2_ti_uq"),
+ ForeignKeyConstraint(
+ ["task_instance_id"], ["task_instance.id"], name="rtif_v2_ti_fkey", ondelete="CASCADE"
+ ),
)
+ task_instance = relationship("TaskInstance", viewonly=True, lazy="raise")
+
+ @classmethod
+ @provide_session
+ def get_for_attempt(cls, task_instance_id: UUID, *, session: Session = NEW_SESSION):
+ return _rendered_fields_for_ids([task_instance_id], session=session).get(task_instance_id)
+
+ @classmethod
+ @provide_session
+ def set_for_attempt(
+ cls,
+ *,
+ task_instance_id: UUID,
+ rendered_fields: dict,
+ k8s_pod_yaml: dict | None = None,
+ session: Session = NEW_SESSION,
+ ) -> None:
+ from airflow._shared.secrets_masker import redact
+
+ updated = {
+ "rendered_fields": {key: redact(value, key) for key, value in rendered_fields.items()},
+ "k8s_pod_yaml": redact(k8s_pod_yaml) if k8s_pod_yaml else k8s_pod_yaml,
+ }
+ session.flush()
+ session.execute(
+ build_upsert_stmt(
+ get_dialect_name(session),
+ cls,
+ ["task_instance_id"],
+ {"id": uuid6.uuid7(), "task_instance_id": task_instance_id, **updated},
+ updated,
+ )
+ )
+ for existing in session.identity_map.values():
+ if (
+ isinstance(existing, cls)
+ and existing.__dict__.get("task_instance_id", task_instance_id) == task_instance_id
+ ):
+ session.expire(existing, list(updated))
+
+ @classmethod
+ @provide_session
+ def delete_for_attempts(cls, *, producer_ids, session: Session = NEW_SESSION) -> None:
+ owner = LegacyTaskDataOwner.__table__
+ legacy = LegacyRenderedTaskInstanceFields.__table__
+ owns_legacy = (
+ select(1)
+ .where(
+ owner.c.task_instance_id.in_(producer_ids),
+ *(owner.c[name] == legacy.c[name] for name in ("dag_id", "task_id", "run_id", "map_index")),
+ )
+ .exists()
+ )
+ session.execute(delete(legacy).where(owns_legacy))
+ session.execute(
+ delete(cls)
+ .where(cls.task_instance_id.in_(producer_ids))
+ .execution_options(synchronize_session="fetch")
+ )
- logical_date = association_proxy("dag_run", "logical_date")
+ @staticmethod
+ def _attempt_id(ti: TaskInstance | TaskInstanceKey, session: Session):
+ if not isinstance(ti, TaskInstanceKey):
+ return ti.id
+ from airflow.models.taskinstance import TaskInstance
+
+ return session.scalar(
+ select(TaskInstance.id).where(
+ TaskInstance.dag_id == ti.dag_id,
+ TaskInstance.task_id == ti.task_id,
+ TaskInstance.run_id == ti.run_id,
+ TaskInstance.map_index == ti.map_index,
+ TaskInstance.try_number == ti.try_number,
+ )
+ )
def __init__(self, ti: TaskInstance, render_templates=True, rendered_fields=None):
- self.dag_id = ti.dag_id
- self.task_id = ti.task_id
- self.run_id = ti.run_id
- self.map_index = ti.map_index
+ self.task_instance_id = ti.id
self.ti = ti
if render_templates:
raise ValueError("render_templates=True is no longer supported")
@@ -170,15 +247,14 @@ class RenderedTaskInstanceFields(TaskInstanceDependencies):
from airflow.providers.cncf.kubernetes.template_rendering import render_k8s_pod_yaml
self.k8s_pod_yaml = render_k8s_pod_yaml(ti)
- self.rendered_fields = rendered_fields or get_serialized_template_fields(task=ti.task)
+ self.rendered_fields = (
+ rendered_fields if rendered_fields is not None else get_serialized_template_fields(task=ti.task)
+ )
self._redact()
def __repr__(self):
- prefix = f"<{self.__class__.__name__}: {self.dag_id}.{self.task_id} {self.run_id}"
- if self.map_index != -1:
- prefix += f" map_index={self.map_index}"
- return prefix + ">"
+ return f"<{self.__class__.__name__}: {self.task_instance_id}>"
def _redact(self):
from airflow._shared.secrets_masker import redact
@@ -192,86 +268,26 @@ class RenderedTaskInstanceFields(TaskInstanceDependencies):
@classmethod
@provide_session
def get_templated_fields(
- cls,
- ti: TaskInstance | TaskInstanceKey,
- *,
- session: Session = NEW_SESSION,
+ cls, ti: TaskInstance | TaskInstanceKey, *, session: Session = NEW_SESSION
) -> dict | None:
- """
- Get templated field for a TaskInstance from the RenderedTaskInstanceFields table.
-
- :param ti: Task Instance
- :param session: SqlAlchemy Session
- :return: Rendered Templated TI field
- """
- result = session.scalar(
- select(cls).where(
- cls.dag_id == ti.dag_id,
- cls.task_id == ti.task_id,
- cls.run_id == ti.run_id,
- cls.map_index == ti.map_index,
- )
- )
-
- if result:
- rendered_fields = result.rendered_fields
- return rendered_fields
- return None
+ result = cls.get_for_attempt(cls._attempt_id(ti, session), session=session)
+ return result.rendered_fields if result else None
@classmethod
@provide_session
def get_k8s_pod_yaml(cls, ti: TaskInstance, *, session: Session = NEW_SESSION) -> dict | None:
- """
- Get rendered Kubernetes Pod Yaml for a TaskInstance from the RenderedTaskInstanceFields table.
-
- :param ti: Task Instance
- :param session: SqlAlchemy Session
- :return: Kubernetes Pod Yaml
- """
- result = session.scalar(
- select(cls).where(
- cls.dag_id == ti.dag_id,
- cls.task_id == ti.task_id,
- cls.run_id == ti.run_id,
- cls.map_index == ti.map_index,
- )
- )
+ result = cls.get_for_attempt(ti.id, session=session)
return result.k8s_pod_yaml if result else None
@provide_session
@retry_db_transaction
def write(self, *, session: Session = NEW_SESSION) -> None:
- """
- Write instance to database.
-
- Uses a database-level upsert (INSERT ... ON CONFLICT DO UPDATE) to
- atomically insert or update the record, avoiding race conditions that
- can occur with session.merge() when concurrent requests (e.g. from
- client-side timeout retries) target the same primary key.
-
- :param session: SqlAlchemy Session
- """
- values = {
- "dag_id": self.dag_id,
- "task_id": self.task_id,
- "run_id": self.run_id,
- "map_index": self.map_index,
- "rendered_fields": self.rendered_fields,
- "k8s_pod_yaml": self.k8s_pod_yaml,
- }
- update_on_conflict = {
- "rendered_fields": self.rendered_fields,
- "k8s_pod_yaml": self.k8s_pod_yaml,
- }
-
- stmt = build_upsert_stmt(
- get_dialect_name(session),
- RenderedTaskInstanceFields,
- ["dag_id", "task_id", "run_id", "map_index"],
- values,
- update_on_conflict,
+ self.set_for_attempt(
+ task_instance_id=self.task_instance_id,
+ rendered_fields=self.rendered_fields,
+ k8s_pod_yaml=self.k8s_pod_yaml,
+ session=session,
)
- session.execute(stmt)
@classmethod
@provide_session
@@ -335,15 +351,83 @@ class RenderedTaskInstanceFields(TaskInstanceDependencies):
run_ids_to_keep: list[str] | ScalarSelect[str],
session: Session,
) -> None:
- # This query might deadlock occasionally and it should be retried if fails (see decorator)
- stmt = (
+ from airflow.models.taskinstance import TaskInstance
+
+ legacy = LegacyRenderedTaskInstanceFields.__table__
+ session.execute(
+ delete(legacy).where(
+ legacy.c.dag_id == dag_id,
+ legacy.c.task_id == task_id,
+ legacy.c.run_id.not_in(run_ids_to_keep),
+ )
+ )
+ session.execute(
delete(cls)
.where(
- cls.dag_id == dag_id,
- cls.task_id == task_id,
- cls.run_id.not_in(run_ids_to_keep),
+ select(1)
+ .where(
+ TaskInstance.id == cls.task_instance_id,
+ TaskInstance.dag_id == dag_id,
+ TaskInstance.task_id == task_id,
+ TaskInstance.run_id.not_in(run_ids_to_keep),
+ )
+ .exists()
)
- .execution_options(synchronize_session=False)
+ .execution_options(synchronize_session="fetch")
)
- session.execute(stmt)
+
+def _legacy_rendered_fields_for_ids(
+ producer_ids: Collection[UUID], *, session: Session
+) -> dict[UUID, LegacyRenderedTaskInstanceFields]:
+ if not producer_ids:
+ return {}
+ owner = LegacyTaskDataOwner
+ legacy = LegacyRenderedTaskInstanceFields
+ legacy_rows = (
+ select(owner.task_instance_id, legacy)
+ .join(
+ legacy,
+ sa.and_(
+ *(
+ getattr(owner, name) == getattr(legacy, name)
+ for name in ("dag_id", "task_id", "run_id", "map_index")
+ )
+ ),
+ )
+ .where(owner.task_instance_id.in_(producer_ids))
+ )
+ return {owner_id: row for owner_id, row in session.execute(legacy_rows)}
+
+
+def _rendered_fields_for_ids(
+ producer_ids: Sequence[UUID], *, session: Session
+) -> dict[UUID, RenderedTaskInstanceFields | LegacyRenderedTaskInstanceFields]:
+ if not producer_ids:
+ return {}
+ fields: dict[UUID, RenderedTaskInstanceFields | LegacyRenderedTaskInstanceFields] = {
+ row.task_instance_id: row
+ for row in session.scalars(
+ select(RenderedTaskInstanceFields).where(
+ RenderedTaskInstanceFields.task_instance_id.in_(producer_ids)
+ )
+ )
+ }
+ fields.update(_legacy_rendered_fields_for_ids(set(producer_ids) - fields.keys(), session=session))
+ return fields
+
+
+def load_legacy_rendered_fields(task_instances: Sequence[TaskInstance], *, session: Session) -> None:
+ """Give task instances with no joined v2 row the rendered fields of their legacy owner, if any."""
+ for start in range(0, len(task_instances), 400):
+ batch = task_instances[start : start + 400]
+ loaded: dict[UUID, Any] = {
+ ti.id: sa.inspect(ti).attrs.rendered_task_instance_fields.loaded_value for ti in batch
+ }
+ found = {
+ **_legacy_rendered_fields_for_ids([i for i, v in loaded.items() if v is None], session=session),
+ **_rendered_fields_for_ids([i for i, v in loaded.items() if v is NO_VALUE], session=session),
+ }
+ for ti in batch:
+ if loaded[ti.id] is None or loaded[ti.id] is NO_VALUE:
+ set_committed_value(ti, "rendered_task_instance_fields", found.get(ti.id))
diff --git a/airflow-core/src/airflow/models/taskinstance.py b/airflow-core/src/airflow/models/taskinstance.py
index 7a470e1c0e7..f385c56f758 100644
--- a/airflow-core/src/airflow/models/taskinstance.py
+++ b/airflow-core/src/airflow/models/taskinstance.py
@@ -36,6 +36,8 @@ import uuid6
from opentelemetry import trace
from sqlalchemy import (
JSON,
+ Boolean,
+ CheckConstraint,
Float,
ForeignKey,
ForeignKeyConstraint,
@@ -53,10 +55,12 @@ from sqlalchemy import (
extract,
false,
func,
+ insert,
inspect,
or_,
select,
text,
+ true,
tuple_,
update,
)
@@ -67,6 +71,7 @@ from sqlalchemy.ext.mutable import MutableDict
from sqlalchemy.orm import Mapped, lazyload, mapped_column, reconstructor, relationship
from sqlalchemy.orm.attributes import NO_VALUE, set_committed_value
from sqlalchemy.orm.exc import DetachedInstanceError, ObjectDeletedError
+from sqlalchemy.sql.elements import ColumnElement
from airflow import settings
from airflow._shared.observability.metrics import stats
@@ -82,7 +87,7 @@ from airflow.exceptions import RemovedInAirflow4Warning
from airflow.executors.workloads import BaseWorkload
from airflow.listeners.listener import get_listener_manager
from airflow.models.asset import AssetModel
-from airflow.models.base import Base, StringID, TaskInstanceDependencies
+from airflow.models.base import Base, StringID
from airflow.models.dag_version import DagVersion
from airflow.models.deadline import Deadline, ReferenceModels
from airflow.models.deadline_alert import DeadlineAlert as DeadlineAlertModel
@@ -92,7 +97,7 @@ from airflow.models.hitl import HITLDetail # noqa: F401
from airflow.models.log import Log
from airflow.models.taskinstancekey import TaskInstanceKey
from airflow.models.taskreschedule import TaskReschedule
-from airflow.models.xcom import XCOM_RETURN_KEY, LazyXComSelectSequence, XComModel
+from airflow.models.xcom import XCOM_RETURN_KEY, LazyXComSelectSequence
from airflow.serialization.enums import stringify_encoding_keys
from airflow.settings import task_instance_mutation_hook
from airflow.task.priority_strategy import validate_and_load_priority_weight_strategy
@@ -362,6 +367,7 @@ def _pin_versionless_tis_to_run_version(dag_run: DagRun, dag_version_id: UUID, s
session.execute(
update(TaskInstance)
.where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == dag_run.dag_id,
TaskInstance.run_id == dag_run.run_id,
TaskInstance.dag_version_id.is_(None),
@@ -379,7 +385,7 @@ def clear_task_instances(
dag_run_state: DagRunState | Literal[False] = DagRunState.QUEUED,
run_on_latest_version: bool = False,
prevent_running_task: bool | None = None,
-) -> None:
+) -> list[TaskInstance]:
"""
Clear a set of task instances, but make sure the running ones get killed.
@@ -403,7 +409,11 @@ def clear_task_instances(
from airflow.models.dagbag import DBDagBag
scheduler_dagbag = DBDagBag(load_op_links=False)
- for ti in tis:
+ cleared = []
+ for original in tis:
+ ti = original if original in session else session.get(TaskInstance, original.id)
+ if ti is None or ti.working_set is not True:
+ raise ValueError("A retired task instance cannot be cleared")
if ti.state in (TaskInstanceState.RUNNING, TaskInstanceState.RESTARTING):
if prevent_running_task:
raise AirflowClearRunningTaskException(
@@ -421,7 +431,7 @@ def clear_task_instances(
previous_try_number = max(0, ti.try_number - 1)
else:
previous_try_number = ti.try_number
- ti.prepare_db_for_next_try(session)
+ ti = ti.prepare_db_for_next_try(session)
dr = ti.dag_run
# A run with no version of its own has nothing to re-run on but the latest, and the
# run loop below moves it there.
@@ -444,7 +454,7 @@ def clear_task_instances(
# task are not found since database records could be
# outdated. We make max_tries the maximum value of its
# original max_tries or the last attempted try number.
- ti.max_tries = max(ti.max_tries, previous_try_number)
+ ti.max_tries = max(ti.max_tries or 0, previous_try_number)
ti.state = None
ti.external_executor_id = None
ti.clear_next_method_args()
@@ -458,7 +468,9 @@ def clear_task_instances(
# only go there.
ti.dag_version_id = dr.created_dag_version_id
session.merge(ti)
+ cleared.append(ti)
+ tis = cleared
if dag_run_state is not False and tis:
from airflow.models.dagrun import ( # Avoid circular import
DagRun,
@@ -543,6 +555,7 @@ def clear_task_instances(
for ti in tis:
ti.context_carrier = new_task_run_carrier(ti.dag_run.context_carrier)
session.flush()
+ return cleared
def _creator_note(val):
@@ -603,6 +616,29 @@ def uuid7() -> UUID:
return uuid6.uuid7()
+class LegacyTaskDataOwner(Base):
+ """Map the dag, task, run and map index of pre-3.4 XCom and rendered fields rows to their attempt UUID."""
+
+ __tablename__ = "legacy_task_data_owner"
+
+ dag_id: Mapped[str] = mapped_column(StringID(), nullable=False)
+ task_id: Mapped[str] = mapped_column(StringID(), nullable=False)
+ run_id: Mapped[str] = mapped_column(StringID(), nullable=False)
+ map_index: Mapped[int] = mapped_column(Integer, nullable=False)
+ task_instance_id: Mapped[UUID] = mapped_column(Uuid(), nullable=False)
+
+ __table_args__ = (
+ PrimaryKeyConstraint("dag_id", "task_id", "run_id", "map_index", name="legacy_task_data_owner_pkey"),
+ ForeignKeyConstraint(
+ ["task_instance_id"],
+ ["task_instance.id"],
+ name="legacy_task_data_owner_ti_fkey",
+ ondelete="CASCADE",
+ ),
+ Index("idx_legacy_task_data_owner_ti", "task_instance_id"),
+ )
+
+
class TaskInstance(Base, LoggingMixin, BaseWorkload):
"""
Task instances store the state of a task instance.
@@ -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())
+ archived_reason: Mapped[str | None] = mapped_column(String(50))
hostname: Mapped[str | None] = mapped_column(String(1000), nullable=True)
unixname: Mapped[str | None] = mapped_column(String(1000), nullable=True)
pool: Mapped[str] = mapped_column(String(256), nullable=False)
@@ -680,6 +718,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
_task_display_property_value: Mapped[str | None] = mapped_column(
"task_display_name", String(2000), nullable=True
)
+ # Legacy rows can predate DAG versioning; migration 0142 sets history references to missing dag versions to NULL.
dag_version_id: Mapped[UUID | None] = mapped_column(
Uuid(),
ForeignKey("dag_version.id", ondelete="RESTRICT"),
@@ -701,8 +740,30 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
Index("ti_trigger_id", trigger_id),
Index("ti_heartbeat", last_heartbeat_at),
Index("ti_dag_version_id", dag_version_id),
+ Index(
+ "ti_current_state",
+ working_set,
+ state,
+ postgresql_where=working_set.is_(True),
+ sqlite_where=working_set.is_(True),
+ ),
+ Index(
+ "ti_current_dag_run",
+ working_set,
+ dag_id,
+ run_id,
+ state,
+ postgresql_where=working_set.is_(True),
+ sqlite_where=working_set.is_(True),
+ ),
PrimaryKeyConstraint("id", name="task_instance_pkey"),
- UniqueConstraint("dag_id", "task_id", "run_id", "map_index", name="task_instance_composite_key"),
+ UniqueConstraint(
+ "dag_id", "task_id", "run_id", "map_index", "working_set", name="task_instance_current_key"
+ ),
+ UniqueConstraint(
+ "dag_id", "task_id", "run_id", "map_index", "try_number", name="task_instance_try_key"
+ ),
+ CheckConstraint("working_set IS NULL OR working_set = TRUE", name="ti_working_set_true_or_null"),
ForeignKeyConstraint(
[trigger_id],
["trigger.id"],
@@ -730,7 +791,11 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
triggerer_job = association_proxy("trigger", "triggerer_job")
dag_run = relationship("DagRun", back_populates="task_instances", lazy="joined", innerjoin=True)
rendered_task_instance_fields = relationship(
- "RenderedTaskInstanceFields", lazy="raise", uselist=False, passive_deletes=True
+ "RenderedTaskInstanceFields",
+ primaryjoin="TaskInstance.id == foreign(RenderedTaskInstanceFields.task_instance_id)",
+ viewonly=True,
+ lazy="raise",
+ uselist=False,
)
hitl_detail = relationship("HITLDetail", lazy="raise", uselist=False, passive_deletes=True)
@@ -917,6 +982,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
) -> TaskInstance | None:
query = (
select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
.options(lazyload(TaskInstance.dag_run)) # lazy load dag run to avoid locking it
.filter_by(
dag_id=dag_id,
@@ -956,12 +1022,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
query = select(
# Select the columns, not the ORM object, to bypass any session/ORM caching layer
*TaskInstance.__table__.columns
- ).filter_by(
- dag_id=self.dag_id,
- run_id=self.run_id,
- task_id=self.task_id,
- map_index=self.map_index,
- )
+ ).where(TaskInstance.id == self.id)
if lock_for_update:
query = query.with_for_update()
@@ -979,16 +1040,6 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
set_committed_value(self, attr_name, source[col.name])
- # ID may have changed, update SQLAs state and object tracking
- newkey = session.identity_key(type(self), (self.id,))
-
- # Delete anything under the new key
- if newkey != target_state.key:
- old = session.identity_map.get(newkey)
- if old is not self and old is not None:
- session.expunge(old)
- target_state.key = newkey
-
if target_state.attrs.dag_run.loaded_value is not NO_VALUE:
dr_key = session.identity_key(type(self.dag_run), (self.dag_run.id,))
if (dr := session.identity_map.get(dr_key)) is not None:
@@ -1071,28 +1122,98 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
# is the task still in the retry waiting period?
return self.state == TaskInstanceState.UP_FOR_RETRY and not self.ready_for_retry()
- def prepare_db_for_next_try(self, session: Session):
- """Archive this attempt and allocate the next attempt's UUID and try number."""
- from airflow.models.taskinstancehistory import TaskInstanceHistory
+ def retire(self, *, reason: str, session: Session) -> None:
+ """Remove this attempt from the working set while retaining its UUID and children."""
+ current = session.scalar(
+ select(TaskInstance.working_set).where(TaskInstance.id == self.id).with_for_update()
+ )
+ if current is not True:
+ raise ValueError("A retired task instance cannot be retired again")
+ if self.state not in State.finished:
+ self.state = TaskInstanceState.FAILED
+ if self.end_date is None:
+ self.end_date = timezone.utcnow()
+ self.set_duration()
+ self.working_set = None
+ self.archived_reason = reason
+ self.trigger_id = None
+ session.flush()
- TaskInstanceHistory.record_ti(self, session=session)
- session.execute(delete(TaskReschedule).filter_by(ti_id=self.id))
- self.external_executor_id = None
- self.id = uuid7()
- self.try_number += 1
+ @classmethod
+ def delete_attempts(
+ cls,
+ *,
+ dag_id: str,
+ run_id: str,
+ task_id: str,
+ map_index: int | None = None,
+ session: Session,
+ ) -> None:
+ """Delete every attempt, current and retired, of a task; all map indexes if ``map_index`` is None."""
+ statement = delete(cls).where(cls.dag_id == dag_id, cls.run_id == run_id, cls.task_id == task_id)
+ if map_index is not None:
+ statement = statement.where(cls.map_index == map_index)
+ session.execute(statement)
+
+ @classmethod
+ def get_last_try_numbers(
+ cls,
+ *,
+ dag_id: str,
+ task_id: str,
+ run_id: str,
+ map_indexes: Collection[int] | None = None,
+ session: Session,
+ ) -> dict[int, int]:
+ """Return the highest try number per map index across current and historical task instances."""
+ if map_indexes is not None and not map_indexes:
+ return {}
+ statement = (
+ select(cls.map_index, func.max(cls.try_number))
+ .where(cls.dag_id == dag_id, cls.task_id == task_id, cls.run_id == run_id)
+ .group_by(cls.map_index)
+ )
+ if map_indexes is not None:
+ statement = statement.where(cls.map_index.in_(map_indexes))
+ return {map_index: last_try for map_index, last_try in session.execute(statement)}
+
+ def prepare_db_for_next_try(self, session: Session) -> TaskInstance:
+ """Retire this UUID and return its successor in the caller's transaction."""
+ successor_state = self.state
+ dag_version_id = self.dag_version_id
+ self.retire(reason="retry", session=session)
+ values = {
+ attribute.columns[0].name: getattr(self, attribute.key)
+ for attribute in inspect(TaskInstance).column_attrs
+ }
+ values.update(
+ id=uuid7(),
+ try_number=self.try_number + 1,
+ working_set=True,
+ archived_reason=None,
+ trigger_id=None,
+ external_executor_id=None,
+ dag_version_id=dag_version_id,
+ state=successor_state,
+ )
+ session.execute(insert(TaskInstance.__table__).values(values))
+ successor = session.scalars(select(TaskInstance).where(TaskInstance.id == values["id"])).one()
+ successor.task = self.task
+ return successor
- def complete_restart(self, *, session: Session) -> None:
+ def complete_restart(self, *, session: Session) -> TaskInstance:
"""Release a cleared attempt after termination; the caller must hold its row lock."""
- if self.state != TaskInstanceState.RESTARTING:
- raise ValueError("Only a restarting task instance can complete a restart")
+ if self.state != TaskInstanceState.RESTARTING or self.working_set is not True:
+ raise ValueError("Only a current restarting task instance can complete a restart")
+ successor = self.prepare_db_for_next_try(session)
if self.task is not None:
- self.max_tries = self.try_number + self.task.retries
+ successor.max_tries = self.try_number + self.task.retries
else:
- self.max_tries = max(self.max_tries, self.try_number)
- self.prepare_db_for_next_try(session)
- self.state = None
- self.clear_next_method_args()
+ successor.max_tries = max(self.max_tries or 0, self.try_number)
+ successor.state = None
+ successor.clear_next_method_args()
session.flush()
+ return successor
@provide_session
def are_dependents_done(self, *, session: Session = NEW_SESSION) -> bool:
@@ -1115,6 +1236,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
return True
ti = select(func.count(TaskInstance.task_id)).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == self.dag_id,
TaskInstance.task_id.in_(task.downstream_task_ids),
TaskInstance.run_id == self.run_id,
@@ -1822,7 +1944,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
with create_session() as session:
session.execute(
update(TaskInstance)
- .where(TaskInstance.id == self.id)
+ .where(TaskInstance.working_set.is_(True), TaskInstance.id == self.id)
.values(last_heartbeat_at=timezone.utcnow())
)
@@ -1960,8 +2082,8 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
ti.state = State.UP_FOR_RETRY
ti.notify_failure(error)
- if allocate_next_try:
- ti.prepare_db_for_next_try(session)
+ if allocate_next_try and not test_mode:
+ ti = ti.prepare_db_for_next_try(session)
return ti
@@ -1989,7 +2111,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
test_mode: bool | None = None,
*,
session: Session = NEW_SESSION,
- ) -> None:
+ ) -> TaskInstance:
"""
Handle Failure for a task instance.
@@ -2018,6 +2140,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
if not test_mode:
TaskInstance.save_to_db(ti, session=session)
+ return ti
def is_eligible_to_retry(self) -> bool:
"""Is task instance is eligible for retry."""
@@ -2057,15 +2180,9 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
:param key: Key to store the value under.
:param value: Value to store. Only be JSON-serializable may be used otherwise.
"""
- XComModel.set(
- key=key,
- value=value,
- task_id=self.task_id,
- dag_id=self.dag_id,
- run_id=self.run_id,
- map_index=self.map_index,
- session=session,
- )
+ from airflow.models.xcom import XComModel
+
+ XComModel.set_for_attempt(task_instance_id=self.id, key=key, value=value, session=session)
@provide_session
def xcom_pull(
@@ -2083,6 +2200,8 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
""":meta private:""" # noqa: D400
# This is only kept for compatibility in tests for now while AIP-72 is in progress.
+ from airflow.models.xcom import XComModel, xcom_entity
+
if dag_id is None:
dag_id = self.dag_id
if run_id is None:
@@ -2096,6 +2215,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
map_indexes=map_indexes,
include_prior_dates=include_prior_dates,
)
+ entity = xcom_entity(query)
# NOTE: Since we're only fetching the value field and not the whole
# class, the @recreate annotation does not kick in. Therefore we need to
@@ -2105,11 +2225,11 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
if (task_ids is None or isinstance(task_ids, str)) and not isinstance(map_indexes, Iterable):
first = session.execute(
query.with_only_columns(
- XComModel.run_id,
- XComModel.task_id,
- XComModel.dag_id,
- XComModel.map_index,
- XComModel.value,
+ entity.run_id,
+ entity.task_id,
+ entity.dag_id,
+ entity.map_index,
+ entity.value,
).limit(1)
).first()
if first is None: # No matching XCom at all.
@@ -2119,8 +2239,8 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
return XComModel.deserialize_value(first)
return LazyXComSelectSequence.from_select(
- query.with_only_columns(XComModel.value).order_by(None),
- order_by=[XComModel.map_index.expression],
+ query.with_only_columns(entity.value).order_by(None),
+ order_by=[entity.map_index.expression],
session=session,
)
@@ -2128,24 +2248,24 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
# Order return values to match task_ids and map_indexes ordering.
ordering: list[Any] = []
if task_ids is None or isinstance(task_ids, str):
- ordering.append(XComModel.task_id)
+ ordering.append(entity.task_id)
elif task_id_whens := {tid: i for i, tid in enumerate(task_ids)}:
- ordering.append(case(task_id_whens, value=XComModel.task_id))
+ ordering.append(case(task_id_whens, value=entity.task_id))
else:
- ordering.append(XComModel.task_id)
+ ordering.append(entity.task_id)
if map_indexes is None or isinstance(map_indexes, int):
- ordering.append(XComModel.map_index)
+ ordering.append(entity.map_index)
elif isinstance(map_indexes, range):
if map_indexes.step < 0:
- ordering.append(XComModel.map_index.desc())
+ ordering.append(entity.map_index.desc())
else:
- ordering.append(XComModel.map_index)
+ ordering.append(entity.map_index)
elif map_index_whens := {map_index: i for i, map_index in enumerate(map_indexes)}:
- ordering.append(case(map_index_whens, value=XComModel.map_index))
+ ordering.append(case(map_index_whens, value=entity.map_index))
else:
- ordering.append(XComModel.map_index)
+ ordering.append(entity.map_index)
return LazyXComSelectSequence.from_select(
- query.with_only_columns(XComModel.value).order_by(None),
+ query.with_only_columns(entity.value).order_by(None),
order_by=ordering,
session=session,
)
@@ -2193,7 +2313,11 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
stmt = (
select(func.count())
.select_from(TaskInstance)
- .where(TaskInstance.dag_id == self.dag_id, TaskInstance.task_id == self.task_id)
+ .where(
+ TaskInstance.working_set.is_(True),
+ TaskInstance.dag_id == self.dag_id,
+ TaskInstance.task_id == self.task_id,
+ )
)
if states:
stmt = stmt.where(or_(*(TaskInstance.state == s for s in states)))
@@ -2342,21 +2466,12 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
:meta private:
"""
from airflow.models.renderedtifields import RenderedTaskInstanceFields
+ from airflow.models.xcom import XComModel
- tables: list[type[TaskInstanceDependencies]] = [
- XComModel,
- RenderedTaskInstanceFields,
- ]
+ producer_ids = select(TaskInstance.id).where(TaskInstance.id == self.id)
+ XComModel.delete_for_attempts(producer_ids=producer_ids, key=None, session=session)
+ RenderedTaskInstanceFields.delete_for_attempts(producer_ids=producer_ids, session=session)
tables_by_id: list[type[Base]] = [TaskInstanceNote, TaskReschedule]
- for table in tables:
- session.execute(
- delete(table).where(
- table.dag_id == self.dag_id,
- table.task_id == self.task_id,
- table.run_id == self.run_id,
- table.map_index == self.map_index,
- )
- )
for table in tables_by_id:
session.execute(delete(table).where(table.ti_id == self.id))
@@ -2398,6 +2513,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
state: str | None = None
unmapped_ti: TaskInstance | None = session.scalars(
select(TaskInstance).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == task.dag_id,
TaskInstance.task_id == task.task_id,
TaskInstance.run_id == run_id,
@@ -2406,6 +2522,10 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
)
).one_or_none()
+ last_tries = TaskInstance.get_last_try_numbers(
+ dag_id=task.dag_id, task_id=task.task_id, run_id=run_id, session=session
+ )
+
all_expanded_tis: list[TaskInstance] = []
if unmapped_ti:
@@ -2430,7 +2550,9 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
unmapped_ti.state = TaskInstanceState.SKIPPED
else:
dr = unmapped_ti.dag_run
+ state = unmapped_ti.state
zero_index_ti_exists = exists_query(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == task.dag_id,
TaskInstance.task_id == task.task_id,
TaskInstance.run_id == run_id,
@@ -2440,6 +2562,11 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
if not zero_index_ti_exists:
# Otherwise convert this into the first mapped index, and create
# TaskInstance for other indexes.
+ promoted_try = max(unmapped_ti.try_number, last_tries.get(0, -1) + 1)
+ unmapped_ti.max_tries = (
+ (unmapped_ti.max_tries or 0) + promoted_try - unmapped_ti.try_number
+ )
+ unmapped_ti.try_number = promoted_try
unmapped_ti.map_index = 0
task.log.debug("Updated in place to become %s", unmapped_ti)
all_expanded_tis.append(unmapped_ti)
@@ -2449,7 +2576,6 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
else:
task.log.debug("Deleting the original task instance: %s", unmapped_ti)
session.delete(unmapped_ti)
- state = unmapped_ti.state
if total_length is None or total_length < 1:
# Nothing to fixup.
@@ -2459,6 +2585,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
current_max_mapping = (
session.scalar(
select(func.max(TaskInstance.map_index)).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == task.dag_id,
TaskInstance.task_id == task.task_id,
TaskInstance.run_id == run_id,
@@ -2494,6 +2621,8 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
state=state,
dag_version_id=dag_version_id,
)
+ ti.try_number = last_tries.get(index, -1) + 1
+ ti.max_tries += ti.try_number
task.log.debug("Expanding TIs upserted %s", ti)
_add_and_prime_mapped_ti(
ti, task, dr, session=session, context_carrier=new_task_run_carrier(dr.context_carrier)
@@ -2510,6 +2639,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
# Any (old) task instances with inapplicable indexes (>= the total
# number we need) are set to "REMOVED".
query = select(TaskInstance).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == task.dag_id,
TaskInstance.task_id == task.task_id,
TaskInstance.run_id == run_id,
diff --git a/airflow-core/src/airflow/models/taskinstancehistory.py b/airflow-core/src/airflow/models/taskinstancehistory.py
deleted file mode 100644
index 1f741507bd5..00000000000
--- a/airflow-core/src/airflow/models/taskinstancehistory.py
+++ /dev/null
@@ -1,225 +0,0 @@
-#
-# 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.
-from __future__ import annotations
-
-from datetime import datetime
-from typing import TYPE_CHECKING
-from uuid import UUID
-
-import dill
-from sqlalchemy import (
- JSON,
- DateTime,
- Float,
- ForeignKeyConstraint,
- Index,
- Integer,
- String,
- Text,
- UniqueConstraint,
- Uuid,
- func,
- select,
-)
-from sqlalchemy.dialects import postgresql
-from sqlalchemy.ext.mutable import MutableDict
-from sqlalchemy.orm import Mapped, mapped_column, relationship
-
-from airflow._shared.timezones import timezone
-from airflow.models.base import Base, StringID
-from airflow.models.hitl import HITLDetail
-from airflow.models.hitl_history import HITLDetailHistory
-from airflow.utils.session import NEW_SESSION, provide_session
-from airflow.utils.sqlalchemy import (
- ExecutorConfigType,
- ExtendedJSON,
- UtcDateTime,
-)
-from airflow.utils.state import State, TaskInstanceState
-
-if TYPE_CHECKING:
- from sqlalchemy.orm.session import Session
-
- from airflow.models import DagRun
- from airflow.models.taskinstance import TaskInstance
- from airflow.models.taskinstancekey import TaskInstanceKey
-
-
-class TaskInstanceHistory(Base):
- """
- Store old tries of TaskInstances.
-
- :meta private:
- """
-
- __tablename__ = "task_instance_history"
- task_instance_id: Mapped[UUID] = mapped_column(
- Uuid(),
- nullable=False,
- primary_key=True,
- )
- task_id: Mapped[str] = mapped_column(StringID(), nullable=False)
- dag_id: Mapped[str] = mapped_column(StringID(), nullable=False)
- run_id: Mapped[str] = mapped_column(StringID(), nullable=False)
- map_index: Mapped[int] = mapped_column(Integer, nullable=False, server_default="-1")
- try_number: Mapped[int] = mapped_column(Integer, nullable=False)
- start_date: Mapped[datetime | None] = mapped_column(UtcDateTime, nullable=True)
- end_date: Mapped[datetime | None] = mapped_column(UtcDateTime, nullable=True)
- duration: Mapped[float | None] = mapped_column(Float, nullable=True)
- state: Mapped[str | None] = mapped_column(String(20), nullable=True)
- max_tries: Mapped[int | None] = mapped_column(Integer, server_default="-1", nullable=True)
- hostname: Mapped[str | None] = mapped_column(String(1000), nullable=True)
- unixname: Mapped[str | None] = mapped_column(String(1000), nullable=True)
- pool: Mapped[str] = mapped_column(String(256), nullable=False)
- pool_slots: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
- queue: Mapped[str | None] = mapped_column(String(256), nullable=True)
- priority_weight: Mapped[int | None] = mapped_column(Integer, nullable=True)
- operator: Mapped[str | None] = mapped_column(String(1000), nullable=True)
- custom_operator_name: Mapped[str | None] = mapped_column(String(1000), nullable=True)
- queued_dttm: Mapped[datetime | None] = mapped_column(UtcDateTime, nullable=True)
- scheduled_dttm: Mapped[datetime | None] = mapped_column(UtcDateTime, nullable=True)
- queued_by_job_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
- pid: Mapped[int | None] = mapped_column(Integer, nullable=True)
- executor: Mapped[str | None] = mapped_column(String(1000), nullable=True)
- executor_config: Mapped[dict | None] = mapped_column(ExecutorConfigType(pickler=dill), nullable=True)
- updated_at: Mapped[datetime | None] = mapped_column(
- UtcDateTime, default=timezone.utcnow, onupdate=timezone.utcnow, nullable=True
- )
- rendered_map_index: Mapped[str | None] = mapped_column(String(250), nullable=True)
- context_carrier: Mapped[dict | None] = mapped_column(MutableDict.as_mutable(ExtendedJSON), nullable=True)
-
- external_executor_id: Mapped[str | None] = mapped_column(Text(), nullable=True)
- trigger_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
- trigger_timeout: Mapped[DateTime | None] = mapped_column(DateTime, nullable=True)
- next_method: Mapped[str | None] = mapped_column(String(1000), nullable=True)
- next_kwargs: Mapped[dict | None] = mapped_column(
- MutableDict.as_mutable(JSON().with_variant(postgresql.JSONB, "postgresql")), nullable=True
- )
-
- task_display_name: Mapped[str | None] = mapped_column(String(2000), nullable=True)
- dag_version_id: Mapped[UUID | None] = mapped_column(Uuid(), nullable=True)
-
- # Retry policy snapshot: copied from TaskInstance on record_ti() so the
- # audit trail of "why did the policy decide N seconds, reason X" is
- # preserved per try (TI columns are cleared on the next ti_run).
- retry_delay_override: Mapped[float | None] = mapped_column(Float, nullable=True)
- retry_reason: Mapped[str | None] = mapped_column(String(500), nullable=True)
-
- dag_version = relationship(
- "DagVersion",
- primaryjoin="TaskInstanceHistory.dag_version_id == DagVersion.id",
- viewonly=True,
- foreign_keys=[dag_version_id],
- )
-
- dag_run = relationship(
- "DagRun",
- primaryjoin="and_(TaskInstanceHistory.run_id == DagRun.run_id, DagRun.dag_id == TaskInstanceHistory.dag_id)",
- viewonly=True,
- foreign_keys=[run_id, dag_id],
- )
-
- hitl_detail = relationship("HITLDetailHistory", lazy="raise", uselist=False)
-
- def __init__(
- self,
- ti: TaskInstance,
- state: str | None = None,
- ):
- super().__init__()
- for column in self.__table__.columns:
- if column.name == "id":
- continue
- if column.name == "task_instance_id":
- setattr(self, column.name, ti.id)
- continue
- setattr(self, column.name, getattr(ti, column.name))
-
- if state:
- self.state = state
-
- __table_args__ = (
- ForeignKeyConstraint(
- [dag_id, task_id, run_id, map_index],
- [
- "task_instance.dag_id",
- "task_instance.task_id",
- "task_instance.run_id",
- "task_instance.map_index",
- ],
- name="task_instance_history_ti_fkey",
- ondelete="CASCADE",
- onupdate="CASCADE",
- ),
- UniqueConstraint(
- "dag_id",
- "task_id",
- "run_id",
- "map_index",
- "try_number",
- name="task_instance_history_dtrt_uq",
- ),
- Index("idx_tih_dag_run", dag_id, run_id),
- )
-
- @property
- def id(self) -> UUID:
- """Alias for primary key field to support TaskInstance."""
- return self.task_instance_id
-
- @property
- def key(self) -> TaskInstanceKey:
- """Returns a key that identifies this history record, mirroring TaskInstance.key."""
- from airflow.models.taskinstancekey import TaskInstanceKey
-
- return TaskInstanceKey(self.dag_id, self.task_id, self.run_id, self.try_number, self.map_index)
-
- @staticmethod
- @provide_session
- def record_ti(ti: TaskInstance, *, session: Session = NEW_SESSION) -> None:
- """Record a TaskInstance to TaskInstanceHistory."""
- exists_q = session.scalar(
- select(func.count(TaskInstanceHistory.task_id)).where(
- TaskInstanceHistory.dag_id == ti.dag_id,
- TaskInstanceHistory.task_id == ti.task_id,
- TaskInstanceHistory.run_id == ti.run_id,
- TaskInstanceHistory.map_index == ti.map_index,
- TaskInstanceHistory.try_number == ti.try_number,
- )
- )
- if exists_q:
- return
- ti_history_state = ti.state
- if ti.state not in State.finished:
- ti_history_state = TaskInstanceState.FAILED
- # Callers that know when the try actually ended (e.g. the Execution API
- # retry path) pre-set end_date and duration; only stamp archive time when unset.
- if ti.end_date is None:
- ti.end_date = timezone.utcnow()
- ti.set_duration()
- ti_history = TaskInstanceHistory(ti, state=ti_history_state)
- session.add(ti_history)
-
- ti_hitl_detail = session.scalar(select(HITLDetail).where(HITLDetail.ti_id == ti.id))
- if ti_hitl_detail is not None:
- session.add(HITLDetailHistory(ti_hitl_detail))
-
- @provide_session
- def get_dagrun(self, *, session: Session = NEW_SESSION) -> DagRun:
- """Return the DagRun for this TaskInstanceHistory, matching TaskInstance."""
- return self.dag_run
diff --git a/airflow-core/src/airflow/models/trigger.py b/airflow-core/src/airflow/models/trigger.py
index 6a3e704fe79..2a6cce907c9 100644
--- a/airflow-core/src/airflow/models/trigger.py
+++ b/airflow-core/src/airflow/models/trigger.py
@@ -245,7 +245,9 @@ class Trigger(Base):
session.execute(
update(TaskInstance)
.where(
- TaskInstance.state != TaskInstanceState.DEFERRED, TaskInstance.trigger_id.is_not(None)
+ TaskInstance.working_set.is_(True),
+ TaskInstance.state != TaskInstanceState.DEFERRED,
+ TaskInstance.trigger_id.is_not(None),
)
.values(trigger_id=None)
)
@@ -280,7 +282,9 @@ class Trigger(Base):
# Resume deferred tasks
for task_instance in session.scalars(
select(TaskInstance).where(
- TaskInstance.trigger_id == trigger_id, TaskInstance.state == TaskInstanceState.DEFERRED
+ TaskInstance.working_set.is_(True),
+ TaskInstance.trigger_id == trigger_id,
+ TaskInstance.state == TaskInstanceState.DEFERRED,
)
):
handle_event_submit(event, task_instance=task_instance, session=session)
@@ -319,7 +323,9 @@ class Trigger(Base):
"""
for task_instance in session.scalars(
select(TaskInstance).where(
- TaskInstance.trigger_id == trigger_id, TaskInstance.state == TaskInstanceState.DEFERRED
+ TaskInstance.working_set.is_(True),
+ TaskInstance.trigger_id == trigger_id,
+ TaskInstance.state == TaskInstanceState.DEFERRED,
)
):
# Add the error and set the next_method to the fail state
@@ -467,7 +473,10 @@ class Trigger(Base):
select(cls.id)
.prefix_with("STRAIGHT_JOIN", dialect="mysql")
.join(TaskInstance, cls.id == TaskInstance.trigger_id, isouter=False)
- .where(or_(cls.triggerer_id.is_(None), cls.triggerer_id.not_in(alive_triggerer_ids)))
+ .where(
+ TaskInstance.working_set.is_(True),
+ or_(cls.triggerer_id.is_(None), cls.triggerer_id.not_in(alive_triggerer_ids)),
+ )
.order_by(coalesce(TaskInstance.priority_weight, 0).desc(), cls.created_date),
# Asset triggers
select(cls.id)
@@ -652,9 +661,6 @@ def _(event: BaseTaskEndEvent, *, task_instance: TaskInstance, session: Session)
from airflow.callbacks.database_callback_sink import DatabaseCallbackSink
from airflow.utils.state import TaskInstanceState
- # Prevent the task from resuming on a worker.
- task_instance.trigger_id = None
-
callback_type = event.task_instance_state
should_retry = False
@@ -729,9 +735,10 @@ def _(event: BaseTaskEndEvent, *, task_instance: TaskInstance, session: Session)
task_instance.end_date = timezone.utcnow()
task_instance.set_duration()
task_instance.clear_next_method_args()
- task_instance.prepare_db_for_next_try(session)
+ task_instance = task_instance.prepare_db_for_next_try(session)
task_instance.state = TaskInstanceState.UP_FOR_RETRY
else:
+ task_instance.trigger_id = None
task_instance.set_state(event.task_instance_state, session=session)
_push_xcoms_if_necessary()
diff --git a/airflow-core/src/airflow/models/xcom.py b/airflow-core/src/airflow/models/xcom.py
index 58e5c429f66..d47d55f66c0 100644
--- a/airflow-core/src/airflow/models/xcom.py
+++ b/airflow-core/src/airflow/models/xcom.py
@@ -19,10 +19,13 @@ from __future__ import annotations
import json
import logging
+import threading
from collections.abc import Iterable
from datetime import datetime
from typing import TYPE_CHECKING, Any, cast
+from uuid import UUID
+import uuid6
from sqlalchemy import (
JSON,
Boolean,
@@ -32,37 +35,46 @@ from sqlalchemy import (
Integer,
PrimaryKeyConstraint,
String,
+ UniqueConstraint,
+ Uuid,
+ and_,
delete,
+ event,
func,
select,
+ union_all,
)
from sqlalchemy.dialects import postgresql
-from sqlalchemy.ext.associationproxy import association_proxy
-from sqlalchemy.orm import Mapped, mapped_column, relationship
+from sqlalchemy.orm import Mapped, aliased, foreign, mapped_column, relationship
+from sqlalchemy.schema import conv
from airflow._shared.timezones import timezone
-from airflow.models.base import COLLATION_ARGS, ID_LEN, TaskInstanceDependencies
+from airflow.models.base import COLLATION_ARGS, ID_LEN, Base, TaskInstanceDependencies
from airflow.utils.db import LazySelectSequence
from airflow.utils.helpers import is_container
from airflow.utils.json import XComDecoder, XComEncoder
from airflow.utils.session import NEW_SESSION, provide_session
-from airflow.utils.sqlalchemy import UtcDateTime
+from airflow.utils.sqlalchemy import UtcDateTime, build_upsert_stmt
log = logging.getLogger(__name__)
if TYPE_CHECKING:
from sqlalchemy.engine import Row
from sqlalchemy.orm import Session
+ from sqlalchemy.orm.util import AliasedClass
from sqlalchemy.sql.expression import Select, TextClause
+ from airflow.models.dagrun import DagRun
+ from airflow.models.taskinstance import TaskInstance
+
XCOM_RETURN_KEY = "return_value"
-class XComModel(TaskInstanceDependencies):
- """XCom model class. Contains table and some utilities."""
+class XComModelV1(TaskInstanceDependencies):
+ """XCom values stored before Airflow 3.4, keyed by dag, task, run and map index."""
- __tablename__ = "xcom"
+ __tablename__ = "xcom_v1"
dag_run_id: Mapped[int] = mapped_column(Integer(), nullable=False, primary_key=True)
task_id: Mapped[str] = mapped_column(String(ID_LEN, **COLLATION_ARGS), nullable=False, primary_key=True)
@@ -86,35 +98,123 @@ class XComModel(TaskInstanceDependencies):
# separately, and enforce uniqueness with DagRun.id instead.
Index("idx_xcom_key", key),
Index("idx_xcom_task_instance", dag_id, task_id, run_id, map_index),
- CheckConstraint(mapped_length >= 0, name="mapped_length_not_negative"),
+ CheckConstraint(mapped_length >= 0, name=conv("ck_xcom_mapped_length_not_negative")),
PrimaryKeyConstraint("dag_run_id", "task_id", "map_index", "key", name="xcom_pkey"),
ForeignKeyConstraint(
[dag_id, task_id, run_id, map_index],
[
- "task_instance.dag_id",
- "task_instance.task_id",
- "task_instance.run_id",
- "task_instance.map_index",
+ "legacy_task_data_owner.dag_id",
+ "legacy_task_data_owner.task_id",
+ "legacy_task_data_owner.run_id",
+ "legacy_task_data_owner.map_index",
],
name="xcom_task_instance_fkey",
ondelete="CASCADE",
),
)
- dag_run = relationship(
- "DagRun",
- primaryjoin="XComModel.dag_run_id == foreign(DagRun.id)",
- uselist=False,
- lazy="joined",
- passive_deletes="all",
- )
- logical_date = association_proxy("dag_run", "logical_date")
- task = relationship(
- "TaskInstance",
- viewonly=True,
- lazy="raise",
+class XComModelV2(Base):
+ """XCom values stored per task attempt, keyed by the attempt UUID."""
+
+ __tablename__ = "xcom_v2"
+
+ id: Mapped[UUID] = mapped_column(Uuid(), primary_key=True, default=uuid6.uuid7)
+ task_instance_id: Mapped[UUID] = mapped_column(Uuid(), nullable=False)
+ key: Mapped[str] = mapped_column(String(512, **COLLATION_ARGS), nullable=False)
+ value: Mapped[Any] = mapped_column(JSON().with_variant(postgresql.JSONB, "postgresql"), nullable=True)
+ timestamp: Mapped[datetime] = mapped_column(UtcDateTime, default=timezone.utcnow, nullable=False)
+ dag_result: Mapped[bool | None] = mapped_column(Boolean, nullable=True, default=False)
+ mapped_length: Mapped[int | None] = mapped_column(Integer, nullable=True)
+
+ __table_args__ = (
+ PrimaryKeyConstraint("id", name="xcom_v2_pkey"),
+ UniqueConstraint("task_instance_id", "key", name="xcom_v2_ti_key_uq"),
+ ForeignKeyConstraint(
+ ["task_instance_id"], ["task_instance.id"], name="xcom_v2_ti_fkey", ondelete="CASCADE"
+ ),
+ CheckConstraint(mapped_length >= 0, name="xcom_v2_mapped_length_not_negative"),
)
+ task = relationship("TaskInstance", viewonly=True, lazy="raise")
+
+ @classmethod
+ def get_for_attempt(cls, task_instance_id: UUID, key: str, *, session: Session) -> XComModelV2 | None:
+ return session.scalar(select(cls).where(cls.task_instance_id == task_instance_id, cls.key == key))
+
+
+class _XComOperations:
+ @classmethod
+ @provide_session
+ def set_for_attempt(
+ cls,
+ *,
+ task_instance_id: UUID,
+ key: str,
+ value: Any,
+ serialize: bool = True,
+ dag_result: bool = False,
+ mapped_length: int | None = None,
+ session: Session = NEW_SESSION,
+ ) -> None:
+ if not key:
+ raise ValueError(f"XCom key must be a non-empty string. Received: {key!r}")
+ if isinstance(value, LazySelectSequence):
+ log.warning("Coercing mapped lazy XCom for attempt %s to a list", task_instance_id)
+ value = list(value)
+ if serialize:
+ value = cls.serialize_value(value, key=key)
+ updated = {
+ "value": value,
+ "timestamp": timezone.utcnow(),
+ "dag_result": dag_result,
+ "mapped_length": mapped_length,
+ }
+ session.flush()
+ session.execute(
+ build_upsert_stmt(
+ session.get_bind().dialect.name,
+ XComModelV2,
+ ["task_instance_id", "key"],
+ {"id": uuid6.uuid7(), "task_instance_id": task_instance_id, "key": key, **updated},
+ updated,
+ )
+ )
+ for existing in session.identity_map.values():
+ if (
+ isinstance(existing, XComModelV2)
+ and existing.__dict__.get("task_instance_id", task_instance_id) == task_instance_id
+ and existing.__dict__.get("key", key) == key
+ ):
+ session.expire(existing, list(updated))
+
+ @classmethod
+ @provide_session
+ def delete_for_attempts(
+ cls,
+ *,
+ producer_ids: Select,
+ key: str | None,
+ session: Session = NEW_SESSION,
+ ) -> None:
+ from airflow.models.taskinstance import LegacyTaskDataOwner
+
+ owner = LegacyTaskDataOwner.__table__
+ legacy = XComModelV1.__table__
+ owns_legacy = (
+ select(1)
+ .where(
+ owner.c.task_instance_id.in_(producer_ids),
+ *(owner.c[name] == legacy.c[name] for name in ("dag_id", "task_id", "run_id", "map_index")),
+ )
+ .exists()
+ )
+ v1_delete = delete(legacy).where(owns_legacy)
+ v2_delete = delete(XComModelV2).where(XComModelV2.task_instance_id.in_(producer_ids))
+ if key is not None:
+ v1_delete = v1_delete.where(legacy.c.key == key)
+ v2_delete = v2_delete.where(XComModelV2.key == key)
+ session.execute(v1_delete)
+ session.execute(v2_delete.execution_options(synchronize_session="fetch"))
@classmethod
@provide_session
@@ -149,14 +249,10 @@ class XComModel(TaskInstanceDependencies):
if not run_id:
raise ValueError(f"run_id must be passed. Passed run_id={run_id}")
-
- # Use bulk delete for efficiency instead of loading and deleting one by one
- delete_stmt = delete(cls).where(cls.dag_id == dag_id, cls.task_id == task_id, cls.run_id == run_id)
- if map_index is not None:
- delete_stmt = delete_stmt.where(cls.map_index == map_index)
-
- session.execute(delete_stmt)
- session.commit()
+ producer_ids = select_producers(
+ dag_ids=dag_id, task_ids=task_id, run_id=run_id, map_indexes=map_index
+ )
+ cls.delete_for_attempts(producer_ids=producer_ids, key=None, session=session)
@classmethod
@provide_session
@@ -190,73 +286,24 @@ class XComModel(TaskInstanceDependencies):
:param session: Database session. If not given, a new session will be
created for this function.
"""
- from airflow.models.dagrun import DagRun
-
- if not key:
- raise ValueError(f"XCom key must be a non-empty string. Received: {key!r}")
-
if not run_id:
raise ValueError(f"run_id must be passed. Passed run_id={run_id}")
-
- dag_run_id = session.scalar(select(DagRun.id).where(DagRun.dag_id == dag_id, DagRun.run_id == run_id))
- if dag_run_id is None:
- raise ValueError(f"DAG run not found on DAG {dag_id!r} with ID {run_id!r}")
-
- # Seamlessly resolve LazySelectSequence to a list. This intends to work
- # as a "lazy list" to avoid pulling a ton of XComs unnecessarily, but if
- # it's pushed into XCom, the user should be aware of the performance
- # implications, and this avoids leaking the implementation detail.
- if isinstance(value, LazySelectSequence):
- warning_message = (
- "Coercing mapped lazy proxy %s from task %s (DAG %s, run %s) "
- "to list, which may degrade performance. Review resource "
- "requirements for this operation, and call list() to suppress "
- "this message. See Dynamic Task Mapping documentation for "
- "more information about lazy proxy objects."
- )
- log.warning(
- warning_message,
- "return value" if key == XCOM_RETURN_KEY else f"value {key}",
- task_id,
- dag_id,
- run_id,
- )
- value = list(value)
-
- if serialize:
- value = cls.serialize_value(
- value=value,
- key=key,
- task_id=task_id,
- dag_id=dag_id,
- run_id=run_id,
- map_index=map_index,
- )
-
- # Remove duplicate XComs and insert a new one.
- session.execute(
- delete(cls).where(
- cls.key == key,
- cls.run_id == run_id,
- cls.task_id == task_id,
- cls.dag_id == dag_id,
- cls.map_index == map_index,
- )
+ owner = session.scalar(
+ select_producers(dag_ids=dag_id, task_ids=task_id, run_id=run_id, map_indexes=map_index)
)
-
- new = cls(
- dag_run_id=dag_run_id,
+ if owner is None:
+ raise ValueError(
+ f"Task instance not found: {dag_id}.{task_id} in {run_id}, map index {map_index}"
+ )
+ cls.set_for_attempt(
+ task_instance_id=owner,
key=key,
value=value,
- run_id=run_id,
- task_id=task_id,
- dag_id=dag_id,
- map_index=map_index,
+ serialize=serialize,
dag_result=dag_result,
mapped_length=mapped_length,
+ session=session,
)
- session.add(new)
- session.flush()
@classmethod
def get_many(
@@ -269,6 +316,7 @@ class XComModel(TaskInstanceDependencies):
map_indexes: int | Iterable[int] | None = None,
include_prior_dates: bool = False,
limit: int | None = None,
+ try_number: int | None = None,
) -> Select[tuple[XComModel]]:
"""
Composes a query to get one or more XCom entries.
@@ -276,6 +324,8 @@ class XComModel(TaskInstanceDependencies):
This function returns an SQLAlchemy query of full XCom objects. If you
just want one stored value, use :meth:`get_one` instead.
+ Use :func:`xcom_entity` for columns added to the returned statement.
+
:param run_id: DAG run ID for the task.
:param key: A key for the XComs. If provided, only XComs with matching
keys will be returned. Pass *None* (default) to remove the filter.
@@ -288,58 +338,30 @@ class XComModel(TaskInstanceDependencies):
:param include_prior_dates: If *False* (default), only XComs from the
specified DAG run are returned. If *True*, all matching XComs are
returned regardless of the run it belongs to.
- :param session: Database session. If not given, a new session will be
- created for this function.
:param limit: Limiting returning XComs
+ :param try_number: Read the XComs of this public try, current or retired, instead of
+ the current attempt.
"""
- from airflow.models.dagrun import DagRun
-
if key is not None and not key:
raise ValueError(f"XCom key must be a non-empty string. Received: {key!r}")
-
if not run_id:
raise ValueError(f"run_id must be passed. Passed run_id={run_id}")
-
- query = select(cls).join(XComModel.dag_run)
-
- if key:
- query = query.where(XComModel.key == key)
-
- if is_container(task_ids):
- query = query.where(cls.task_id.in_(task_ids))
- elif task_ids is not None:
- query = query.where(cls.task_id == task_ids)
-
- if is_container(dag_ids):
- query = query.where(cls.dag_id.in_(dag_ids))
- elif dag_ids is not None:
- query = query.where(cls.dag_id == dag_ids)
-
- if isinstance(map_indexes, range) and map_indexes.step == 1:
- query = query.where(cls.map_index >= map_indexes.start, cls.map_index < map_indexes.stop)
- elif is_container(map_indexes):
- query = query.where(cls.map_index.in_(map_indexes))
- elif map_indexes is not None:
- query = query.where(cls.map_index == map_indexes)
-
- if include_prior_dates:
- dag_run_date_for_run_id = (
- select(func.coalesce(DagRun.logical_date, DagRun.run_after))
- .where(DagRun.run_id == run_id, DagRun.dag_id == cls.dag_id)
- .correlate(cls)
- .scalar_subquery()
- )
-
- query = query.where(
- func.coalesce(DagRun.logical_date, DagRun.run_after) <= dag_run_date_for_run_id
- )
- else:
- query = query.where(cls.run_id == run_id)
-
- query = query.order_by(DagRun.logical_date.desc(), cls.timestamp.desc())
+ statement = build_xcom_read_query(
+ producer_ids=select_producers(
+ run_id=run_id,
+ task_ids=task_ids,
+ dag_ids=dag_ids,
+ map_indexes=map_indexes,
+ include_prior_dates=include_prior_dates,
+ try_number=try_number,
+ ),
+ key=key,
+ )
+ entity = xcom_entity(statement)
+ statement = statement.order_by(entity.logical_date.desc(), entity.timestamp.desc())
if limit:
- return query.limit(limit)
- return query
+ statement = statement.limit(limit)
+ return statement
@staticmethod
def serialize_value(
@@ -399,6 +421,190 @@ class XComModel(TaskInstanceDependencies):
return result.value
+def _rows(*, producer_ids: Select | None = None, key: str | None = None):
+ from airflow.models.dagrun import DagRun
+ from airflow.models.taskinstance import LegacyTaskDataOwner, TaskInstance
+
+ coordinates = ("dag_id", "task_id", "run_id", "map_index")
+ data = ("key", "value", "timestamp", "dag_result", "mapped_length")
+ run_join = and_(DagRun.dag_id == TaskInstance.dag_id, DagRun.run_id == TaskInstance.run_id)
+ context = [
+ *(getattr(TaskInstance, name) for name in coordinates),
+ DagRun.id.label("dag_run_id"),
+ DagRun.logical_date,
+ DagRun.run_after,
+ ]
+ new_rows = (
+ select(XComModelV2.task_instance_id, *(getattr(XComModelV2, name) for name in data), *context)
+ .select_from(XComModelV2)
+ .join(TaskInstance, XComModelV2.task_instance_id == TaskInstance.id)
+ .join(DagRun, run_join)
+ )
+ old_rows = (
+ select(LegacyTaskDataOwner.task_instance_id, *(getattr(XComModelV1, name) for name in data), *context)
+ .select_from(LegacyTaskDataOwner)
+ .join(
+ XComModelV1,
+ and_(*(getattr(LegacyTaskDataOwner, name) == getattr(XComModelV1, name) for name in coordinates)),
+ )
+ .join(TaskInstance, LegacyTaskDataOwner.task_instance_id == TaskInstance.id)
+ .join(DagRun, run_join)
+ .where(
+ ~select(1)
+ .select_from(XComModelV2)
+ .where(
+ XComModelV2.task_instance_id == LegacyTaskDataOwner.task_instance_id,
+ XComModelV2.key == XComModelV1.key,
+ )
+ .exists()
+ )
+ )
+ if producer_ids is not None:
+ new_rows = new_rows.where(XComModelV2.task_instance_id.in_(producer_ids))
+ old_rows = old_rows.where(LegacyTaskDataOwner.task_instance_id.in_(producer_ids))
+ if key is not None:
+ new_rows = new_rows.where(XComModelV2.key == key)
+ old_rows = old_rows.where(XComModelV1.key == key)
+ return union_all(new_rows, old_rows)
+
+
+if TYPE_CHECKING:
+
+ class XComModel(_XComOperations, Base):
+ """Read both stores without sharing writable ORM identity."""
+
+ task_instance_id: Mapped[UUID]
+ key: Mapped[str]
+ value: Mapped[Any]
+ timestamp: Mapped[datetime]
+ dag_result: Mapped[bool | None]
+ mapped_length: Mapped[int | None]
+ dag_id: Mapped[str]
+ task_id: Mapped[str]
+ run_id: Mapped[str]
+ map_index: Mapped[int]
+ dag_run_id: Mapped[int]
+ logical_date: Mapped[datetime | None]
+ run_after: Mapped[datetime]
+ dag_run: Mapped[DagRun]
+ task: Mapped[TaskInstance]
+
+
+_xcom_model_lock = threading.RLock()
+_xcom_model: type[XComModel] | None = None
+
+
+def get_xcom_model() -> type[XComModel]:
+ """
+ Return ``XComModel``, defining it on first use.
+
+ Its table is built from ``TaskInstance`` and ``DagRun`` columns, so defining the class when this module
+ is imported would force the module to import them first, and ``taskinstance`` could then no longer
+ import this module without a circular import.
+ """
+ global _xcom_model
+ with _xcom_model_lock:
+ if _xcom_model is None:
+ _xcom_model = _define_xcom_model()
+ return _xcom_model
+
+
+def _define_xcom_model() -> type[XComModel]:
+ from airflow.models.dagrun import DagRun
+ from airflow.models.taskinstance import TaskInstance
+
+ class XComModel(_XComOperations, Base):
+ """Read both stores without sharing writable ORM identity."""
+
+ __table__ = _rows().subquery("xcom")
+ __mapper_args__ = {"primary_key": [__table__.c.task_instance_id, __table__.c.key]}
+
+ dag_run = relationship(
+ DagRun,
+ primaryjoin=foreign(__table__.c.dag_run_id) == DagRun.id,
+ viewonly=True,
+ uselist=False,
+ lazy="raise",
+ )
+ task = relationship(
+ TaskInstance,
+ primaryjoin=foreign(__table__.c.task_instance_id) == TaskInstance.id,
+ viewonly=True,
+ uselist=False,
+ lazy="raise",
+ )
+
+ XComModel.__qualname__ = "XComModel"
+ for mutation in ("before_insert", "before_update", "before_delete"):
+ event.listen(XComModel, mutation, _reject_projection_write)
+ return XComModel
+
+
+def _reject_projection_write(mapper, connection, target):
+ raise TypeError("XCom read projection is read-only")
+
+
+def build_xcom_read_query(*, producer_ids: Select, key: str | None = None) -> Select[tuple[XComModel]]:
+ entity = aliased(
+ get_xcom_model(), _rows(producer_ids=producer_ids, key=key).subquery("xcom"), adapt_on_names=True
+ )
+ return select(entity).execution_options(populate_existing=True)
+
+
+def xcom_entity(statement: Select) -> AliasedClass:
+ """Return the mapped XCom alias selected by a dual-store read."""
+ return statement.column_descriptions[0]["entity"]
+
+
+def select_producers(
+ *,
+ run_id=None,
+ dag_ids=None,
+ task_ids=None,
+ map_indexes=None,
+ include_prior_dates=False,
+ try_number=None,
+):
+ from airflow.models.dagrun import DagRun
+ from airflow.models.taskinstance import TaskInstance
+
+ query = select(TaskInstance.id)
+ if try_number is None:
+ query = query.where(TaskInstance.working_set.is_(True))
+ else:
+ query = query.where(TaskInstance.try_number == try_number)
+ for column, value in ((TaskInstance.dag_id, dag_ids), (TaskInstance.task_id, task_ids)):
+ if is_container(value):
+ query = query.where(column.in_(value))
+ elif value is not None:
+ query = query.where(column == value)
+ if isinstance(map_indexes, range) and map_indexes.step == 1:
+ query = query.where(
+ TaskInstance.map_index >= map_indexes.start, TaskInstance.map_index < map_indexes.stop
+ )
+ elif is_container(map_indexes):
+ query = query.where(TaskInstance.map_index.in_(map_indexes))
+ elif map_indexes is not None:
+ query = query.where(TaskInstance.map_index == map_indexes)
+ if include_prior_dates:
+ requested_run = aliased(DagRun)
+ cutoff = (
+ select(func.coalesce(requested_run.logical_date, requested_run.run_after))
+ .where(
+ requested_run.dag_id == TaskInstance.dag_id,
+ requested_run.run_id == run_id,
+ )
+ .correlate(TaskInstance)
+ .scalar_subquery()
+ )
+ query = query.join(
+ DagRun, and_(TaskInstance.dag_id == DagRun.dag_id, TaskInstance.run_id == DagRun.run_id)
+ ).where(func.coalesce(DagRun.logical_date, DagRun.run_after) <= cutoff)
+ elif run_id is not None:
+ query = query.where(TaskInstance.run_id == run_id)
+ return query
+
+
class LazyXComSelectSequence(LazySelectSequence[Any]):
"""
List-like interface to lazily access XCom values.
@@ -408,11 +614,11 @@ class LazyXComSelectSequence(LazySelectSequence[Any]):
@staticmethod
def _rebuild_select(stmt: TextClause) -> Select[tuple[Any]]:
- return cast("Select[tuple[Any]]", select(XComModel.value).from_statement(stmt))
+ return cast("Select[tuple[Any]]", select(get_xcom_model().value).from_statement(stmt))
@staticmethod
def _process_row(row: Row) -> Any:
- return XComModel.deserialize_value(row)
+ return get_xcom_model().deserialize_value(row)
__compat_imports = {
@@ -428,6 +634,9 @@ def __getattr__(name: str):
from airflow.utils.deprecation_tools import DeprecatedImportWarning
+ if name == "XComModel":
+ return get_xcom_model()
+
try:
modpath = __compat_imports[name]
except KeyError:
diff --git a/airflow-core/src/airflow/plugins_manager.py b/airflow-core/src/airflow/plugins_manager.py
index 8b2ea644e0b..b652f9a58f3 100644
--- a/airflow-core/src/airflow/plugins_manager.py
+++ b/airflow-core/src/airflow/plugins_manager.py
@@ -100,6 +100,7 @@ def _get_plugins() -> tuple[list[AirflowPlugin], dict[str, str]]:
Plugins are only loaded if they have not been previously loaded.
"""
from airflow._shared.observability.metrics import stats
+ from airflow.providers_manager import provider_incompatibility_reason
if not settings.PLUGINS_FOLDER:
raise ValueError("Plugins folder is not set")
@@ -140,7 +141,7 @@ def _get_plugins() -> tuple[list[AirflowPlugin], dict[str, str]]:
ignore_file_syntax=ignore_file_syntax,
)
)
- __register_plugins(*_load_entrypoint_plugins())
+ __register_plugins(*_load_entrypoint_plugins(provider_incompatibility_reason))
if not settings.LAZY_LOAD_PROVIDERS:
__register_plugins(*_load_providers_plugins())
diff --git a/airflow-core/src/airflow/providers_manager.py b/airflow-core/src/airflow/providers_manager.py
index 8e270209a8b..d268423b5f2 100644
--- a/airflow-core/src/airflow/providers_manager.py
+++ b/airflow-core/src/airflow/providers_manager.py
@@ -33,6 +33,9 @@ from importlib.resources import files as resource_files
from time import perf_counter
from typing import TYPE_CHECKING, Any, NamedTuple, ParamSpec, TypeVar, cast
+from packaging.utils import canonicalize_name
+from packaging.version import Version
+
from airflow import DeprecatedImportWarning
from airflow._shared.module_loading import import_string
from airflow._shared.providers_discovery import discover_all_providers_from_packages
@@ -40,6 +43,8 @@ from airflow.exceptions import AirflowOptionalProviderFeatureException, AirflowP
from airflow.utils.log.logging_mixin import LoggingMixin
if TYPE_CHECKING:
+ from importlib.metadata import Distribution
+
from airflow.cli.cli_config import CLICommand
log = logging.getLogger(__name__)
@@ -52,6 +57,33 @@ MIN_PROVIDER_VERSIONS = {
"apache-airflow-providers-celery": "2.1.0",
}
+BLOCKED_PROVIDER_MIN_VERSIONS = {
+ "apache-airflow-providers-common-ai": "1.0.0",
+}
+
+
+def _is_source_install(dist: Distribution) -> bool:
+ """Whether the distribution was installed from a local directory, editable or not (PEP 610)."""
+ with contextlib.suppress(ValueError):
+ return "dir_info" in json.loads(dist.read_text("direct_url.json") or "{}")
+ return False
+
+
+def provider_incompatibility_reason(dist: Distribution) -> str | None:
+ """Return a reason to skip a provider that cannot run with this Airflow version."""
+ package_name = canonicalize_name(dist.metadata["Name"])
+ minimum_version = BLOCKED_PROVIDER_MIN_VERSIONS.get(package_name)
+ if minimum_version is None or Version(dist.version) >= Version(minimum_version):
+ return None
+ # A source tree reports the last released version, so version alone can't tell it apart; this
+ # exemption can go as soon as a version > 0.10.0 exists.
+ if _is_source_install(dist):
+ return None
+ return (
+ f"Skipping incompatible provider {package_name} {dist.version}; "
+ f"install {package_name}>={minimum_version} for this version of Airflow."
+ )
+
def _ensure_prefix_for_placeholders(field_behaviors: dict[str, Any], conn_type: str):
"""
@@ -521,7 +553,9 @@ class ProvidersManager(LoggingMixin):
# Development purpose. In production provider.yaml files are not present in the 'airflow" directory
# So there is no risk we are going to override package provider accidentally. This can only happen
# in case of local development
- discover_all_providers_from_packages(self._provider_dict, self._provider_schema_validator)
+ discover_all_providers_from_packages(
+ self._provider_dict, self._provider_schema_validator, provider_incompatibility_reason
+ )
self._verify_all_providers_all_compatible()
self._provider_dict = dict(sorted(self._provider_dict.items()))
diff --git a/airflow-core/src/airflow/serialization/definitions/dag.py b/airflow-core/src/airflow/serialization/definitions/dag.py
index e6979fc44f3..66bf4819ae8 100644
--- a/airflow-core/src/airflow/serialization/definitions/dag.py
+++ b/airflow-core/src/airflow/serialization/definitions/dag.py
@@ -538,6 +538,7 @@ class SerializedDAG:
total_tasks = session.scalar(
select(func.count(TaskInstance.task_id)).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == self.dag_id,
TaskInstance.state == TaskInstanceState.RUNNING,
)
@@ -1065,10 +1066,10 @@ class SerializedDAG:
TaskInstance.task_id,
TaskInstance.run_id,
TaskInstance.map_index,
- )
+ ).where(TaskInstance.working_set.is_(True))
tis_pk = tis_pk.join(TaskInstance.dag_run)
else:
- tis_full = select(TaskInstance)
+ tis_full = select(TaskInstance).where(TaskInstance.working_set.is_(True))
tis_full = tis_full.join(TaskInstance.dag_run)
# Apply common filters
@@ -1145,7 +1146,7 @@ class SerializedDAG:
# We've been asked for objects, lets combine it all back in to a result set
ti_filters = TaskInstance.filter_for_tis(result)
if ti_filters is not None:
- tis_final = select(TaskInstance).where(ti_filters)
+ tis_final = select(TaskInstance).where(TaskInstance.working_set.is_(True), ti_filters)
return session.scalars(tis_final)
elif exclude_task_ids is None:
pass # Disable filter if not set.
diff --git a/airflow-core/src/airflow/serialization/definitions/operatorlink.py b/airflow-core/src/airflow/serialization/definitions/operatorlink.py
index 86e245b4c63..02f5a5ad779 100644
--- a/airflow-core/src/airflow/serialization/definitions/operatorlink.py
+++ b/airflow-core/src/airflow/serialization/definitions/operatorlink.py
@@ -23,7 +23,7 @@ from typing import TYPE_CHECKING
import attrs
-from airflow.models.xcom import XComModel
+from airflow.models.xcom import XComModel, xcom_entity
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow.utils.session import create_session
@@ -55,17 +55,16 @@ class XComOperatorLink(LoggingMixin):
"Attempting to retrieve link from XComs with key: %s for task id: %s", self.xcom_key, ti_key
)
with create_session() as session:
- result = session.execute(
- XComModel.get_many(
- key=self.xcom_key,
- run_id=ti_key.run_id,
- dag_ids=ti_key.dag_id,
- task_ids=ti_key.task_id,
- map_indexes=ti_key.map_index,
- )
- .with_only_columns(XComModel.value)
- .limit(1)
- ).first()
+ read = XComModel.get_many(
+ key=self.xcom_key,
+ run_id=ti_key.run_id,
+ dag_ids=ti_key.dag_id,
+ task_ids=ti_key.task_id,
+ map_indexes=ti_key.map_index,
+ try_number=ti_key.try_number,
+ )
+ entity = xcom_entity(read)
+ result = session.execute(read.with_only_columns(entity.value).limit(1)).first()
if not result:
self.log.debug(
"No link with name: %s present in XCom as key: %s, returning empty link",
diff --git a/airflow-core/src/airflow/serialization/definitions/xcom_arg.py b/airflow-core/src/airflow/serialization/definitions/xcom_arg.py
index cd544ae5c7b..748114cb810 100644
--- a/airflow-core/src/airflow/serialization/definitions/xcom_arg.py
+++ b/airflow-core/src/airflow/serialization/definitions/xcom_arg.py
@@ -22,7 +22,7 @@ from functools import singledispatch
from typing import TYPE_CHECKING, Any
import attrs
-from sqlalchemy import func, or_, select
+from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from airflow.models.referencemixin import ReferenceMixin
@@ -154,7 +154,7 @@ def get_task_map_length(xcom_arg: SchedulerXComArg, run_id: str, *, session: Ses
@get_task_map_length.register
def _(xcom_arg: SchedulerPlainXComArg, run_id: str, *, session: Session) -> int | None:
from airflow.models.taskinstance import TaskInstance
- from airflow.models.xcom import XComModel
+ from airflow.models.xcom import XComModel, xcom_entity
from airflow.serialization.definitions.mappedoperator import is_mapped
dag_id = xcom_arg.operator.dag_id
@@ -162,6 +162,7 @@ def _(xcom_arg: SchedulerPlainXComArg, run_id: str, *, session: Session) -> int
if is_mapped(xcom_arg.operator):
unfinished_ti_exists = exists_query(
+ TaskInstance.working_set.is_(True),
TaskInstance.dag_id == dag_id,
TaskInstance.run_id == run_id,
TaskInstance.task_id == task_id,
@@ -176,26 +177,17 @@ def _(xcom_arg: SchedulerPlainXComArg, run_id: str, *, session: Session) -> int
)
if unfinished_ti_exists:
return None # Not all of the expanded tis are done yet.
+ read = XComModel.get_many(dag_ids=dag_id, run_id=run_id, task_ids=task_id, key=XCOM_RETURN_KEY)
+ entity = xcom_entity(read)
return session.scalar(
- select(func.count(XComModel.map_index)).where(
- XComModel.dag_id == dag_id,
- XComModel.run_id == run_id,
- XComModel.task_id == task_id,
- XComModel.map_index >= 0,
- XComModel.key == XCOM_RETURN_KEY,
- )
+ read.order_by(None).where(entity.map_index >= 0).with_only_columns(func.count(entity.map_index))
)
- # Not xcom_arg.key: the SDK records the length of the whole return value, never per key.
- return session.scalar(
- select(XComModel.mapped_length).where(
- XComModel.dag_id == dag_id,
- XComModel.run_id == run_id,
- XComModel.task_id == task_id,
- XComModel.map_index == -1,
- XComModel.key == XCOM_RETURN_KEY,
- )
+ read = XComModel.get_many(
+ dag_ids=dag_id, run_id=run_id, task_ids=task_id, map_indexes=-1, key=XCOM_RETURN_KEY
)
+ entity = xcom_entity(read)
+ return session.scalar(read.with_only_columns(entity.mapped_length))
@get_task_map_length.register
diff --git a/airflow-core/src/airflow/ti_deps/deps/mapped_task_upstream_dep.py b/airflow-core/src/airflow/ti_deps/deps/mapped_task_upstream_dep.py
index e1957b9a342..afc0df74828 100644
--- a/airflow-core/src/airflow/ti_deps/deps/mapped_task_upstream_dep.py
+++ b/airflow-core/src/airflow/ti_deps/deps/mapped_task_upstream_dep.py
@@ -72,6 +72,7 @@ class MappedTaskUpstreamDep(BaseTIDep):
mapped_dependency_tis = (
session.scalars(
select(TaskInstance).where(
+ TaskInstance.working_set.is_(True),
TaskInstance.task_id.in_(operator.task_id for operator in mapped_dependencies),
TaskInstance.dag_id == ti.dag_id,
TaskInstance.run_id == ti.run_id,
diff --git a/airflow-core/src/airflow/ti_deps/deps/prev_dagrun_dep.py b/airflow-core/src/airflow/ti_deps/deps/prev_dagrun_dep.py
index a1bf124be39..056c0c667b8 100644
--- a/airflow-core/src/airflow/ti_deps/deps/prev_dagrun_dep.py
+++ b/airflow-core/src/airflow/ti_deps/deps/prev_dagrun_dep.py
@@ -62,6 +62,7 @@ class PrevDagrunDep(BaseTIDep):
This function exists for easy mocking in tests.
"""
return exists_query(
+ TI.working_set.is_(True),
TI.dag_id == dagrun.dag_id,
TI.task_id == task_id,
TI.run_id == dagrun.run_id,
@@ -76,6 +77,7 @@ class PrevDagrunDep(BaseTIDep):
This function exists for easy mocking in tests.
"""
query = exists_query(
+ TI.working_set.is_(True),
TI.dag_id == ti.dag_id,
TI.task_id == ti.task_id,
TI.logical_date < ti.logical_date,
@@ -96,6 +98,7 @@ class PrevDagrunDep(BaseTIDep):
"""
unsuccessful_tis_count = session.scalar(
select(func.count()).where(
+ TI.working_set.is_(True),
TI.dag_id == dagrun.dag_id,
TI.task_id == task_id,
TI.run_id == dagrun.run_id,
@@ -118,6 +121,7 @@ class PrevDagrunDep(BaseTIDep):
if not task.downstream_task_ids:
return False
return exists_query(
+ TI.working_set.is_(True),
TI.dag_id == dagrun.dag_id,
TI.task_id.in_(task.downstream_task_ids),
TI.run_id == dagrun.run_id,
diff --git a/airflow-core/src/airflow/ti_deps/deps/trigger_rule_dep.py b/airflow-core/src/airflow/ti_deps/deps/trigger_rule_dep.py
index f49b71f7ca9..dd9b77ed44f 100644
--- a/airflow-core/src/airflow/ti_deps/deps/trigger_rule_dep.py
+++ b/airflow-core/src/airflow/ti_deps/deps/trigger_rule_dep.py
@@ -302,7 +302,11 @@ class TriggerRuleDep(BaseTIDep):
else:
task_id_counts = session.execute(
select(TaskInstance.task_id, func.count(TaskInstance.task_id))
- .where(TaskInstance.dag_id == ti.dag_id, TaskInstance.run_id == ti.run_id)
+ .where(
+ TaskInstance.working_set.is_(True),
+ TaskInstance.dag_id == ti.dag_id,
+ TaskInstance.run_id == ti.run_id,
+ )
.where(or_(*_iter_upstream_conditions(relevant_tasks=indirect_setups)))
.group_by(TaskInstance.task_id)
).all()
@@ -410,7 +414,11 @@ class TriggerRuleDep(BaseTIDep):
(task_id, count)
for task_id, count in session.execute(
select(TaskInstance.task_id, func.count(TaskInstance.task_id))
- .where(TaskInstance.dag_id == ti.dag_id, TaskInstance.run_id == ti.run_id)
+ .where(
+ TaskInstance.working_set.is_(True),
+ TaskInstance.dag_id == ti.dag_id,
+ TaskInstance.run_id == ti.run_id,
+ )
.where(or_(*_iter_upstream_conditions(relevant_tasks=upstream_tasks)))
.group_by(TaskInstance.task_id)
)
@@ -706,7 +714,11 @@ class TriggerRuleDep(BaseTIDep):
expected = (
session.scalar(
select(func.count(TaskInstance.task_id))
- .where(TaskInstance.dag_id == ti.dag_id, TaskInstance.run_id == ti.run_id)
+ .where(
+ TaskInstance.working_set.is_(True),
+ TaskInstance.dag_id == ti.dag_id,
+ TaskInstance.run_id == ti.run_id,
+ )
.where(or_(*_iter_upstream_conditions(relevant_tasks=in_scope_tasks)))
)
or 0
diff --git a/airflow-core/src/airflow/utils/db.py b/airflow-core/src/airflow/utils/db.py
index f160cb0597d..7e276d02c86 100644
--- a/airflow-core/src/airflow/utils/db.py
+++ b/airflow-core/src/airflow/utils/db.py
@@ -117,7 +117,7 @@ _REVISION_HEADS_MAP: dict[str, str] = {
"3.1.8": "509b94a1042d",
"3.2.0": "1d6611b6ab7c",
"3.3.0": "d2f4e1b3c5a7",
- "3.4.0": "90e4d18ccadf",
+ "3.4.0": "e7c2a91bd540",
}
# Prefix used to identify tables holding data moved during migration.
@@ -1080,7 +1080,7 @@ def synchronize_log_template(*, session: Session = NEW_SESSION) -> None:
session.add(LogTemplate(filename=filename, elasticsearch_id=elasticsearch_id))
-def reflect_tables(tables: list[MappedClassProtocol | str] | None, session, schema: str | None = None):
+def reflect_tables(tables: Sequence[MappedClassProtocol | str] | None, session, schema: str | None = None):
"""
When running checks prior to upgrades, we use reflection to determine current state of the database.
diff --git a/airflow-core/src/airflow/utils/db_cleanup.py b/airflow-core/src/airflow/utils/db_cleanup.py
index ad41b482c44..795200648cc 100644
--- a/airflow-core/src/airflow/utils/db_cleanup.py
+++ b/airflow-core/src/airflow/utils/db_cleanup.py
@@ -31,6 +31,7 @@ from collections.abc import Generator
from contextlib import contextmanager, suppress
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any, cast
+from uuid import uuid4
from sqlalchemy import and_, column, func, inspect, literal, literal_column, or_, select, table, text
from sqlalchemy.exc import OperationalError, ProgrammingError
@@ -51,7 +52,7 @@ from airflow.utils.types import DagRunType
if TYPE_CHECKING:
from pendulum import DateTime
- from sqlalchemy import Select
+ from sqlalchemy import Select, Table
from sqlalchemy.engine import CursorResult
from sqlalchemy.orm import Session
@@ -258,12 +259,9 @@ config_list: list[_TableConfig] = [
_TableConfig(
table_name="task_instance",
recency_column_name="start_date",
- dependent_tables=["task_instance_history", "xcom", "task_reschedule"],
+ dependent_tables=["xcom_v1", "xcom_v2", "task_reschedule"],
dag_id_column_name="dag_id",
),
- _TableConfig(
- table_name="task_instance_history", recency_column_name="start_date", dag_id_column_name="dag_id"
- ),
_TableConfig(
table_name="task_state_store",
recency_column_name="expires_at",
@@ -277,7 +275,13 @@ config_list: list[_TableConfig] = [
extra_columns=["ti_id"],
dag_id_scope=_IndirectDagScope(fk_column="ti_id", referenced_table="task_instance"),
),
- _TableConfig(table_name="xcom", recency_column_name="timestamp", dag_id_column_name="dag_id"),
+ _TableConfig(table_name="xcom_v1", recency_column_name="timestamp", dag_id_column_name="dag_id"),
+ _TableConfig(
+ table_name="xcom_v2",
+ recency_column_name="timestamp",
+ extra_columns=["task_instance_id"],
+ dag_id_scope=_IndirectDagScope(fk_column="task_instance_id", referenced_table="task_instance"),
+ ),
_TableConfig(table_name="_xcom_archive", recency_column_name="timestamp", dag_id_column_name="dag_id"),
_TableConfig(
table_name="callback",
@@ -352,6 +356,12 @@ if (
config_list.append(_TableConfig(table_name="session", recency_column_name="expiry"))
config_dict: dict[str, _TableConfig] = {x.table_name: x for x in sorted(config_list)}
+_LEGACY_TABLE_ALIASES = {"xcom": ("xcom_v1", "xcom_v2")}
+_HISTORY_CONFIG = dataclasses.replace(
+ config_dict["task_instance"],
+ dependent_tables=None,
+ extra_filters=[literal_column(f"{_BASE_TABLE_ALIAS}.working_set").is_(None)],
+)
def _check_for_rows(*, session: Session, query: Select, print_rows: bool = False) -> int:
@@ -383,6 +393,81 @@ def _dump_table_to_file(*, target_table: str, file_path: str, export_format: str
raise AirflowException(f"Export format {export_format} is not supported.")
+_ATTEMPT_UUID_CHILDREN = {
+ "legacy_task_data_owner": "task_instance_id",
+ "xcom_v2": "task_instance_id",
+ "rtif_v2": "task_instance_id",
+ "task_instance_note": "ti_id",
+ "task_reschedule": "ti_id",
+ "hitl_detail": "ti_id",
+}
+_ATTEMPT_ARCHIVE_TABLES = {*_ATTEMPT_UUID_CHILDREN, "xcom_v1", "rtif_v1", "task_instance"}
+
+
+def _archive_cascading_attempt_data(
+ *, source, parent_archive, archives: dict[str, Table], archive_suffix: str, session: Session
+) -> None:
+ """Archive owned rows under parent locks before their FK cascades run."""
+ names = [_format_table_name(source.schema, name) for name in _ATTEMPT_ARCHIVE_TABLES]
+ metadata = reflect_tables(names, session)
+ tables = {
+ name: metadata.tables[_format_table_name(source.schema, name)] for name in _ATTEMPT_ARCHIVE_TABLES
+ }
+ ti = tables["task_instance"]
+ if source.name == "task_instance":
+ producer_ids = select(ti.c.id).where(ti.c.id.in_(select(parent_archive.c.id)))
+ else:
+ producer_ids = select(ti.c.id).where(
+ tuple_(ti.c.dag_id, ti.c.run_id).in_(select(parent_archive.c.dag_id, parent_archive.c.run_id))
+ )
+ selections = {
+ name: select(tables[name]).where(tables[name].c[fk].in_(producer_ids))
+ for name, fk in _ATTEMPT_UUID_CHILDREN.items()
+ }
+ owner = tables["legacy_task_data_owner"]
+ coordinates = ("dag_id", "task_id", "run_id", "map_index")
+ for name in ("xcom_v1", "rtif_v1"):
+ child = tables[name]
+ selections[name] = select(child).where(
+ tuple_(*(child.c[c] for c in coordinates)).in_(
+ select(*(owner.c[c] for c in coordinates)).where(owner.c.task_instance_id.in_(producer_ids))
+ )
+ )
+ if source.name == "dag_run":
+ selections["task_instance"] = select(ti).where(ti.c.id.in_(producer_ids))
+
+ if not archives:
+ archive_names = {}
+ for name in selections:
+ archive_name = _format_table_name(
+ source.schema, f"{ARCHIVE_TABLE_PREFIX}{name}__{archive_suffix}"
+ )
+ if session.get_bind().dialect.name == "mysql":
+ original_name = _format_table_name(source.schema, name)
+ session.execute(text(f"CREATE TABLE {archive_name} LIKE {original_name}"))
+ else:
+ session.execute(CreateTableAs(archive_name, select(tables[name]).where(literal(False))))
+ archive_names[name] = archive_name
+ # MySQL DDL commits implicitly. Create every archive before taking row locks.
+ session.commit()
+ archive_metadata = reflect_tables(list(archive_names.values()), session)
+ archives.update(
+ {name: archive_metadata.tables[archive_name] for name, archive_name in archive_names.items()}
+ )
+ parent_ids = select(parent_archive.c.id)
+ lock_queries = [select(source.c.id).where(source.c.id.in_(parent_ids))]
+ if source.name == "dag_run":
+ lock_queries.append(producer_ids)
+ for query in lock_queries:
+ for _ in session.execute(query.with_for_update().execution_options(yield_per=1000)):
+ pass
+ for name, query in selections.items():
+ for _ in session.execute(query.with_for_update().execution_options(yield_per=1000)):
+ pass
+ archive = archives[name]
+ session.execute(archive.insert().from_select(list(archive.c), query))
+
+
def _do_delete(
*,
query: Select,
@@ -400,6 +485,8 @@ def _do_delete(
dialect_name = bind.dialect.name
batch_counter = itertools.count(1)
source_table_name = _format_table_name(orm_model.schema, orm_model.name)
+ attempt_archives: dict[str, Table] = {}
+ attempt_archive_suffix = uuid4().hex[:16]
while True:
limited_query = query.limit(batch_size) if batch_size else query
@@ -451,6 +538,14 @@ def _do_delete(
source_table = metadata.tables[source_table_name]
target_table = metadata.tables[target_table_name]
logger.debug("rows moved; purging from %s", source_table.name)
+ if not skip_archive and source_table.name in {"task_instance", "dag_run"}:
+ _archive_cascading_attempt_data(
+ source=source_table,
+ parent_archive=target_table,
+ archives=attempt_archives,
+ archive_suffix=attempt_archive_suffix,
+ session=session,
+ )
if dialect_name == "sqlite":
pk_cols = source_table.primary_key.columns
delete = source_table.delete().where(
@@ -707,6 +802,15 @@ def _cleanup_table(
num_rows = _check_for_rows(session=session, query=query, print_rows=False)
if num_rows and not dry_run:
+ if orm_model.name == "xcom_v2":
+ legacy_query = _shadowed_legacy_xcom_query(query)
+ _do_delete(
+ query=legacy_query,
+ orm_model=config_dict["xcom_v1"].orm_model,
+ skip_archive=skip_archive,
+ session=session,
+ batch_size=batch_size,
+ )
_do_delete(
query=query,
orm_model=orm_model,
@@ -720,6 +824,36 @@ def _cleanup_table(
session.commit()
+def _shadowed_legacy_xcom_query(v2_query: Select) -> Select:
+ legacy = aliased(config_dict["xcom_v1"].orm_model, name=_BASE_TABLE_ALIAS)
+ owner = table(
+ "legacy_task_data_owner",
+ column("dag_id"),
+ column("task_id"),
+ column("run_id"),
+ column("map_index"),
+ column("task_instance_id"),
+ )
+ selected_v2 = v2_query.subquery("selected_v2")
+ coordinates = ("dag_id", "task_id", "run_id", "map_index")
+ shadowed = (
+ select(literal(1))
+ .select_from(
+ owner.join(
+ selected_v2,
+ owner.c.task_instance_id == literal_column("selected_v2.task_instance_id"),
+ )
+ )
+ .where(
+ *(literal_column(f"{_BASE_TABLE_ALIAS}.{name}") == owner.c[name] for name in coordinates),
+ literal_column(f"{_BASE_TABLE_ALIAS}.key") == literal_column("selected_v2.key"),
+ )
+ .correlate(legacy)
+ .exists()
+ )
+ return select(text(f"{_BASE_TABLE_ALIAS}.*")).select_from(legacy).where(shadowed)
+
+
def _confirm_delete(
*,
date: DateTime,
@@ -795,8 +929,11 @@ def _suppress_with_logging(table: str, session: Session) -> Generator[SimpleName
def _effective_table_names(*, table_names: list[str] | None) -> tuple[list[str], dict[str, _TableConfig]]:
desired_table_names = set(table_names or config_dict)
+ desired_table_names = {
+ expanded for name in desired_table_names for expanded in _LEGACY_TABLE_ALIASES.get(name, (name,))
+ }
- outliers = desired_table_names - set(config_dict.keys())
+ outliers = desired_table_names - (config_dict.keys() | {"task_instance_history"})
if outliers:
logger.warning(
"The following table(s) are not valid choices and will be skipped: %s",
@@ -811,7 +948,7 @@ def _effective_table_names(*, table_names: list[str] | None) -> tuple[list[str],
if table in visited:
return
visited.add(table)
- config = config_dict[table]
+ config = _HISTORY_CONFIG if table == "task_instance_history" else config_dict[table]
for dep in config.dependent_tables or []:
collect_deps(dep)
effective_table_names.append(table)
@@ -819,7 +956,9 @@ def _effective_table_names(*, table_names: list[str] | None) -> tuple[list[str],
for table_name in desired_table_names:
collect_deps(table_name)
- effective_config_dict = {n: config_dict[n] for n in effective_table_names}
+ effective_config_dict = {
+ n: _HISTORY_CONFIG if n == "task_instance_history" else config_dict[n] for n in effective_table_names
+ }
if not effective_config_dict:
raise SystemExit("No tables selected for db cleanup. Please choose valid table names.")
@@ -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"}:
+ archive_sources.update(_ATTEMPT_ARCHIVE_TABLES)
archived_table_names: list[str] = []
for schema in schemas:
@@ -845,7 +993,7 @@ def _get_archived_table_names(table_names: list[str] | None, session: Session) -
_format_table_name(schema, name)
for name in db_table_names
if (
- any(f"__{config.bare_table_name}__" in name for config in effective_config_dict.values())
+ any(f"__{source}__" in name for source in archive_sources)
or (schema is None and name in ARCHIVED_TABLES_FROM_DB_MIGRATIONS)
)
)
@@ -918,7 +1066,8 @@ def run_cleanup(
}
failed_tables: list[str] = []
for table_name, table_config in effective_config_dict.items():
- if table_name in existing_tables:
+ physical_name = _format_table_name(table_config.schema_name, table_config.bare_table_name)
+ if physical_name in existing_tables:
with _suppress_with_logging(table_name, session) as ctx:
_cleanup_table(
clean_before_timestamp=clean_before_timestamp,
diff --git a/airflow-core/src/airflow/utils/log/file_task_handler.py b/airflow-core/src/airflow/utils/log/file_task_handler.py
index d22ce48fa08..8a116e39b4e 100644
--- a/airflow-core/src/airflow/utils/log/file_task_handler.py
+++ b/airflow-core/src/airflow/utils/log/file_task_handler.py
@@ -60,7 +60,6 @@ if TYPE_CHECKING:
)
from airflow.executors.base_executor import BaseExecutor
from airflow.models.taskinstance import TaskInstance
- from airflow.models.taskinstancehistory import TaskInstanceHistory
CHUNK_SIZE = 1024 * 1024 * 5 # 5MB
DEFAULT_SORT_DATETIME = pendulum.datetime(2000, 1, 1)
@@ -462,9 +461,7 @@ class FileTaskHandler(logging.Handler):
Some handlers emit "end of log" markers, and may not wish to do so when task defers.
"""
- def set_context(
- self, ti: TaskInstance | TaskInstanceHistory, *, identifier: str | None = None
- ) -> None | SetContextPropagate:
+ def set_context(self, ti: TaskInstance, *, identifier: str | None = None) -> None | SetContextPropagate:
"""
Provide task_instance context to airflow task handler.
@@ -520,9 +517,7 @@ class FileTaskHandler(logging.Handler):
self.handler.close()
@provide_session
- def _render_filename(
- self, ti: TaskInstance | TaskInstanceHistory, try_number: int, *, session=NEW_SESSION
- ) -> str:
+ def _render_filename(self, ti: TaskInstance, try_number: int, *, session=NEW_SESSION) -> str:
"""Return the worker log filename."""
dag_run = ti.get_dagrun(session=session)
@@ -557,7 +552,7 @@ class FileTaskHandler(logging.Handler):
)
raise RuntimeError(f"Unable to render log filename for {ti}. This should never happen")
- def _get_executor(self, ti: TaskInstance | TaskInstanceHistory) -> BaseExecutor:
+ def _get_executor(self, ti: TaskInstance) -> BaseExecutor:
"""
Get the executor of current task instance.
@@ -579,7 +574,7 @@ class FileTaskHandler(logging.Handler):
def _read(
self,
- ti: TaskInstance | TaskInstanceHistory,
+ ti: TaskInstance,
try_number: int,
metadata: LogMetadata | None = None,
) -> tuple[LogHandlerOutputStream | LegacyProvidersLogType, LogMetadata]:
@@ -700,7 +695,7 @@ class FileTaskHandler(logging.Handler):
}
@staticmethod
- def _get_pod_namespace(ti: TaskInstance | TaskInstanceHistory):
+ def _get_pod_namespace(ti: TaskInstance):
pod_override = getattr(ti.executor_config, "pod_override", None)
metadata = getattr(pod_override, "metadata", None)
namespace = None
@@ -710,7 +705,7 @@ class FileTaskHandler(logging.Handler):
def _get_log_retrieval_url(
self,
- ti: TaskInstance | TaskInstanceHistory,
+ ti: TaskInstance,
log_relative_path: str,
log_type: LogType | None = None,
) -> tuple[str | None, str | None]:
@@ -751,7 +746,7 @@ class FileTaskHandler(logging.Handler):
def read(
self,
- task_instance: TaskInstance | TaskInstanceHistory,
+ task_instance: TaskInstance,
try_number: int | None = None,
metadata: LogMetadata | None = None,
) -> tuple[LogHandlerOutputStream, LogMetadata]:
@@ -914,7 +909,7 @@ class FileTaskHandler(logging.Handler):
def _read_from_logs_server(
self,
- ti: TaskInstance | TaskInstanceHistory,
+ ti: TaskInstance,
worker_log_rel_path: str,
) -> StreamingLogResponse:
sources: LogSourceInfo = []
diff --git a/airflow-core/src/airflow/utils/log/log_reader.py b/airflow-core/src/airflow/utils/log/log_reader.py
index a4d641b1a6f..3fa8825667e 100644
--- a/airflow-core/src/airflow/utils/log/log_reader.py
+++ b/airflow-core/src/airflow/utils/log/log_reader.py
@@ -33,7 +33,6 @@ if TYPE_CHECKING:
from typing import TypeAlias
from airflow.models.taskinstance import TaskInstance
- from airflow.models.taskinstancehistory import TaskInstanceHistory
from airflow.utils.log.file_task_handler import LogHandlerOutputStream, LogMetadata
LogReaderOutputStream: TypeAlias = Generator[str, None, None]
@@ -51,7 +50,7 @@ class TaskLogReader:
"""Number of empty loop iterations before stopping the stream"""
@staticmethod
- def get_no_log_state_message(ti: TaskInstance | TaskInstanceHistory) -> Iterator[StructuredLogMessage]:
+ def get_no_log_state_message(ti: TaskInstance) -> Iterator[StructuredLogMessage]:
"""Yield standardized no-log messages for a given TI state."""
if ti.state == TaskInstanceState.SKIPPED:
msg = "Task was skipped — no logs available."
@@ -69,7 +68,7 @@ class TaskLogReader:
def read_log_chunks(
self,
- ti: TaskInstance | TaskInstanceHistory,
+ ti: TaskInstance,
try_number: int | None,
metadata: LogMetadata,
) -> tuple[LogHandlerOutputStream, LogMetadata]:
@@ -100,7 +99,7 @@ class TaskLogReader:
def read_log_stream(
self,
- ti: TaskInstance | TaskInstanceHistory,
+ ti: TaskInstance,
try_number: int | None,
metadata: LogMetadata,
) -> Iterator[str]:
diff --git a/airflow-core/tests/unit/always/test_providers_manager.py b/airflow-core/tests/unit/always/test_providers_manager.py
index c77155c5e4b..192b4ab66ca 100644
--- a/airflow-core/tests/unit/always/test_providers_manager.py
+++ b/airflow-core/tests/unit/always/test_providers_manager.py
@@ -17,17 +17,22 @@
# under the License.
from __future__ import annotations
+import json
import logging
import re
import sys
from collections.abc import Callable
+from email.message import Message
+from importlib.metadata import EntryPoint
+from types import SimpleNamespace
from typing import TYPE_CHECKING
+import airflow._shared.providers_discovery.providers_discovery as provider_discovery_module
from airflow.exceptions import AirflowProviderDeprecationWarning
from airflow.sdk import BaseHook
PY313 = sys.version_info >= (3, 13)
-from unittest.mock import patch
+from unittest.mock import Mock, patch
import pytest
@@ -38,6 +43,7 @@ from airflow.providers_manager import (
ProviderInfo,
ProvidersManager,
RemoteLoggingInfo,
+ provider_incompatibility_reason,
)
from tests_common.test_utils.markers import skip_if_force_lowest_dependencies_marker
@@ -575,3 +581,63 @@ class TestProvidersMetadataLoading:
pm = ProvidersManager()
with pytest.warns(DeprecationWarning, match="already_initialized_provider_configs.*deprecated"):
pm.already_initialized_provider_configs
+
+
+def make_distribution(name: str, version: str, direct_url: dict | None = None) -> SimpleNamespace:
+ metadata = Message()
+ metadata["Name"] = name
+ return SimpleNamespace(
+ metadata=metadata,
+ version=version,
+ read_text=lambda filename: json.dumps(direct_url) if direct_url else None,
+ )
+
+
+@pytest.mark.parametrize(
+ ("version", "direct_url", "allowed"),
+ [
+ pytest.param("0.10.0", None, False, id="released-0.10.0"),
+ pytest.param("1.0.0rc1", None, False, id="released-1.0.0rc1"),
+ pytest.param("1.0.0", None, True, id="released-1.0.0"),
+ pytest.param("1.1.0", None, True, id="released-1.1.0"),
+ pytest.param("0.10.0", {"dir_info": {"editable": True}}, True, id="editable-source-install"),
+ pytest.param("0.10.0", {"dir_info": {}}, True, id="directory-source-install"),
+ pytest.param("0.10.0", {"archive_info": {}}, False, id="local-archive-install"),
+ ],
+)
+def test_common_ai_provider_discovery_checks_installed_version_before_import(
+ monkeypatch, caplog, version, direct_url, allowed
+):
+ distribution = make_distribution("apache-airflow-providers-common-ai", version, direct_url)
+ entry_point = Mock(spec=EntryPoint)
+ entry_point.load.return_value = lambda: {"package-name": "apache-airflow-providers-common-ai"}
+ monkeypatch.setattr(
+ provider_discovery_module,
+ "entry_points_with_dist",
+ lambda group: [(entry_point, distribution)],
+ )
+ providers = {}
+
+ with caplog.at_level(logging.WARNING):
+ provider_discovery_module.discover_all_providers_from_packages(
+ providers, Mock(spec=["validate"]), provider_incompatibility_reason
+ )
+
+ assert ("apache-airflow-providers-common-ai" in providers) is allowed
+ assert entry_point.load.called is allowed
+ if not allowed:
+ assert f"apache-airflow-providers-common-ai {version}" in caplog.text
+ assert "apache-airflow-providers-common-ai>=1.0.0" in caplog.text
+
+
+def test_unrelated_provider_is_not_blocked():
+ distribution = make_distribution("apache-airflow-providers-standard", "0.1.0")
+
+ assert provider_incompatibility_reason(distribution) is None
+
+
+def test_core_provider_manager_passes_compatibility_policy(cleanup_providers_manager):
+ with patch("airflow.providers_manager.discover_all_providers_from_packages", autospec=True) as discover:
+ ProvidersManager.initialize_providers_list.__wrapped__(ProvidersManager())
+
+ assert discover.call_args.args[2] is provider_incompatibility_reason
diff --git a/airflow-core/tests/unit/api/common/test_delete_dag.py b/airflow-core/tests/unit/api/common/test_delete_dag.py
index 14f96e3b6fe..f21e6f5aaf1 100644
--- a/airflow-core/tests/unit/api/common/test_delete_dag.py
+++ b/airflow-core/tests/unit/api/common/test_delete_dag.py
@@ -20,12 +20,15 @@ from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
-from sqlalchemy import func, select
+from sqlalchemy import event, func, select
from airflow.api.common.delete_dag import delete_dag
+from airflow.exceptions import AirflowException
from airflow.models import DagModel
from airflow.models.errors import ParseImportError
+from airflow.models.taskinstance import TaskInstance
from airflow.providers.standard.operators.empty import EmptyOperator
+from airflow.utils.state import TaskInstanceState
from tests_common.test_utils.db import clear_db_import_errors
@@ -88,6 +91,48 @@ def test_delete_dag_does_not_read_back_deleted_row_keys(dag_maker: DagMaker[Seri
assert session.scalar(select(func.count()).select_from(DagModel).where(DagModel.dag_id == DAG_ID)) == 0
+def test_delete_dag_running_check_selects_current_attempts(dag_maker: DagMaker[SerializedDAG], session):
+ import airflow.settings
+
+ with dag_maker(DAG_ID, session=session):
+ EmptyOperator(task_id="task")
+ dag_run = dag_maker.create_dagrun()
+ attempt = dag_run.get_task_instance("task", session=session)
+ assert attempt is not None
+ attempt.state = TaskInstanceState.RUNNING
+ successor = attempt.prepare_db_for_next_try(session)
+ successor.state = TaskInstanceState.RUNNING
+ session.commit()
+
+ statements = []
+
+ def capture(_conn, _cursor, statement, _parameters, _context, _executemany):
+ statements.append(" ".join(statement.split()).upper())
+
+ event.listen(airflow.settings.engine, "before_cursor_execute", capture)
+ try:
+ with pytest.raises(AirflowException, match="TaskInstances still running"):
+ delete_dag(DAG_ID, session=session)
+ finally:
+ event.remove(airflow.settings.engine, "before_cursor_execute", capture)
+
+ running_checks = [
+ statement
+ for statement in statements
+ if "FROM TASK_INSTANCE" in statement and "RUNNING" not in statement
+ ]
+ assert running_checks
+ assert all("WORKING_SET" in statement for statement in running_checks)
+ successor.state = TaskInstanceState.SUCCESS
+ session.commit()
+ delete_dag(DAG_ID, session=session)
+ session.commit()
+ assert (
+ session.scalar(select(func.count()).select_from(TaskInstance).where(TaskInstance.dag_id == DAG_ID))
+ == 0
+ )
+
+
@pytest.mark.parametrize(
"matching_column",
[
diff --git a/airflow-core/tests/unit/api_fastapi/common/test_parameters.py b/airflow-core/tests/unit/api_fastapi/common/test_parameters.py
index d6cb3c40a6a..086fbaf40cb 100644
--- a/airflow-core/tests/unit/api_fastapi/common/test_parameters.py
+++ b/airflow-core/tests/unit/api_fastapi/common/test_parameters.py
@@ -26,6 +26,7 @@ from unittest import mock
import pytest
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy import Column, MetaData, String, Table, create_engine, select
+from sqlalchemy.orm import aliased
from airflow.api_fastapi.common.parameters import (
FilterParam,
@@ -113,6 +114,16 @@ class TestFilterParam:
class TestSortParam:
+ def test_sort_columns_and_primary_key_use_the_selected_alias(self):
+ rows = select(DagRun).subquery("filtered_runs")
+ entity = aliased(DagRun, rows)
+ param = SortParam(["run_id"], entity).set_value(["run_id"])
+
+ query = param.to_orm(select(entity))
+
+ assert all(column.table is rows for _, column, _ in param.get_resolved_columns())
+ assert "ORDER BY filtered_runs.run_id ASC, filtered_runs.id ASC" in str(query)
+
def test_sort_param_max_number_of_filers(self):
param = SortParam([], None, None)
n_filters = param.MAX_SORT_PARAMS + 1
diff --git a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py
index d0da9a9b1ea..76f7ed723aa 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py
@@ -2267,6 +2267,7 @@ class TestClearDagRun:
assert response.status_code == 200
body = response.json()
assert body["total_entries"] == 2
+ assert len(body["task_instances"]) == 2
for ti in body["task_instances"]:
# Fields that require dag_run → dag_model join (previously missing)
diff --git a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_extra_links.py b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_extra_links.py
index 57f8b94f8e4..8bf0034b983 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_extra_links.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_extra_links.py
@@ -425,10 +425,9 @@ class TestGetExtraLinks:
assert ti is not None
ti.try_number = 1
ti.state = "success"
- ti.prepare_db_for_next_try(session=session)
- ti.state = None
+ successor = ti.prepare_db_for_next_try(session=session)
session.commit()
- current_id = ti.id
+ current_id = successor.id
response = test_client.get(
f"/dags/{self.dag_id}/dagRuns/{self.dag_run_id}/taskInstances/{self.task_single_link}/links",
@@ -440,13 +439,14 @@ class TestGetExtraLinks:
)
# Verify the live TI try_number was NOT modified
- session.expire(ti)
+ session.expire(successor)
ti = session.scalar(
select(TaskInstance).where(
TaskInstance.dag_id == self.dag_id,
TaskInstance.run_id == self.dag_run_id,
TaskInstance.task_id == self.task_single_link,
TaskInstance.map_index == -1,
+ TaskInstance.working_set.is_(True),
)
)
assert ti is not None
diff --git a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py
index 9981432d0c4..00152a18e29 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py
@@ -329,6 +329,48 @@ def sample_update_payload() -> dict[str, Any]:
class TestUpdateHITLDetailEndpoint:
+ def test_response_rejects_attempt_retired_after_lookup(
+ self,
+ test_client,
+ sample_ti,
+ sample_hitl_detail,
+ sample_ti_url_identifier,
+ sample_update_payload,
+ session,
+ mocker,
+ ):
+ get_task_instance = hitl_routes._get_task_instance_with_hitl_detail
+
+ def retire_after_lookup(*args, **kwargs):
+ task_instance = get_task_instance(*args, **kwargs)
+ with Session(bind=session.get_bind()) as other_session:
+ current = other_session.get(TIModel, task_instance.id)
+ current.prepare_db_for_next_try(other_session)
+ other_session.commit()
+ return task_instance
+
+ mocker.patch.object(
+ hitl_routes, "_get_task_instance_with_hitl_detail", autospec=True, side_effect=retire_after_lookup
+ )
+
+ response = test_client.patch(f"{sample_ti_url_identifier}/hitlDetails", json=sample_update_payload)
+
+ assert response.status_code == 409
+ with Session(bind=session.get_bind()) as verify_session:
+ assert verify_session.get(TIModel, sample_ti.id).working_set is None
+ assert not verify_session.get(HITLDetail, sample_ti.id).response_received
+ current = verify_session.scalar(
+ select(TIModel).where(
+ TIModel.dag_id == sample_ti.dag_id,
+ TIModel.task_id == sample_ti.task_id,
+ TIModel.run_id == sample_ti.run_id,
+ TIModel.working_set.is_(True),
+ )
+ )
+ assert current.id != sample_ti.id
+ assert current.state is None
+ assert verify_session.get(HITLDetail, current.id) is None
+
@time_machine.travel(datetime(2025, 7, 3, 0, 0, 0), tick=False)
@pytest.mark.usefixtures("sample_hitl_detail")
@mock.patch(
@@ -731,13 +773,41 @@ class TestGetHITLDetailEndpoint:
class TestGetHITLDetailsEndpoint:
+ def test_lists_only_current_task_instance_details(
+ self, test_client, sample_ti, sample_hitl_detail, session
+ ):
+ old_id = sample_ti.id
+ successor = sample_ti.prepare_db_for_next_try(session)
+ session.add(
+ HITLDetail(
+ ti_id=successor.id,
+ options=["Approve", "Reject"],
+ subject="Current subject",
+ body="Current body",
+ defaults=["Approve"],
+ multiple=False,
+ params={},
+ assignees=None,
+ )
+ )
+ session.commit()
+
+ response = test_client.get("/dags/~/dagRuns/~/hitlDetails")
+
+ assert response.status_code == 200
+ assert response.json()["total_entries"] == 1
+ assert [detail["task_instance"]["id"] for detail in response.json()["hitl_details"]] == [
+ str(successor.id)
+ ]
+ assert session.get(HITLDetail, sample_hitl_detail.ti_id).ti_id == old_id
+
@pytest.mark.usefixtures("sample_hitl_detail")
def test_should_respond_200_with_existing_response(
self,
test_client: TestClient,
expected_sample_hitl_detail_dict: dict[str, Any],
) -> None:
- with assert_queries_count(3):
+ with assert_queries_count(5):
response = test_client.get("/dags/~/dagRuns/~/hitlDetails")
assert response.status_code == 200
assert response.json() == {
@@ -813,7 +883,7 @@ class TestGetHITLDetailsEndpoint:
params: dict[str, Any],
expected_ti_count: int,
) -> None:
- with assert_queries_count(3):
+ with assert_queries_count(5):
response = test_client.get("/dags/~/dagRuns/~/hitlDetails", params=params)
assert response.status_code == 200
assert response.json()["total_entries"] == expected_ti_count
diff --git a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py
index 265bab04ca7..3648fc28928 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py
@@ -44,7 +44,6 @@ from airflow.models.dagbundle import DagBundleModel
from airflow.models.renderedtifields import RenderedTaskInstanceFields as RTIF
from airflow.models.task_state_store import TaskStateStoreModel
from airflow.models.taskinstance import uuid7
-from airflow.models.taskinstancehistory import TaskInstanceHistory
from airflow.models.team import Team
from airflow.models.trigger import Trigger
from airflow.sdk import BaseOperator, TaskGroup
@@ -176,11 +175,23 @@ class TestTaskInstanceEndpoint:
session.merge(ti)
session.flush()
dag.clear(session=session)
+ successors = []
for ti in tis:
- assert ti.try_number == 2, "pre-condition: dag-clear moved tries along"
- ti.queue = "default_queue"
- session.merge(ti)
+ current = session.scalar(
+ select(TaskInstance).where(
+ TaskInstance.dag_id == ti.dag_id,
+ TaskInstance.task_id == ti.task_id,
+ TaskInstance.run_id == ti.run_id,
+ TaskInstance.map_index == ti.map_index,
+ TaskInstance.working_set.is_(True),
+ )
+ )
+ assert current.id != ti.id
+ assert current.try_number == 2
+ current.queue = "default_queue"
+ successors.append(current)
session.flush()
+ tis = successors
session.commit()
return tis
@@ -635,10 +646,11 @@ class TestGetMappedTaskInstance(TestTaskInstanceEndpoint):
ti = TaskInstance(
task=old_ti.task, run_id=old_ti.run_id, map_index=idx, dag_version_id=old_ti.dag_version_id
)
- ti.rendered_task_instance_fields = RTIF(ti, render_templates=False)
for attr in ["duration", "end_date", "pid", "start_date", "state", "queue", "note", "try_number"]:
setattr(ti, attr, getattr(old_ti, attr))
session.add(ti)
+ session.flush()
+ session.add(RTIF(ti, render_templates=False))
session.commit()
# in each loop, we should get the right mapped TI back
@@ -868,7 +880,7 @@ class TestGetMappedTaskInstances:
assert response.json() == {"detail": "The Dag with ID: `mapped_tis` was not found"}
def test_should_respond_200(self, one_task_with_many_mapped_tis, test_client):
- with assert_queries_count(4):
+ with assert_queries_count(5):
response = test_client.get(
"/dags/mapped_tis/dagRuns/run_mapped_tis/taskInstances/task_2/listMapped",
)
@@ -920,7 +932,7 @@ class TestGetMappedTaskInstances:
):
from airflow.configuration import conf
- with assert_queries_count(4):
+ with assert_queries_count(5):
response = test_client.get(
"/dags/mapped_tis/dagRuns/run_mapped_tis/taskInstances/task_2/listMapped",
params=params,
@@ -1206,7 +1218,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/example_python_operator/dagRuns/~/taskInstances",
{"logical_date_lte": DEFAULT_DATETIME_1},
1,
- 5,
+ 6,
id="test logical date filter",
),
pytest.param(
@@ -1219,7 +1231,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/example_python_operator/dagRuns/~/taskInstances",
{"start_date_gte": DEFAULT_DATETIME_1, "start_date_lte": DEFAULT_DATETIME_STR_2},
2,
- 5,
+ 6,
id="test start date filter",
),
pytest.param(
@@ -1235,7 +1247,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"start_date_lt": DEFAULT_DATETIME_STR_2,
},
1,
- 5,
+ 6,
id="test start date gt and lt filter",
),
pytest.param(
@@ -1248,7 +1260,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/example_python_operator/dagRuns/~/taskInstances?",
{"end_date_gte": DEFAULT_DATETIME_1, "end_date_lte": DEFAULT_DATETIME_STR_2},
2,
- 5,
+ 6,
id="test end date filter",
),
pytest.param(
@@ -1264,7 +1276,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"end_date_lt": (DEFAULT_DATETIME_2 + dt.timedelta(hours=1)).isoformat(),
},
1,
- 5,
+ 6,
id="test end date gt and lt filter",
),
pytest.param(
@@ -1277,7 +1289,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances",
{"duration_gte": 100, "duration_lte": 200},
3,
- 7,
+ 8,
id="test duration filter",
),
pytest.param(
@@ -1290,7 +1302,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"duration_gte": 100, "duration_lte": 200},
3,
- 3,
+ 4,
id="test duration filter ~",
),
pytest.param(
@@ -1303,7 +1315,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"duration_gt": 100, "duration_lt": 200},
1,
- 3,
+ 4,
id="test duration gt and lt filter ~",
),
pytest.param(
@@ -1317,7 +1329,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances"),
{"state": ["running", "queued", "none"]},
3,
- 7,
+ 8,
id="test state filter",
),
pytest.param(
@@ -1331,7 +1343,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances"),
{"state": ["no_status"]},
1,
- 7,
+ 8,
id="test no_status state filter",
),
pytest.param(
@@ -1345,7 +1357,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances"),
{},
4,
- 7,
+ 8,
id="test null states with no filter",
),
pytest.param(
@@ -1354,7 +1366,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances",
{"start_date_gte": DEFAULT_DATETIME_STR_1},
1,
- 7,
+ 8,
id="test start_date coalesce with null",
),
pytest.param(
@@ -1367,7 +1379,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances"),
{"pool": ["test_pool_1", "test_pool_2"]},
2,
- 7,
+ 8,
id="test pool filter",
),
pytest.param(
@@ -1380,7 +1392,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"pool": ["test_pool_1", "test_pool_2"]},
2,
- 3,
+ 4,
id="test pool filter ~",
),
pytest.param(
@@ -1393,7 +1405,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"pool_name_pattern": "test_pool"},
3,
- 3,
+ 4,
id="test pool_name_pattern filter",
),
pytest.param(
@@ -1406,7 +1418,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"pool_name_prefix_pattern": "test_pool"},
3,
- 3,
+ 4,
id="test pool_name_prefix_pattern filter",
),
pytest.param(
@@ -1419,7 +1431,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances",
{"queue": ["test_queue_1", "test_queue_2"]},
2,
- 7,
+ 8,
id="test queue filter",
),
pytest.param(
@@ -1432,7 +1444,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"queue": ["test_queue_1", "test_queue_2"]},
2,
- 3,
+ 4,
id="test queue filter ~",
),
pytest.param(
@@ -1447,7 +1459,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"queue_name_pattern": "test"},
3,
- 3,
+ 4,
id="test queue_name_pattern filter",
),
pytest.param(
@@ -1462,7 +1474,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"queue_name_prefix_pattern": "test"},
3,
- 3,
+ 4,
id="test queue_name_prefix_pattern filter",
),
pytest.param(
@@ -1475,7 +1487,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances"),
{"executor": ["test_exec_1", "test_exec_2"]},
2,
- 7,
+ 8,
id="test_executor_filter",
),
pytest.param(
@@ -1488,7 +1500,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"executor": ["test_exec_1", "test_exec_2"]},
2,
- 3,
+ 4,
id="test executor filter ~",
),
pytest.param(
@@ -1501,7 +1513,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/~/dagRuns/~/taskInstances"),
{"task_display_name_pattern": "task_name"},
2,
- 3,
+ 4,
id="test task_display_name_pattern filter",
),
pytest.param(
@@ -1514,7 +1526,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/~/dagRuns/~/taskInstances"),
{"task_display_name_prefix_pattern": "task_name"},
2,
- 3,
+ 4,
id="test task_display_name_prefix_pattern filter",
),
pytest.param(
@@ -1523,7 +1535,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/example_task_group/dagRuns/TEST_DAG_RUN_ID/taskInstances"),
{"task_group_id": "section_1"},
3,
- 7,
+ 8,
id="test task_group filter with exact match",
),
pytest.param(
@@ -1532,7 +1544,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/example_task_group/dagRuns/TEST_DAG_RUN_ID/taskInstances"),
{"task_group_id": "section_2"},
4, # section_2 has 4 tasks: task_1 + inner_section_2 (task_2, task_3, task_4)
- 7,
+ 8,
id="test task_group filter exact match on group_id",
),
pytest.param(
@@ -1545,7 +1557,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/~/dagRuns/~/taskInstances"),
{"task_id": "task_match_id_2"},
1,
- 3,
+ 4,
id="test task_id filter",
),
pytest.param(
@@ -1556,7 +1568,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/~/dagRuns/~/taskInstances"),
{"version_number": [2]},
2,
- 3,
+ 4,
id="test version number filter",
),
pytest.param(
@@ -1568,7 +1580,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
{"version_number": [1, 2, 3]},
7, # apart from the TIs in the fixture, we also get one from
# the create_task_instances method
- 3,
+ 4,
id="test multiple version numbers filter",
),
pytest.param(
@@ -1584,7 +1596,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances"),
{"try_number": [0, 1]},
5,
- 7,
+ 8,
id="test_try_number_filter",
),
pytest.param(
@@ -1603,7 +1615,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/~/dagRuns/~/taskInstances"),
{"operator": ["FirstOperator", "SecondOperator"]},
5,
- 3,
+ 4,
id="test operator type filter filter",
),
pytest.param(
@@ -1618,7 +1630,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"operator_name_pattern": "Custom"},
2,
- 3,
+ 4,
id="test operator_name_pattern filter",
),
pytest.param(
@@ -1633,7 +1645,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"operator_name_prefix_pattern": "Custom"},
2,
- 3,
+ 4,
id="test operator_name_prefix_pattern filter",
),
pytest.param(
@@ -1651,7 +1663,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/~/dagRuns/~/taskInstances"),
{"map_index": [0, 1]},
2,
- 3,
+ 4,
id="test map_index filter",
),
pytest.param(
@@ -1665,7 +1677,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"rendered_map_index_prefix_pattern": "table_"},
2,
- 3,
+ 4,
id="test rendered_map_index_prefix_pattern filter",
),
pytest.param(
@@ -1679,7 +1691,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"rendered_map_index_pattern": "_users|table_orders"},
2,
- 3,
+ 4,
id="test rendered_map_index_pattern filter",
),
pytest.param(
@@ -1691,7 +1703,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
{"run_id_pattern": "TEST_DAG_"},
1, # apart from the TIs in the fixture, we also get one from
# the create_task_instances method
- 3,
+ 4,
id="test run_id_pattern filter",
),
pytest.param(
@@ -1702,7 +1714,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
("/dags/~/dagRuns/~/taskInstances"),
{"run_id_prefix_pattern": "TEST_DAG_"},
1,
- 3,
+ 4,
id="test run_id_prefix_pattern filter",
),
pytest.param(
@@ -1711,7 +1723,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"dag_id_pattern": "example_python_operator"},
14, # Based on test failure - example_python_operator creates 14 task instances
- 3,
+ 4,
id="test dag_id_pattern exact match",
),
pytest.param(
@@ -1720,7 +1732,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"dag_id_pattern": "example_%"},
22, # Based on test failure - both DAGs together create 22 task instances
- 3,
+ 4,
id="test dag_id_pattern wildcard prefix",
),
pytest.param(
@@ -1729,7 +1741,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"dag_id_pattern": "%skip%"},
8, # Based on test failure - example_skip_dag creates 8 task instances
- 3,
+ 4,
id="test dag_id_pattern wildcard contains",
),
pytest.param(
@@ -1747,7 +1759,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"dag_id_prefix_pattern": "example_python_operator"},
14,
- 3,
+ 4,
id="test dag_id_prefix_pattern exact match",
),
pytest.param(
@@ -1756,7 +1768,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"dag_id_prefix_pattern": "example_"},
22,
- 3,
+ 4,
id="test dag_id_prefix_pattern prefix",
),
pytest.param(
@@ -1765,7 +1777,7 @@ class TestGetTaskInstances(TestTaskInstanceEndpoint):
"/dags/~/dagRuns/~/taskInstances",
{"dag_id_prefix_pattern": "example_skip"},
8,
- 3,
+ 4,
id="test dag_id_prefix_pattern specific prefix",
),
pytest.param(
@@ -2552,7 +2564,7 @@ class TestGetTaskInstancesBatch(TestTaskInstanceEndpoint):
update_extras=update_extras,
task_instances=task_instances,
)
- with assert_queries_count(4):
+ with assert_queries_count(5):
response = test_client.post(
"/dags/~/dagRuns/~/taskInstances/list",
json=payload,
@@ -2938,19 +2950,23 @@ class TestGetTaskInstanceTry(TestTaskInstanceEndpoint):
ti = TaskInstance(
task=old_ti.task, run_id=old_ti.run_id, map_index=idx, dag_version_id=old_ti.dag_version_id
)
- ti.rendered_task_instance_fields = RTIF(ti, render_templates=False)
ti.try_number = 1
for attr in ["duration", "end_date", "pid", "start_date", "state", "queue", "note", "try_number"]:
setattr(ti, attr, getattr(old_ti, attr))
session.add(ti)
+ session.flush()
+ session.add(RTIF(ti, render_templates=False))
session.commit()
- tis = session.scalars(select(TaskInstance)).all()
+ tis = session.scalars(select(TaskInstance).where(TaskInstance.working_set.is_(True))).all()
# Record the task instance history
from airflow.models.taskinstance import clear_task_instances
- clear_task_instances(tis, session)
- for ti in tis:
+ successors = clear_task_instances(tis, session)
+ for old_ti, ti in zip(tis, successors):
if ti.map_index > 0:
+ assert old_ti.working_set is None
+ assert old_ti.try_number == 1
+ assert ti.id != old_ti.id
assert ti.try_number == 2
ti.queue = "default_queue"
session.merge(ti)
@@ -3020,14 +3036,12 @@ class TestGetTaskInstanceTry(TestTaskInstanceEndpoint):
ti.try_number = 1
session.merge(ti)
session.flush()
- ti.prepare_db_for_next_try(session=session)
- ti.state = None
+ successor = ti.prepare_db_for_next_try(session=session)
+ successor.state = None
session.flush()
- # Set duration and end_date in TaskInstanceHistory for easy testing
- tih = session.scalars(select(TaskInstanceHistory).limit(1)).one()
- tih.duration = 10000
- tih.end_date = self.default_time + dt.timedelta(days=2)
- session.merge(tih)
+ ti.duration = 10000
+ ti.end_date = self.default_time + dt.timedelta(days=2)
+ session.merge(ti)
session.commit()
# Get the task instance details from TIHistory:
response = test_client.get(
@@ -4301,12 +4315,12 @@ class TestPostClearTaskInstances(TestTaskInstanceEndpoint):
"only_failed": True,
"only_running": False,
}
- self.create_task_instances(
+ old_ti = self.create_task_instances(
session,
dag_id=dag_id,
task_instances=[{"logical_date": DEFAULT_DATETIME_1, "state": State.FAILED}],
update_extras=False,
- )
+ )[0]
response = test_client.post(
f"/dags/{dag_id}/clearTaskInstances",
json=payload,
@@ -4315,7 +4329,9 @@ class TestPostClearTaskInstances(TestTaskInstanceEndpoint):
response_data = response.json()
assert response_data["total_entries"] == 1
ti_id = response_data["task_instances"][0]["id"]
- _check_task_instance_note(session, ti_id, {"content": "placeholder-note", "user_id": None})
+ assert ti_id != str(old_ti.id)
+ _check_task_instance_note(session, old_ti.id, {"content": "placeholder-note", "user_id": None})
+ _check_task_instance_note(session, ti_id, None)
@pytest.mark.db_test
def test_clear_dry_run_does_not_set_note(self, test_client, session):
@@ -4560,6 +4576,23 @@ class TestPostClearTaskInstances(TestTaskInstanceEndpoint):
class TestGetTaskInstanceTries(TestTaskInstanceEndpoint):
+ def test_history_without_dag_version_serializes_null(self, test_client, session):
+ self.create_task_instances(
+ session=session, task_instances=[{"state": State.SUCCESS}], with_ti_history=True
+ )
+ historical = session.scalar(select(TaskInstance).where(TaskInstance.working_set.is_(None)))
+ historical.dag_version_id = None
+ session.commit()
+
+ response = test_client.get(
+ "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context/tries"
+ )
+
+ assert response.status_code == 200
+ attempts = {item["try_number"]: item for item in response.json()["task_instances"]}
+ assert attempts[1]["dag_version"] is None
+ assert attempts[2]["dag_version"] is not None
+
def test_should_respond_200(self, test_client, session):
self.create_task_instances(
session=session, task_instances=[{"state": State.SUCCESS}], with_ti_history=True
@@ -4670,7 +4703,7 @@ class TestGetTaskInstanceTries(TestTaskInstanceEndpoint):
self.create_task_instances(
session=session, task_instances=[{"state": State.FAILED}], with_ti_history=True
)
- ti = session.scalars(select(TaskInstance)).one()
+ ti = session.scalars(select(TaskInstance).where(TaskInstance.working_set.is_(True))).one()
ti.state = State.UP_FOR_RETRY
session.commit()
@@ -4701,9 +4734,12 @@ class TestGetTaskInstanceTries(TestTaskInstanceEndpoint):
# Record the task instance history
from airflow.models.taskinstance import clear_task_instances
- clear_task_instances(tis, session)
- for ti in tis:
+ successors = clear_task_instances(tis, session)
+ for old_ti, ti in zip(tis, successors):
if ti.map_index > 0:
+ assert old_ti.working_set is None
+ assert old_ti.try_number == 1
+ assert ti.id != old_ti.id
assert ti.try_number == 2
ti.queue = "default_queue"
session.merge(ti)
@@ -5514,10 +5550,11 @@ class TestPatchTaskInstance(TestTaskInstanceEndpoint):
ti = TaskInstance(
task=old_ti.task, run_id=old_ti.run_id, map_index=idx, dag_version_id=old_ti.dag_version_id
)
- ti.rendered_task_instance_fields = RTIF(ti, render_templates=False)
for attr in ["duration", "end_date", "pid", "start_date", "state", "queue", "note", "try_number"]:
setattr(ti, attr, getattr(old_ti, attr))
session.add(ti)
+ session.flush()
+ session.add(RTIF(ti, render_templates=False))
session.commit()
# in each loop, we should get the right mapped TI back
@@ -5600,10 +5637,11 @@ class TestPatchTaskInstance(TestTaskInstanceEndpoint):
ti = TaskInstance(
task=old_ti.task, run_id=old_ti.run_id, map_index=idx, dag_version_id=old_ti.dag_version_id
)
- ti.rendered_task_instance_fields = RTIF(ti, render_templates=False)
for attr in ["duration", "end_date", "pid", "start_date", "state", "queue", "note", "try_number"]:
setattr(ti, attr, getattr(old_ti, attr))
session.add(ti)
+ session.flush()
+ session.add(RTIF(ti, render_templates=False))
session.commit()
new_note_value = "My super cool TaskInstance note"
@@ -6391,6 +6429,68 @@ class TestBulkTaskInstances(TestTaskInstanceEndpoint):
BASH_TASK_ID = "also_run_this"
WILDCARD_ENDPOINT = "/dags/~/dagRuns/~/taskInstances"
+ @pytest.mark.parametrize("delete_mode", ["single", "bulk-exact", "bulk-all"])
+ def test_delete_removes_current_and_retired_tries(self, test_client, session, delete_mode):
+ current_tis = self.create_task_instances(
+ session,
+ task_instances=[{"task_id": self.TASK_ID, "state": State.SUCCESS, "map_indexes": (0, 1, 2)}],
+ with_ti_history=True,
+ )
+ session.delete(next(ti for ti in current_tis if ti.map_index == 2))
+ session.flush()
+ task_rows = session.scalars(
+ select(TaskInstance).where(
+ TaskInstance.dag_id == self.DAG_ID,
+ TaskInstance.run_id == self.RUN_ID,
+ TaskInstance.task_id == self.TASK_ID,
+ )
+ ).all()
+ ids_by_index = {
+ map_index: {ti.id for ti in task_rows if ti.map_index == map_index} for map_index in (0, 1, 2)
+ }
+ assert [len(ids_by_index[index]) for index in (0, 1, 2)] == [2, 2, 1]
+ session.commit()
+
+ if delete_mode == "single":
+ assert (
+ test_client.delete(f"{self.ENDPOINT_URL}/{self.TASK_ID}", params={"map_index": 2}).status_code
+ == 404
+ )
+ assert (
+ session.scalar(select(TaskInstance.id).where(TaskInstance.id.in_(ids_by_index[2])))
+ in ids_by_index[2]
+ )
+ response = test_client.delete(f"{self.ENDPOINT_URL}/{self.TASK_ID}", params={"map_index": 0})
+ else:
+ entity = {"task_id": self.TASK_ID}
+ if delete_mode == "bulk-exact":
+ entity["map_index"] = 0
+ response = test_client.patch(
+ self.ENDPOINT_URL,
+ json={"actions": [{"action": "delete", "entities": [entity]}]},
+ )
+ assert response.status_code == 200
+ if delete_mode != "single":
+ expected_indexes = {0, 1} if delete_mode == "bulk-all" else {0}
+ assert set(response.json()["delete"]["success"]) == {
+ f"{self.DAG_ID}.{self.RUN_ID}.{self.TASK_ID}[{index}]" for index in expected_indexes
+ }
+
+ session.expire_all()
+ remaining_ids = ids_by_index[1] | ids_by_index[2] if delete_mode != "bulk-all" else set()
+ assert (
+ set(
+ session.scalars(
+ select(TaskInstance.id).where(
+ TaskInstance.dag_id == self.DAG_ID,
+ TaskInstance.run_id == self.RUN_ID,
+ TaskInstance.task_id == self.TASK_ID,
+ )
+ )
+ )
+ == remaining_ids
+ )
+
@pytest.fixture(autouse=True)
def clean_db(self, session):
clear_db_runs()
@@ -7187,12 +7287,9 @@ class TestBulkTaskInstances(TestTaskInstanceEndpoint):
@pytest.mark.parametrize("task_count", [5, 10, 20])
def test_bulk_delete_query_count_scales_linearly_with_task_count(self, test_client, session, task_count):
- # Regression guard for the N+1 fix in BulkTaskInstanceService.handle_bulk_delete:
- # each extra task instance must add exactly QUERIES_PER_TASK_INSTANCE query (its DELETE),
- # not 2 (DELETE + re-SELECT). A regression that re-queries inside the loop would make
- # each run strictly exceed BASE_QUERY_COUNT + task_count * QUERIES_PER_TASK_INSTANCE.
+ # Each extra task instance adds one coordinate DELETE, with no per-instance re-SELECT.
QUERIES_PER_TASK_INSTANCE = 1
- BASE_QUERY_COUNT = 4
+ BASE_QUERY_COUNT = 2
self.create_task_instances(
session,
@@ -7579,8 +7676,10 @@ class TestPatchTaskGroup(TestTaskInstanceEndpoint):
TaskInstance.dag_id == self.DAG_ID,
TaskInstance.run_id == self.RUN_ID,
TaskInstance.task_id.in_(downstream_task_ids),
+ TaskInstance.working_set.is_(True),
)
).all()
+ assert {ti.task_id for ti in downstream_tis} == set(downstream_task_ids)
for ti in downstream_tis:
assert ti.state != TaskInstanceState.UPSTREAM_FAILED, (
f"Expected {ti.task_id} to be cleared from upstream_failed, got {ti.state}"
diff --git a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_xcom.py b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_xcom.py
index 93e7f40cfec..22c683e29db 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_xcom.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_xcom.py
@@ -22,7 +22,7 @@ from typing import TYPE_CHECKING
from unittest import mock
import pytest
-from sqlalchemy import select, update
+from sqlalchemy import update
from sqlalchemy.orm import Session
from airflow._shared.timezones import timezone
@@ -32,7 +32,7 @@ from airflow.models.dag_version import DagVersion
from airflow.models.dagbundle import DagBundleModel
from airflow.models.dagrun import DagRun
from airflow.models.team import Team
-from airflow.models.xcom import XCOM_RETURN_KEY, XComModel
+from airflow.models.xcom import XCOM_RETURN_KEY, XComModel, xcom_entity
from airflow.providers.standard.operators.empty import EmptyOperator
from airflow.sdk import DAG, AssetAlias
from airflow.sdk.bases.xcom import BaseXCom
@@ -776,7 +776,7 @@ class TestCreateXComEntry(TestXComEndpoint):
def test_create_xcom_entry_duplicate_check_is_bounded(self, test_client):
"""Checking for an existing XCom before inserting must ask the database for one row."""
- with capture_orm_selects("xcom") as statements:
+ with capture_orm_selects("xcom_v2") as statements:
response = test_client.post(
f"/dags/{TEST_DAG_ID}/dagRuns/{run_id}/taskInstances/{TEST_TASK_ID}/xcomEntries",
json=XComCreateBody(key=TEST_XCOM_KEY, value=TEST_XCOM_VALUE).model_dump(),
@@ -1108,14 +1108,6 @@ class TestPatchXComEntry(TestXComEndpoint):
assert response.status_code == 200
assert response.json()["value"] == [9, 9, 9]
- assert (
- session.scalar(
- select(XComModel.mapped_length).where(
- XComModel.dag_id == TEST_DAG_ID,
- XComModel.task_id == TEST_TASK_ID,
- XComModel.run_id == run_id,
- XComModel.key == key,
- )
- )
- == 3
- )
+ read = XComModel.get_many(run_id=run_id, dag_ids=TEST_DAG_ID, task_ids=TEST_TASK_ID, key=key)
+ entity = xcom_entity(read)
+ assert session.scalar(read.with_only_columns(entity.mapped_length)) == 3
diff --git a/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_dags.py b/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_dags.py
index 2321e6a4a95..23c7e8ec82f 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_dags.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_dags.py
@@ -404,6 +404,24 @@ class TestGetDagRuns(TestPublicDagEndpoint):
pending_actions.sort(key=lambda x: x["subject"])
assert pending_actions == expected_pending_actions
+ def test_pending_actions_filter_ignores_archived_task_instances_with_stale_pending_state(
+ self, test_client: TestClient, setup_hitl_data, session: Session
+ ):
+ pending_details = session.scalars(select(HITLDetail).where(HITLDetail.responded_at.is_(None))).all()
+ assert len(pending_details) == 3
+ for detail in pending_details:
+ detail.task_instance.working_set = None
+ detail.task_instance.archived_reason = "retry"
+ session.commit()
+
+ with_pending = test_client.get("/dags", params={"has_pending_actions": True})
+ without_pending = test_client.get("/dags", params={"has_pending_actions": False})
+
+ assert with_pending.status_code == 200
+ assert with_pending.json()["total_entries"] == 0
+ assert without_pending.status_code == 200
+ assert without_pending.json()["total_entries"] == 3
+
def test_should_response_401(self, unauthenticated_test_client):
response = unauthenticated_test_client.get("/dags", params={})
assert response.status_code == 401
diff --git a/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_dashboard.py b/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_dashboard.py
index e37dca7892e..e7948a2049b 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_dashboard.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_dashboard.py
@@ -23,11 +23,13 @@ from unittest import mock
import pendulum
import pytest
+from sqlalchemy import select
from airflow.api_fastapi.core_api.routes.ui import dashboard
from airflow.models.dag import DagModel
from airflow.models.dagbag import DBDagBag
from airflow.models.dagrun import DagRun
+from airflow.models.taskinstance import TaskInstance
from airflow.providers.standard.operators.empty import EmptyOperator
from airflow.utils.state import DagRunState, TaskInstanceState
from airflow.utils.types import DagRunType
@@ -245,6 +247,24 @@ def make_multiple_dags(dag_maker, session):
class TestHistoricalMetricsDataEndpoint:
+ @pytest.mark.usefixtures("freeze_time_for_dagruns", "make_dag_runs")
+ def test_retired_task_instance_is_excluded_from_state_counts(self, test_client, session):
+ ti = session.scalar(select(TaskInstance).where(TaskInstance.state == TaskInstanceState.SUCCESS))
+ successor = ti.prepare_db_for_next_try(session)
+ successor.state = TaskInstanceState.RUNNING
+ session.commit()
+
+ response = test_client.get(
+ "/dashboard/historical_metrics_data",
+ params={"start_date": "2023-01-01T00:00", "end_date": "2023-08-02T00:00"},
+ )
+
+ assert response.status_code == 200
+ states = response.json()["task_instance_states"]
+ assert states["success"] == 1
+ assert states["running"] == 1
+ assert response.json()["task_instance_counts_are_lower_bounds"] is False
+
@pytest.mark.parametrize(
("params", "expected"),
[
diff --git a/airflow-core/tests/unit/api_fastapi/execution_api/test_app.py b/airflow-core/tests/unit/api_fastapi/execution_api/test_app.py
index 3938b490fec..1cbb610a418 100644
--- a/airflow-core/tests/unit/api_fastapi/execution_api/test_app.py
+++ b/airflow-core/tests/unit/api_fastapi/execution_api/test_app.py
@@ -30,7 +30,7 @@ from fastapi.params import Security as SecurityParam
from fastapi.routing import APIRoute
from fastapi.testclient import TestClient
from opentelemetry import context as otel_context, propagate as otel_propagate
-from sqlalchemy import event, text
+from sqlalchemy import event, select, text
from sqlalchemy.exc import SQLAlchemyError
from airflow import settings
@@ -43,6 +43,7 @@ from airflow.api_fastapi.execution_api.datamodels.taskinstance import TaskInstan
from airflow.api_fastapi.execution_api.datamodels.token import TIClaims, TIToken
from airflow.api_fastapi.execution_api.security import require_auth
from airflow.api_fastapi.execution_api.versions import bundle
+from airflow.models.xcom import XComModel
from airflow.utils.session import create_session_async
from tests_common.test_utils.config import conf_vars
@@ -167,6 +168,21 @@ def test_in_process_execution_api_runs_without_jwt_secret():
assert response.status_code == 200
+def test_in_process_task_xcom_write_uses_its_attempt_id(create_task_instance, session):
+ ti = create_task_instance()
+ session.commit()
+ path = f"/xcoms/{ti.dag_id}/{ti.run_id}/{ti.task_id}/return_value"
+
+ with TestClient(InProcessExecutionAPI().app) as client:
+ wrong = client.post(path, json="wrong", headers={"X-Airflow-In-Process-Attempt-Id": str(UUID(int=1))})
+ correct = client.post(path, json="correct", headers={"X-Airflow-In-Process-Attempt-Id": str(ti.id)})
+
+ assert wrong.status_code == 404
+ assert correct.status_code == 201
+ stored = session.scalar(select(XComModel).where(XComModel.task_instance_id == ti.id))
+ assert stored.value == "correct"
+
+
def test_in_process_execution_api_transport_lifecycle():
"""The background loop + thread lifecycle is tied to the ``.transport``, not the factory instance.
diff --git a/airflow-core/tests/unit/api_fastapi/execution_api/test_security.py b/airflow-core/tests/unit/api_fastapi/execution_api/test_security.py
index 1f2bb1825fa..72ebeee2e5f 100644
--- a/airflow-core/tests/unit/api_fastapi/execution_api/test_security.py
+++ b/airflow-core/tests/unit/api_fastapi/execution_api/test_security.py
@@ -16,16 +16,24 @@
# under the License.
from __future__ import annotations
+from concurrent.futures import ThreadPoolExecutor
+from threading import Event
+from types import SimpleNamespace
from unittest.mock import MagicMock, patch
-from uuid import UUID
+from uuid import UUID, uuid4
+import anyio
+import jwt
import pytest
import svcs
from fastapi import APIRouter, FastAPI, Request, Security
from fastapi.testclient import TestClient
+from sqlalchemy import select
from structlog.testing import capture_logs
from airflow.api_fastapi.auth.tokens import JWTValidator
+from airflow.api_fastapi.execution_api import security
+from airflow.api_fastapi.execution_api.app import InProcessExecutionAPI
from airflow.api_fastapi.execution_api.datamodels.token import TIClaims, TIToken, TokenScope
from airflow.api_fastapi.execution_api.security import (
ExecutionAPIRoute,
@@ -33,6 +41,17 @@ from airflow.api_fastapi.execution_api.security import (
get_team_name_dep,
require_auth,
)
+from airflow.models.callback import Callback, CallbackFetchMethod
+from airflow.models.connection_test import ConnectionTestRequest, ConnectionTestState
+from airflow.models.renderedtifields import RenderedTaskInstanceFields
+from airflow.models.taskinstance import LegacyTaskDataOwner, TaskInstance
+from airflow.models.variable import Variable
+from airflow.models.xcom import XComModel, XComModelV1, XComModelV2
+from airflow.sdk.api.client import XComOperations
+from airflow.sdk.bases.xcom import BaseXCom
+from airflow.sdk.execution_time import request_handlers, task_runner
+from airflow.sdk.execution_time.comms import DeleteXCom, GetXCom
+from airflow.utils.state import CallbackState, TaskInstanceState
class TestTIClaims:
@@ -283,3 +302,351 @@ class TestGetTeamNameDep:
assert result is None
mock_create_session.assert_not_called()
+
+
+@pytest.mark.db_test
+class TestAttemptLiveness:
+ @pytest.fixture
+ def caller(self, client, exec_app, monkeypatch, create_task_instance, session):
+ ti = create_task_instance(state=TaskInstanceState.RUNNING)
+ session.commit()
+ token = TIToken(id=ti.id, claims=TIClaims())
+
+ async def authenticated_token():
+ return token
+
+ monkeypatch.delitem(exec_app.dependency_overrides, require_auth)
+ monkeypatch.setitem(exec_app.dependency_overrides, _jwt_bearer, authenticated_token)
+ return ti, token
+
+ @pytest.mark.parametrize("retirement", ["retry", "delete"])
+ def test_retired_attempt_cannot_replace_or_delete_xcom(self, client, caller, session, retirement):
+ ti, token = caller
+ path = f"/execution/xcoms/{ti.dag_id}/{ti.run_id}/{ti.task_id}/result"
+ assert client.post(path, json="original").status_code == 201
+ old_id = ti.id
+ if retirement == "retry":
+ successor = ti.prepare_db_for_next_try(session)
+ successor.state = TaskInstanceState.UP_FOR_RETRY
+ else:
+ session.delete(ti)
+ session.commit()
+
+ expected_status = 410 if retirement == "retry" else 404
+ assert client.post(path, json="stale").status_code == expected_status
+ assert client.delete(path).status_code == expected_status
+
+ if retirement == "retry":
+ assert (
+ session.scalar(
+ select(TaskInstance.id).where(
+ TaskInstance.id == old_id, TaskInstance.working_set.is_(None)
+ )
+ )
+ == old_id
+ )
+ assert client.get(path).status_code == 410
+ token.id = successor.id
+ assert client.post(path, json="replacement").status_code == 201
+ token.id = old_id
+ assert client.delete(path).status_code == 410
+ assert client.get(path).status_code == 410
+
+ def test_unknown_execution_identity_cannot_write(self, client, caller):
+ _, token = caller
+ token.id = uuid4()
+ key = f"attempt-liveness-{uuid4()}"
+ try:
+ response = client.put(f"/execution/variables/{key}", json={"value": "unowned"})
+ assert response.status_code == 404
+ with pytest.raises(KeyError):
+ Variable.get(key)
+ finally:
+ Variable.delete(key)
+
+ RETIRED_ROUTES = [
+ ("put", "/execution/store/ti/{ti_id}/key", {"value": "stale"}),
+ ("delete", "/execution/store/ti/{ti_id}/key", None),
+ ("delete", "/execution/store/ti/{ti_id}", None),
+ ("put", "/execution/task-instances/{ti_id}/rtif", {}),
+ ("post", "/execution/hitlDetails/{ti_id}", {}),
+ ("patch", "/execution/hitlDetails/{ti_id}", {}),
+ ("put", "/execution/store/asset/by-name/value?name=asset&key=k", {"value": "stale"}),
+ ("delete", "/execution/store/asset/by-name/clear?name=asset", None),
+ ("post", "/execution/dag-runs/target/run", {}),
+ ("post", "/execution/dag-runs/target/run/clear", None),
+ ("put", "/execution/variables/key", {"value": "stale"}),
+ ("delete", "/execution/variables/key", None),
+ ("post", "/execution/xcoms/{dag_id}/{run_id}/{task_id}/key", "late"),
+ ]
+ # Clients older than the Cadwyn change that identifies retired attempts get 404, not 410.
+ OLD_CLIENT_ROUTES = [
+ ("put", "/execution/task-instances/{ti_id}/heartbeat", {"hostname": "w", "pid": 1}),
+ ("put", "/execution/task-instances/{ti_id}/rtif", {"field": "late"}),
+ ("post", "/execution/xcoms/{dag_id}/{run_id}/{task_id}/key", "late"),
+ ]
+
+ @pytest.mark.parametrize(
+ ("method", "path", "body", "version", "expected_status"),
+ [
+ *(pytest.param(*route, None, 410, id=f"{route[0]}:{route[1]}") for route in RETIRED_ROUTES),
+ *(
+ pytest.param(*route, version, 404, id=f"{route[0]}:{route[1]}:{version}")
+ for route in OLD_CLIENT_ROUTES
+ for version in ("2025-04-11", "2026-06-30")
+ ),
+ ],
+ )
+ def test_retired_attempt_rejected_before_mutation(
+ self, client, caller, session, method, path, body, version, expected_status
+ ):
+ ti, token = caller
+ path = path.format(ti_id=token.id, dag_id=ti.dag_id, run_id=ti.run_id, task_id=ti.task_id)
+ ti.prepare_db_for_next_try(session)
+ session.commit()
+
+ response = client.request(
+ method, path, json=body, headers={"Airflow-API-Version": version} if version else {}
+ )
+
+ assert response.status_code == expected_status, response.text
+
+ def test_callback_execution_token_can_mutate_variable(self, client, caller, session):
+ _, token = caller
+ callback = Callback()
+ callback.fetch_method = CallbackFetchMethod.IMPORT_PATH
+ callback.state = CallbackState.QUEUED
+ session.add(callback)
+ session.commit()
+ token.id = callback.id
+ token.claims.scope = "callback"
+ key = f"attempt-liveness-{uuid4()}"
+ try:
+ response = client.patch(f"/execution/callbacks/{callback.id}/run")
+ assert response.status_code == 204
+ claims = jwt.decode(response.headers["Refreshed-API-Token"], options={"verify_signature": False})
+ token.id = UUID(claims["sub"])
+ token.claims = TIClaims(**claims)
+
+ assert client.put(f"/execution/variables/{key}", json={"value": "callback"}).status_code == 201
+ assert Variable.get(key) == "callback"
+ finally:
+ Variable.delete(key)
+ session.delete(callback)
+ session.commit()
+
+ def test_connection_test_workload_keeps_its_own_lifecycle(self, client, caller, session):
+ _, token = caller
+ connection_test = ConnectionTestRequest(connection_id="liveness", conn_type="http")
+ connection_test.state = ConnectionTestState.QUEUED
+ session.add(connection_test)
+ session.commit()
+ token.id = connection_test.id
+ token.claims.scope = "workload"
+ try:
+ assert client.get(f"/execution/connection-tests/{token.id}/connection").status_code == 200
+ response = client.patch(
+ f"/execution/connection-tests/{token.id}", json={"state": "success", "result_message": "ok"}
+ )
+ assert response.status_code == 204
+ session.refresh(connection_test)
+ assert connection_test.state == ConnectionTestState.SUCCESS
+ finally:
+ session.delete(connection_test)
+ session.commit()
+
+ def test_trusted_in_process_caller_without_ti_can_write(self):
+ key = f"attempt-liveness-{uuid4()}"
+ try:
+ with TestClient(InProcessExecutionAPI().app) as client:
+ response = client.put(f"/variables/{key}", json={"value": "watcher"})
+ assert response.status_code == 201
+ assert Variable.get(key) == "watcher"
+ finally:
+ Variable.delete(key)
+
+ @pytest.mark.parametrize("delete_rejected", [False, True], ids=["accepted", "retired-token-rejected"])
+ def test_trusted_in_process_xcom_uses_current_owner_without_attempt_token(
+ self, caller, create_task_instance, session, monkeypatch, delete_rejected
+ ):
+ retired, _ = caller
+ XComModel.set_for_attempt(
+ task_instance_id=retired.id, key="key", value="retired", serialize=False, session=session
+ )
+ current = retired.prepare_db_for_next_try(session)
+ other = create_task_instance(dag_id="other_dag", task_id="other_task")
+ session.commit()
+ path = f"/xcoms/{retired.dag_id}/{retired.run_id}/{retired.task_id}/key"
+
+ with TestClient(InProcessExecutionAPI().app) as client:
+ mismatched = {"X-Airflow-In-Process-Attempt-Id": str(other.id)}
+ assert client.post(path, json="wrong", headers=mismatched).status_code == 403
+ assert client.delete(path, headers=mismatched).status_code == 403
+ retired_header = {"X-Airflow-In-Process-Attempt-Id": str(retired.id)}
+ assert client.post(path, json="stale", headers=retired_header).status_code == 410
+ assert client.delete(path, headers=retired_header).status_code == 410
+ assert client.post(path, json="current").status_code == 201
+ session.expire_all()
+ assert XComModelV2.get_for_attempt(current.id, "key", session=session).value == "current"
+
+ class APITransport:
+ def get(self, path, *, params):
+ response = client.get(f"/{path}", params=params)
+ response.raise_for_status()
+ return response
+
+ def delete(self, path, *, params):
+ headers = (
+ {"X-Airflow-In-Process-Attempt-Id": str(retired.id)} if delete_rejected else None
+ )
+ response = client.delete(f"/{path}", params=params, headers=headers)
+ if response.status_code != 200:
+ raise RuntimeError(f"DELETE rejected: {response.status_code}")
+ return response
+
+ api = SimpleNamespace(xcoms=XComOperations(APITransport()))
+
+ class InlineComms:
+ def send(self, message):
+ if isinstance(message, GetXCom):
+ return request_handlers.handle_get_xcom(api, message)[0]
+ if isinstance(message, DeleteXCom):
+ return request_handlers.handle_delete_xcom(api, message)[0]
+ raise AssertionError(type(message))
+
+ monkeypatch.setattr(task_runner, "SUPERVISOR_COMMS", InlineComms(), raising=False)
+ with patch.object(BaseXCom, "purge", autospec=True) as purge:
+ kwargs = {
+ "key": "key",
+ "dag_id": retired.dag_id,
+ "run_id": retired.run_id,
+ "task_id": retired.task_id,
+ "map_index": retired.map_index,
+ }
+ if delete_rejected:
+ with pytest.raises(RuntimeError, match="DELETE rejected: 410"):
+ BaseXCom.delete(**kwargs)
+ purge.assert_not_called()
+ else:
+ BaseXCom.delete(**kwargs)
+ assert purge.call_args.args[0].value == "current"
+
+ session.expire_all()
+ current_row = XComModelV2.get_for_attempt(current.id, "key", session=session)
+ assert (current_row.value if current_row is not None else None) == (
+ "current" if delete_rejected else None
+ )
+ assert XComModelV2.get_for_attempt(retired.id, "key", session=session).value == "retired"
+
+ @pytest.mark.parametrize("operation", ["xcom_write", "xcom_delete", "rtif_write", "variable_write"])
+ def test_admitted_child_mutation_stays_with_retired_uuid(
+ self, client, caller, session, monkeypatch, request, operation
+ ):
+ attempt, _ = caller
+ old_id = attempt.id
+ variable_key = f"attempt-liveness-{uuid4()}"
+ request.addfinalizer(lambda: Variable.delete(variable_key))
+ xcom_path = f"/execution/xcoms/{attempt.dag_id}/{attempt.run_id}/{attempt.task_id}/value"
+ XComModel.set_for_attempt(
+ task_instance_id=old_id, key="value", value="original", serialize=False, session=session
+ )
+ if operation == "xcom_delete":
+ session.add(
+ LegacyTaskDataOwner(
+ dag_id=attempt.dag_id,
+ task_id=attempt.task_id,
+ run_id=attempt.run_id,
+ map_index=attempt.map_index,
+ task_instance_id=old_id,
+ )
+ )
+ session.add(
+ XComModelV1(
+ dag_run_id=attempt.dag_run.id,
+ dag_id=attempt.dag_id,
+ task_id=attempt.task_id,
+ run_id=attempt.run_id,
+ map_index=attempt.map_index,
+ key="value",
+ value="legacy",
+ )
+ )
+ session.commit()
+ path = {
+ "rtif_write": f"/execution/task-instances/{old_id}/rtif",
+ "variable_write": f"/execution/variables/{variable_key}",
+ }.get(operation, xcom_path)
+ method = {
+ "xcom_write": "POST",
+ "xcom_delete": "DELETE",
+ "rtif_write": "PUT",
+ "variable_write": "PUT",
+ }[operation]
+ body = {"rtif_write": {"field": "late"}, "variable_write": {"value": "in flight"}}.get(
+ operation, "late"
+ )
+ admitted, finish = Event(), Event()
+ check = security._require_live_attempt
+
+ async def pause_after_check(*args, **kwargs):
+ await check(*args, **kwargs)
+ admitted.set()
+ assert await anyio.to_thread.run_sync(finish.wait, 10)
+
+ monkeypatch.setattr(security, "_require_live_attempt", pause_after_check)
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ pending = pool.submit(client.request, method, path, json=body)
+ try:
+ assert admitted.wait(10)
+ successor = attempt.prepare_db_for_next_try(session)
+ XComModel.set_for_attempt(
+ task_instance_id=successor.id,
+ key="value",
+ value="successor",
+ serialize=False,
+ session=session,
+ )
+ RenderedTaskInstanceFields.set_for_attempt(
+ task_instance_id=successor.id, rendered_fields={"field": "successor"}, session=session
+ )
+ session.commit()
+ finally:
+ finish.set()
+ response = pending.result(timeout=10)
+ expected_status = {"xcom_write": 201, "xcom_delete": 200, "rtif_write": 410, "variable_write": 201}[
+ operation
+ ]
+ assert response.status_code == expected_status, response.text
+ session.expire_all()
+ assert XComModelV2.get_for_attempt(successor.id, "value", session=session).value == "successor"
+ assert RenderedTaskInstanceFields.get_for_attempt(successor.id, session=session).rendered_fields == {
+ "field": "successor"
+ }
+ if operation == "xcom_write":
+ assert XComModelV2.get_for_attempt(old_id, "value", session=session).value == "late"
+ elif operation == "xcom_delete":
+ assert XComModelV2.get_for_attempt(old_id, "value", session=session) is None
+ assert (
+ session.get(XComModelV1, (attempt.dag_run.id, attempt.task_id, attempt.map_index, "value"))
+ is None
+ )
+ elif operation == "variable_write":
+ assert Variable.get(variable_key) == "in flight"
+ assert client.put(path, json={"value": "too late"}).status_code == 410
+ assert Variable.get(variable_key) == "in flight"
+ else:
+ assert RenderedTaskInstanceFields.get_for_attempt(old_id, session=session) is None
+
+ def test_public_execution_api_ignores_in_process_attempt_header(self, client, caller, session):
+ retired, _ = caller
+ successor = retired.prepare_db_for_next_try(session)
+ session.commit()
+
+ response = client.post(
+ f"/execution/xcoms/{retired.dag_id}/{retired.run_id}/{retired.task_id}/value",
+ headers={"X-Airflow-In-Process-Attempt-Id": str(successor.id)},
+ json="spoofed",
+ )
+
+ assert response.status_code == 410
+ assert XComModelV2.get_for_attempt(successor.id, "value", session=session) is None
diff --git a/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py b/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py
index a70b03b093c..48bed6901cc 100644
--- a/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py
+++ b/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py
@@ -57,7 +57,6 @@ from airflow.models.dagbag import DBDagBag
from airflow.models.log import Log
from airflow.models.task_state_store import TaskStateStoreModel
from airflow.models.taskinstance import TaskInstance, clear_task_instances
-from airflow.models.taskinstancehistory import TaskInstanceHistory
from airflow.providers.standard.operators.empty import EmptyOperator
from airflow.sdk import Asset, TaskGroup, TriggerRule, task, task_group
from airflow.state.metastore import MetastoreBackend
@@ -1337,6 +1336,7 @@ class TestTIRunState:
logs = session.scalars(select(Log).where(Log.dag_id == ti.dag_id)).all()
assert len(logs) == 1
assert logs[0].event == TaskInstanceState.RUNNING.value
+ assert logs[0].task_instance_id == ti.id
assert logs[0].task_id == ti.task_id
assert logs[0].dag_id == ti.dag_id
assert logs[0].run_id == ti.run_id
@@ -1437,7 +1437,11 @@ class TestTIUpdateState:
assert response.status_code == (204 if matching_worker else 409)
session.expunge_all()
- current = session.scalar(select(TaskInstance).where(TaskInstance.task_id == "stopped_restart"))
+ current = session.scalar(
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.task_id == "stopped_restart")
+ )
if not matching_worker:
assert (current.id, current.try_number, current.state) == (old_id, 3, State.RESTARTING)
return
@@ -1447,7 +1451,7 @@ class TestTIUpdateState:
assert current.max_tries == expected_max_tries
assert current.state is None
history = session.scalar(
- select(TaskInstanceHistory).where(TaskInstanceHistory.task_instance_id == old_id)
+ select(TaskInstance).where(TaskInstance.working_set.is_(None)).where(TaskInstance.id == old_id)
)
assert history.try_number == 3
assert history.end_date == DEFAULT_END_DATE
@@ -1458,7 +1462,7 @@ class TestTIUpdateState:
assert (current.id, current.try_number, current.state) == (new_id, 4, None)
assert current.max_tries == expected_max_tries
assert session.scalars(
- select(TaskInstanceHistory).where(TaskInstanceHistory.task_instance_id == old_id)
+ select(TaskInstance).where(TaskInstance.working_set.is_(None)).where(TaskInstance.id == old_id)
).all() == [history]
@pytest.mark.parametrize("first_report", ["api", "executor"])
@@ -1530,7 +1534,11 @@ class TestTIUpdateState:
SchedulerJobRunner.process_executor_events(executor, None, DBDagBag(), session)
session.commit()
session.expunge_all()
- current = session.scalar(select(TaskInstance).where(TaskInstance.task_id == "restart_reports"))
+ current = session.scalar(
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.task_id == "restart_reports")
+ )
if definition == "broken_task":
assert (current.id, current.try_number, current.state, current.max_tries) == (
old_id,
@@ -1540,7 +1548,9 @@ class TestTIUpdateState:
)
assert (
session.scalar(
- select(TaskInstanceHistory).where(TaskInstanceHistory.task_id == "restart_reports")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(TaskInstance.task_id == "restart_reports")
)
is None
)
@@ -1551,9 +1561,11 @@ class TestTIUpdateState:
assert (current.id, current.try_number, current.state) == (replacement_id, 4, None)
assert current.max_tries == (5 if definition == "available" else 3)
history = session.scalars(
- select(TaskInstanceHistory).where(TaskInstanceHistory.task_id == "restart_reports")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(TaskInstance.task_id == "restart_reports")
).one()
- assert (history.task_instance_id, history.try_number, history.state) == (old_id, 3, State.FAILED)
+ assert (history.id, history.try_number, history.state) == (old_id, 3, State.FAILED)
def setup_method(self):
clear_db_assets()
@@ -1667,6 +1679,7 @@ class TestTIUpdateState:
logs = session.scalars(select(Log).where(Log.dag_id == ti.dag_id)).all()
assert len(logs) == 1
assert logs[0].event == expected_event
+ assert logs[0].task_instance_id == ti.id
assert logs[0].task_id == ti.task_id
assert logs[0].dag_id == ti.dag_id
assert logs[0].run_id == ti.run_id
@@ -2006,7 +2019,7 @@ class TestTIUpdateState:
"""
ti = create_task_instance(
task_id="test_ti_update_state_database_error",
- state=State.QUEUED,
+ state=State.RUNNING,
)
session.commit()
payload = {
@@ -2014,46 +2027,18 @@ class TestTIUpdateState:
"end_date": "2024-10-31T12:00:00Z",
}
- with (
- mock.patch(
- "airflow.api_fastapi.common.db.common.Session.execute",
- side_effect=[
- mock.Mock(
- one=lambda: (
- "running",
- 1,
- 0,
- "dag",
- "task",
- "run",
- -1,
- "localhost",
- timezone.utcnow(),
- "test_owner",
- )
- ), # First call returns "queued"
- mock.Mock(
- one=lambda: (
- "running",
- 1,
- 0,
- "dag",
- "task",
- "run",
- -1,
- "localhost",
- timezone.utcnow(),
- "test_owner",
- )
- ), # Second call returns "queued"
- SQLAlchemyError("Database error"), # Last call raises an error
- ],
- ),
- mock.patch(
- "airflow.models.taskinstance.TaskInstance.register_asset_changes_in_db",
- ) as mock_register_asset_changes_in_db,
+ execute = Session.execute
+
+ def fail_ti_update(db_session, statement, *args, **kwargs):
+ if getattr(statement, "is_update", False) and statement.table.name == "task_instance":
+ raise SQLAlchemyError("Database error")
+ return execute(db_session, statement, *args, **kwargs)
+
+ with mock.patch(
+ "airflow.api_fastapi.common.db.common.Session.execute",
+ autospec=True,
+ side_effect=fail_ti_update,
):
- mock_register_asset_changes_in_db.return_value = None
response = client.patch(f"/execution/task-instances/{ti.id}/state", json=payload)
assert response.status_code == 500
detail = response.json()["detail"]
@@ -2180,7 +2165,7 @@ class TestTIUpdateState:
session.expire_all()
- tis = session.scalars(select(TaskInstance)).all()
+ tis = session.scalars(select(TaskInstance).where(TaskInstance.working_set.is_(True))).all()
assert len(tis) == 1
assert tis[0].state == TaskInstanceState.DEFERRED
@@ -2309,7 +2294,7 @@ class TestTIUpdateState:
session.expire_all()
- tis = session.scalars(select(TaskInstance)).all()
+ tis = session.scalars(select(TaskInstance).where(TaskInstance.working_set.is_(True))).all()
assert len(tis) == 1
assert tis[0].state == TaskInstanceState.UP_FOR_RESCHEDULE
assert tis[0].next_method is None
@@ -2463,7 +2448,9 @@ class TestTIUpdateState:
assert response.text == ""
ti = session.scalar(
- select(TaskInstance).filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
)
# ti = session.get(TaskInstance, ti.id)
assert ti.state == State.UP_FOR_RETRY
@@ -2471,15 +2458,40 @@ class TestTIUpdateState:
assert ti.next_kwargs is None
tih = session.scalars(
- select(TaskInstanceHistory).where(
- TaskInstanceHistory.task_id == ti.task_id, TaskInstanceHistory.run_id == ti.run_id
- )
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(TaskInstance.task_id == ti.task_id, TaskInstance.run_id == ti.run_id)
).one()
- assert tih.task_instance_id
- assert tih.task_instance_id != ti.id
+ assert tih.id
+ assert tih.id != ti.id
assert tih.try_number == 3
assert ti.try_number == 4
+ def test_retry_helper_failure_keeps_failed_attempt_current(self, client, session, create_task_instance):
+ ti = create_task_instance(task_id="retry_helper_failure", state=State.RUNNING)
+ attempt_id = ti.id
+ session.commit()
+
+ with mock.patch(
+ "airflow.api_fastapi.execution_api.routes.task_instances._create_ti_state_update_query_and_update_state",
+ autospec=True,
+ side_effect=RuntimeError("state update failed"),
+ ):
+ response = client.patch(
+ f"/execution/task-instances/{attempt_id}/state",
+ json={"state": State.UP_FOR_RETRY, "end_date": DEFAULT_END_DATE.isoformat()},
+ )
+
+ assert response.status_code == 204
+ session.expire_all()
+ attempts = session.scalars(
+ select(TaskInstance).where(TaskInstance.task_id == "retry_helper_failure")
+ ).all()
+ assert len(attempts) == 1
+ assert attempts[0].id == attempt_id
+ assert attempts[0].state == State.FAILED
+ assert attempts[0].working_set is True
+
@pytest.mark.parametrize("replacement_state", [State.UP_FOR_RETRY, State.RUNNING])
@pytest.mark.parametrize("reported_state", [State.UP_FOR_RETRY, State.FAILED])
def test_retired_attempt_report_does_not_change_replacement(
@@ -2493,7 +2505,9 @@ class TestTIUpdateState:
assert client.patch(f"/execution/task-instances/{old_id}/state", json=payload).status_code == 204
session.expunge_all()
replacement = session.scalar(
- select(TaskInstance).where(TaskInstance.task_id == "retired_attempt_report")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.task_id == "retired_attempt_report")
)
replacement.state = replacement_state
replacement.external_executor_id = "replacement-worker"
@@ -2518,9 +2532,11 @@ class TestTIUpdateState:
"replacement-worker",
)
history = session.scalars(
- select(TaskInstanceHistory).where(TaskInstanceHistory.task_id == "retired_attempt_report")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(TaskInstance.task_id == "retired_attempt_report")
).all()
- assert [(attempt.task_instance_id, attempt.try_number) for attempt in history] == [(old_id, 3)]
+ assert [(attempt.id, attempt.try_number) for attempt in history] == [(old_id, 3)]
def test_ti_update_state_retry_with_policy_overrides(self, client, session, create_task_instance):
"""Test that retry_delay_seconds and retry_reason from a RetryPolicy are stored on the TI."""
@@ -2543,7 +2559,9 @@ class TestTIUpdateState:
assert response.status_code == 204
ti = session.scalar(
- select(TaskInstance).filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
)
assert ti.state == State.UP_FOR_RETRY
assert ti.retry_delay_override == 42.5
@@ -2552,12 +2570,7 @@ class TestTIUpdateState:
def test_ti_update_state_retry_policy_overrides_persisted_in_history(
self, client, session, create_task_instance
):
- """The finished try's values must be archived to task_instance_history.
-
- record_ti() snapshots columns off the TI object, so the overrides, end_date,
- and rendered_map_index must be set on the TI before prepare_db_for_next_try()
- archives it; the live-row UPDATE is not visible to it.
- """
+ """The retired attempt keeps its retry policy and rendered-index values."""
ti = create_task_instance(
task_id="test_retry_policy_override_history",
state=State.RUNNING,
@@ -2578,11 +2591,14 @@ class TestTIUpdateState:
assert response.status_code == 204
+ session.expire_all()
tih = session.scalars(
- select(TaskInstanceHistory).where(
- TaskInstanceHistory.dag_id == ti.dag_id,
- TaskInstanceHistory.task_id == ti.task_id,
- TaskInstanceHistory.run_id == ti.run_id,
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(
+ TaskInstance.dag_id == ti.dag_id,
+ TaskInstance.task_id == ti.task_id,
+ TaskInstance.run_id == ti.run_id,
)
).one()
assert tih.retry_delay_override == 42.5
@@ -2620,16 +2636,21 @@ class TestTIUpdateState:
assert response.status_code == 204
+ session.expire_all()
ti = session.scalars(
- select(TaskInstance).filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
).one()
assert ti.rendered_map_index is None
tih = session.scalars(
- select(TaskInstanceHistory).where(
- TaskInstanceHistory.dag_id == ti.dag_id,
- TaskInstanceHistory.task_id == ti.task_id,
- TaskInstanceHistory.run_id == ti.run_id,
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(
+ TaskInstance.dag_id == ti.dag_id,
+ TaskInstance.task_id == ti.task_id,
+ TaskInstance.run_id == ti.run_id,
)
).one()
assert tih.rendered_map_index is None
@@ -2653,17 +2674,21 @@ class TestTIUpdateState:
assert response.status_code == 204
ti = session.scalar(
- select(TaskInstance).filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
)
assert ti.state == State.UP_FOR_RETRY
assert ti.retry_delay_override is None
assert ti.retry_reason is None
tih = session.scalars(
- select(TaskInstanceHistory).where(
- TaskInstanceHistory.dag_id == ti.dag_id,
- TaskInstanceHistory.task_id == ti.task_id,
- TaskInstanceHistory.run_id == ti.run_id,
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(
+ TaskInstance.dag_id == ti.dag_id,
+ TaskInstance.task_id == ti.task_id,
+ TaskInstance.run_id == ti.run_id,
)
).one()
assert tih.retry_delay_override is None
@@ -2695,7 +2720,9 @@ class TestTIUpdateState:
session.expire_all()
ti = session.scalar(
- select(TaskInstance).filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
)
assert ti.state == State.RUNNING
assert ti.retry_delay_override is None
@@ -2735,7 +2762,9 @@ class TestTIUpdateState:
if target_state == State.UP_FOR_RETRY:
# Retry creates a new TI ID, so we need to fetch by unique key
ti = session.scalar(
- select(TaskInstance).filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .filter_by(task_id=ti.task_id, run_id=ti.run_id, dag_id=ti.dag_id)
)
else:
session.expire_all()
@@ -3404,9 +3433,9 @@ class TestTIHealthEndpoint:
ti.prepare_db_for_next_try(session)
session.commit()
- assert session.get(TaskInstance, old_ti_id) is None
+ assert session.get(TaskInstance, old_ti_id) is not None
tih = session.scalar(
- select(TaskInstanceHistory).where(TaskInstanceHistory.task_instance_id == old_ti_id)
+ select(TaskInstance).where(TaskInstance.working_set.is_(None)).where(TaskInstance.id == old_ti_id)
)
assert tih is not None
@@ -3524,7 +3553,13 @@ class TestTIHealthEndpoint:
assert response.status_code == 204
assert len(task_instance_updates) == 1
- assert _where_column_keys(task_instance_updates[0]) == {"id", "state", "hostname", "pid"}
+ assert _where_column_keys(task_instance_updates[0]) == {
+ "id",
+ "state",
+ "hostname",
+ "pid",
+ "working_set",
+ }
assert len(for_update_selects) == 0
session.refresh(ti)
assert ti.last_heartbeat_at == new_time
@@ -3707,10 +3742,7 @@ class TestTIPutRTIF:
rtifs = session.scalars(select(RenderedTaskInstanceFields)).all()
assert len(rtifs) == 1
- assert rtifs[0].dag_id == "dag"
- assert rtifs[0].run_id == "test"
- assert rtifs[0].task_id == "test_ti_put_rtif_success"
- assert rtifs[0].map_index == -1
+ assert rtifs[0].task_instance_id == ti.id
assert rtifs[0].rendered_fields == payload
def test_ti_put_rtif_missing_ti(self, client, session, create_task_instance):
@@ -3744,8 +3776,7 @@ class TestTIPutRTIF:
ti.prepare_db_for_next_try(session)
session.commit()
- assert session.get(TaskInstance, old_ti_id) is None
- assert session.get(TaskInstanceHistory, old_ti_id) is not None
+ assert session.get(TaskInstance, old_ti_id) is not None
response = client.put(
f"/execution/task-instances/{old_ti_id}/rtif",
@@ -3757,6 +3788,14 @@ class TestTIPutRTIF:
"reason": "not_found",
"message": "Task Instance not found, it may have been moved to the Task Instance History table",
}
+ assert (
+ session.scalar(
+ select(RenderedTaskInstanceFields.id).where(
+ RenderedTaskInstanceFields.task_instance_id == old_ti_id
+ )
+ )
+ is None
+ )
class TestPreviousDagRun:
diff --git a/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_xcoms.py b/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_xcoms.py
index 559bfe11aff..c762d29f513 100644
--- a/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_xcoms.py
+++ b/airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_xcoms.py
@@ -20,6 +20,7 @@ from __future__ import annotations
import logging
import re
import urllib.parse
+from unittest.mock import patch
from uuid import uuid4
import pytest
@@ -27,15 +28,17 @@ from fastapi import FastAPI, HTTPException, Path, Request, status
from sqlalchemy import delete, select, update
from airflow._shared.timezones import timezone
+from airflow.api_fastapi.auth.tokens import JWTValidator
from airflow.api_fastapi.execution_api.datamodels.token import TIClaims, TIToken
from airflow.api_fastapi.execution_api.datamodels.xcom import XComResponse
-from airflow.api_fastapi.execution_api.security import require_auth
+from airflow.api_fastapi.execution_api.security import _jwt_bearer, require_auth
from airflow.models.dagrun import DagRun
-from airflow.models.xcom import XCOM_RETURN_KEY, XComModel
+from airflow.models.taskinstance import LegacyTaskDataOwner
+from airflow.models.xcom import XCOM_RETURN_KEY, XComModel, XComModelV1, XComModelV2, xcom_entity
from airflow.providers.standard.operators.empty import EmptyOperator
from airflow.sdk.serde import deserialize, serialize
from airflow.utils.session import create_session
-from airflow.utils.state import DagRunState
+from airflow.utils.state import DagRunState, TaskInstanceState
from tests_common.test_utils.asserts import capture_orm_selects
from tests_common.test_utils.config import conf_vars
@@ -48,7 +51,18 @@ def reset_db():
"""Reset XCom entries."""
with create_session() as session:
session.execute(delete(DagRun))
- session.execute(delete(XComModel))
+ session.execute(delete(XComModelV2))
+
+
+@pytest.fixture
+def authenticate_as(exec_app):
+ def bind(ti):
+ async def authenticated_token(request: Request) -> TIToken:
+ return TIToken(id=ti.id, claims=TIClaims(scope="execution"))
+
+ exec_app.dependency_overrides[require_auth] = authenticated_token
+
+ return bind
@pytest.fixture
@@ -99,13 +113,10 @@ class TestXComsGetEndpoint:
# The tests expect serialised strings because v2 serialised and stored in the DB
ti = create_task_instance()
- x = XComModel(
+ x = XComModelV2(
key="xcom_1",
value=db_value,
- dag_run_id=ti.dag_run.id,
- run_id=ti.run_id,
- task_id=ti.task_id,
- dag_id=ti.dag_id,
+ task_instance_id=ti.id,
)
session.add(x)
session.commit()
@@ -203,14 +214,10 @@ class TestXComsGetEndpoint:
if db_value is None: # We don't put None to XCom.
continue
ti = tis[map_index]
- x = XComModel(
+ x = XComModelV2(
key="xcom_1",
value=db_value,
- dag_run_id=ti.dag_run.id,
- run_id=ti.run_id,
- task_id=ti.task_id,
- dag_id=ti.dag_id,
- map_index=map_index,
+ task_instance_id=ti.id,
)
session.add(x)
session.commit()
@@ -261,14 +268,10 @@ class TestXComsGetEndpoint:
if db_value is None: # We don't put None to XCom.
continue
ti = tis[map_index]
- x = XComModel(
+ x = XComModelV2(
key="xcom_1",
value=db_value,
- dag_run_id=ti.dag_run.id,
- run_id=ti.run_id,
- task_id=ti.task_id,
- dag_id=ti.dag_id,
- map_index=map_index,
+ task_instance_id=ti.id,
)
session.add(x)
session.commit()
@@ -307,21 +310,15 @@ class TestXComsGetEndpoint:
earlier_ti = earlier_run.get_task_instance("task")
later_ti = later_run.get_task_instance("task")
- earlier_xcom = XComModel(
+ earlier_xcom = XComModelV2(
key="test_key",
value="earlier_value",
- dag_run_id=earlier_ti.dag_run.id,
- run_id=earlier_ti.run_id,
- task_id=earlier_ti.task_id,
- dag_id=earlier_ti.dag_id,
+ task_instance_id=earlier_ti.id,
)
- later_xcom = XComModel(
+ later_xcom = XComModelV2(
key="test_key",
value="later_value",
- dag_run_id=later_ti.dag_run.id,
- run_id=later_ti.run_id,
- task_id=later_ti.task_id,
- dag_id=later_ti.dag_id,
+ task_instance_id=later_ti.id,
)
session.add_all([earlier_xcom, later_xcom])
session.commit()
@@ -348,19 +345,15 @@ class TestXComsGetEndpoint:
dag_run = dag_maker.create_dagrun(run_id="runid")
for ti in dag_run.task_instances:
session.add(
- XComModel(
+ XComModelV2(
key="xcom_1",
value=xcom_values[ti.map_index],
- dag_run_id=ti.dag_run.id,
- run_id=ti.run_id,
- task_id=ti.task_id,
- dag_id=ti.dag_id,
- map_index=ti.map_index,
+ task_instance_id=ti.id,
)
)
session.commit()
- with capture_orm_selects("xcom") as statements:
+ with capture_orm_selects("xcom_v2") as statements:
response = client.get(f"/execution/xcoms/dag/runid/task/xcom_1/item/{offset}")
assert response.status_code == 200
@@ -388,18 +381,15 @@ class TestXComsGetEndpoint:
]:
dag_run = dag_maker.create_dagrun(run_id=run_id, logical_date=timezone.parse(logical_date))
session.add(
- XComModel(
+ XComModelV2(
key="xcom_1",
value=value,
- dag_run_id=dag_run.id,
- run_id=run_id,
- task_id="task",
- dag_id="dag",
+ task_instance_id=dag_run.get_task_instance("task", session=session).id,
)
)
session.commit()
- with capture_orm_selects("xcom") as statements:
+ with capture_orm_selects("xcom_v2") as statements:
response = client.get(f"/execution/xcoms/dag/later_run/task/xcom_1{query_string}")
assert response.status_code == 200
@@ -408,6 +398,36 @@ class TestXComsGetEndpoint:
for sql in statements:
assert re.search(r"\bLIMIT 1\b", sql), f"XCom lookup is not bounded to one row: {sql}"
+ @pytest.mark.parametrize(
+ ("version", "expected_status"),
+ [("2025-04-11", 404), ("2026-06-30", 404), ("2026-10-30", 410)],
+ )
+ def test_retired_attempt_read_response_by_version(
+ self, client, exec_app, monkeypatch, create_task_instance, session, version, expected_status
+ ):
+ attempt = create_task_instance(state=TaskInstanceState.RUNNING)
+ attempt.prepare_db_for_next_try(session)
+ session.commit()
+
+ async def authenticated_token():
+ return TIToken(id=attempt.id, claims=TIClaims())
+
+ monkeypatch.delitem(exec_app.dependency_overrides, require_auth)
+ monkeypatch.setitem(exec_app.dependency_overrides, _jwt_bearer, authenticated_token)
+
+ with patch.object(
+ JWTValidator,
+ "avalidated_claims",
+ autospec=True,
+ return_value={"sub": str(attempt.id), "scope": "execution"},
+ ):
+ response = client.get(
+ f"/execution/xcoms/{attempt.dag_id}/{attempt.run_id}/{attempt.task_id}/key",
+ headers={"Airflow-API-Version": version},
+ )
+
+ assert response.status_code == expected_status, response.text
+
class TestXComsSetEndpoint:
@pytest.mark.parametrize(
@@ -420,7 +440,7 @@ class TestXComsSetEndpoint:
(None, None),
],
)
- def test_xcom_set(self, client, create_task_instance, session, value, expected_value):
+ def test_xcom_set(self, client, create_task_instance, authenticate_as, session, value, expected_value):
"""
Test that XCom value is set correctly. The request body can be either:
- a JSON string (e.g. '"value"', '{"k":"v"}', '[1]'), which is stored as-is (a string) in the DB
@@ -431,6 +451,7 @@ class TestXComsSetEndpoint:
"""
ti = create_task_instance()
session.commit()
+ authenticate_as(ti)
value = serialize(value)
response = client.post(
f"/execution/xcoms/{ti.dag_id}/{ti.run_id}/{ti.task_id}/xcom_1",
@@ -440,13 +461,7 @@ class TestXComsSetEndpoint:
assert response.status_code == 201
assert response.json() == {"message": "XCom successfully set"}
- xcom = session.scalars(
- select(XComModel).where(
- XComModel.task_id == ti.task_id,
- XComModel.dag_id == ti.dag_id,
- XComModel.key == "xcom_1",
- )
- ).first()
+ xcom = XComModelV2.get_for_attempt(ti.id, "xcom_1", session=session)
assert xcom.value == expected_value
assert xcom.mapped_length is None, "Should not be mapped"
@@ -471,7 +486,9 @@ class TestXComsSetEndpoint:
),
],
)
- def test_xcom_round_trip(self, client, create_task_instance, session, orig_value, ser_value, deser_value):
+ def test_xcom_round_trip(
+ self, client, create_task_instance, authenticate_as, session, orig_value, ser_value, deser_value
+ ):
"""
Test that deserialization works when XCom values are stored directly in the DB with API Server.
@@ -485,6 +502,7 @@ class TestXComsSetEndpoint:
ti = create_task_instance()
session.commit()
+ authenticate_as(ti)
# Serialize the value to simulate the client SDK
value = serialize(orig_value)
@@ -499,14 +517,14 @@ class TestXComsSetEndpoint:
assert response.status_code == 201
- stored_value = session.execute(
- XComModel.get_many(
- key="xcom_1",
- dag_ids=ti.dag_id,
- task_ids=ti.task_id,
- run_id=ti.run_id,
- ).with_only_columns(XComModel.value)
- ).first()
+ read = XComModel.get_many(
+ key="xcom_1",
+ dag_ids=ti.dag_id,
+ task_ids=ti.task_id,
+ run_id=ti.run_id,
+ )
+ entity = xcom_entity(read)
+ stored_value = session.execute(read.with_only_columns(entity.value)).first()
deserialized_value = XComModel.deserialize_value(stored_value)
assert deserialized_value == deser_value
@@ -514,9 +532,10 @@ class TestXComsSetEndpoint:
# Ensure that the deserialized value on the client side is the same as the original value
assert deserialize(deserialized_value) == orig_value
- def test_xcom_set_mapped(self, client, create_task_instance, session):
+ def test_xcom_set_mapped(self, client, create_task_instance, authenticate_as, session):
ti = create_task_instance()
session.commit()
+ authenticate_as(ti)
value = serialize("value1")
@@ -529,25 +548,27 @@ class TestXComsSetEndpoint:
assert response.status_code == 201
assert response.json() == {"message": "XCom successfully set"}
- xcom = session.scalars(
- select(XComModel).where(
- XComModel.task_id == ti.task_id,
- XComModel.dag_id == ti.dag_id,
- XComModel.key == XCOM_RETURN_KEY,
- XComModel.map_index == -1,
- )
- ).first()
+ xcom = XComModelV2.get_for_attempt(ti.id, XCOM_RETURN_KEY, session=session)
assert xcom.value == "value1"
- assert xcom.dag_id == "dag"
- assert xcom.run_id == "test"
- assert xcom.task_id == "op1"
- assert xcom.map_index == -1
+ read = XComModel.get_many(
+ run_id=ti.run_id, task_ids=ti.task_id, dag_ids=ti.dag_id, key=XCOM_RETURN_KEY
+ )
+ logical = session.scalars(read).one()
+ assert (logical.dag_id, logical.run_id, logical.task_id, logical.map_index) == (
+ ti.dag_id,
+ ti.run_id,
+ ti.task_id,
+ -1,
+ )
assert xcom.mapped_length == 3
- def test_xcom_set_mapped_rejects_non_return_value_key(self, client, create_task_instance, session):
+ def test_xcom_set_mapped_rejects_non_return_value_key(
+ self, client, create_task_instance, authenticate_as, session
+ ):
"""Only the return value expands a downstream, so a length under any other key is refused."""
ti = create_task_instance()
session.commit()
+ authenticate_as(ti)
response = client.post(
f"/execution/xcoms/{ti.dag_id}/{ti.run_id}/{ti.task_id}/xcom_1",
@@ -558,16 +579,7 @@ class TestXComsSetEndpoint:
assert response.status_code == 400
assert response.json()["detail"]["reason"] == "invalid_mapped_length_key"
- assert (
- session.scalars(
- select(XComModel).where(
- XComModel.task_id == ti.task_id,
- XComModel.dag_id == ti.dag_id,
- XComModel.key == "xcom_1",
- )
- ).one_or_none()
- is None
- )
+ assert XComModelV2.get_for_attempt(ti.id, "xcom_1", session=session) is None
@pytest.mark.parametrize(
("length", "expected_status"),
@@ -577,7 +589,7 @@ class TestXComsSetEndpoint:
],
)
def test_xcom_set_downstream_of_mapped(
- self, client, create_task_instance, session, length, expected_status
+ self, client, create_task_instance, authenticate_as, session, length, expected_status
):
"""
Test that XCom value is set correctly. The value is passed as a JSON string in the request body.
@@ -586,6 +598,7 @@ class TestXComsSetEndpoint:
"""
ti = create_task_instance()
session.commit()
+ authenticate_as(ti)
response = client.post(
f"/execution/xcoms/{ti.dag_id}/{ti.run_id}/{ti.task_id}/{XCOM_RETURN_KEY}",
@@ -594,13 +607,7 @@ class TestXComsSetEndpoint:
)
assert response.status_code == expected_status
- xcom = session.scalars(
- select(XComModel).where(
- XComModel.task_id == ti.task_id,
- XComModel.dag_id == ti.dag_id,
- XComModel.key == XCOM_RETURN_KEY,
- )
- ).one_or_none()
+ xcom = XComModelV2.get_for_attempt(ti.id, XCOM_RETURN_KEY, session=session)
if expected_status < 400:
assert xcom.mapped_length == length
else:
@@ -631,7 +638,9 @@ class TestXComsSetEndpoint:
('["value1"]', '["value1"]'),
],
)
- def test_xcom_roundtrip(self, client, create_task_instance, session, value, expected_value):
+ def test_xcom_roundtrip(
+ self, client, create_task_instance, authenticate_as, session, value, expected_value
+ ):
"""
Test that XCom value is set and retrieved correctly using API.
@@ -644,18 +653,13 @@ class TestXComsSetEndpoint:
value = serialize(value)
session.commit()
+ authenticate_as(ti)
client.post(
f"/execution/xcoms/{ti.dag_id}/{ti.run_id}/{ti.task_id}/test_xcom_roundtrip",
json=value,
)
- xcom = session.scalars(
- select(XComModel).where(
- XComModel.task_id == ti.task_id,
- XComModel.dag_id == ti.dag_id,
- XComModel.key == "test_xcom_roundtrip",
- )
- ).first()
+ xcom = XComModelV2.get_for_attempt(ti.id, "test_xcom_roundtrip", session=session)
assert xcom.value == expected_value
response = client.get(f"/execution/xcoms/{ti.dag_id}/{ti.run_id}/{ti.task_id}/test_xcom_roundtrip")
@@ -663,36 +667,53 @@ class TestXComsSetEndpoint:
assert response.status_code == 200
assert XComResponse.model_validate_json(response.read()).value == expected_value
- def test_xcom_dag_result(self, client, create_task_instance, session):
+ def test_xcom_dag_result(self, client, create_task_instance, authenticate_as, session):
"""
Test that the dag_result flag propagates to XComModel.
"""
ti = create_task_instance()
+ session.commit()
+ authenticate_as(ti)
client.post(
f"/execution/xcoms/{ti.dag_id}/{ti.run_id}/{ti.task_id}/return_value",
params={"dag_result": True},
json=123,
)
- dag_result = session.scalar(
- select(XComModel.dag_result).where(
- XComModel.task_id == ti.task_id,
- XComModel.dag_id == ti.dag_id,
- XComModel.key == "return_value",
- )
- )
+ dag_result = XComModelV2.get_for_attempt(ti.id, "return_value", session=session).dag_result
assert dag_result is True
class TestXComsDeleteEndpoint:
- def test_xcom_delete_endpoint(self, client, create_task_instance, session):
+ def test_xcom_delete_endpoint(self, client, create_task_instance, authenticate_as, session):
"""Test that XCom value is deleted when Delete API is called."""
ti = create_task_instance()
ti.xcom_push(key="xcom_1", value='"value1"', session=session)
+ session.add(
+ LegacyTaskDataOwner(
+ dag_id=ti.dag_id,
+ task_id=ti.task_id,
+ run_id=ti.run_id,
+ map_index=ti.map_index,
+ task_instance_id=ti.id,
+ )
+ )
+ session.add(
+ XComModelV1(
+ dag_run_id=ti.dag_run.id,
+ dag_id=ti.dag_id,
+ task_id=ti.task_id,
+ run_id=ti.run_id,
+ map_index=ti.map_index,
+ key="xcom_1",
+ value="legacy",
+ )
+ )
ti1 = create_task_instance(dag_id="my_dag_1", task_id="task_1")
ti1.xcom_push(key="xcom_1", value='"value2"', session=session)
session.commit()
+ authenticate_as(ti)
xcoms = session.scalars(select(XComModel).where(XComModel.key == "xcom_1")).all()
assert xcoms is not None
@@ -703,23 +724,10 @@ class TestXComsDeleteEndpoint:
assert response.status_code == 200
assert response.json() == {"message": "XCom with key: xcom_1 successfully deleted."}
- xcom_ti = session.scalars(
- select(XComModel).where(
- XComModel.task_id == ti.task_id,
- XComModel.dag_id == ti.dag_id,
- XComModel.key == "xcom_1",
- )
- ).first()
- assert xcom_ti is None
-
- xcom_ti = session.scalars(
- select(XComModel).where(
- XComModel.task_id == ti1.task_id,
- XComModel.dag_id == ti1.dag_id,
- XComModel.key == "xcom_1",
- )
- ).first()
- assert xcom_ti is not None
+ with create_session(scoped=False) as verify:
+ assert XComModelV2.get_for_attempt(ti.id, "xcom_1", session=verify) is None
+ assert verify.get(XComModelV1, (ti.dag_run.id, ti.task_id, ti.map_index, "xcom_1")) is None
+ assert XComModelV2.get_for_attempt(ti1.id, "xcom_1", session=verify) is not None
class TestXComTeamAccess:
@@ -755,15 +763,12 @@ class TestXComTeamAccess:
return dr, ti
@staticmethod
- def _insert_xcom(session, dag_run, dag_id, key="k", value="v"):
+ def _insert_xcom(session, dag_run, key="k", value="v"):
session.add(
- XComModel(
+ XComModelV2(
key=key,
value=value,
- dag_run_id=dag_run.id,
- run_id=dag_run.run_id,
- task_id="task",
- dag_id=dag_id,
+ task_instance_id=dag_run.get_task_instance("task", session=session).id,
)
)
session.commit()
@@ -784,7 +789,7 @@ class TestXComTeamAccess:
_, requester_ti = self._make_dag(session, dag_maker, f"req_{uuid4().hex}", "team_a")
target_dag = f"tgt_{uuid4().hex}"
target_dr, _ = self._make_dag(session, dag_maker, target_dag, "team_b")
- self._insert_xcom(session, target_dr, target_dag)
+ self._insert_xcom(session, target_dr)
self._authenticate_as(exec_app, requester_ti.id)
with conf_vars({("core", "multi_team"): "False"}):
@@ -797,7 +802,7 @@ class TestXComTeamAccess:
"""A task may read, write, and delete XCom within its own team."""
dag_id = f"dag_{uuid4().hex}"
dag_run, ti = self._make_dag(session, dag_maker, dag_id, "team_a")
- self._insert_xcom(session, dag_run, dag_id, key="existing", value="v")
+ self._insert_xcom(session, dag_run, key="existing", value="v")
self._authenticate_as(exec_app, ti.id)
with conf_vars({("core", "multi_team"): "True"}):
@@ -815,7 +820,7 @@ class TestXComTeamAccess:
_, requester_ti = self._make_dag(session, dag_maker, f"req_{uuid4().hex}", "team_a")
target_dag = f"tgt_{uuid4().hex}"
target_dr, _ = self._make_dag(session, dag_maker, target_dag, "team_a")
- self._insert_xcom(session, target_dr, target_dag)
+ self._insert_xcom(session, target_dr)
self._authenticate_as(exec_app, requester_ti.id)
with conf_vars({("core", "multi_team"): "True"}):
@@ -844,7 +849,7 @@ class TestXComTeamAccess:
_, requester_ti = self._make_dag(session, dag_maker, f"req_{uuid4().hex}", "team_a")
global_dag = f"global_{uuid4().hex}"
global_dr, _ = self._make_dag(session, dag_maker, global_dag, None)
- self._insert_xcom(session, global_dr, global_dag, key="k", value="v")
+ self._insert_xcom(session, global_dr, key="k", value="v")
self._authenticate_as(exec_app, requester_ti.id)
with conf_vars({("core", "multi_team"): "True"}):
@@ -862,7 +867,7 @@ class TestXComTeamAccess:
self._make_dag(session, dag_maker, team_dag, "team_b")
global_dag = f"global_{uuid4().hex}"
global_dr, _ = self._make_dag(session, dag_maker, global_dag, None)
- self._insert_xcom(session, global_dr, global_dag, key="k", value="v")
+ self._insert_xcom(session, global_dr, key="k", value="v")
with conf_vars({("core", "multi_team"): "True"}):
forbidden = client.get(self._url(team_dag, key="k"))
diff --git a/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2025_04_28/test_xcom.py b/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2025_04_28/test_xcom.py
index 1f7c34b43fe..6d26a05b5fa 100644
--- a/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2025_04_28/test_xcom.py
+++ b/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2025_04_28/test_xcom.py
@@ -19,7 +19,7 @@ from __future__ import annotations
import pytest
-from airflow.models.xcom import XComModel
+from airflow.models.xcom import XComModelV2
from airflow.providers.standard.operators.empty import EmptyOperator
pytestmark = pytest.mark.db_test
@@ -90,14 +90,10 @@ class TestXComsGetEndpoint:
if db_value is None: # We don't put None to XCom.
continue
ti = tis[map_index]
- x = XComModel(
+ x = XComModelV2(
+ task_instance_id=ti.id,
key="xcom_1",
value=db_value,
- dag_run_id=ti.dag_run.id,
- run_id=ti.run_id,
- task_id=ti.task_id,
- dag_id=ti.dag_id,
- map_index=map_index,
)
session.add(x)
session.commit()
diff --git a/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2026_10_30/test_task_instances.py b/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2026_10_30/test_task_instances.py
index e8ee725940c..7668e2528b6 100644
--- a/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2026_10_30/test_task_instances.py
+++ b/airflow-core/tests/unit/api_fastapi/execution_api/versions/v2026_10_30/test_task_instances.py
@@ -52,7 +52,11 @@ def test_retired_state_report_response_by_version(
assert response.status_code == expected_status
session.expunge_all()
- replacement = session.scalar(select(TaskInstance).where(TaskInstance.task_id == "retired_state_report"))
+ replacement = session.scalar(
+ select(TaskInstance).where(
+ TaskInstance.task_id == "retired_state_report", TaskInstance.working_set.is_(True)
+ )
+ )
assert replacement.id != old_id
assert (replacement.try_number, replacement.state) == (2, State.UP_FOR_RETRY)
diff --git a/airflow-core/tests/unit/cli/commands/test_partition_command.py b/airflow-core/tests/unit/cli/commands/test_partition_command.py
index 7892c5bd74d..9e02e2fa7bc 100644
--- a/airflow-core/tests/unit/cli/commands/test_partition_command.py
+++ b/airflow-core/tests/unit/cli/commands/test_partition_command.py
@@ -102,7 +102,11 @@ def _set_tis_state(run_id: str, state: TaskInstanceState) -> None:
def _get_tis(run_id: str) -> list[TaskInstance]:
with create_session() as session:
- return list(session.scalars(select(TaskInstance).where(TaskInstance.run_id == run_id)))
+ return list(
+ session.scalars(
+ select(TaskInstance).where(TaskInstance.run_id == run_id, TaskInstance.working_set.is_(True))
+ )
+ )
@pytest.mark.usefixtures("setup_partitioned_runs")
@@ -1334,6 +1338,7 @@ class TestPartitionsClear:
select(TaskInstance).where(
TaskInstance.dag_id == dag_id_target,
TaskInstance.run_id == shared_run_id,
+ TaskInstance.working_set.is_(True),
)
)
)
diff --git a/airflow-core/tests/unit/jobs/test_scheduler_job.py b/airflow-core/tests/unit/jobs/test_scheduler_job.py
index eafe68660aa..a98decba84a 100644
--- a/airflow-core/tests/unit/jobs/test_scheduler_job.py
+++ b/airflow-core/tests/unit/jobs/test_scheduler_job.py
@@ -100,7 +100,6 @@ from airflow.models.log import Log, resolve_team_name
from airflow.models.pool import Pool, PoolStats
from airflow.models.serialized_dag import SerializedDagModel
from airflow.models.taskinstance import TaskInstance, clear_task_instances
-from airflow.models.taskinstancehistory import TaskInstanceHistory
from airflow.models.team import Team
from airflow.models.trigger import Trigger
from airflow.partition_mappers.base import (
@@ -690,27 +689,43 @@ class TestSchedulerJob:
assert f"ti_id={retiring_id}," in completion_logs[0]
assert "state=restarting," in completion_logs[0]
assert f"executor_state={executor_state}, try_number=4, max_tries={max_tries}," in completion_logs[0]
- assert ti1.state is None, "Task should be set to None (scheduled) state after RESTARTING processing"
- assert ti1.id != retiring_id
- assert ti1.try_number == 5
+ replacement = session.scalar(
+ select(TaskInstance).where(
+ TaskInstance.dag_id == dag_id,
+ TaskInstance.task_id == task_id,
+ TaskInstance.working_set.is_(True),
+ )
+ )
+ assert replacement.state is None, "Replacement should be ready to schedule after termination"
+ assert replacement.id != retiring_id
+ assert replacement.try_number == 5
mock_task_callback.assert_not_called()
# Verify max_tries was adjusted to allow retry
- assert ti1.max_tries == expected_max_tries, (
- f"max_tries should be adjusted to {expected_max_tries}, got {ti1.max_tries}"
+ assert replacement.max_tries == expected_max_tries, (
+ f"max_tries should be adjusted to {expected_max_tries}, got {replacement.max_tries}"
)
- assert ti1.is_eligible_to_retry() is retry_eligible
+ assert replacement.is_eligible_to_retry() is retry_eligible
history = session.scalars(
- select(TaskInstanceHistory).where(TaskInstanceHistory.dag_id == dag_id)
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(TaskInstance.dag_id == dag_id)
).one()
- assert (history.task_instance_id, history.try_number, history.state) == (retiring_id, 4, State.FAILED)
+ assert (history.id, history.try_number, history.state) == (retiring_id, 4, State.FAILED)
+ assert history.max_tries == max_tries
assert history.end_date is not None
- replacement_id = ti1.id
+ replacement_id = replacement.id
executor.event_buffer[TaskInstanceUuid(retiring_id)] = executor_state, None
job_runner._process_executor_events(executor=executor, session=session)
- ti1.refresh_from_db(session=session)
- assert (ti1.id, ti1.try_number, ti1.state) == (replacement_id, 5, None)
+ replacement.refresh_from_db(session=session)
+ assert (replacement.id, replacement.try_number, replacement.state) == (replacement_id, 5, None)
+ assert (
+ session.scalar(
+ select(func.count()).select_from(TaskInstance).where(TaskInstance.dag_id == dag_id)
+ )
+ == 2
+ )
@pytest.mark.parametrize("event_state", [State.QUEUED, State.RUNNING])
def test_restarting_waits_for_terminal_executor_event(self, dag_maker, session, event_state):
@@ -733,8 +748,9 @@ class TestSchedulerJob:
assert (
session.scalar(
select(func.count())
- .select_from(TaskInstanceHistory)
- .where(TaskInstanceHistory.dag_id == ti.dag_id)
+ .select_from(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(TaskInstance.dag_id == ti.dag_id)
)
== 0
)
@@ -757,24 +773,25 @@ class TestSchedulerJob:
retired_key = executor.get_task_key(ti)
retired_coordinates = ti.key
clear_task_instances([ti], session=session)
- ti.complete_restart(session=session)
- ti.state = State.QUEUED
- ti.external_executor_id = "replacement"
+ replacement = ti.complete_restart(session=session)
+ replacement.state = State.QUEUED
+ replacement.external_executor_id = "replacement"
session.flush()
if include_current:
- executor._register_task(ti)
- executor.event_buffer[executor.get_task_key(ti)] = State.RUNNING, "current_worker"
+ executor._register_task(replacement)
+ executor.event_buffer[executor.get_task_key(replacement)] = State.RUNNING, "current_worker"
executor.event_buffer[retired_key] = event_state, "retired_worker"
runner = SchedulerJobRunner(Job(), executors=[executor])
runner._process_executor_events(executor=executor, session=session)
session.flush()
session.refresh(ti)
+ session.refresh(replacement)
- assert ti.state == State.QUEUED
- assert ti.id != retired_id
- assert ti.try_number == 2
- assert ti.external_executor_id == ("current_worker" if include_current else "replacement")
+ assert (ti.id, ti.try_number, ti.state, ti.working_set) == (retired_id, 1, State.FAILED, None)
+ assert replacement.state == State.QUEUED
+ assert replacement.try_number == 2
+ assert replacement.external_executor_id == ("current_worker" if include_current else "replacement")
assert any(
"Received executor event" in record.message
and str(retired_id) in record.message
@@ -789,7 +806,7 @@ class TestSchedulerJob:
)
if include_current:
assert not any(
- "Discarding executor event" in record.message and str(ti.id) in record.message
+ "Discarding executor event" in record.message and str(replacement.id) in record.message
for record in caplog.records
)
@@ -863,7 +880,10 @@ class TestSchedulerJob:
self.job_runner._process_executor_events(executor=executor, session=session)
ti1.refresh_from_db(session=session)
- assert ti1.state == State.UP_FOR_RETRY
+ assert ti1.state == State.FAILED
+ successor = ti1.dag_run.get_task_instance(task1.task_id, session=session)
+ assert successor.id != ti1.id
+ assert successor.state == State.UP_FOR_RETRY
self.job_runner.executor.callback_sink.send.assert_not_called()
# ti in success state
@@ -2551,6 +2571,7 @@ class TestSchedulerJob:
session.scalar(
select(func.count())
.select_from(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
.where(TaskInstance.dag_id == dag_id, TaskInstance.state == State.SCHEDULED)
)
== 1
@@ -2559,6 +2580,7 @@ class TestSchedulerJob:
session.scalar(
select(func.count())
.select_from(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
.where(TaskInstance.dag_id == dag_id, TaskInstance.state == State.QUEUED)
)
== 1
@@ -2677,7 +2699,7 @@ class TestSchedulerJob:
assert queued_runs["run_3"] == 2
session.commit()
- session.scalars(select(TaskInstance)).all()
+ session.scalars(select(TaskInstance).where(TaskInstance.working_set.is_(True))).all()
# now we still have max tis running so no more will be queued
queued_tis = self.job_runner._select_task_instances_to_queue(
@@ -4997,7 +5019,9 @@ class TestSchedulerJob:
# Verify the task instance was created
initial_tis = session.scalars(
- select(TaskInstance).where(TaskInstance.dag_id == dag_id, TaskInstance.task_id == "dummy")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.dag_id == dag_id, TaskInstance.task_id == "dummy")
).all()
assert len(initial_tis) == 1
@@ -5024,7 +5048,9 @@ class TestSchedulerJob:
# Verify no new task instances were created for the removed task in the new dagrun
new_tis = session.scalars(
- select(TaskInstance).where(
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(
TaskInstance.dag_id == dag_id,
TaskInstance.task_id == "dummy",
TaskInstance.run_id == "test_run_2",
@@ -5108,7 +5134,16 @@ class TestSchedulerJob:
run_job(scheduler_job, execute_callable=self.job_runner._execute)
# zero tasks ran
- assert len(session.scalars(select(TaskInstance).where(TaskInstance.dag_id == dag_id)).all()) == 0
+ assert (
+ len(
+ session.scalars(
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.dag_id == dag_id)
+ ).all()
+ )
+ == 0
+ )
session.commit()
assert self.null_exec.sorted_tasks == []
@@ -5127,7 +5162,16 @@ class TestSchedulerJob:
run_after=data_interval_end,
)
# one task "ran"
- assert len(session.scalars(select(TaskInstance).where(TaskInstance.dag_id == dag_id)).all()) == 1
+ assert (
+ len(
+ session.scalars(
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.dag_id == dag_id)
+ ).all()
+ )
+ == 1
+ )
session.commit()
scheduler_job = Job()
@@ -5136,7 +5180,16 @@ class TestSchedulerJob:
run_job(scheduler_job, execute_callable=self.job_runner._execute)
# still one task
- assert len(session.scalars(select(TaskInstance).where(TaskInstance.dag_id == dag_id)).all()) == 1
+ assert (
+ len(
+ session.scalars(
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.dag_id == dag_id)
+ ).all()
+ )
+ == 1
+ )
session.commit()
assert self.null_exec.sorted_tasks == []
@@ -5168,10 +5221,14 @@ class TestSchedulerJob:
session = settings.Session()
ti1s = session.scalars(
- select(TaskInstance).where(TaskInstance.dag_id == dag_id, TaskInstance.task_id == "dummy1")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.dag_id == dag_id, TaskInstance.task_id == "dummy1")
).all()
ti2s = session.scalars(
- select(TaskInstance).where(TaskInstance.dag_id == dag_id, TaskInstance.task_id == "dummy2")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.dag_id == dag_id, TaskInstance.task_id == "dummy2")
).all()
# With catchup=True, future task start dates are respected
@@ -5207,10 +5264,14 @@ class TestSchedulerJob:
session = settings.Session()
ti1s = session.scalars(
- select(TaskInstance).where(TaskInstance.dag_id == dag_id, TaskInstance.task_id == "dummy1")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.dag_id == dag_id, TaskInstance.task_id == "dummy1")
).all()
ti2s = session.scalars(
- select(TaskInstance).where(TaskInstance.dag_id == dag_id, TaskInstance.task_id == "dummy2")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.dag_id == dag_id, TaskInstance.task_id == "dummy2")
).all()
# With catchup=False, future task start dates are ignored
@@ -5248,7 +5309,16 @@ class TestSchedulerJob:
# zero tasks ran
dag_id = "test_start_date_scheduling"
session = settings.Session()
- assert len(session.scalars(select(TaskInstance).where(TaskInstance.dag_id == dag_id)).all()) == 0
+ assert (
+ len(
+ session.scalars(
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.dag_id == dag_id)
+ ).all()
+ )
+ == 0
+ )
def test_scheduler_verify_pool_full(self, dag_maker, mock_executor):
"""
@@ -5459,17 +5529,23 @@ class TestSchedulerJob:
assert len(task_instances_list) == 2
ti0 = session.scalars(
- select(TaskInstance).where(TaskInstance.task_id == "test_scheduler_verify_priority_and_slots_t0")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.task_id == "test_scheduler_verify_priority_and_slots_t0")
).first()
assert ti0.state == State.SCHEDULED
ti1 = session.scalars(
- select(TaskInstance).where(TaskInstance.task_id == "test_scheduler_verify_priority_and_slots_t1")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.task_id == "test_scheduler_verify_priority_and_slots_t1")
).first()
assert ti1.state == State.QUEUED
ti2 = session.scalars(
- select(TaskInstance).where(TaskInstance.task_id == "test_scheduler_verify_priority_and_slots_t2")
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.task_id == "test_scheduler_verify_priority_and_slots_t2")
).first()
assert ti2.state == State.QUEUED
@@ -5667,7 +5743,9 @@ class TestSchedulerJob:
do_schedule()
with create_session() as session:
ti = session.scalars(
- select(TaskInstance).where(
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(
TaskInstance.dag_id == "test_retry_still_in_executor",
TaskInstance.task_id == "test_retry_handling_op",
)
@@ -5680,12 +5758,24 @@ class TestSchedulerJob:
run_task_instance(ti, dag_task1, ignore_ti_state=ignore_ti_state)
assert ti.try_number == 1
+
# At this point, scheduler has tried to schedule the task once and
# heartbeated the executor once, which moved the state of the task from
# SCHEDULED to QUEUED and then to SCHEDULED, to fail the task execution
# we need to ignore the TaskInstance state as SCHEDULED is not a valid state to start
# executing task.
+ def get_current_ti():
+ session.expire_all()
+ return session.scalar(
+ select(TaskInstance).where(
+ TaskInstance.working_set.is_(True),
+ TaskInstance.dag_id == "test_retry_still_in_executor",
+ TaskInstance.task_id == "test_retry_handling_op",
+ )
+ )
+
run_with_error(ti, ignore_ti_state=True)
+ ti = get_current_ti()
assert ti.state == State.UP_FOR_RETRY
assert ti.try_number == 2
@@ -5697,7 +5787,7 @@ class TestSchedulerJob:
# To verify that task does get re-queued.
executor.do_update = True
do_schedule()
- ti.refresh_from_db()
+ ti = get_current_ti()
assert ti.try_number == 2
assert ti.state == State.SUCCESS
@@ -5713,7 +5803,6 @@ class TestSchedulerJob:
list(sorted(State.adoptable_states)),
)
def test_adopt_or_reset_resettable_tasks(self, dag_maker, adoptable_state, session):
- from airflow.models.taskinstancehistory import TaskInstanceHistory
dag_id = "test_adopt_or_reset_adoptable_tasks_" + adoptable_state.name
with dag_maker(dag_id=dag_id, schedule="@daily"):
@@ -5739,16 +5828,21 @@ class TestSchedulerJob:
assert num_reset_tis == 1
ti.refresh_from_db(session=session)
- assert ti.id != old_ti_id
+ assert ti.id == old_ti_id
+ assert ti.working_set is None
+ current = dr1.get_task_instance(task_id, session=session)
+ assert current.id != old_ti_id
assert (
session.scalar(
- select(TaskInstanceHistory).where(
- TaskInstanceHistory.dag_id == ti.dag_id,
- TaskInstanceHistory.task_id == ti.task_id,
- TaskInstanceHistory.run_id == ti.run_id,
- TaskInstanceHistory.map_index == ti.map_index,
- TaskInstanceHistory.try_number == old_try_number,
- TaskInstanceHistory.task_instance_id == old_ti_id,
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(
+ TaskInstance.dag_id == ti.dag_id,
+ TaskInstance.task_id == ti.task_id,
+ TaskInstance.run_id == ti.run_id,
+ TaskInstance.map_index == ti.map_index,
+ TaskInstance.try_number == old_try_number,
+ TaskInstance.id == old_ti_id,
)
)
is not None
@@ -5794,16 +5888,22 @@ class TestSchedulerJob:
session.expire_all()
ti.refresh_from_db(session=session)
+ successor = session.scalar(
+ select(TaskInstance).where(
+ TaskInstance.dag_id == dag_id,
+ TaskInstance.task_id == task_id,
+ TaskInstance.working_set.is_(True),
+ )
+ )
- assert ti.state == State.UP_FOR_RETRY
- assert ti.try_number == 2
- assert ti.id != old_ti_id, "prepare_db_for_next_try must assign a new UUID"
- assert ti.external_executor_id is None
-
- from airflow.models.taskinstancehistory import TaskInstanceHistory
+ assert successor.state == State.UP_FOR_RETRY
+ assert successor.try_number == 2
+ assert successor.id != old_ti_id, "prepare_db_for_next_try must assign a new UUID"
+ assert successor.external_executor_id is None
+ assert (ti.id, ti.state, ti.working_set) == (old_ti_id, State.FAILED, None)
tih = session.scalar(
- select(TaskInstanceHistory).where(TaskInstanceHistory.task_instance_id == old_ti_id)
+ select(TaskInstance).where(TaskInstance.working_set.is_(None)).where(TaskInstance.id == old_ti_id)
)
assert tih is not None, "TaskInstanceHistory must be created for non-RUNNING retry"
assert tih.try_number == 1
@@ -5953,7 +6053,10 @@ class TestSchedulerJob:
assert num_reset_tis == 1
session.refresh(ti1)
- assert ti1.state is None
+ assert ti1.state == State.FAILED
+ current = dr1.get_task_instance(ti1.task_id, session=session)
+ assert current.id != ti1.id
+ assert current.state is None
session.refresh(ti2)
assert ti2.state == State.QUEUED
session.rollback()
@@ -7311,6 +7414,7 @@ class TestSchedulerJob:
def complete_one_dagrun():
ti = session.scalars(
select(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
.join(TaskInstance.dag_run)
.where(TaskInstance.state != State.SUCCESS)
.order_by(DagRun.logical_date)
@@ -8299,6 +8403,7 @@ class TestSchedulerJob:
session.scalar(
select(func.count())
.select_from(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
.where(TaskInstance.state == State.SCHEDULED)
)
== 1
@@ -8352,6 +8457,7 @@ class TestSchedulerJob:
session.scalar(
select(func.count())
.select_from(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
.where(TaskInstance.state == State.SCHEDULED)
)
== 1
@@ -8405,6 +8511,7 @@ class TestSchedulerJob:
session.scalar(
select(func.count())
.select_from(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
.where(TaskInstance.state == State.SCHEDULED)
)
== 1
@@ -8465,6 +8572,7 @@ class TestSchedulerJob:
session.scalar(
select(func.count())
.select_from(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
.where(TaskInstance.state == State.SCHEDULED)
)
== 2
@@ -8516,7 +8624,10 @@ class TestSchedulerJob:
session.expunge_all()
assert (
session.scalar(
- select(func.count()).select_from(TaskInstance).where(TaskInstance.state == State.SCHEDULED)
+ select(func.count())
+ .select_from(TaskInstance)
+ .where(TaskInstance.working_set.is_(True))
+ .where(TaskInstance.state == State.SCHEDULED)
)
== 2
)
@@ -9086,7 +9197,7 @@ class TestSchedulerJob:
self.job_runner._schedule_dag_run(dr, session)
session.expunge_all()
with create_session() as session:
- tis = session.scalars(select(TaskInstance)).all()
+ tis = session.scalars(select(TaskInstance).where(TaskInstance.working_set.is_(True))).all()
dags = [entry.dag for entry in self.job_runner.scheduler_dag_bag._dags.values()]
assert [dag.dag_id for dag in dags] == ["test_only_empty_tasks"]
@@ -9114,7 +9225,7 @@ class TestSchedulerJob:
self.job_runner._schedule_dag_run(dr, session)
session.expunge_all()
with create_session() as session:
- tis = session.scalars(select(TaskInstance)).all()
+ tis = session.scalars(select(TaskInstance).where(TaskInstance.working_set.is_(True))).all()
assert len(tis) == 6
assert {
@@ -9783,7 +9894,11 @@ class TestSchedulerJob:
session.expire_all()
ti.refresh_from_db(session=session)
- assert ti.state == expected
+ assert ti.state == State.FAILED
+ if expected == TaskInstanceState.UP_FOR_RETRY:
+ current = dag_run.get_task_instance(ti.task_id, session=session)
+ assert current.id != ti.id
+ assert current.state == expected
@pytest.mark.parametrize(
("state", "retries", "try_number", "expected_callback_type", "expected_dispatched_callback"),
@@ -10060,8 +10175,7 @@ class TestSchedulerJob:
old_id = ti.id
old_key = ti.key
- clear_task_instances([ti], session=session)
- ti = session.merge(ti)
+ ti = clear_task_instances([ti], session=session)[0]
session.commit()
assert ti.state == TaskInstanceState.RESTARTING
executor._register_task(ti)
@@ -10083,11 +10197,21 @@ class TestSchedulerJob:
session.expire_all()
ti.refresh_from_db(session=session)
- assert ti.max_tries == expected_max_tries
- assert ti.state is None
- assert ti.try_number == next_try
- assert ti.id != old_id
- assert ti.external_executor_id is None
+ assert (ti.id, ti.try_number, ti.state, ti.max_tries, ti.working_set) == (
+ old_id,
+ cleared_try,
+ TaskInstanceState.FAILED,
+ retries,
+ None,
+ )
+ current = dag_run.get_task_instance("t1", session=session)
+ assert current.id != old_id
+ assert (current.try_number, current.state, current.max_tries) == (
+ next_try,
+ None,
+ expected_max_tries,
+ )
+ assert current.external_executor_id is None
assert executor_key not in executor.running
assert executor.event_buffer == {executor_key: (TaskInstanceState.FAILED, None)}
assert executor._drain_events_with_task_ids() == (
@@ -10146,16 +10270,21 @@ class TestSchedulerJob:
session.flush()
session.refresh(ti)
- assert ti.id != old_id
- assert (ti.try_number, ti.state, ti.max_tries) == (4, None, expected_max_tries)
- assert ti.external_executor_id is None
+ assert ti.id == old_id
+ assert ti.working_set is None
+ current = dr.get_task_instance("task", session=session)
+ assert current.id != old_id
+ assert (current.try_number, current.state, current.max_tries) == (4, None, expected_max_tries)
+ assert current.external_executor_id is None
assert TaskInstanceUuid(old_id) not in executor.running
assert executor.event_buffer == {TaskInstanceUuid(old_id): (State.FAILED, None)}
history = session.scalars(
- select(TaskInstanceHistory).where(TaskInstanceHistory.dag_id == ti.dag_id)
+ select(TaskInstance)
+ .where(TaskInstance.working_set.is_(None))
+ .where(TaskInstance.dag_id == ti.dag_id)
).one()
- assert (history.task_instance_id, history.try_number, history.state) == (old_id, 3, State.FAILED)
+ assert (history.id, history.try_number, history.state) == (old_id, 3, State.FAILED)
def test_heartbeat_timeout_honors_fail_fast(self, dag_maker, session):
"""
diff --git a/airflow-core/tests/unit/jobs/test_triggerer_job.py b/airflow-core/tests/unit/jobs/test_triggerer_job.py
index ff9d8806cf4..67a5fb522ad 100644
--- a/airflow-core/tests/unit/jobs/test_triggerer_job.py
+++ b/airflow-core/tests/unit/jobs/test_triggerer_job.py
@@ -74,7 +74,7 @@ from airflow.models.dagbag import DBDagBag
from airflow.models.dagbundle import DagBundleModel
from airflow.models.serialized_dag import SerializedDagModel
from airflow.models.taskinstance import TaskInstance
-from airflow.models.xcom import XComModel
+from airflow.models.xcom import XComModel, XComModelV2
from airflow.providers.standard.operators.empty import EmptyOperator
from airflow.providers.standard.operators.python import PythonOperator
from airflow.providers.standard.triggers.file import FileDeleteTrigger
@@ -2493,6 +2493,9 @@ async def test_trigger_can_call_variables_connections_and_xcoms_methods(session,
}
}
assert task_instance.next_kwargs == expected_event
+ session.expire_all()
+ assert XComModelV2.get_for_attempt(task_instance.id, "test_set_xcom", session=session).value == "set_xcom"
+ assert XComModelV2.get_for_attempt(task_instance.id, "test_delete_xcom", session=session) is None
class CustomTriggerDagRun(BaseTrigger):
diff --git a/airflow-core/tests/unit/migrations/test_0142_unify_task_attempt_ownership.py b/airflow-core/tests/unit/migrations/test_0142_unify_task_attempt_ownership.py
new file mode 100644
index 00000000000..d346d3c1d89
--- /dev/null
+++ b/airflow-core/tests/unit/migrations/test_0142_unify_task_attempt_ownership.py
@@ -0,0 +1,653 @@
+#
+# 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.
+
+from __future__ import annotations
+
+from shutil import copyfile
+from uuid import uuid4
+
+import pytest
+import sqlalchemy as sa
+from alembic import command
+from sqlalchemy.exc import IntegrityError, OperationalError
+
+from airflow import settings
+from airflow.utils.db import _get_alembic_config
+
+from tests_common.test_utils.attempt_ownership import (
+ CURRENT_ID,
+ DANGLING_VERSION,
+ HISTORY_ID,
+ NOW,
+ table,
+)
+
+pytestmark = [pytest.mark.db_test, pytest.mark.execution_timeout(60)]
+
+PREDECESSOR = "90e4d18ccadf"
+REVISION = "e7c2a91bd540"
+
+
+@pytest.fixture(scope="module")
+def predecessor_template_db(tmp_path_factory):
+ templates = {}
+
+ def clone(revision, name, target_path):
+ source = settings.engine
+ dialect = source.dialect.name
+ if dialect == "mysql":
+ return False
+ if revision not in templates:
+ template_name = f"ti141_template_{uuid4().hex}"
+ if dialect == "sqlite":
+ template_path = tmp_path_factory.mktemp("ti141_template") / f"{template_name}.db"
+ template_url = source.url.set(database=str(template_path))
+ templates[revision] = template_path
+ else:
+ template_url = source.url.set(database=template_name)
+ with source.connect().execution_options(isolation_level="AUTOCOMMIT") as admin:
+ admin.exec_driver_sql(f"CREATE DATABASE {template_name}")
+ templates[revision] = template_name
+ template_engine = sa.create_engine(template_url)
+ try:
+ with template_engine.connect() as connection:
+ config = _get_alembic_config()
+ config.attributes["connection"] = connection
+ command.upgrade(config, revision)
+ connection.commit()
+ finally:
+ template_engine.dispose()
+ if dialect == "sqlite":
+ copyfile(templates[revision], target_path)
+ else:
+ with source.connect().execution_options(isolation_level="AUTOCOMMIT") as admin:
+ admin.exec_driver_sql(f"CREATE DATABASE {name} TEMPLATE {templates[revision]}")
+ return True
+
+ yield clone
+
+ if settings.engine.dialect.name == "postgresql":
+ with settings.engine.connect().execution_options(isolation_level="AUTOCOMMIT") as admin:
+ for template_name in templates.values():
+ admin.exec_driver_sql(f"DROP DATABASE {template_name}")
+
+
+@pytest.fixture
+def predecessor(tmp_path, request, predecessor_template_db):
+ source = settings.engine
+ name = f"ti141_{uuid4().hex}"
+ revision = getattr(request, "param", PREDECESSOR)
+ if source.dialect.name == "sqlite":
+ database_path = tmp_path / "predecessor.db"
+ url = source.url.set(database=str(database_path))
+ else:
+ url = source.url.set(database=name)
+ cloned = predecessor_template_db(
+ revision, name, database_path if source.dialect.name == "sqlite" else None
+ )
+ if not cloned:
+ with source.connect().execution_options(isolation_level="AUTOCOMMIT") as admin:
+ admin.exec_driver_sql(f"CREATE DATABASE {name}")
+ engine = sa.create_engine(url)
+ try:
+ with engine.connect() as connection:
+ config = _get_alembic_config()
+ config.attributes["connection"] = connection
+ if not cloned:
+ command.upgrade(config, revision)
+ connection.commit()
+ if engine.dialect.name == "sqlite":
+ connection.exec_driver_sql("PRAGMA foreign_keys=ON")
+ connection.commit()
+
+ def enable_foreign_keys(dbapi_connection, connection_record):
+ dbapi_connection.execute("PRAGMA foreign_keys=ON")
+
+ sa.event.listen(engine, "connect", enable_foreign_keys)
+ yield connection, config
+ finally:
+ engine.dispose()
+ if source.dialect.name != "sqlite":
+ with source.connect().execution_options(isolation_level="AUTOCOMMIT") as admin:
+ admin.exec_driver_sql(f"DROP DATABASE {name}")
+
+
+@pytest.fixture
+def populated_predecessor(predecessor):
+ connection, config = predecessor
+ dag_run = table(connection, "dag_run")
+ connection.execute(
+ dag_run.insert().values(
+ id=41,
+ dag_id="ownership",
+ run_id="manual",
+ run_type="manual",
+ run_after=NOW,
+ state="running",
+ start_date=NOW,
+ )
+ )
+ coordinates = dict(dag_id="ownership", task_id="task", run_id="manual", map_index=-1)
+ live = table(connection, "task_instance", "id")
+ connection.execute(
+ live.insert().values(
+ **coordinates,
+ id=CURRENT_ID,
+ try_number=2,
+ pool="default_pool",
+ pool_slots=1,
+ state="running",
+ max_tries=3,
+ )
+ )
+ history = table(connection, "task_instance_history", "task_instance_id", "dag_version_id")
+ connection.execute(
+ history.insert().values(
+ **coordinates,
+ task_instance_id=HISTORY_ID,
+ try_number=1,
+ pool="default_pool",
+ pool_slots=1,
+ state="failed",
+ max_tries=None,
+ trigger_id=987654,
+ dag_version_id=DANGLING_VERSION,
+ hostname=None,
+ duration=12.5,
+ )
+ )
+ connection.execute(
+ table(connection, "xcom")
+ .insert()
+ .values(
+ **coordinates,
+ dag_run_id=41,
+ key="return_value",
+ value={"legacy": True},
+ timestamp=NOW,
+ mapped_length=3,
+ )
+ )
+ connection.execute(
+ table(connection, "rendered_task_instance_fields")
+ .insert()
+ .values(
+ **coordinates,
+ rendered_fields={"field": "legacy"},
+ k8s_pod_yaml={"kind": "Pod"},
+ )
+ )
+ connection.execute(
+ table(connection, "task_instance_note", "ti_id")
+ .insert()
+ .values(
+ ti_id=CURRENT_ID,
+ content="keep this note",
+ created_at=NOW,
+ updated_at=NOW,
+ )
+ )
+ connection.execute(
+ table(connection, "task_reschedule", "ti_id")
+ .insert()
+ .values(
+ ti_id=CURRENT_ID,
+ start_date=NOW,
+ end_date=NOW,
+ duration=0,
+ reschedule_date=NOW,
+ )
+ )
+ connection.execute(
+ table(connection, "hitl_detail_history", "ti_history_id")
+ .insert()
+ .values(
+ ti_history_id=HISTORY_ID,
+ options=["yes", "no"],
+ subject="approval",
+ params={},
+ params_input={"answer": 1},
+ created_at=NOW,
+ )
+ )
+ connection.commit()
+ return connection, config
+
+
+def test_upgrade_emits_mysql_sql_offline_without_live_schema_reads(capsys, monkeypatch):
+ monkeypatch.setattr(settings, "SQL_ALCHEMY_CONN", "mysql://")
+
+ command.upgrade(_get_alembic_config(), f"{PREDECESSOR}:{REVISION}", sql=True)
+
+ emitted = capsys.readouterr().out
+ assert "CREATE TABLE legacy_task_data_owner" in emitted
+ assert "INSERT INTO task_instance" in emitted
+ assert "CREATE TABLE xcom_v2" in emitted
+ assert emitted.count("ALGORITHM=INPLACE, LOCK=NONE") == 4
+ assert emitted.count("DROP FOREIGN KEY") >= 2
+ assert emitted.count("ADD CONSTRAINT") >= 2
+ assert emitted.count("SET SESSION foreign_key_checks = 0") == 2
+ assert emitted.count("SET SESSION foreign_key_checks = @ti141_foreign_key_checks") == 2
+ assert "ALGORITHM=COPY" not in emitted
+
+
+def test_offline_sql_refuses_what_it_cannot_verify_or_render(monkeypatch):
+ monkeypatch.setattr(settings, "SQL_ALCHEMY_CONN", "postgresql://")
+ with pytest.raises(RuntimeError, match="Offline downgrade cannot verify retained attempt ownership"):
+ command.downgrade(_get_alembic_config(), f"{REVISION}:{PREDECESSOR}", sql=True)
+
+ monkeypatch.setattr(settings, "SQL_ALCHEMY_CONN", "sqlite://")
+ with pytest.raises(
+ RuntimeError, match="SQLite offline SQL cannot render this migration's table rebuilds"
+ ):
+ command.upgrade(_get_alembic_config(), f"{PREDECESSOR}:{REVISION}", sql=True)
+
+
+def test_upgrade_retains_history_and_legacy_owner(populated_predecessor):
+ connection, config = populated_predecessor
+ foreign_key_checks = (
+ connection.scalar(sa.text("SELECT @@SESSION.foreign_key_checks"))
+ if connection.dialect.name == "mysql"
+ else None
+ )
+ source_history = (
+ connection.execute(sa.select(table(connection, "task_instance_history"))).mappings().one()
+ )
+ valid_version = uuid4()
+ versioned_history_id = uuid4()
+ connection.execute(table(connection, "dag_bundle").insert().values(name="test_bundle"))
+ connection.execute(
+ table(connection, "dag")
+ .insert()
+ .values(
+ dag_id="ownership",
+ bundle_name="test_bundle",
+ is_paused=False,
+ is_stale=False,
+ max_active_tasks=16,
+ max_consecutive_failed_dag_runs=0,
+ has_task_concurrency_limits=False,
+ timetable_type="",
+ partition_mapper_info=[],
+ )
+ )
+ connection.execute(
+ table(connection, "dag_version", "id")
+ .insert()
+ .values(
+ id=valid_version,
+ dag_id="ownership",
+ version_number=1,
+ created_at=NOW,
+ last_updated=NOW,
+ )
+ )
+ connection.execute(
+ table(connection, "task_instance_history", "task_instance_id", "dag_version_id")
+ .insert()
+ .values(
+ dag_id="ownership",
+ task_id="task",
+ run_id="manual",
+ map_index=-1,
+ task_instance_id=versioned_history_id,
+ try_number=3,
+ pool="default_pool",
+ pool_slots=1,
+ state="failed",
+ max_tries=1,
+ dag_version_id=valid_version,
+ )
+ )
+ connection.commit()
+ command.upgrade(config, REVISION)
+ ti = table(connection, "task_instance", "id", "dag_version_id")
+ rows = {row.id: row for row in connection.execute(sa.select(ti))}
+ assert set(rows) == {CURRENT_ID, HISTORY_ID, versioned_history_id}
+ assert rows[versioned_history_id].dag_version_id == valid_version
+ assert rows[CURRENT_ID].working_set is True
+ old = rows[HISTORY_ID]
+ assert old.working_set is None
+ assert old.max_tries == 0
+ assert old.duration == 12.5
+ assert old.trigger_id is None
+ assert old.dag_version_id is None
+ for name, value in source_history.items():
+ if name not in {"task_instance_id", "trigger_id", "dag_version_id", "max_tries"}:
+ assert old._mapping[name] == value
+ owner = table(connection, "legacy_task_data_owner", "task_instance_id")
+ assert connection.scalar(sa.select(owner.c.task_instance_id)) == CURRENT_ID
+ hitl = table(connection, "hitl_detail", "ti_id")
+ assert connection.scalar(sa.select(hitl.c.ti_id)) == HISTORY_ID
+ for name in ("xcom_v1", "rtif_v1", "task_instance_note", "task_reschedule"):
+ assert connection.scalar(sa.select(sa.func.count()).select_from(table(connection, name))) == 1
+ assert "task_instance_history" not in sa.inspect(connection).get_table_names()
+ assert "hitl_detail_history" not in sa.inspect(connection).get_table_names()
+ if foreign_key_checks is not None:
+ assert connection.scalar(sa.text("SELECT @@SESSION.foreign_key_checks")) == foreign_key_checks
+ inspector = sa.inspect(connection)
+ for name, constraint in (
+ ("xcom_v1", "xcom_task_instance_fkey"),
+ ("rtif_v1", "rtif_ti_fkey"),
+ ):
+ foreign_key = next(fk for fk in inspector.get_foreign_keys(name) if fk["name"] == constraint)
+ assert foreign_key["referred_table"] == "legacy_task_data_owner"
+
+
+def test_upgrade_discards_only_history_conflicting_with_live_try(populated_predecessor):
+ connection, config = populated_predecessor
+ conflicting_id = uuid4()
+ connection.execute(
+ table(connection, "task_instance_history", "task_instance_id")
+ .insert()
+ .values(
+ dag_id="ownership",
+ task_id="task",
+ run_id="manual",
+ map_index=-1,
+ task_instance_id=conflicting_id,
+ try_number=2,
+ pool="default_pool",
+ pool_slots=1,
+ state="success",
+ max_tries=7,
+ )
+ )
+ connection.execute(
+ table(connection, "hitl_detail_history", "ti_history_id")
+ .insert()
+ .values(
+ ti_history_id=conflicting_id,
+ options=["yes"],
+ subject="conflicting review",
+ params={},
+ params_input={},
+ created_at=NOW,
+ )
+ )
+ connection.commit()
+
+ command.upgrade(config, REVISION)
... 4897 lines suppressed ...