dabla commented on code in PR #75659:
URL: https://github.com/apache/airflow/pull/75659#discussion_r4697038273


##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -1096,7 +1212,9 @@ def _select_task_instances_to_queue(
         stats.gauge("scheduler.tasks.starving", num_starving_tasks_total)
         stats.gauge("scheduler.tasks.executable", len(executable_tis))
 
-        return self._mark_task_instances_queued(executable_tis, 
session=session)
+        num_deferred_tis = self._defer_tis_to_triggerer(tis_to_defer, 
session=session)

Review Comment:
   **[warning]** The deferral adds several round trips per TI while the 
critical-section lock is held.
   
   For each TI to defer, `_defer_tis_to_triggerer` runs a `SAVEPOINT`, the 
`Trigger` `INSERT` with its own `flush()` (in `defer_task`), and a `RELEASE`. 
The TI's `UPDATE` comes on top at the commit. That's three or four round trips 
per TI, one TI after another, all before the commit that releases the pool rows 
and the advisory lock. With `max_tis_per_query` 512 and a batch of deferrable 
sensors, that is about 2,000 sequential round trips. At 0.5 ms each to a 
managed database, the lock is held for about a second.
   
   #77546 goes the other way: it moves the per-TI work of the batch (JWT 
signing, ~300 ms for 512 TIs) out of the critical section, so the other 
schedulers stop skipping their turn (`critical_section_duration` p50 −71%). 
This PR would add a comparable per-TI cost back inside it.
   
   The savepoints aren't needed for what they protect against. `DBAPIError` is 
re-raised anyway, so they only cover Python errors: a task not found, or the 
serde/Fernet encryption of the kwargs, which already happens when 
`Trigger(kwargs=...)` is constructed, before any SQL. If the Python part runs 
first, per TI inside the `try`, building the `Trigger` objects and the new TI 
values, the rows can then be written in bulk: one `add_all` + `flush()` 
(multi-row `INSERT ... RETURNING` on Postgres), then the TI updates. Measuring 
`critical_section_duration` with a batch of `start_from_trigger` tasks against 
`main` would show what this costs today.



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -782,24 +863,47 @@ def _select_task_instances_to_queue(
         pools: dict[str, PoolStats],
         starved_pools: set[str],
         *,
+        max_tis_to_queue: int | None = None,
         session: Session,
     ) -> list[TI]:
+        """Return the TIs that ``_select_task_instances_to_queue_or_defer`` 
moved to QUEUED state."""

Review Comment:
   **[nit]** `_select_task_instances_to_queue` no longer has a production 
caller, and its name hides that it also defers.
   
   The only caller in `airflow-core/src` is now 
`_select_task_instances_to_queue_or_defer`, from the critical section. The 
wrapper stays for the existing tests, but calling it also defers TIs and throws 
away the count, which its name and docstring ("Return the TIs ... moved to 
QUEUED state") don't say. Moving the tests to 
`_select_task_instances_to_queue_or_defer` and dropping the wrapper would avoid 
production code that only exists for tests.



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -197,6 +197,20 @@
 :meta private:
 """
 
+_DEFERRED_AT_START_FILTERS = (TI.start_from_trigger.is_(True), 
TI.next_method.is_(None))

Review Comment:
   **[nit]** One concept, four names.
   
   The column and the operator attribute are `start_from_trigger`, the helper 
in `taskinstance.py` is `is_started_from_trigger`, and here it's 
`_DEFERRED_AT_START_FILTERS`, `_is_deferred_at_start` and 
`only_deferred_at_start`, next to `_has_tis_to_defer` and 
`_defer_tis_to_triggerer`. A reader has to check whether "deferred at start" 
and "started from trigger" mean different things (they don't). One term 
throughout, ideally the user-facing `start_from_trigger`, would read better 
([Ubiquitous Language](https://martinfowler.com/bliki/UbiquitousLanguage.html)).



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -1405,18 +1533,27 @@ def _critical_section_enqueue_task_instances(self, 
session: Session) -> int:
         # we need to make sure in the scheduler now that we don't schedule 
more than core.parallelism totally
         # across all executors.
         num_occupied_slots = sum([executor.slots_occupied for executor in 
self.executors])
-        if self.job.max_tis_per_query == 0:
-            max_tis = self._parallelism - num_occupied_slots
-        else:
-            max_tis = min(self.job.max_tis_per_query, self._parallelism - 
num_occupied_slots)
+        max_tis = self.job.max_tis_per_query or self._parallelism

Review Comment:
   **[warning]** When any `start_from_trigger` TI is waiting, the selection 
under the lock fetches more rows and runs one more query, even if that TI can't 
be deferred.
   
   On `main`, `max_tis` is `min(max_tis_per_query, parallelism - occupied)`. 
Here, once `_has_tis_to_defer` finds a single deferrable TI anywhere (blocked 
by its pool or not), `max_tis` stays at `max_tis_per_query`, while 
`max_tis_to_queue` keeps the executor limit. With `max_tis_per_query` 512 and 2 
free executor slots:
   
   1. The first selection query fetches and row-locks up to 512 TIs instead of 
2. With #77545 that is `max_tis * CANDIDATE_BATCHES` = 2,048 candidates joined 
back to `task_instance` instead of 8. The extra rows that can't be queued are 
dropped with `continue`.
   2. `found_new_filters` is then forced to `True` (`not only_deferred_at_start 
and len(executable_tis) >= max_tis_to_queue`), so the loop runs a second 
selection query, filtered to deferrable TIs. That query takes the same path 
#77545 measured at 954 ms on `main` with 70k waiting (122 ms with #77545). 
After #77548, each refill that brings new Dags with task-level limits also runs 
a per-task count query.
   
   Both costs come on every loop while the deferrable TI stays blocked, and 
only one scheduler can be in the critical section at a time. One way around 
both: keep the regular query at `max_tis_to_queue` as on `main`, and select the 
deferrable TIs with their own query, limited to `max_tis - max_tis_to_queue`. 
That query would run only when `_has_tis_to_defer` is true, and would be cheap 
with the partial index from [2].



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -642,6 +656,73 @@ def _debug_dump(self, signum: int, frame: FrameType | 
None) -> None:
             self.log.info("\n\t".join(map(repr, callstack)))
             self.log.info("-" * 80)
 
+    def _has_tis_to_defer(self, *, session: Session) -> bool:
+        """Return whether a SCHEDULED TI waits for the scheduler to defer it 
to the triggerer."""
+        query = (
+            select(TI.id)
+            .join(TI.dag_run)
+            .join(TI.dag_model)
+            .where(
+                TI.state == TaskInstanceState.SCHEDULED,
+                *_DEFERRED_AT_START_FILTERS,
+                DR.state == DagRunState.RUNNING,
+                ~DM.is_paused,
+            )
+            .limit(1)
+        )
+        return session.scalar(query) is not None
+
+    def _defer_tis_to_triggerer(self, task_instances: Collection[TI], *, 
session: Session) -> int:
+        """
+        Defer the selected TIs whose task has ``start_from_trigger`` to the 
triggerer.
+
+        This runs in the critical section, so a TI that fails to defer is 
logged and stays SCHEDULED
+        instead of failing the critical section for every Dag.
+
+        :return: Number of TIs deferred.
+
+        :meta private:
+        """
+        if not task_instances:
+            return 0
+        num_deferred = 0
+        serialized_dags: dict[tuple[str, str], SerializedDAG | None] = {}
+        team_names = (
+            self._get_team_names_for_dag_ids({ti.dag_id for ti in 
task_instances}, session)
+            if self._multi_team
+            else {}
+        )
+        for task_instance in task_instances:
+            dag_run_key = (task_instance.dag_id, task_instance.run_id)
+            try:
+                with session.begin_nested():
+                    if dag_run_key not in serialized_dags:
+                        serialized_dags[dag_run_key] = 
self.scheduler_dag_bag.get_dag_for_run(
+                            dag_run=task_instance.dag_run, session=session
+                        )
+                    serialized_dag = serialized_dags[dag_run_key]
+                    if not serialized_dag or not 
serialized_dag.has_task(task_instance.task_id):
+                        self.log.warning(
+                            "Cannot find the task of %s to defer it to the 
triggerer, it stays scheduled",
+                            task_instance,
+                        )
+                        continue
+                    task = serialized_dag.get_task(task_instance.task_id)
+                    if not is_started_from_trigger(task):
+                        # The run moved to a Dag version where the task no 
longer starts from the triggerer.
+                        task_instance.start_from_trigger = False
+                        continue
+                    task_instance.task = task
+                    task_instance.defer_task(
+                        team_name=team_names.get(task_instance.dag_id, 
NOTSET), session=session
+                    )
+                    num_deferred += 1
+            except DBAPIError:
+                raise
+            except Exception:
+                self.log.exception("Failed to defer %s to the triggerer, it 
stays scheduled", task_instance)

Review Comment:
   **[warning]** A TI that can never be deferred stays SCHEDULED forever and 
holds a pool slot in every loop.
   
   The savepoint fixes the crash loop, thanks. But the TI is left SCHEDULED, so 
the next loop selects it again. In the selection loop it has already taken its 
pool slot (`open_slots -= task_instance.pool_slots`) and its `max_active_tasks` 
slot before `_defer_tis_to_triggerer` fails. If it has the highest priority in 
a pool with one slot, no other task in that pool is ever selected, and the 
scheduler logs the same traceback every loop. The "Cannot find the task" branch 
above has the same effect.
   
   On `main`, a failing `defer_task()` left the TI out of SCHEDULED, so it 
never touched pool accounting. For a missing Dag, 
`_task_concurrency_allows_execution` already fails the scheduled TIs instead of 
leaving them. Failing the TI here too (or sending it to `UP_FOR_RETRY` through 
the normal failure path) would turn a permanent error into a visible task 
failure instead of a stuck pool. That would change 
`test_defer_tis_to_triggerer_keeps_a_failed_ti_scheduled` accordingly.



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -642,6 +656,73 @@ def _debug_dump(self, signum: int, frame: FrameType | 
None) -> None:
             self.log.info("\n\t".join(map(repr, callstack)))
             self.log.info("-" * 80)
 
+    def _has_tis_to_defer(self, *, session: Session) -> bool:

Review Comment:
   **[warning]** This probe runs on every loop when executors are saturated, 
and with a SCHEDULED backlog its `LIMIT 1` can't stop early.
   
   It runs from `_do_scheduling` whenever all executors are full, and from 
`_critical_section_enqueue_task_instances` whenever executor capacity is below 
`max_tis_per_query`. Both happen exactly when there is a backlog. On `main`, a 
full executor skipped the critical section with no query at all.
   
   The only usable index is `ti_state`. When no row matches (the common case: 
no `start_from_trigger` tasks waiting), the database walks every SCHEDULED TI 
and joins each one to `dag_run` and `dag` before it can answer "none". With 
tens of thousands of SCHEDULED TIs, that's an extra full scan per loop.
   
   A second effect: the probe ignores pools and concurrency. When the only 
deferrable TIs are blocked by a full pool or `max_active_tis_per_dag`, every 
loop with full executors still takes the critical-section lock and runs the 
selection queries, only to defer nothing.
   
   This is the same backlog that #77545 measures: ranking the 70,000 waiting 
TIs costs 954 ms per loop on PostgreSQL 14 for the selection query. The probe 
does a lighter version of that work (ids only, no window function), but it does 
it on top, on every saturated loop.
   
   Could you share `scheduler.critical_section_duration` and loop-time numbers 
with a large SCHEDULED backlog and full executors, with and without the change? 
The scenario of #77545 (70k waiting, several schedulers) would make the numbers 
comparable. If the scan shows up, a partial index on Postgres (for example 
`(state) WHERE start_from_trigger`) would let the probe stop at the first row. 
A partial index only gets entries for rows that match its predicate, so it 
doesn't add write cost to ordinary TIs, and it doesn't touch 
`last_heartbeat_at`. Heartbeats would stay HOT updates, which is what #77547 is 
after.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to