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 f99c69c8adf Build task workloads after releasing the scheduler 
critical section (#77546)
f99c69c8adf is described below

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

    Build task workloads after releasing the scheduler critical section (#77546)
    
    Building a task instance's workload signs a JWT for it. That happened while
    the scheduler still held the critical-section lock, so the other schedulers
    skipped their turn for that long: little with the defaults, but about 300 ms
    for a batch of 512 task instances with an RSA 2048 key. Committing the
    QUEUED state first releases the lock before the workloads are built.
    
    That commit also releases the row locks on the batch. Workloads are then
    built only for the task instances still queued by this scheduler, read
    without waiting for row locks, so a task instance changed or deleted in
    between is skipped instead of failing the batch or stalling the scheduler.
    
    If building or handing over the workloads then fails, the task instances go
    back to SCHEDULED and their workloads are dropped from the executors' 
queues.
    After a lock error, that rollback used to leave the workloads queued, and 
the
    executors sent them for task instances that were back in SCHEDULED.
    
    * Signal deleted Dag runs explicitly when building task workloads
    
    The scheduler inferred that a Dag run had been deleted from a KeyError 
raised while preparing log addresses, and retried with an extra query to 
confirm it. Any other KeyError in that code was then read as a deletion first. 
A single condition type for pre-assigning executors also stops callers from 
having to tell True, False and a SQL clause apart, where a plain truth test 
fails only in mixed-executor deployments.
    
    Executors that write to the session in queue_workload() now see those 
writes committed after the QUEUED state, so the change gets a significant 
newsfragment.
---
 .../administration-and-deployment/scheduler.rst    |   8 +-
 airflow-core/docs/core-concepts/executor/index.rst |   2 +-
 airflow-core/newsfragments/77546.significant.rst   |  18 +
 .../src/airflow/executors/base_executor.py         |  10 +
 .../src/airflow/jobs/scheduler_job_runner.py       | 264 ++++++++--
 .../src/airflow/utils/log/task_log_address.py      |  36 +-
 airflow-core/tests/unit/jobs/test_scheduler_job.py | 542 ++++++++++++++++++++-
 .../tests/unit/utils/log/test_task_log_address.py  |  37 +-
 .../observability/metrics/metrics_template.yaml    |   2 +-
 9 files changed, 845 insertions(+), 74 deletions(-)

diff --git a/airflow-core/docs/administration-and-deployment/scheduler.rst 
b/airflow-core/docs/administration-and-deployment/scheduler.rst
index 1bcf7dab90b..99b3dbcfdb9 100644
--- a/airflow-core/docs/administration-and-deployment/scheduler.rst
+++ b/airflow-core/docs/administration-and-deployment/scheduler.rst
@@ -109,10 +109,10 @@ calculations in memory (because having to round-trip to 
the DB for each TaskInst
 need to ensure that only a single scheduler is in this critical section at 
once - otherwise limits would not
 be correctly respected. To achieve this we use database row-level locks (using 
``SELECT ... FOR UPDATE``).
 
-This critical section is where TaskInstances go from scheduled state and are 
enqueued to the executor, whilst
-ensuring the various concurrency and pool limits are respected. The critical 
section is obtained by asking for
-a row-level write lock on every row of the Pool table (roughly equivalent to 
``SELECT * FROM slot_pool FOR
-UPDATE NOWAIT`` but the exact query is slightly different).
+This critical section is where TaskInstances go from scheduled to queued 
state, whilst ensuring the various
+concurrency and pool limits are respected; they are sent to the executor after 
the scheduler leaves it. The
+critical section is obtained by asking for a row-level write lock on every row 
of the Pool table (roughly
+equivalent to ``SELECT * FROM slot_pool FOR UPDATE NOWAIT`` but the exact 
query is slightly different).
 
 The following databases are fully supported and provide an "optimal" 
experience:
 
diff --git a/airflow-core/docs/core-concepts/executor/index.rst 
b/airflow-core/docs/core-concepts/executor/index.rst
index 1b61553c621..1e112836c0d 100644
--- a/airflow-core/docs/core-concepts/executor/index.rst
+++ b/airflow-core/docs/core-concepts/executor/index.rst
@@ -297,7 +297,7 @@ Important BaseExecutor Methods
 These methods don't require overriding to implement your own executor, but are 
useful to be aware of:
 
 * ``heartbeat``: The Airflow scheduler Job loop will periodically call 
heartbeat on the executor. This is one of the main points of interaction 
between the Airflow scheduler and the executor. This method updates some 
metrics, triggers newly queued tasks to execute and updates state of 
running/completed tasks.
-* ``queue_workload``: The Airflow Executor will call this method of the 
BaseExecutor to provide tasks to be run by the executor. The BaseExecutor 
simply adds the *workloads* (check section above to understand) to an internal 
list of queued workloads to run within the executor. All executors present in 
the repository use this method.
+* ``queue_workload``: The Airflow Executor will call this method of the 
BaseExecutor to provide tasks to be run by the executor. The BaseExecutor 
simply adds the *workloads* (check section above to understand) to an internal 
list of queued workloads to run within the executor. All executors present in 
the repository use this method. An override must only buffer the workload: do 
not send it and do not commit the session; writes to the session (the 
``EdgeExecutor`` writes its ``edge_job``  [...]
 * ``get_event_buffer``: The Airflow scheduler calls this method to retrieve 
the current state of the TaskInstances the executor is executing.
 * ``has_task``: The scheduler uses this BaseExecutor method to determine if an 
executor already has a specific task instance queued or running.
 * ``send_callback``: Sends any callbacks to the sink configured on the 
executor.
diff --git a/airflow-core/newsfragments/77546.significant.rst 
b/airflow-core/newsfragments/77546.significant.rst
new file mode 100644
index 00000000000..cd857bde227
--- /dev/null
+++ b/airflow-core/newsfragments/77546.significant.rst
@@ -0,0 +1,18 @@
+Executors' ``queue_workload()`` writes now commit after the QUEUED state
+
+The scheduler now commits the QUEUED state of a batch of task instances first, 
which releases the
+scheduler critical section, and only then builds their workloads and calls 
each executor's
+``queue_workload()``. Whatever an executor writes to the ``session`` passed to 
``queue_workload()``,
+such as the ``EdgeExecutor``'s ``edge_job`` rows, is committed in that second 
transaction, no longer
+with the QUEUED state.
+
+**Migration for executor authors:**
+
+- ``queue_workload()`` must only buffer the workload until the next 
``heartbeat`` sends it. Do not
+  send it and do not commit ``session``.
+- If building the batch fails, the scheduler rolls ``session`` back, resets 
the task instances that
+  are still QUEUED to SCHEDULED and removes their workloads from 
``executor_queues``. Other in-memory
+  state kept for a workload, such as a key added to ``running``, must stay 
correct when that happens,
+  for example by being reconciled with the database on the next ``sync``.
+- Adoption code must accept a task instance that is QUEUED by a scheduler that 
died between the two
+  commits, before its ``queue_workload()`` writes were committed.
diff --git a/airflow-core/src/airflow/executors/base_executor.py 
b/airflow-core/src/airflow/executors/base_executor.py
index 874161062f3..681a20e5a10 100644
--- a/airflow-core/src/airflow/executors/base_executor.py
+++ b/airflow-core/src/airflow/executors/base_executor.py
@@ -440,6 +440,16 @@ class BaseExecutor(LoggingMixin):
         return workload.key
 
     def queue_workload(self, workload: ExecutorWorkload, session: Session) -> 
None:
+        """
+        Buffer ``workload`` until the next ``heartbeat`` sends it.
+
+        Do not send the workload and do not commit ``session``: writes to 
``session`` are committed or rolled
+        back by the scheduler with the batch. When building the rest of a 
batch of task instances fails, the
+        scheduler rolls ``session`` back, resets its task instances to 
SCHEDULED and removes their workloads
+        from ``executor_queues``. Other in-memory state kept for the workload, 
such as a key added to
+        ``running``, must stay correct when that happens, for example by being 
reconciled with the database
+        on the next ``sync``.
+        """
         if workload.type not in self.supported_workload_types:
             raise NotImplementedError(
                 f"{type(self).__name__} does not support {workload.type.value} 
workloads. "
diff --git a/airflow-core/src/airflow/jobs/scheduler_job_runner.py 
b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
index 93a94fc39aa..0bcc0a233f6 100644
--- a/airflow-core/src/airflow/jobs/scheduler_job_runner.py
+++ b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
@@ -1485,16 +1485,37 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
             # transient (via make_transient) before ExecuteTask.make() reads
             # ti.dag_run.created_dag_version.version_data to ship the bundle 
manifest matching
             # the run's pinned bundle_version. Lazy loads on transient objects 
silently return
-            # None instead of raising DetachedInstanceError. Scope the SELECT 
to version_data
-            # (the PK is auto-included) so we read two columns rather than the 
full row.
+            # None instead of raising DetachedInstanceError. Scope the SELECT 
to version_data and
+            # bundle_version, the columns ExecuteTask.make() reads (the PK is 
auto-included), to
+            # avoid a lazy load after the commit, which fails once the Dag is 
deleted.
             .options(
                 joinedload(TI.dag_run)
                 .selectinload(DagRun.created_dag_version)
-                .load_only(DagVersion.version_data)
+                .load_only(DagVersion.version_data, DagVersion.bundle_version)
             )
             .limit(max_tis)
         )
 
+    def _build_pre_assigning_executor_filter(self) -> ColumnElement[bool]:
+        """Match the task instances routed to an executor that sets 
``pre_assigns_external_executor_id``."""
+        pre_assign_executors = {e for e in self.executors if 
e.pre_assigns_external_executor_id}
+        if not pre_assign_executors:
+            return expression.false()
+        if pre_assign_executors == set(self.executors):
+            return expression.true()
+        opt_in_names: set[str] = set()
+        for exc in pre_assign_executors:
+            if exc.name:
+                if exc.name.alias:
+                    opt_in_names.add(exc.name.alias)
+                opt_in_names.add(exc.name.module_path)
+        conditions = []
+        if opt_in_names:
+            conditions.append(TI.executor.in_(opt_in_names))
+        if self.executor in pre_assign_executors:
+            conditions.append(TI.executor.is_(None))
+        return or_(*conditions) if conditions else expression.false()
+
     def _mark_task_instances_queued(self, executable_tis: list[TI], *, 
session: Session) -> list[TI]:
         """
         Bulk-update ``executable_tis`` to QUEUED state and detach them from 
the session.
@@ -1536,26 +1557,12 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
             # pre_assigns_external_executor_id (e.g. CeleryExecutor uses it as 
the
             # Celery task_id passed to apply_async). In mixed-executor 
deployments,
             # a CASE expression limits the UUID to TIs targeting an opt-in 
executor.
-            pre_assign_executors = {e for e in self.executors if 
e.pre_assigns_external_executor_id}
-            if pre_assign_executors == set(self.executors):
-                # All executors opt in — unconditional UUID for every TI.
-                queued_values["external_executor_id"] = random_db_uuid()
-            elif pre_assign_executors:
-                # Mixed — only TIs routed to an opt-in executor get a UUID.
-                opt_in_names: set[str] = set()
-                default_opts_in = self.executor in pre_assign_executors
-                for exc in pre_assign_executors:
-                    if exc.name:
-                        if exc.name.alias:
-                            opt_in_names.add(exc.name.alias)
-                        opt_in_names.add(exc.name.module_path)
-                whens = []
-                if opt_in_names:
-                    whens.append((TI.executor.in_(opt_in_names), 
sql_cast(random_db_uuid(), Text)))
-                if default_opts_in:
-                    whens.append((TI.executor.is_(None), 
sql_cast(random_db_uuid(), Text)))
-                if whens:
-                    queued_values["external_executor_id"] = case(*whens, 
else_=TI.external_executor_id)
+            pre_assigning = any(e.pre_assigns_external_executor_id for e in 
self.executors)
+            if pre_assigning:
+                queued_values["external_executor_id"] = case(
+                    (self._build_pre_assigning_executor_filter(), 
sql_cast(random_db_uuid(), Text)),
+                    else_=TI.external_executor_id,
+                )
 
             queued_update = (
                 update(TI)
@@ -1564,7 +1571,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
                 .execution_options(synchronize_session=False)
             )
 
-            if pre_assign_executors:
+            if pre_assigning:
                 # Read the DB-generated UUIDs back onto the in-memory objects 
so the
                 # workload DTO carries them through to 
send_workload_to_executor (the
                 # objects are about to be detached by make_transient). Use 
RETURNING
@@ -1592,14 +1599,15 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
         return executable_tis
 
     def _enqueue_task_instances_with_queued_state(
-        self, task_instances: list[TI], executor: BaseExecutor, session: 
Session
-    ) -> None:
+        self, task_instances: list[TI], executor: BaseExecutor, *, session: 
Session
+    ) -> int:
         """
         Enqueue task_instances which should have been set to queued with the 
executor.
 
         :param task_instances: TaskInstances to enqueue
         :param executor: The executor to enqueue tasks for
         :param session: The session object
+        :return: How many workloads were enqueued.
         """
 
         def _get_sentry_integration(executor: BaseExecutor) -> str:
@@ -1619,17 +1627,32 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
                 return ""
             return sentry_integration
 
+        log_tis = [
+            ti
+            for ti in task_instances
+            if ti.dag_version_id and ti.dag_run.state not in 
State.finished_dr_states
+        ]
         log_contexts = prepare_task_log_contexts(
-            [
-                ti
-                for ti in task_instances
-                if ti.dag_version_id and ti.dag_run.state not in 
State.finished_dr_states
-            ],
+            log_tis,
             session=session,
             dag_bag=self.scheduler_dag_bag,
             filename_template=conf.get("logging", "log_filename_template"),
+            skip_missing_regions=True,
         )
+        # Nothing locks the batch while its workloads are built. Regions are 
only deleted with their Dag run
+        # (ON DELETE CASCADE), so a missing one means its Dag run was deleted 
meanwhile: drop all its task
+        # instances. Those of a deleted Dag run with no region in the batch 
are not detected here: their
+        # workloads are sent, and the server rejects their start.
+        deleted_runs = {(ti.dag_id, ti.run_id) for ti in log_tis if ti.id not 
in log_contexts}
+        if deleted_runs:
+            deleted = [ti for ti in task_instances if (ti.dag_id, ti.run_id) 
in deleted_runs]
+            self.log.warning(
+                "Not enqueuing %s task instances deleted while their workloads 
were built", len(deleted)
+            )
+            self.log.debug("Task instances deleted while their workloads were 
built: %s", deleted)
+            task_instances = [ti for ti in task_instances if (ti.dag_id, 
ti.run_id) not in deleted_runs]
         # actually enqueue them
+        num_enqueued = 0
         for ti in task_instances:
             if ti.dag_run.state in State.finished_dr_states:
                 ti.set_state(None, session=session)
@@ -1657,16 +1680,17 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
                 log_context=log_contexts[ti.id],
             )
             executor.queue_workload(workload, session=session)
+            num_enqueued += 1
+        return num_enqueued
 
-    def _critical_section_enqueue_task_instances(self, session: Session) -> 
int:
+    def _critical_section_queue_task_instances(self, *, session: Session) -> 
list[TI]:
         """
-        Enqueues TaskInstances for execution.
+        Pick TaskInstances to run and mark them QUEUED.
 
-        There are three steps:
+        There are two steps:
         1. Pick TIs by priority with the constraint that they are in the 
expected states
         and that we do not exceed max_active_runs or pool limits.
         2. Change the state for the TIs above atomically.
-        3. Enqueue the TIs in the executor.
 
         HA note: This function is a "critical section" meaning that only a 
single scheduler process can
         execute this function at the same time. This is achieved by doing
@@ -1675,8 +1699,12 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
         etc.); DBs that don't support this (such as MariaDB or MySQL 5.x) the 
other schedulers will wait for
         the lock before continuing.
 
+        The lock is held until the caller commits. Build and enqueue the 
workloads only after that commit,
+        with ``_enqueue_workloads_or_reset``: building a workload signs a JWT 
for each task
+        instance, which with an asymmetric signing key costs up to a few 
milliseconds each.
+
         :param session:
-        :return: Number of task instance with state changed.
+        :return: The task instances moved to QUEUED.
         """
         # The user can either request a certain number of tis to schedule per 
main scheduler loop (default
         # is non-zero). If that value has been set to zero, that means use the 
value of core.parallelism (or
@@ -1692,15 +1720,43 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
             max_tis = min(self.job.max_tis_per_query, self._parallelism - 
num_occupied_slots)
         if max_tis <= 0:
             self.log.debug("max_tis query size is less than or equal to zero. 
No query will be performed!")
-            return 0
+            return []
 
         pools, max_tis, starved_pools = self._acquire_pool_capacity(max_tis, 
session=session)
         if max_tis == 0:
-            return 0
-        queued_tis = self._select_task_instances_to_queue(max_tis, pools, 
starved_pools, session=session)
+            return []
+        return self._select_task_instances_to_queue(max_tis, pools, 
starved_pools, session=session)
+
+    def _enqueue_workloads(self, queued_tis: list[TI], *, session: Session) -> 
int:
+        """
+        Build the workloads of TaskInstances already committed as QUEUED and 
enqueue them in their executors.
 
+        :return: How many workloads were enqueued.
+        """
+        # Committing the QUEUED state released the row locks the selection 
took, so another transaction may
+        # have changed or deleted some of these task instances since. Building 
the workloads does not lock
+        # them again: it only builds workloads for the ones still queued by 
this scheduler.
+        still_queued_ids = set(
+            session.scalars(
+                select(TI.id).where(
+                    TI.id.in_([ti.id for ti in queued_tis]),
+                    TI.state == TaskInstanceState.QUEUED,
+                    TI.queued_by_job_id == self.job.id,
+                )
+            )
+        )
+        if len(still_queued_ids) < len(queued_tis):
+            skipped = [ti for ti in queued_tis if ti.id not in 
still_queued_ids]
+            self.log.info(
+                "Not enqueuing %s of %s task instances changed or deleted 
after they were queued",
+                len(skipped),
+                len(queued_tis),
+            )
+            self.log.debug("Task instances changed or deleted after they were 
queued: %s", skipped)
+            queued_tis = [ti for ti in queued_tis if ti.id in still_queued_ids]
         # Sort queued TIs to their respective executor
         executor_to_queued_tis = self._executor_to_workloads(queued_tis, 
session)
+        num_enqueued = 0
         for executor, queued_tis_per_executor in 
executor_to_queued_tis.items():
             self.log.info(
                 "Trying to enqueue tasks: %s for executor: %s",
@@ -1708,9 +1764,117 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
                 executor,
             )
 
-            
self._enqueue_task_instances_with_queued_state(queued_tis_per_executor, 
executor, session=session)
+            num_enqueued += self._enqueue_task_instances_with_queued_state(
+                queued_tis_per_executor, executor, session=session
+            )
+        return num_enqueued
+
+    def _enqueue_workloads_or_reset(
+        self, queued_tis: list[TI], *, guard: CommitProhibitorGuard, session: 
Session
+    ) -> int:
+        """
+        Enqueue the workloads of TaskInstances committed as QUEUED, or reset 
them to SCHEDULED on failure.
 
-        return len(queued_tis)
+        A failure while building or enqueuing the workloads, or while flushing 
what the executors wrote,
+        resets the batch; a failure of the commit itself does not, since that 
commit may have succeeded.
+
+        :return: How many were enqueued; 0 when a lock error made it fail. 
Other errors are re-raised.
+        """
+        try:
+            num_enqueued = self._enqueue_workloads(queued_tis, session=session)
+            session.flush()
+        except BaseException as e:
+            self._reset_batch(queued_tis, error=e, guard=guard, 
session=session)
+            if isinstance(e, OperationalError) and 
is_lock_not_available_error(error=e):
+                return 0
+            raise
+        guard.commit()
+        return num_enqueued
+
+    def _reset_batch(
+        self, tis: list[TI], *, error: BaseException, guard: 
CommitProhibitorGuard, session: Session
+    ) -> None:
+        """Reset ``tis`` to SCHEDULED after ``error`` and drop the workloads 
of the ones reset, logging failures."""
+        # QUEUED is committed, so the batch would otherwise wait for 
task_queued_timeout. queue_workload()
+        # only buffers: executors send their queues on their next heartbeat, 
and anything else it writes is
+        # in this transaction, so nothing of the batch has run.
+        try:
+            session.rollback()
+            reset_ids = self._reset_task_instances_to_scheduled(tis, 
session=session)
+            guard.commit()
+        except Exception:
+            # The task instances stay QUEUED by this scheduler, so their 
workloads are kept and sent as usual.
+            self.log.exception(
+                "Failed to reset %s task instances to SCHEDULED after failing 
to enqueue their workloads",
+                len(tis),
+            )
+            with suppress(Exception):
+                session.rollback()
+            return
+        self._discard_unsent_workloads([ti for ti in tis if ti.id in 
reset_ids])
+        self.log.warning(
+            "Reset %s of %s task instances to SCHEDULED after failing to 
enqueue their workloads: %r",
+            len(reset_ids),
+            len(tis),
+            error,
+        )
+
+    def _discard_unsent_workloads(self, tis: list[TI]) -> None:
+        """Remove the workloads of ``tis`` from the executors' queues, before 
an executor heartbeat sends them."""
+        for executor in self.executors:
+            task_queue = 
executor.executor_queues[workloads.WorkloadType.EXECUTE_TASK]
+            for ti in tis:
+                task_queue.pop(executor.get_task_key(ti), None)
+
+    def _reset_task_instances_to_scheduled(self, tis: list[TI], *, session: 
Session) -> set[UUID]:
+        """
+        Reset TaskInstances this scheduler marked QUEUED to SCHEDULED, unless 
they changed since.
+
+        Clears what the QUEUED update set, including the 
``external_executor_id`` pre-assigned for some
+        executors. Rows locked by another transaction are skipped instead of 
waited for: that transaction
+        is changing them, and what it leaves QUEUED is recovered by 
task_queued_timeout or adoption. This
+        needs row-level locking (the default): with ``[scheduler] 
use_row_level_locking = False``, which
+        is only for single-scheduler setups, the ``UPDATE`` can wait on rows 
another transaction holds.
+
+        :return: The ids of the task instances reset.
+        """
+        reset_ids = set(
+            session.scalars(
+                with_row_locks(
+                    select(TI.id).where(
+                        TI.id.in_([ti.id for ti in tis]),
+                        TI.state == TaskInstanceState.QUEUED,
+                        TI.queued_by_job_id == self.job.id,
+                    ),
+                    of=TI,
+                    session=session,
+                    skip_locked=True,
+                )
+            )
+        )
+        if len(reset_ids) < len(tis) and self.log.isEnabledFor(logging.DEBUG):
+            self.log.debug(
+                "Not resetting task instances changed or locked by another 
transaction: %s",
+                [ti for ti in tis if ti.id not in reset_ids],
+            )
+        if not reset_ids:
+            return reset_ids
+        values: dict[str, Any] = {
+            "state": TaskInstanceState.SCHEDULED,
+            "queued_dttm": None,
+            "queued_by_job_id": None,
+        }
+        if any(e.pre_assigns_external_executor_id for e in self.executors):
+            values["external_executor_id"] = case(
+                (self._build_pre_assigning_executor_filter(), None), 
else_=TI.external_executor_id
+            )
+        session.execute(
+            update(TI)
+            .where(TI.id.in_(reset_ids))
+            .values(**values)
+            .execution_options(synchronize_session=False)
+        )
+        return reset_ids
 
     def _enqueue_executor_callbacks(self, session: Session) -> None:
         """
@@ -2622,10 +2786,10 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
           limit will allow more throughput for smaller DAGs but will likely 
slow down throughput for larger
           (>500 tasks.) DAGs
 
-        - Then, via a Critical Section (locking the rows of the Pool model) we 
queue tasks, and then send them
-          to the executor.
+        - Then, via a Critical Section (locking the rows of the Pool model) we 
queue tasks. Their workloads
+          are built and sent to the executors after the critical section.
 
-          See docs of _critical_section_enqueue_task_instances for more.
+          See docs of _critical_section_queue_task_instances for more.
 
         :return: Number of TIs enqueued in this iteration
         """
@@ -2674,17 +2838,17 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
 
             # Attempt to schedule even if some executors are full but not all.
             total_free_executor_slots = sum([executor.slots_available for 
executor in self.executors])
+            queued_tis: list[TI] = []
             if total_free_executor_slots <= 0:
                 # We know we can't do anything here, so don't even try!
                 self.log.debug("All executors are full, skipping critical 
section")
-                num_queued_tis = 0
             else:
                 try:
                     timer = stats.timer("scheduler.critical_section_duration")
                     timer.start()
 
-                    # Find any TIs in state SCHEDULED, try to QUEUE them (send 
it to the executors)
-                    num_queued_tis = 
self._critical_section_enqueue_task_instances(session=session)
+                    # Find any TIs in state SCHEDULED, try to QUEUE them
+                    queued_tis = 
self._critical_section_queue_task_instances(session=session)
 
                     # Make sure we only sent this metric if we obtained the 
lock, otherwise we'll skew the
                     # metric, way down
@@ -2699,9 +2863,13 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
                         return 0
                     raise
 
+            # Releases the critical-section lock.
             guard.commit()
 
-        return num_queued_tis
+            if queued_tis:
+                return self._enqueue_workloads_or_reset(queued_tis, 
guard=guard, session=session)
+
+        return 0
 
     def _warn_unreachable_asset_partition(
         self,
diff --git a/airflow-core/src/airflow/utils/log/task_log_address.py 
b/airflow-core/src/airflow/utils/log/task_log_address.py
index 27be654a274..ff757d6f8d4 100644
--- a/airflow-core/src/airflow/utils/log/task_log_address.py
+++ b/airflow-core/src/airflow/utils/log/task_log_address.py
@@ -171,12 +171,33 @@ def _load_node_kinds(
     return kinds
 
 
+def _has_loaded_regions(region_id: UUID, regions: Mapping[UUID, 
DynamicRegion]) -> bool:
+    """Whether ``region_id`` and every region it is nested in or forked from 
are in ``regions``."""
+    seen: set[UUID] = set()
+    pending = [region_id]
+    while pending:
+        current = pending.pop()
+        if current in seen:
+            continue
+        seen.add(current)
+        region = regions.get(current)
+        if region is None:
+            return False
+        pending.extend(
+            ancestor_id
+            for ancestor_id in (region.parent_region_id, 
region.forked_from_region_id)
+            if ancestor_id is not None
+        )
+    return True
+
+
 def prepare_task_log_contexts(
     tis: Collection[TaskInstance],
     *,
     session: Session | None = None,
     dag_bag: DBDagBag | None = None,
     filename_template: str | None = None,
+    skip_missing_regions: bool = False,
 ) -> dict[UUID, TaskLogContext]:
     """
     Load shared address inputs in batches before rendering workloads or 
reading logs.
@@ -184,13 +205,20 @@ def prepare_task_log_contexts(
     Pass the caller's ``dag_bag`` so the loop and map nodes of a Dag version 
come from its cache instead of
     deserializing the Dag again. Writers pass the configured 
``filename_template``; readers omit it to use
     each run's pinned template.
+
+    :param skip_missing_regions: Leave out the task instances whose regions 
are not all found, such as those
+        of a Dag run deleted meanwhile, instead of raising ``KeyError``.
     """
     if not tis:
         return {}
     if session is None:
         with create_session(scoped=False) as session:
             return prepare_task_log_contexts(
-                tis, session=session, dag_bag=dag_bag, 
filename_template=filename_template
+                tis,
+                session=session,
+                dag_bag=dag_bag,
+                filename_template=filename_template,
+                skip_missing_regions=skip_missing_regions,
             )
     runs: dict[tuple[str, str], DagRun] = {}
     for ti in tis:
@@ -234,6 +262,12 @@ def prepare_task_log_contexts(
         node_kinds = _load_node_kinds(nested, runs, session, dag_bag)
     contexts = {}
     for ti in tis:
+        if (
+            skip_missing_regions
+            and ti.region_id != SENTINEL_REGION_ID
+            and not _has_loaded_regions(ti.region_id, regions)
+        ):
+            continue
         run = runs[ti.dag_id, ti.run_id]
         template = filename_template if filename_template is not None else 
templates.get(run.log_template_id)
         if template is None:
diff --git a/airflow-core/tests/unit/jobs/test_scheduler_job.py 
b/airflow-core/tests/unit/jobs/test_scheduler_job.py
index 7b8948ef71a..eee92510985 100644
--- a/airflow-core/tests/unit/jobs/test_scheduler_job.py
+++ b/airflow-core/tests/unit/jobs/test_scheduler_job.py
@@ -22,6 +22,7 @@ import datetime
 import logging
 import os
 import re
+import threading
 import time
 from collections import Counter, deque
 from collections.abc import Callable, Generator, Iterator
@@ -41,7 +42,7 @@ import pytest
 import time_machine
 from sqlalchemy import Delete, delete, event as sa_event, func, inspect, 
select, text, update
 from sqlalchemy.dialects import mysql
-from sqlalchemy.exc import IntegrityError, InvalidRequestError
+from sqlalchemy.exc import IntegrityError, InvalidRequestError, 
OperationalError
 from sqlalchemy.orm import joinedload
 
 from airflow import settings
@@ -49,6 +50,7 @@ from airflow._shared.module_loading import qualname
 from airflow._shared.observability.metrics.base_stats_logger import StatsLogger
 from airflow._shared.observability.metrics.metrics_registry import 
MetricsRegistry
 from airflow._shared.timezones import timezone
+from airflow.api.common.delete_dag import delete_dag
 from airflow.api_fastapi.auth.tokens import JWTGenerator
 from airflow.api_fastapi.execution_api.datamodels.taskinstance import 
TaskInstance as TIDataModel
 from airflow.assets.manager import AssetManager
@@ -68,7 +70,7 @@ from airflow.executors.executor_constants import MOCK_EXECUTOR
 from airflow.executors.executor_loader import ExecutorLoader
 from airflow.executors.executor_utils import ExecutorName
 from airflow.executors.local_executor import LocalExecutor
-from airflow.executors.workloads import WorkloadType
+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.scheduler_job_runner import (
@@ -105,7 +107,7 @@ from airflow.models.dagwarning import DagWarning
 from airflow.models.db_callback_request import DbCallbackRequest
 from airflow.models.deadline import Deadline
 from airflow.models.deadline_alert import DeadlineAlert
-from airflow.models.dynamic_region import DynamicRegion
+from airflow.models.dynamic_region import SENTINEL_REGION_ID, DynamicRegion
 from airflow.models.hitl import HITLDetail
 from airflow.models.log import Log, resolve_team_name
 from airflow.models.pool import Pool, PoolStats
@@ -170,8 +172,9 @@ from airflow.timetables.simple import (
 )
 from airflow.triggers.base import AssetTriggerEvent, TriggerEvent
 from airflow.utils.event_scheduler import EventScheduler
+from airflow.utils.log.task_log_address import prepare_task_log_contexts
 from airflow.utils.session import NEW_SESSION, create_session, provide_session
-from airflow.utils.sqlalchemy import CommitProhibitorGuard, with_row_locks
+from airflow.utils.sqlalchemy import CommitProhibitorGuard, get_dialect_name, 
with_row_locks
 from airflow.utils.state import CallbackState, DagRunState, 
DagSchedulingState, State, TaskInstanceState
 from airflow.utils.types import DagRunTriggeredByType, DagRunType
 
@@ -430,6 +433,13 @@ def _is_waiting_for_lock(waiter_id: int, blocker_id: int) 
-> bool:
         return bool(probe.execute(waiting, {"waiter": waiter_id}).scalar())
 
 
+def _queue_and_enqueue(runner: SchedulerJobRunner, session: Session) -> int:
+    """Queue task instances and enqueue their workloads in one transaction, 
without the commit in between."""
+    queued_tis = runner._critical_section_queue_task_instances(session=session)
+    runner._enqueue_workloads(queued_tis, session=session)
+    return len(queued_tis)
+
+
 def assign_executor_to_team(executor: MagicMock, team_name: str) -> None:
     # ExecutorLoader.load_executor sets the team on both; the scheduler reads 
it from the name.
     executor.team_name = team_name
@@ -2090,7 +2100,7 @@ class TestSchedulerJob:
         (ti1,) = dr1.task_instances
         ti1.state = State.SCHEDULED
 
-        self.job_runner._critical_section_enqueue_task_instances(session)
+        _queue_and_enqueue(self.job_runner, session)
         session.flush()
         ti1.refresh_from_db(session=session)
         assert ti1.state == State.SCHEDULED
@@ -2109,7 +2119,7 @@ class TestSchedulerJob:
         session.flush()
 
         self.job_runner = SchedulerJobRunner(job=Job(), 
executors=[self.null_exec])
-        self.job_runner._critical_section_enqueue_task_instances(session)
+        _queue_and_enqueue(self.job_runner, session)
         session.flush()
 
         task_instance.refresh_from_db(session=session)
@@ -2229,7 +2239,7 @@ class TestSchedulerJob:
         session.flush()
         assert dr1.run_type == DagRunType.BACKFILL_JOB
 
-        self.job_runner._critical_section_enqueue_task_instances(session)
+        _queue_and_enqueue(self.job_runner, session)
         session.flush()
         ti1.refresh_from_db()
         assert ti1.state == TaskInstanceState.QUEUED
@@ -4607,7 +4617,7 @@ class TestSchedulerJob:
         ],
     )
     @pytest.mark.usefixtures("mock_executors")
-    def test_critical_section_enqueue_task_instances(self, task1_exec, 
task2_exec, dag_maker, session):
+    def test_critical_section_queue_task_instances(self, task1_exec, 
task2_exec, dag_maker, session):
         dag_id = "SchedulerJobTest.test_execute_task_instances"
         # important that len(tasks) is less than max_active_tasks
         # because before scheduler._execute_task_instances would only
@@ -4662,7 +4672,7 @@ class TestSchedulerJob:
 
         assert dr2.state == State.RUNNING
 
-        num_queued = 
self.job_runner._critical_section_enqueue_task_instances(session=session)
+        num_queued = _queue_and_enqueue(self.job_runner, session)
         assert num_queued == 3
 
         # check that max_active_tasks is respected
@@ -4680,9 +4690,507 @@ class TestSchedulerJob:
         assert dr2_counter[State.QUEUED] == 3
         assert dr2_counter[State.SCHEDULED] == 1
 
-        num_queued = 
self.job_runner._critical_section_enqueue_task_instances(session=session)
+        num_queued = _queue_and_enqueue(self.job_runner, session)
         assert num_queued == 0
 
+    @mock.patch.object(ExecuteTask, "make", autospec=True, 
wraps=ExecuteTask.make)
+    def test_workloads_are_built_after_the_queued_state_is_committed(self, 
mock_make, dag_maker, session):
+        with dag_maker(dag_id="build_after_commit", session=session):
+            EmptyOperator(task_id="t1")
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        (ti,) = dr.get_task_instances(session=session)
+        ti.state = TaskInstanceState.SCHEDULED
+        job = Job()
+        session.add(job)
+        session.commit()
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+        committed_states = []
+
+        def read_committed_state(ti, **kwargs):
+            # A separate connection only sees committed rows, and the same 
commit releases the lock.
+            with create_session(scoped=False) as other_session:
+                committed_states.append(
+                    
other_session.scalar(select(TaskInstance.state).where(TaskInstance.id == ti.id))
+                )
+            return mock.DEFAULT
+
+        mock_make.side_effect = read_committed_state
+
+        assert self.job_runner._do_scheduling(session) == 1
+        assert committed_states == [TaskInstanceState.QUEUED]
+
+    @pytest.mark.parametrize(
+        ("error", "raised"),
+        [
+            pytest.param(RuntimeError("boom"), True, id="error"),
+            pytest.param(SystemExit(0), True, id="shutdown"),
+            pytest.param(
+                OperationalError("lock", params=None, 
orig=RuntimeError("55P03")),
+                False,
+                id="lock-not-available",
+            ),
+        ],
+    )
+    @mock.patch.object(ExecuteTask, "make", autospec=True, 
wraps=ExecuteTask.make)
+    def test_queued_task_instances_go_back_to_scheduled_when_enqueuing_fails(
+        self, mock_make, error, raised, dag_maker, session
+    ):
+        with dag_maker(dag_id="enqueue_fails", session=session):
+            EmptyOperator(task_id="t1")
+            EmptyOperator(task_id="t2")
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        for ti in dr.get_task_instances(session=session):
+            ti.state = TaskInstanceState.SCHEDULED
+        job = Job()
+        session.add(job)
+        session.commit()
+        # Like CeleryExecutor: external_executor_id is set with the QUEUED 
state.
+        self.null_exec.pre_assigns_external_executor_id = True
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+        # The first workload reaches the executor's queue before the second 
one fails.
+        mock_make.side_effect = [mock.DEFAULT, error]
+
+        if raised:
+            with pytest.raises(type(error)):
+                self.job_runner._do_scheduling(session)
+            # As create_session() does when the error leaves the scheduler 
loop.
+            session.rollback()
+        else:
+            assert self.job_runner._do_scheduling(session) == 0
+
+        assert mock_make.call_count == 2
+        assert not self.null_exec.executor_queues[WorkloadType.EXECUTE_TASK]
+        assert {
+            (ti.task_id, ti.state, ti.queued_by_job_id, ti.queued_dttm, 
ti.external_executor_id)
+            for ti in dr.get_task_instances(session=session)
+        } == {
+            ("t1", TaskInstanceState.SCHEDULED, None, None, None),
+            ("t2", TaskInstanceState.SCHEDULED, None, None, None),
+        }
+
+    @mock.patch.object(SchedulerJobRunner, 
"_reset_task_instances_to_scheduled", autospec=True)
+    @mock.patch.object(ExecuteTask, "make", autospec=True, 
wraps=ExecuteTask.make)
+    def test_failed_reset_keeps_the_workloads_and_raises_the_original_error(
+        self, mock_make, mock_reset, dag_maker, session
+    ):
+        with dag_maker(dag_id="reset_fails", session=session):
+            EmptyOperator(task_id="t1")
+            EmptyOperator(task_id="t2")
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        for ti in dr.get_task_instances(session=session):
+            ti.state = TaskInstanceState.SCHEDULED
+        job = Job()
+        session.add(job)
+        session.commit()
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+        mock_make.side_effect = [mock.DEFAULT, RuntimeError("boom")]
+        mock_reset.side_effect = RuntimeError("cannot reset")
+
+        with pytest.raises(RuntimeError, match="boom"):
+            self.job_runner._do_scheduling(session)
+        session.rollback()
+
+        mock_reset.assert_called_once()
+        # Still QUEUED by this scheduler: the workload already built is kept, 
to be sent as usual.
+        assert len(self.null_exec.executor_queues[WorkloadType.EXECUTE_TASK]) 
== 1
+        assert {ti.state for ti in dr.get_task_instances(session=session)} == 
{TaskInstanceState.QUEUED}
+
+    @pytest.mark.parametrize("raised", [True, False], ids=["duplicate-row", 
"lock-not-available"])
+    def test_batch_is_reset_when_flushing_the_executor_writes_fails(self, 
raised, dag_maker, session):
+        with dag_maker(dag_id="flush_fails", session=session):
+            EmptyOperator(task_id="t1")
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        (ti,) = dr.get_task_instances(session=session)
+        ti.state = TaskInstanceState.SCHEDULED
+        job = Job()
+        session.add(job)
+        session.commit()
+        queue_workload = self.null_exec.queue_workload
+
+        def queue_workload_and_write(workload, session):
+            # Like the EdgeExecutor, which writes its edge_job rows here.
+            queue_workload(workload, session)
+            if raised:
+                session.add(Pool(pool="default_pool", slots=1, 
include_deferred=False))
+            else:
+                session.add(Log(event="queued"))
+
+                def lock_not_available(*args, **kwargs):
+                    raise OperationalError("flush", params=None, 
orig=RuntimeError("55P03"))
+
+                sa_event.listen(session, "before_flush", lock_not_available, 
once=True)
+
+        self.null_exec.queue_workload = queue_workload_and_write
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+
+        if raised:
+            with pytest.raises(IntegrityError):
+                self.job_runner._do_scheduling(session)
+            session.rollback()
+        else:
+            assert self.job_runner._do_scheduling(session) == 0
+
+        assert dr.get_task_instance("t1", session=session).state == 
TaskInstanceState.SCHEDULED
+        assert not self.null_exec.executor_queues[WorkloadType.EXECUTE_TASK]
+
+    @pytest.mark.parametrize("supports_uuid", [True, False], 
ids=["keyed-by-id", "keyed-by-coordinates"])
+    @mock.patch.object(ExecuteTask, "make", autospec=True, 
wraps=ExecuteTask.make)
+    def test_enqueuing_failure_discards_mapped_workloads_by_the_executor_key(
+        self, mock_make, supports_uuid, dag_maker, session
+    ):
+        class CoordinateKeyedExecutor(MockExecutor):
+            supports_task_instance_uuid = False
+
+        with dag_maker(dag_id="mapped_enqueue_fails", session=session):
+            MockOperator.partial(task_id="mapped").expand(arg1=[1, 2])
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        dr.task_instance_scheduling_decisions(session=session)
+        for ti in dr.get_task_instances(session=session):
+            ti.state = TaskInstanceState.SCHEDULED
+        job = Job()
+        session.add(job)
+        session.commit()
+        executor = MockExecutor() if supports_uuid else 
CoordinateKeyedExecutor()
+        self.job_runner = SchedulerJobRunner(job=job, executors=[executor])
+        # The workload of the first mapped task instance is queued, keyed like 
the executor keys it.
+        mock_make.side_effect = [mock.DEFAULT, RuntimeError("boom")]
+
+        with pytest.raises(RuntimeError, match="boom"):
+            self.job_runner._do_scheduling(session)
+        session.rollback()
+
+        assert not executor.executor_queues[WorkloadType.EXECUTE_TASK]
+        assert {ti.state for ti in dr.get_task_instances(session=session)} == 
{TaskInstanceState.SCHEDULED}
+
+    @mock.patch.object(ExecuteTask, "make", autospec=True, 
wraps=ExecuteTask.make)
+    def test_enqueuing_failure_discards_the_workloads_of_every_executor(self, 
mock_make, dag_maker, session):
+        with dag_maker(dag_id="enqueue_fails_two_executors", session=session):
+            EmptyOperator(task_id="t1", executor="executor_b", 
priority_weight=2)
+            EmptyOperator(task_id="t2", executor="executor_a", 
priority_weight=1)
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        for ti in dr.get_task_instances(session=session):
+            ti.state = TaskInstanceState.SCHEDULED
+            ti.external_executor_id = "previous-id"
+        job = Job()
+        session.add(job)
+        session.commit()
+        executor_a, executor_b = MockExecutor(), MockExecutor()
+        executor_a.name = ExecutorName(module_path="path.to.ExecutorA", 
alias="executor_a")
+        executor_b.name = ExecutorName(module_path="path.to.ExecutorB", 
alias="executor_b")
+        # Only executor_a's task instances get an external_executor_id with 
the QUEUED state.
+        executor_a.pre_assigns_external_executor_id = True
+        self.job_runner = SchedulerJobRunner(job=job, executors=[executor_a, 
executor_b])
+        # t1's workload reaches the queue of executor_b, the second executor, 
before t2's fails.
+        mock_make.side_effect = [mock.DEFAULT, RuntimeError("boom")]
+
+        with pytest.raises(RuntimeError, match="boom"):
+            self.job_runner._do_scheduling(session)
+        session.rollback()
+
+        assert [call.args[0].task_id for call in mock_make.call_args_list] == 
["t1", "t2"]
+        assert not executor_a.executor_queues[WorkloadType.EXECUTE_TASK]
+        assert not executor_b.executor_queues[WorkloadType.EXECUTE_TASK]
+        assert {
+            (ti.task_id, ti.state, ti.external_executor_id) for ti in 
dr.get_task_instances(session=session)
+        } == {
+            ("t1", TaskInstanceState.SCHEDULED, "previous-id"),
+            ("t2", TaskInstanceState.SCHEDULED, None),
+        }
+
+    @staticmethod
+    def _schedule_dag_runs_with_a_mapped_task(dag_maker, session, num_runs: 
int = 2) -> list[DagRun]:
+        with dag_maker(dag_id="mapped_runs", session=session):
+            MockOperator.partial(task_id="mapped").expand(arg1=[1, 2])
+            EmptyOperator(task_id="plain")
+        dag_runs = [dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)]
+        while len(dag_runs) < num_runs:
+            dag_runs.append(
+                dag_maker.create_dagrun_after(dag_runs[-1], 
run_type=DagRunType.SCHEDULED, session=session)
+            )
+        for dr in dag_runs:
+            dr.task_instance_scheduling_decisions(session=session)
+            for ti in dr.get_task_instances(session=session):
+                # Mapped task instances have a region, which their log address 
is read from.
+                assert (ti.region_id != SENTINEL_REGION_ID) == (ti.task_id == 
"mapped")
+                ti.state = TaskInstanceState.SCHEDULED
+        return dag_runs
+
+    @staticmethod
+    def _delete_dag_run(dr: DagRun) -> None:
+        with create_session(scoped=False) as other_session:
+            # Fail instead of hanging if the scheduler's transaction holds a 
lock this needs.
+            if get_dialect_name(other_session) == "postgresql":
+                other_session.execute(text("SET LOCAL lock_timeout = '5s'"))
+            other_session.execute(
+                delete(DagRun).where(DagRun.dag_id == dr.dag_id, DagRun.run_id 
== dr.run_id)
+            )
+
+    def _enqueued_task_instance_ids(self) -> set[UUID]:
+        assert self.null_exec is not None
+        return {
+            workload.ti.id
+            for workload in 
self.null_exec.executor_queues[WorkloadType.EXECUTE_TASK].values()
+            if isinstance(workload, ExecuteTask)
+        }
+
+    @mock.patch.object(
+        SchedulerJobRunner,
+        "_enqueue_workloads",
+        autospec=True,
+        wraps=SchedulerJobRunner._enqueue_workloads,
+    )
+    def test_task_instances_changed_after_they_are_queued_are_not_enqueued(
+        self, mock_enqueue, dag_maker, session
+    ):
+        deleted_run, kept_run = 
self._schedule_dag_runs_with_a_mapped_task(dag_maker, session)
+        job, other_job = Job(), Job()
+        session.add_all([job, other_job])
+        session.commit()
+        kept_tis = kept_run.get_task_instances(session=session)
+        marked_success = next(ti.id for ti in kept_tis if ti.task_id == 
"plain")
+        adopted, still_queued = sorted((ti.id for ti in kept_tis if ti.task_id 
== "mapped"), key=str)
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+
+        def change_the_batch_after_the_commit(*args, **kwargs):
+            self._delete_dag_run(deleted_run)
+            with create_session(scoped=False) as other_session:
+                other_session.execute(
+                    update(TaskInstance)
+                    .where(TaskInstance.id == marked_success)
+                    .values(state=TaskInstanceState.SUCCESS)
+                )
+                other_session.execute(
+                    update(TaskInstance)
+                    .where(TaskInstance.id == adopted)
+                    .values(queued_by_job_id=other_job.id)
+                )
+            return mock.DEFAULT
+
+        mock_enqueue.side_effect = change_the_batch_after_the_commit
+
+        assert self.job_runner._do_scheduling(session) == 1
+        assert self._enqueued_task_instance_ids() == {still_queued}
+
+    @mock.patch(
+        "airflow.jobs.scheduler_job_runner.prepare_task_log_contexts",
+        autospec=True,
+        wraps=prepare_task_log_contexts,
+    )
+    @pytest.mark.parametrize("num_deleted", [1, 2], ids=["one-run-deleted", 
"two-runs-deleted"])
+    def 
test_task_instances_deleted_while_their_workloads_are_built_are_not_enqueued(
+        self, mock_prepare, num_deleted, dag_maker, session
+    ):
+        *deleted_runs, kept_run = self._schedule_dag_runs_with_a_mapped_task(
+            dag_maker, session, num_runs=num_deleted + 1
+        )
+        job = Job()
+        session.add(job)
+        session.commit()
+        kept_ids = {ti.id for ti in 
kept_run.get_task_instances(session=session)}
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+
+        def delete_dag_runs_while_building(*args, **kwargs):
+            for dr in deleted_runs:
+                self._delete_dag_run(dr)
+            return mock.DEFAULT
+
+        mock_prepare.side_effect = delete_dag_runs_while_building
+
+        assert self.job_runner._do_scheduling(session) == len(kept_ids)
+        # The task instances without a region of the deleted Dag runs are 
dropped with the mapped ones.
+        assert self._enqueued_task_instance_ids() == kept_ids
+        assert mock_prepare.call_count == 1
+
+    @mock.patch(
+        "airflow.jobs.scheduler_job_runner.prepare_task_log_contexts",
+        autospec=True,
+        wraps=prepare_task_log_contexts,
+    )
+    def 
test_dag_deleted_while_workloads_are_built_with_a_pinned_bundle_version(
+        self, mock_prepare, dag_maker, session
+    ):
+        with dag_maker(dag_id="pinned_bundle", session=session):
+            EmptyOperator(task_id="t1")
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        (ti,) = dr.get_task_instances(session=session)
+        ti.state = TaskInstanceState.SCHEDULED
+        dr.bundle_version = "v1"
+        dr.created_dag_version.bundle_version = "v1"
+        dr.created_dag_version.version_data = {"manifest": "v1"}
+        job = Job()
+        session.add(job)
+        session.commit()
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+
+        def delete_dag_while_building(*args, **kwargs):
+            with create_session(scoped=False) as other_session:
+                delete_dag("pinned_bundle", session=other_session)
+            return mock.DEFAULT
+
+        mock_prepare.side_effect = delete_dag_while_building
+
+        # Everything ExecuteTask.make() reads was loaded with the batch, so 
building does not fail. The
+        # workload is sent, and the server rejects the start of the deleted 
task instance.
+        assert self.job_runner._do_scheduling(session) == 1
+        (workload,) = 
self.null_exec.executor_queues[WorkloadType.EXECUTE_TASK].values()
+        assert (workload.bundle_info.version, 
workload.bundle_info.version_data) == ("v1", {"manifest": "v1"})
+
+    @pytest.mark.parametrize(
+        "error",
+        [SystemExit(0), OperationalError("commit", params=None, 
orig=RuntimeError("connection lost"))],
+        ids=["shutdown", "connection-lost"],
+    )
+    def test_batch_is_not_put_back_after_its_final_commit(self, error, 
dag_maker, session):
+        with dag_maker(dag_id="fails_after_commit", session=session):
+            EmptyOperator(task_id="t1")
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        (ti,) = dr.get_task_instances(session=session)
+        ti.state = TaskInstanceState.SCHEDULED
+        job = Job()
+        session.add(job)
+        session.commit()
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+        queued_tis = 
self.job_runner._critical_section_queue_task_instances(session=session)
+        session.commit()
+        guard = mock.create_autospec(CommitProhibitorGuard, instance=True)
+
+        def commit_then_fail():
+            session.commit()
+            raise error
+
+        guard.commit.side_effect = commit_then_fail
+
+        with pytest.raises(type(error)):
+            self.job_runner._enqueue_workloads_or_reset(queued_tis, 
guard=guard, session=session)
+
+        assert dr.get_task_instance("t1", session=session).state == 
TaskInstanceState.QUEUED
+        assert len(self.null_exec.executor_queues[WorkloadType.EXECUTE_TASK]) 
== 1
+
+    @pytest.mark.backend("postgres", "mysql")
+    def test_enqueuing_does_not_wait_for_task_instance_row_locks(self, 
dag_maker, session):
+        with dag_maker(dag_id="locked_elsewhere", session=session):
+            EmptyOperator(task_id="t1")
+            EmptyOperator(task_id="t2")
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        for ti in dr.get_task_instances(session=session):
+            ti.state = TaskInstanceState.SCHEDULED
+        job = Job()
+        session.add(job)
+        session.commit()
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+        queued_tis = 
self.job_runner._critical_section_queue_task_instances(session=session)
+        session.commit()
+        mysql = get_dialect_name(session) == "mysql"
+
+        with create_session(scoped=False) as other_session:
+            # Another transaction holds the row lock of one task instance of 
the batch.
+            other_session.scalars(
+                select(TaskInstance.id).where(TaskInstance.id == 
queued_tis[0].id).with_for_update()
+            ).all()
+            # A wait would raise a lock error after a second instead of 
blocking the test.
+            if mysql:
+                session.execute(text("SET SESSION innodb_lock_wait_timeout = 
1"))
+            else:
+                session.execute(text("SET LOCAL lock_timeout = '1s'"))
+            try:
+                assert self.job_runner._enqueue_workloads(queued_tis, 
session=session) == 2
+            finally:
+                if mysql:
+                    session.execute(text("SET SESSION innodb_lock_wait_timeout 
= DEFAULT"))
+                session.rollback()
+                other_session.rollback()
+
+        assert self._enqueued_task_instance_ids() == {ti.id for ti in 
queued_tis}
+
+    @pytest.mark.backend("postgres", "mysql")
+    @mock.patch.object(ExecuteTask, "make", autospec=True, 
wraps=ExecuteTask.make)
+    def 
test_reset_skips_a_task_instance_locked_elsewhere_and_keeps_its_workload(
+        self, mock_make, dag_maker, session
+    ):
+        with dag_maker(dag_id="reset_locked_elsewhere", session=session):
+            EmptyOperator(task_id="t1", priority_weight=2)
+            EmptyOperator(task_id="t2", priority_weight=1)
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        for ti in dr.get_task_instances(session=session):
+            ti.state = TaskInstanceState.SCHEDULED
+        job = Job()
+        session.add(job)
+        session.commit()
+        t1_id = dr.get_task_instance("t1", session=session).id
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+
+        with create_session(scoped=False) as other_session:
+            # If the reset waited for the lock, this releases it after 10 s 
instead of blocking the test,
+            # and t1 would be reset too.
+            release = threading.Timer(10, other_session.rollback)
+
+            def lock_t1_then_fail(ti, **kwargs):
+                if ti.task_id == "t1":
+                    return mock.DEFAULT
+                # Another transaction holds t1 while the batch is reset.
+                other_session.scalars(
+                    select(TaskInstance.id).where(TaskInstance.id == 
t1_id).with_for_update()
+                ).all()
+                release.start()
+                raise RuntimeError("boom")
+
+            mock_make.side_effect = lock_t1_then_fail
+            try:
+                with pytest.raises(RuntimeError, match="boom"):
+                    self.job_runner._do_scheduling(session)
+            finally:
+                release.cancel()
+                other_session.rollback()
+                session.rollback()
+
+        assert {ti.task_id: ti.state for ti in 
dr.get_task_instances(session=session)} == {
+            "t1": TaskInstanceState.QUEUED,
+            "t2": TaskInstanceState.SCHEDULED,
+        }
+        # t1 is still QUEUED by this scheduler: its workload is kept, to be 
sent as usual.
+        assert self._enqueued_task_instance_ids() == {t1_id}
+
+    @pytest.mark.parametrize(
+        "pre_assigns", [False, True], ids=["executor-id-kept", 
"pre-assigned-id-cleared"]
+    )
+    def test_reset_task_instances_to_scheduled_leaves_the_ones_that_changed(
+        self, pre_assigns, dag_maker, session
+    ):
+        with dag_maker(dag_id="reset_queued", session=session):
+            EmptyOperator(task_id="unchanged")
+            EmptyOperator(task_id="running")
+            EmptyOperator(task_id="queued_by_other_job")
+        dr = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+        job, other_job = Job(), Job()
+        session.add_all([job, other_job])
+        session.flush()
+        tis = {ti.task_id: ti for ti in dr.get_task_instances(session=session)}
+        queued_dttm = timezone.utcnow()
+        for ti in tis.values():
+            ti.state = TaskInstanceState.QUEUED
+            ti.queued_dttm = queued_dttm
+            ti.queued_by_job_id = job.id
+            ti.external_executor_id = "executor-id"
+        tis["running"].state = TaskInstanceState.RUNNING
+        tis["queued_by_other_job"].queued_by_job_id = other_job.id
+        session.flush()
+        self.null_exec.pre_assigns_external_executor_id = pre_assigns
+        self.job_runner = SchedulerJobRunner(job=job, 
executors=[self.null_exec])
+
+        assert 
self.job_runner._reset_task_instances_to_scheduled(list(tis.values()), 
session=session) == {
+            tis["unchanged"].id
+        }
+
+        session.expire_all()
+        assert {
+            (ti.task_id, ti.state, ti.queued_by_job_id, ti.queued_dttm, 
ti.external_executor_id)
+            for ti in dr.get_task_instances(session=session)
+        } == {
+            ("unchanged", TaskInstanceState.SCHEDULED, None, None, None if 
pre_assigns else "executor-id"),
+            ("running", TaskInstanceState.RUNNING, job.id, queued_dttm, 
"executor-id"),
+            ("queued_by_other_job", TaskInstanceState.QUEUED, other_job.id, 
queued_dttm, "executor-id"),
+        }
+
     def test_execute_task_instances_limit_second_executor(self, dag_maker, 
mock_executors):
         dag_id = "SchedulerJobTest.test_execute_task_instances_limit"
         task_id_1 = "dummy_task"
@@ -4722,7 +5230,7 @@ class TestSchedulerJob:
             session.flush()
         scheduler_job.max_tis_per_query = 6
         # First pass we'll grab 6 of the 8 tasks (limited by max_tis_per_query)
-        res = self.job_runner._critical_section_enqueue_task_instances(session)
+        res = _queue_and_enqueue(self.job_runner, session)
         assert res == 6
         session.flush()
         for ti in tis1[:3] + tis2[:3]:
@@ -4733,7 +5241,7 @@ class TestSchedulerJob:
             assert ti.state == TaskInstanceState.SCHEDULED
 
         # The remaining TIs are queued
-        res = self.job_runner._critical_section_enqueue_task_instances(session)
+        res = _queue_and_enqueue(self.job_runner, session)
         assert res == 2
         session.flush()
 
@@ -4787,7 +5295,7 @@ class TestSchedulerJob:
             session.flush()
         scheduler_job.max_tis_per_query = 2
 
-        total_enqueued = 
self.job_runner._critical_section_enqueue_task_instances(session)
+        total_enqueued = _queue_and_enqueue(self.job_runner, session)
         assert total_enqueued == 2
 
     def test_execute_task_instances_limit_slots(self, dag_maker, 
mock_executors):
@@ -4832,12 +5340,12 @@ class TestSchedulerJob:
         # Check that we don't "overfill" an executor when the max tis per 
query is larger than slots
         # available. Of the 8 tasks returned by the query, the default 
executor will only take 2 and the
         # secondary executor will take 4 (since only 4 of the 8 TIs in the 
result will be for that executor)
-        res = self.job_runner._critical_section_enqueue_task_instances(session)
+        res = _queue_and_enqueue(self.job_runner, session)
         assert res == 6
 
         self.job_runner.executor.slots_available = 6  # The default executor 
has more slots freed now and
         # will take the other two TIs.
-        res = self.job_runner._critical_section_enqueue_task_instances(session)
+        res = _queue_and_enqueue(self.job_runner, session)
         assert res == 2
 
     def test_execute_task_instances_unlimited(self, dag_maker, mock_executor):
@@ -4875,7 +5383,7 @@ class TestSchedulerJob:
         self.job_runner.executor.parallelism = 32
         self.job_runner.executor.slots_available = 31
 
-        res = self.job_runner._critical_section_enqueue_task_instances(session)
+        res = _queue_and_enqueue(self.job_runner, session)
         # 20 dag runs * 2 tasks each = 40, but limited by number of slots 
available
         assert res == 31
         session.rollback()
@@ -4930,7 +5438,7 @@ class TestSchedulerJob:
             executor.slots_available = 31
 
         total_enqueued = 0
-        total_enqueued += 
self.job_runner._critical_section_enqueue_task_instances(session)
+        total_enqueued += _queue_and_enqueue(self.job_runner, session)
 
         if task1_exec != task2_exec:
             # Two executors will execute up to core parallelism
diff --git a/airflow-core/tests/unit/utils/log/test_task_log_address.py 
b/airflow-core/tests/unit/utils/log/test_task_log_address.py
index 22be06ddac9..ebfd7fc29a8 100644
--- a/airflow-core/tests/unit/utils/log/test_task_log_address.py
+++ b/airflow-core/tests/unit/utils/log/test_task_log_address.py
@@ -21,11 +21,12 @@ from unittest import mock
 from uuid import UUID, uuid4
 
 import pytest
-from sqlalchemy import event
+from sqlalchemy import delete, event
 
 from airflow.configuration import conf
 from airflow.models.dagbag import DBDagBag
-from airflow.models.dynamic_region import DynamicRegion
+from airflow.models.dagrun import DagRun
+from airflow.models.dynamic_region import SENTINEL_REGION_ID, DynamicRegion
 from airflow.models.taskinstance import TaskInstance
 from airflow.providers.standard.operators.empty import EmptyOperator
 from airflow.providers.standard.operators.python import PythonOperator
@@ -39,6 +40,8 @@ from airflow.utils.log.task_log_address import (
     region_log_position,
     render_task_log_filename,
 )
+from airflow.utils.session import create_session
+from airflow.utils.types import DagRunType
 
 from tests_common.test_utils.asserts import assert_queries_count
 
@@ -360,3 +363,33 @@ def 
test_log_context_falls_back_to_stored_regions_when_the_pinned_dag_lost_the_n
 
     assert context.log_position == "pass=2/map=0"
     assert context.map_index == 0
+
+
[email protected]_test
[email protected]("skip_missing_regions", [True, False])
+def test_log_contexts_of_a_dag_run_deleted_meanwhile(dag_maker, session, 
skip_missing_regions):
+    with dag_maker(serialized=True):
+        PythonOperator.partial(task_id="mapped", 
python_callable=str).expand(op_args=[[1], [2]])
+    deleted_run = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED)
+    kept_run = dag_maker.create_dagrun_after(deleted_run, 
run_type=DagRunType.SCHEDULED)
+    tis = []
+    for run in (deleted_run, kept_run):
+        run.task_instance_scheduling_decisions(session=session)
+        tis.extend(run.get_task_instances(session=session))
+    session.commit()
+    for ti in tis:
+        # Load what is read from the objects, as the scheduler does, before 
their rows are deleted.
+        assert ti.dag_run is not None
+        assert ti.region_id != SENTINEL_REGION_ID
+    session.expunge_all()
+    with create_session(scoped=False) as other_session:
+        other_session.execute(
+            delete(DagRun).where(DagRun.dag_id == deleted_run.dag_id, 
DagRun.run_id == deleted_run.run_id)
+        )
+
+    if skip_missing_regions:
+        contexts = prepare_task_log_contexts(tis, session=session, 
skip_missing_regions=True)
+        assert contexts.keys() == {ti.id for ti in tis if ti.run_id == 
kept_run.run_id}
+    else:
+        with pytest.raises(KeyError):
+            prepare_task_log_contexts(tis, session=session)
diff --git 
a/shared/observability/src/airflow_shared/observability/metrics/metrics_template.yaml
 
b/shared/observability/src/airflow_shared/observability/metrics/metrics_template.yaml
index c382da9b4d3..1d9a5e4a898 100644
--- 
a/shared/observability/src/airflow_shared/observability/metrics/metrics_template.yaml
+++ 
b/shared/observability/src/airflow_shared/observability/metrics/metrics_template.yaml
@@ -293,7 +293,7 @@ metrics:
 
   - name: "scheduler.critical_section_busy"
     description: "Count of times a scheduler process tried to get a lock on 
the critical
-    section (needed to send tasks to the executor) and found it locked by 
another process."
+    section (needed to move tasks to the queued state) and found it locked by 
another process."
     type: "counter"
     legacy_name: "-"
     name_variables: []

Reply via email to