This is an automated email from the ASF dual-hosted git repository.

vincbeck pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new c582d67846a Reset orphaned task instances in bulk to shorten scheduler 
stalls (#77550)
c582d67846a is described below

commit c582d67846a1db04a2c14ec635dab7942ef9385d
Author: Vincent <[email protected]>
AuthorDate: Fri Nov 27 09:34:54 2026 -0500

    Reset orphaned task instances in bulk to shorten scheduler stalls (#77550)
    
    When a scheduler dies, another one marks its job failed and adopts or
    resets the task instances it had queued or started, in one transaction.
    The other schedulers run the same check in their loops and wait on the
    failed job's row until that transaction commits.
    
    The transaction sent several statements per orphaned task instance: the
    orphan query deferred most columns, so routing, executor adoption code
    and the adoption bookkeeping lazy-loaded them one by one, every reset
    copied its attempt through prepare_db_for_next_try on its own, and every
    adopted task instance was updated on its own. With thousands of orphans
    it lasted minutes, during which the other schedulers scheduled nothing.
---
 .../src/airflow/jobs/scheduler_job_runner.py       |  88 ++++++---
 airflow-core/src/airflow/models/taskinstance.py    | 197 ++++++++++++++++++--
 airflow-core/tests/unit/jobs/test_scheduler_job.py | 115 +++++++++++-
 .../tests/unit/models/test_taskinstance.py         | 201 ++++++++++++++++++++-
 4 files changed, 550 insertions(+), 51 deletions(-)

diff --git a/airflow-core/src/airflow/jobs/scheduler_job_runner.py 
b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
index 0bcc0a233f6..f904316deaf 100644
--- a/airflow-core/src/airflow/jobs/scheduler_job_runner.py
+++ b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
@@ -53,7 +53,8 @@ from sqlalchemy import (
     update,
 )
 from sqlalchemy.exc import DBAPIError, OperationalError
-from sqlalchemy.orm import joinedload, lazyload, load_only, make_transient, 
selectinload
+from sqlalchemy.orm import contains_eager, defer, joinedload, load_only, 
make_transient, selectinload
+from sqlalchemy.orm.attributes import set_committed_value
 from sqlalchemy.sql import expression
 
 from airflow import settings
@@ -189,6 +190,10 @@ MAX_PARTITION_DAG_RUNS_PER_LOOP = 500
 # Max number of ADRQ rows deleted per statement, to keep the bind parameter 
count bounded.
 _ADRQ_DELETE_CHUNK_SIZE = 500
 
+# Max number of adopted task instances updated per statement: the same batches 
as the bulk reset of the
+# others (TaskInstance._reset_orphaned_attempts), each task instance binding 
one parameter in the IN list.
+_ADOPTED_TI_UPDATE_CHUNK_SIZE = 250
+
 # Caps how many dag_ids the cap log lists and how many per-Dag audit rows
 # are written per callback run. The backlog's distinct dag_id count is 
unbounded, so
 # writing it straight into a log field or one DB row per Dag without a cap 
risks
@@ -4490,27 +4495,24 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
                         .values(state=JobState.FAILED, 
end_date=timezone.utcnow())
                     )
 
+                    # Every column but executor_config, next_method and 
next_kwargs, and the Dag runs from
+                    # the join: executors' adoption code and the code below 
read various columns, and each
+                    # one left to a lazy load would cost a query per task 
instance while the jobs are locked.
                     query = (
                         select(TI)
-                        .options(lazyload(TI.dag_run))  # avoids double join 
to dag_run
                         .where(TI.state.in_(State.adoptable_states))
                         .join(TI.queued_by_job)
                         .where(Job.state.is_distinct_from(JobState.RUNNING))
                         .join(TI.dag_run)
                         .where(DagRun.state == DagRunState.RUNNING)
                         .options(
-                            load_only(
-                                TI.id,
-                                TI.dag_id,
-                                TI.task_id,
-                                TI.run_id,
-                                TI.region_id,
-                                TI.region_index,
-                                TI.dag_version_id,
-                                TI.try_number,
-                                TI.state,
-                                TI.external_executor_id,
-                            )
+                            # Deferred: only the reset and some executors' 
adoption code read it.
+                            defer(TI.executor_config),
+                            # Deferred: trigger payloads can be large, and the 
successor of a reset clears them.
+                            defer(TI.next_method),
+                            defer(TI.next_kwargs),
+                            # Its JSON columns would be repeated for each of 
the run's task instances.
+                            
contains_eager(TI.dag_run).defer(DagRun.conf).defer(DagRun.context_carrier),
                         )
                     )
 
@@ -4527,24 +4529,18 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
                     for executor, tis in exec_to_tis.items():
                         to_reset.extend(executor.try_adopt_task_instances(tis))
 
-                    reset_tis_message = []
-                    for ti in to_reset:
-                        reset_tis_message.append(repr(ti))
-                        successor = ti.prepare_db_for_next_try(session=session)
-                        successor.state = 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
-                        # If old ti from Airflow 2 and last_heartbeat_at is 
None, set last_heartbeat_at to now
-                        if ti.last_heartbeat_at is None:
-                            ti.last_heartbeat_at = timezone.utcnow()
-                        # If old ti from Airflow 2 and dag_run.conf is None, 
set dag_run.conf to {}
-                        if ti.dag_run.conf is None:
-                            ti.dag_run.conf = {}
+                    reset_tis_message = [repr(ti) for ti in to_reset]
+                    declined = set(to_reset)
+                    adopted = [ti for ti in tis_to_adopt_or_reset if ti not in 
declined]
+                    # The row locks taken above must last until the commit, or 
another scheduler could
+                    # adopt or reset these task instances too, so the reset is 
not split into several
+                    # transactions. Other schedulers wait on the jobs marked 
failed above until then,
+                    # hence a bulk reset: a dead scheduler can leave thousands 
of task instances.
+                    TI._reset_orphaned_attempts(to_reset, session=session)
+                    self._record_adoption(adopted, session=session)
 
                     stats.incr("scheduler.orphaned_tasks.cleared", 
len(to_reset))
-                    stats.incr("scheduler.orphaned_tasks.adopted", 
len(tis_to_adopt_or_reset) - len(to_reset))
+                    stats.incr("scheduler.orphaned_tasks.adopted", 
len(adopted))
                     if to_reset:
                         task_instance_str = "\n\t".join(reset_tis_message)
                         self.log.info(
@@ -4562,6 +4558,38 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
 
         return len(to_reset)
 
+    def _record_adoption(self, tis: Sequence[TI], *, session: Session) -> None:
+        """Make this scheduler's job the owner of adopted task instances, with 
one UPDATE per batch."""
+        now = timezone.utcnow()
+        for batch in chunks(list(tis), _ADOPTED_TI_UPDATE_CHUNK_SIZE):
+            # Task instances that never sent a heartbeat (queued ones, or ones 
from Airflow 2) get one now.
+            session.execute(
+                update(TI)
+                .where(TI.id.in_([ti.id for ti in batch]))
+                .values(
+                    queued_by_job_id=self.job.id,
+                    last_heartbeat_at=func.coalesce(
+                        TI.last_heartbeat_at, literal(now, 
TI.last_heartbeat_at.type)
+                    ),
+                    updated_at=now,
+                )
+                .execution_options(synchronize_session=False)
+            )
+            # The objects hold the values written, as after a flush.
+            for ti in batch:
+                set_committed_value(ti, "queued_by_job_id", self.job.id)
+                set_committed_value(ti, "updated_at", now)
+                if ti.last_heartbeat_at is None:
+                    set_committed_value(ti, "last_heartbeat_at", now)
+            # Dag runs from Airflow 2 may have no conf: they get an empty one.
+            runs = {ti.dag_run.id: ti.dag_run for ti in batch}
+            for run_id, run_conf in session.execute(
+                select(DagRun.id, DagRun.conf).where(DagRun.id.in_(list(runs)))
+            ):
+                set_committed_value(runs[run_id], "conf", run_conf)
+                if run_conf is None:
+                    runs[run_id].conf = {}
+
     @provide_session
     def check_trigger_timeouts(
         self, max_retries: int = MAX_DB_RETRIES, *, session: Session = 
NEW_SESSION
diff --git a/airflow-core/src/airflow/models/taskinstance.py 
b/airflow-core/src/airflow/models/taskinstance.py
index b51a9b5a067..cf244be5c36 100644
--- a/airflow-core/src/airflow/models/taskinstance.py
+++ b/airflow-core/src/airflow/models/taskinstance.py
@@ -168,6 +168,9 @@ _PER_ATTEMPT_COLUMNS = (
     "queued_by_job_id",
     "last_heartbeat_at",
 )
+# Task instances per batch of ``_reset_orphaned_attempts``: its archive UPDATE 
binds up to 3 parameters
+# per task instance, and SQLite before 3.32 allows 999 per statement.
+_RESET_BATCH_SIZE = 250
 tracer = trace.get_tracer(__name__)
 
 if TYPE_CHECKING:
@@ -1099,6 +1102,49 @@ def uuid7() -> UUID:
     return uuid6.uuid7()
 
 
+def _get_successor_overrides(
+    *, try_number: int, state: TaskInstanceState | str | None, retry_at: 
datetime | None
+) -> dict[str, Any]:
+    """Return the columns of a successor attempt that are not copied from the 
attempt it succeeds."""
+    return {
+        **dict.fromkeys(_PER_ATTEMPT_COLUMNS),
+        "id": uuid7(),
+        "try_number": try_number + 1,
+        "working_set": True,
+        "archived_reason": None,
+        "trigger_id": None,
+        "external_executor_id": None,
+        "state": state,
+        "retry_at": retry_at,
+    }
+
+
+def _get_archived_changes(
+    *,
+    reason: str,
+    state: TaskInstanceState | str | None,
+    start_date: datetime | None,
+    end_date: datetime | None,
+    now: datetime,
+) -> dict[str, Any]:
+    """Return the columns ``archive()`` changes on an attempt, besides taking 
it out of the working set."""
+    never_started = reason == "superseded" and state in (
+        None,
+        TaskInstanceState.SCHEDULED,
+        TaskInstanceState.QUEUED,
+        TaskInstanceState.UP_FOR_RETRY,
+    )
+    if state in State.finished or never_started:
+        return {}
+    if end_date is not None:
+        return {"state": TaskInstanceState.FAILED}
+    return {
+        "state": TaskInstanceState.FAILED,
+        "end_date": now,
+        "duration": (now - start_date).total_seconds() if start_date else None,
+    }
+
+
 class LegacyTaskDataOwner(Base):
     """Map the dag, task, run and map index of pre-3.4 XCom and rendered 
fields rows to their attempt UUID."""
 
@@ -1740,17 +1786,15 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
         for name in ("state", "start_date", "end_date"):
             if not state.attrs[name].history.has_changes():
                 setattr(self, name, getattr(current, name))
-        never_started = reason == "superseded" and self.state in (
-            None,
-            TaskInstanceState.SCHEDULED,
-            TaskInstanceState.QUEUED,
-            TaskInstanceState.UP_FOR_RETRY,
+        changes = _get_archived_changes(
+            reason=reason,
+            state=self.state,
+            start_date=self.start_date,
+            end_date=self.end_date,
+            now=timezone.utcnow(),
         )
-        if self.state not in State.finished and not never_started:
-            self.state = TaskInstanceState.FAILED
-            if self.end_date is None:
-                self.end_date = timezone.utcnow()
-                self.set_duration()
+        for name, value in changes.items():
+            setattr(self, name, value)
         self.working_set = None
         self.archived_reason = reason
         self.trigger_id = None
@@ -1815,6 +1859,7 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
 
     def prepare_db_for_next_try(self, session: Session) -> TaskInstance:
         """Archive this UUID and return its successor in the caller's 
transaction."""
+        # _reset_orphaned_attempts writes the same rows in bulk; change both.
         successor_state = self.state
         dag_version_id = self.dag_version_id
         retry_at = None
@@ -1832,16 +1877,8 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
             for attribute in inspect(TaskInstance).column_attrs
         }
         values.update(
-            {name: None for name in _PER_ATTEMPT_COLUMNS},
-            id=uuid7(),
-            try_number=self.try_number + 1,
-            working_set=True,
-            archived_reason=None,
-            trigger_id=None,
-            external_executor_id=None,
+            _get_successor_overrides(try_number=self.try_number, 
state=successor_state, retry_at=retry_at),
             dag_version_id=dag_version_id,
-            state=successor_state,
-            retry_at=retry_at,
         )
         session.execute(insert(TaskInstance.__table__).values(values))
         successor = session.scalars(select(TaskInstance).where(TaskInstance.id 
== values["id"])).one()
@@ -1854,6 +1891,128 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
             successor.task_instance_note = carried
         return successor
 
+    @classmethod
+    def _reset_orphaned_attempts(cls, tis: Sequence[TaskInstance], *, session: 
Session) -> None:
+        """
+        Reset the attempts a dead scheduler left, in bulk.
+
+        Equivalent to ``prepare_db_for_next_try`` on each task instance, 
followed by clearing the
+        successor's ``state``, ``next_method`` and ``next_kwargs``, in a few 
statements per batch of
+        ``_RESET_BATCH_SIZE`` task instances.
+
+        Only meant for ``SchedulerJobRunner.adopt_or_reset_orphaned_tasks``: 
``tis`` are current attempts
+        attached to ``session``, loaded with every column but 
``executor_config``, ``next_method`` and
+        ``next_kwargs``. Like ``archive()``,
+        each batch is locked and its archived outcome decided from what the 
rows hold then, and an
+        attempt that is no longer current raises ``ValueError``. Attempts 
whose state is ``up_for_retry``
+        go through ``prepare_db_for_next_try`` itself, which computes the 
successor's retry deadline.
+        Afterwards the objects hold their archived row, as after ``archive()``.
+        """
+        table = cls.__table__
+        note_table = TaskInstanceNote.__table__
+        # Not loaded by the orphan query: read for the batch below, or cleared 
on the successor.
+        not_loaded = {"executor_config", "next_method", "next_kwargs"}
+        copied_attributes = [attr for attr in inspect(cls).column_attrs if 
attr.key not in not_loaded]
+        archived_values = {"working_set": None, "archived_reason": "retry", 
"trigger_id": None}
+        for batch in chunks(list(tis), _RESET_BATCH_SIZE):
+            # Write what was changed in memory first, so the locked rows below 
hold it.
+            session.flush()
+            in_bulk = []
+            for ti in batch:
+                if ti.state == TaskInstanceState.UP_FOR_RETRY:
+                    successor = ti.prepare_db_for_next_try(session)
+                    successor.state = None
+                    successor.clear_next_method_args()
+                else:
+                    in_bulk.append(ti)
+            if not in_bulk:
+                continue
+            current = {
+                row.id: row
+                for row in session.execute(
+                    select(
+                        table.c.id,
+                        table.c.working_set,
+                        table.c.state,
+                        table.c.start_date,
+                        table.c.end_date,
+                        table.c.executor_config,
+                    )
+                    .where(table.c.id.in_([ti.id for ti in in_bulk]))
+                    .with_for_update()
+                )
+            }
+            if any(ti.id not in current or current[ti.id].working_set is not 
True for ti in in_bulk):
+                raise ValueError("An archived task instance cannot be archived 
again")
+            now = timezone.utcnow()
+            changes = {
+                ti.id: _get_archived_changes(
+                    reason="retry",
+                    state=current[ti.id].state,
+                    start_date=current[ti.id].start_date,
+                    end_date=current[ti.id].end_date,
+                    now=now,
+                )
+                for ti in in_bulk
+            }
+            # One UPDATE per kind of change: within one, only the duration 
differs between rows.
+            by_columns: defaultdict[tuple[str, ...], list[TaskInstance]] = 
defaultdict(list)
+            for ti in in_bulk:
+                by_columns[tuple(changes[ti.id])].append(ti)
+            for columns, group in by_columns.items():
+                values: dict[str, Any] = {name: changes[group[0].id][name] for 
name in columns}
+                if "duration" in columns:
+                    values["duration"] = case(
+                        *((table.c.id == ti.id, changes[ti.id]["duration"]) 
for ti in group),
+                        else_=table.c.duration,
+                    )
+                session.execute(
+                    update(table)
+                    .where(table.c.id.in_([ti.id for ti in group]))
+                    .values(**archived_values, updated_at=now, **values)
+                )
+            successors = [
+                {
+                    **{attr.columns[0].name: getattr(ti, attr.key) for attr in 
copied_attributes},
+                    "executor_config": current[ti.id].executor_config,
+                    **_get_successor_overrides(try_number=ti.try_number, 
state=None, retry_at=None),
+                    "next_method": None,
+                    "next_kwargs": None,
+                    "updated_at": now,
+                }
+                for ti in in_bulk
+            ]
+            # After the archive: only one attempt of a task instance may be in 
the working set.
+            session.execute(insert(table), successors)
+            successor_id_by_archived_id = {
+                ti.id: successor["id"] for ti, successor in zip(in_bulk, 
successors)
+            }
+            if notes := (
+                session.execute(
+                    
select(note_table).where(note_table.c.ti_id.in_(list(successor_id_by_archived_id)))
+                )
+                .mappings()
+                .all()
+            ):
+                session.execute(
+                    insert(note_table),
+                    [{**note, "ti_id": 
successor_id_by_archived_id[note["ti_id"]]} for note in notes],
+                )
+            # The objects hold the archived rows, as after archive().
+            for ti in in_bulk:
+                row = current[ti.id]
+                for key, value in {
+                    "state": row.state,
+                    "start_date": row.start_date,
+                    "end_date": row.end_date,
+                    **changes[ti.id],
+                    **archived_values,
+                    "updated_at": now,
+                }.items():
+                    set_committed_value(ti, key, value)
+        # The successors of attempts reset through prepare_db_for_next_try.
+        session.flush()
+
     def complete_restart(
         self, *, session: Session, terminal_outcome: TaskInstanceState | None 
= None
     ) -> TaskInstance:
diff --git a/airflow-core/tests/unit/jobs/test_scheduler_job.py 
b/airflow-core/tests/unit/jobs/test_scheduler_job.py
index eee92510985..f2e0ca33a71 100644
--- a/airflow-core/tests/unit/jobs/test_scheduler_job.py
+++ b/airflow-core/tests/unit/jobs/test_scheduler_job.py
@@ -72,7 +72,7 @@ from airflow.executors.executor_utils import ExecutorName
 from airflow.executors.local_executor import LocalExecutor
 from airflow.executors.workloads import ExecuteTask, WorkloadType
 from airflow.executors.workloads.types import TaskInstanceUuid
-from airflow.jobs.job import EXECUTOR_JOB_TYPE, Job, run_job
+from airflow.jobs.job import EXECUTOR_JOB_TYPE, Job, JobState, run_job
 from airflow.jobs.scheduler_job_runner import (
     MAX_TI_REFILL_QUERIES_PER_LOOP,
     TASK_STUCK_IN_QUEUED_RESCHEDULE_EVENT,
@@ -5640,6 +5640,119 @@ class TestSchedulerJob:
         session.refresh(dr)
         assert dr.conf == {}
 
+    @pytest.mark.parametrize("adopt", [False, True], ids=["reset", "adopt"])
+    def 
test_adopt_or_reset_orphaned_tasks_queries_do_not_grow_with_orphans(self, 
dag_maker, session, adopt):
+        class AdoptingExecutor(MockExecutor):
+            def try_adopt_task_instances(self, tis):
+                # Columns that adoption code of remote executors reads, 
besides the routing and the
+                # adoption bookkeeping of the scheduler.
+                self.adopted = tis
+                self.read = [(ti.queue, ti.queued_by_job_id) for ti in tis]
+                return []
+
+        query_counts = []
+        for num_runs, num_tasks in ((1, 1), (5, 3)):
+            with dag_maker(f"test_orphans_{adopt}_{num_runs}", 
session=session):
+                for i in range(num_tasks):
+                    EmptyOperator(task_id=f"task_{i}")
+            old_job = Job()
+            session.add(old_job)
+            session.flush()
+            dag_run = dag_maker.create_dagrun(run_type=DagRunType.MANUAL)
+            dag_runs = [dag_run]
+            for _ in range(num_runs - 1):
+                dag_run = dag_maker.create_dagrun_after(dag_run, 
run_type=DagRunType.MANUAL)
+                dag_runs.append(dag_run)
+            orphans = [ti for dag_run in dag_runs for ti in 
dag_run.get_task_instances(session=session)]
+            for ti in orphans:
+                ti.state = State.RUNNING
+                ti.queued_by_job_id = old_job.id
+            session.commit()
+            # Load the orphans the way the scheduler does, not from the 
identity map.
+            session.expunge_all()
+            # Running, so the next iteration does not treat the task instances 
it adopted as orphans.
+            new_job = Job(state=JobState.RUNNING)
+            session.add(new_job)
+            session.flush()
+            executor = AdoptingExecutor() if adopt else MockExecutor()
+            self.job_runner = SchedulerJobRunner(job=new_job, 
executors=[executor])
+
+            # Counted on the engine, so statements flushed by the session 
count too.
+            with count_queries() as result:
+                num_reset = 
self.job_runner.adopt_or_reset_orphaned_tasks(session=session)
+            if adopt:
+                # Left to the executors that read them, as before.
+                assert all(
+                    {"executor_config", "next_method", "next_kwargs"} <= 
inspect(ti).unloaded
+                    for ti in executor.adopted
+                )
+            session.commit()
+
+            query_counts.append(sum(result.values()))
+            current = [ti for dag_run in dag_runs for ti in 
dag_run.get_task_instances(session=session)]
+            assert len(current) == num_runs * num_tasks
+            if adopt:
+                assert num_reset == 0
+                assert {(ti.state, ti.queued_by_job_id) for ti in current} == 
{(State.RUNNING, new_job.id)}
+            else:
+                assert num_reset == num_runs * num_tasks
+                assert {(ti.state, ti.try_number) for ti in current} == 
{(None, 1)}
+
+        assert query_counts[0] == query_counts[1]
+
+    @time_machine.travel("2026-11-16 12:00:00+00:00", tick=False)
+    
@mock.patch("airflow.jobs.scheduler_job_runner._ADOPTED_TI_UPDATE_CHUNK_SIZE", 
2)
+    def test_adopt_or_reset_orphaned_tasks_records_adoption_per_batch(self, 
dag_maker, session):
+        with 
dag_maker("test_adopt_or_reset_orphaned_tasks_records_adoption_per_batch", 
session=session):
+            for i in range(5):
+                EmptyOperator(task_id=f"task_{i}")
+        old_job = Job()
+        session.add(old_job)
+        session.flush()
+        dag_run = dag_maker.create_dagrun(run_type=DagRunType.MANUAL)
+        heartbeat = timezone.utcnow() - datetime.timedelta(minutes=1)
+        for ti in dag_run.get_task_instances(session=session):
+            ti.state = State.RUNNING
+            ti.queued_by_job_id = old_job.id
+            # Two task instances without a heartbeat, as queued ones or ones 
from Airflow 2.
+            ti.last_heartbeat_at = None if ti.task_id in ("task_0", "task_1") 
else heartbeat
+        session.commit()
+        new_job = Job(state=JobState.RUNNING)
+        session.add(new_job)
+        session.flush()
+
+        class AdoptingExecutor(MockExecutor):
+            def try_adopt_task_instances(self, tis):
+                return []
+
+        self.job_runner = SchedulerJobRunner(job=new_job, 
executors=[AdoptingExecutor()])
+        updates = []
+
+        def capture_task_instance_updates(conn, cursor, statement, parameters, 
context, executemany):
+            if statement.startswith("UPDATE task_instance"):
+                updates.append(executemany)
+
+        engine = session.get_bind()
+        sa_event.listen(engine, "before_cursor_execute", 
capture_task_instance_updates)
+        try:
+            assert 
self.job_runner.adopt_or_reset_orphaned_tasks(session=session) == 0
+        finally:
+            sa_event.remove(engine, "before_cursor_execute", 
capture_task_instance_updates)
+
+        # One statement for each batch of 2, none per row.
+        assert updates == [False, False, False]
+        now = timezone.utcnow()
+        expected = {f"task_{i}": (new_job.id, now if i < 2 else heartbeat, 
now) for i in range(5)}
+
+        def get_adoption(tis):
+            return {ti.task_id: (ti.queued_by_job_id, ti.last_heartbeat_at, 
ti.updated_at) for ti in tis}
+
+        adopted = dag_run.get_task_instances(session=session)
+        assert get_adoption(adopted) == expected
+        assert not any(session.is_modified(ti) for ti in adopted)
+        session.expire_all()
+        assert get_adoption(dag_run.get_task_instances(session=session)) == 
expected
+
     def test_purge_without_heartbeat_skips_when_missing_dag_version(self, 
dag_maker, session, caplog):
         with 
dag_maker("test_purge_without_heartbeat_skips_when_missing_dag_version", 
session=session):
             EmptyOperator(task_id="task")
diff --git a/airflow-core/tests/unit/models/test_taskinstance.py 
b/airflow-core/tests/unit/models/test_taskinstance.py
index ddf6f570829..dfae56016df 100644
--- a/airflow-core/tests/unit/models/test_taskinstance.py
+++ b/airflow-core/tests/unit/models/test_taskinstance.py
@@ -78,6 +78,7 @@ from airflow.models.taskinstance import (
     find_relevant_relatives,
 )
 from airflow.models.taskreschedule import TaskReschedule
+from airflow.models.trigger import Trigger
 from airflow.models.variable import Variable
 from airflow.models.xcom import LazyXComSelectSequence, XComModel, 
XComModelV2, build_xcom_read_query
 from airflow.providers.standard.operators.bash import BashOperator
@@ -127,7 +128,7 @@ from airflow.utils.state import DagRunState, State, 
TaskInstanceState
 from airflow.utils.types import DagRunTriggeredByType, DagRunType
 
 from tests_common.test_utils import db
-from tests_common.test_utils.asserts import assert_queries_count, 
capture_orm_selects
+from tests_common.test_utils.asserts import assert_queries_count, 
capture_orm_selects, count_queries
 from tests_common.test_utils.attempt_ownership import (
     COORDINATES,
     CURRENT_ID,
@@ -923,6 +924,204 @@ class TestTaskInstance:
 
         assert successor.next_retry_datetime() == failed_at + 
datetime.timedelta(seconds=30)
 
+    @time_machine.travel("2026-11-16 12:00:00+00:00", tick=False)
+    @pytest.mark.parametrize(
+        ("state", "started", "ended"),
+        [
+            pytest.param(TaskInstanceState.RUNNING, True, False, id="running"),
+            pytest.param(TaskInstanceState.QUEUED, False, False, 
id="never-started"),
+            pytest.param(TaskInstanceState.RESTARTING, True, True, id="ended"),
+        ],
+    )
+    @pytest.mark.parametrize(
+        "change",
+        [
+            # Unchanged, only the reset itself stamps the rows.
+            pytest.param(None, id="unchanged"),
+            # Changed in memory and not flushed, as an executor may before 
declining to adopt.
+            pytest.param({"queue": "elsewhere", "hostname": "other-worker"}, 
id="columns-in-memory"),
+            pytest.param({"state": TaskInstanceState.SUCCESS}, 
id="success-in-memory"),
+            pytest.param({"state": None}, id="no-state-in-memory"),
+            pytest.param({"state": TaskInstanceState.UP_FOR_RETRY}, 
id="retry-in-memory"),
+            # Written behind the session after the task instance was loaded.
+            pytest.param("written-behind", id="success-written-behind"),
+        ],
+    )
+    @pytest.mark.parametrize("mapped", [False, True], ids=["unmapped", 
"mapped"])
+    def 
test_reset_orphaned_attempts_writes_the_rows_of_prepare_db_for_next_try(
+        self, dag_maker, session, state, started, ended, change, mapped
+    ):
+        with dag_maker("test_reset_orphaned_attempts", session=session):
+            if mapped:
+                
BashOperator.partial(task_id="mapped").expand(bash_command=["echo 0", "echo 1"])
+            else:
+                EmptyOperator(task_id="in_bulk")
+                EmptyOperator(task_id="one_by_one")
+        dag_run = dag_maker.create_dagrun(session=session)
+        trigger = Trigger(classpath="airflow.triggers.testing.SuccessTrigger", 
kwargs={})
+        session.add(trigger)
+        session.flush()
+        now = timezone.utcnow()
+        tis = dict(
+            zip(
+                ("in_bulk", "one_by_one"),
+                sorted(
+                    dag_run.get_task_instances(session=session), key=lambda 
ti: (ti.task_id, ti.map_index)
+                ),
+            )
+        )
+        assert [ti.map_index for ti in tis.values()] == ([0, 1] if mapped else 
[-1, -1])
+        for ti in tis.values():
+            ti.state = state
+            ti.start_date = now - datetime.timedelta(seconds=30) if started 
else None
+            ti.end_date = now - datetime.timedelta(seconds=10) if ended else 
None
+            ti.duration = 20.0 if ended else None
+            ti.hostname, ti.unixname, ti.pid = "worker", "airflow", 1234
+            ti.queued_dttm = ti.scheduled_dttm = ti.last_heartbeat_at = now - 
datetime.timedelta(minutes=1)
+            ti.queued_by_job_id = 7
+            ti.external_executor_id = "worker-id"
+            ti.trigger_id = trigger.id
+            ti.trigger_timeout = now + datetime.timedelta(hours=1)
+            ti.next_method = "resume"
+            ti.next_kwargs = {"event": 1}
+            ti.executor = "a_custom_executor"
+            ti.executor_config = {"key": "value"}
+            ti.max_tries = 3
+            ti.retry_reason = "flaky"
+            ti.retry_delay_override = 5.0
+            ti.note = "needs a look"
+            # Older than the reset, so the test sees both paths stamp the rows 
they write.
+            ti.updated_at = now - datetime.timedelta(hours=1)
+        session.flush()
+        table = TaskInstance.__table__
+        note_table = TaskInstanceNote.__table__
+
+        def get_row(table, column, value):
+            return session.execute(select(table).where(column == 
value)).mappings().one()
+
+        before = {key: get_row(table, table.c.id, ti.id) for key, ti in 
tis.items()}
+        notes_before = {key: get_row(note_table, note_table.c.ti_id, ti.id) 
for key, ti in tis.items()}
+
+        def change_before_reset(ti):
+            if change == "written-behind":
+                session.execute(
+                    update(TaskInstance)
+                    .where(TaskInstance.id == ti.id)
+                    .values(state=TaskInstanceState.SUCCESS, end_date=now - 
datetime.timedelta(seconds=1))
+                    .execution_options(synchronize_session=False)
+                )
+            elif change:
+                for name, value in change.items():
+                    setattr(ti, name, value)
+
+        def get_in_memory(ti):
+            names = ("state", "start_date", "end_date", "duration", 
"working_set", "archived_reason")
+            return {name: getattr(ti, name) for name in (*names, "trigger_id", 
"updated_at")}
+
+        change_before_reset(tis["one_by_one"])
+        successor = tis["one_by_one"].prepare_db_for_next_try(session)
+        successor.state = None
+        successor.clear_next_method_args()
+        session.flush()
+        change_before_reset(tis["in_bulk"])
+        # The orphan query leaves them unloaded.
+        not_loaded = {"executor_config", "next_method", "next_kwargs"}
+        session.expire(tis["in_bulk"], list(not_loaded))
+        TaskInstance._reset_orphaned_attempts([tis["in_bulk"]], 
session=session)
+
+        assert get_in_memory(tis["in_bulk"]) == 
get_in_memory(tis["one_by_one"])
+        if change != {"state": TaskInstanceState.UP_FOR_RETRY}:
+            assert not_loaded <= sa_inspect(tis["in_bulk"]).unloaded
+        session.expire_all()
+
+        def get_changes(key):
+            """Return how each attempt row and its note differ from the 
attempt before the reset."""
+            attempts = (
+                session.execute(
+                    select(table)
+                    .where(
+                        table.c.run_id == dag_run.run_id,
+                        table.c.task_id == before[key]["task_id"],
+                        table.c.region_index == before[key]["region_index"],
+                    )
+                    .order_by(table.c.try_number)
+                    .execution_options(include_all_attempts=True)
+                )
+                .mappings()
+                .all()
+            )
+            assert len(attempts) == 2
+            assert attempts[0]["id"] == before[key]["id"] != attempts[1]["id"]
+            changes = []
+            for attempt in attempts:
+                note = get_row(note_table, note_table.c.ti_id, attempt["id"])
+                changes.append(
+                    (
+                        {k: v for k, v in attempt.items() if k != "id" and v 
!= before[key][k]},
+                        {k: v for k, v in note.items() if k != "ti_id" and v 
!= notes_before[key][k]},
+                    )
+                )
+            return changes
+
+        assert get_changes("in_bulk") == get_changes("one_by_one")
+
+    @time_machine.travel("2026-11-16 12:00:00+00:00", tick=False)
+    @mock.patch("airflow.models.taskinstance._RESET_BATCH_SIZE", 2)
+    def test_reset_orphaned_attempts_in_several_batches(self, dag_maker, 
session):
+        with dag_maker("test_reset_orphaned_attempts_in_several_batches", 
session=session):
+            for i in range(4):
+                EmptyOperator(task_id=f"task_{i}")
+        dag_run = dag_maker.create_dagrun(session=session)
+        now = timezone.utcnow()
+        tis = sorted(dag_run.get_task_instances(session=session), key=lambda 
ti: ti.task_id)
+        for i, ti in enumerate(tis):
+            ti.state = TaskInstanceState.RUNNING
+            ti.start_date = now - datetime.timedelta(seconds=10 * (i + 1))
+            ti.note = f"note of {ti.task_id}"
+        # Already ended: it keeps its end date and duration.
+        tis[3].end_date, tis[3].duration = now - 
datetime.timedelta(seconds=5), 35.0
+        session.flush()
+        archived = {ti.task_id: (ti.id, ti.try_number) for ti in tis}
+
+        TaskInstance._reset_orphaned_attempts(tis, session=session)
+
+        # The objects hold the archived rows without loading them again.
+        with count_queries() as result:
+            in_memory = [(ti.working_set, ti.state, ti.end_date, ti.duration) 
for ti in tis]
+        assert sum(result.values()) == 0
+        assert in_memory == [
+            (None, TaskInstanceState.FAILED, now, 10.0),
+            (None, TaskInstanceState.FAILED, now, 20.0),
+            (None, TaskInstanceState.FAILED, now, 30.0),
+            (None, TaskInstanceState.FAILED, now - 
datetime.timedelta(seconds=5), 35.0),
+        ]
+        session.expire_all()
+        assert [(ti.working_set, ti.state, ti.end_date, ti.duration) for ti in 
tis] == in_memory
+        assert {
+            ti.task_id: (ti.id != archived[ti.task_id][0], ti.try_number, 
ti.state, ti.note)
+            for ti in dag_run.get_task_instances(session=session)
+        } == {
+            task_id: (True, try_number + 1, None, f"note of {task_id}")
+            for task_id, (_, try_number) in archived.items()
+        }
+
+    def test_reset_orphaned_attempts_refuses_archived_attempts(self, 
dag_maker, session):
+        with 
dag_maker("test_reset_orphaned_attempts_refuses_archived_attempts", 
session=session):
+            EmptyOperator(task_id="task")
+        ti = 
dag_maker.create_dagrun(session=session).get_task_instance("task", 
session=session)
+        ti.state = TaskInstanceState.RUNNING
+        session.flush()
+        # Archived since it was loaded, as archive() would find it.
+        session.execute(
+            update(TaskInstance)
+            .where(TaskInstance.id == ti.id)
+            .values(working_set=None)
+            .execution_options(synchronize_session=False)
+        )
+
+        with pytest.raises(ValueError, match="cannot be archived again"):
+            TaskInstance._reset_orphaned_attempts([ti], session=session)
+
     def test_next_retry_datetime(self, dag_maker):
         delay = datetime.timedelta(seconds=30)
         max_delay = datetime.timedelta(minutes=60)

Reply via email to