vincbeck opened a new pull request, #77545:
URL: https://github.com/apache/airflow/pull/77545

   Each scheduler loop picks the next task instances to queue with a selection 
query, inside the critical section that
   only one scheduler can hold at a time (the refill loop re-runs it, up to 
`MAX_TI_REFILL_QUERIES_PER_LOOP` more times
   once some task instances are selected, to skip blocked candidates). The 
query ranked every SCHEDULED task instance
   with **all of its columns** (a window function for `max_active_tasks` per 
Dag run, then the priority order) and
   applied the batch size `max_tis` only on the outer query, after joining back 
to `task_instance`. `max_tis` is the
   smallest of `[scheduler] max_tis_per_query` (default 16; 0 means no limit of 
its own), the free `[core] parallelism`
   and the free pool slots. With tens of thousands of task instances waiting, 
every loop carried all of their full rows
   through the sorts (three on PostgreSQL), whatever `max_tis`.
   
   This PR ranks only the ids, ordering and window columns, keeps `max_tis * 
CANDIDATE_BATCHES` candidates (4 batches)
   in a `candidates` subquery, and only then joins back to `task_instance` for 
the full rows. The outer query keeps the
   same ORDER BY, `LIMIT max_tis`, eager loads and the caller's row locks (`FOR 
NO KEY UPDATE OF task_instance SKIP
   LOCKED` on PostgreSQL); its `row_num <= max_active_tasks` filter moved into 
the `candidates` subquery. The filters,
   the per-Dag-run window, the ordering (`-priority_weight`, `logical_date`, 
`region_index`) and the starvation and
   refill logic are unchanged, apart from the per-Dag-run cap described below. 
Ties between task instances of the same
   priority, logical date and region index are broken arbitrarily, in both 
versions. The caller's check from #77247,
   which drops locked rows that are no longer SCHEDULED, is unchanged: it still 
reads the state of the locked
   `task_instance` row of the outer query.
   
   The ORDER BY of the ranking subquery was dropped: it had no effect on the 
result (no LIMIT there, and the window
   function has its own ORDER BY), but it cost a full sort of the ranked rows 
(27.5 MB on disk on PostgreSQL, a Sort
   under Materialize on MySQL). The new `candidates` subquery orders by the 
same keys because its LIMIT depends on them.
   It is joined as a derived table rather than used as `TI.id IN (SELECT ... 
LIMIT n)`, because MySQL rejects LIMIT in
   an IN subquery (error 1235), and the join carries the ordering columns the 
outer ORDER BY needs. The rows are not
   locked inside the ranking subquery either: PostgreSQL rejects `FOR UPDATE` / 
`FOR NO KEY UPDATE` with window
   functions.
   
   ### Rows locked by other transactions
   
   A candidate that another transaction holds locked (the UI marking a Dag run 
failed, another scheduler timing out a
   Dag run) is skipped by `SKIP LOCKED`. On `main` the next candidate takes its 
place, because the LIMIT comes after the
   locks. With this PR:
   
   - the `candidates` subquery keeps 3 spare batches, so up to `3 * max_tis` 
locked candidates spread over several Dag
     runs are replaced;
   - no Dag run takes more than half of the candidates (`2 * max_tis`), so one 
whose rows are all locked (for example a
     mapped task with hundreds of instances being marked failed) leaves the 
batch to the others, and up to `max_tis`
     locked rows at the top of a Dag run are replaced from that Dag run;
   - beyond that, while the locks are held, a loop can queue fewer task 
instances than on `main`, or lower-priority
     ones first. For example, with `max_tis=1`, Dag run A with `a1` to `a5` at 
priorities 10 to 6, `a1` and `a2`
     locked, and Dag run B with `b1` at priority 1: `main` returns `a3`, this 
PR returns `b1`.
   
   When no row is locked, the result is the same as on `main`: a Dag run never 
has more than `max_tis` rows in it.
   
   <details><summary>Exact conditions, the choice of 4 and of half, and other 
lock holders</summary>
   
   For the effective `max_tis`, a loop queues fewer task instances than on 
`main` only when fewer than `max_tis` of the
   kept candidates are unlocked: for example when more than `3 * max_tis` of 
them are locked across Dag runs (two
   large Dag runs, both ranked above everything else, marked at the same 
moment), or when a single Dag run has
   candidates and more than `max_tis` of its top ones are locked. It then 
queues what it can, and later loops pick up the
   rest once those transactions commit. The selection differs from `main`'s (as 
in the example) when rows of a partly
   locked Dag run beyond its first `2 * max_tis` would have been next.
   
   The cap at half trades two cases: a larger cap keeps more rows of a partly 
locked Dag run (closer to `main` there) but
   lets one fully locked Dag run crowd out the others; a smaller one does the 
reverse. Half covers one fully locked Dag
   run and up to `max_tis` locked rows at the top of a Dag run. The cap is per 
Dag run, not per Dag: `set_state` with
   past or future, and bulk clears, lock rows in several runs of one Dag, and 
two such Dag runs ranked above everything
   else can still fill the candidates while those requests run. Long-lived lock 
holders (a bulk clear, `set_state`
   across many Dag runs in `api/common/mark_tasks.py`) behave the same for as 
long as they hold the locks, where `main`
   skipped past them.
   
   Why 4: one batch to select and 3 spares; with the cap at half, one fully 
locked Dag run still leaves 2 batches to the
   others. It was chosen from that reasoning, not tuned against 2 or 8. A 
larger value joins and sorts more full rows on
   every selection. `CANDIDATE_BATCHES` must be at least 2, or the per-Dag-run 
cap would be smaller than a batch and
   change selections without locked rows. It is a module constant, like 
`MAX_TI_REFILL_QUERIES_PER_LOOP`, not a setting.
   With `max_tis_per_query=0`, the subquery keeps `4 * min(free parallelism, 
free pool slots)` rows: still bounded, and
   never more than `main` joined, which was every candidate. With `[scheduler] 
use_row_level_locking = False` nothing is
   locked, so the spare batches are only a small overhead (3 extra batches of 
full rows joined and sorted).
   
   A short batch is not logged or counted; that would come with the fallback 
below.
   
   </details>
   
   ### Locking behaviour
   
   - PostgreSQL: only the returned rows are locked, on `main` and with this PR 
(plans below).
   - MySQL 8: at 70,000 waiting task instances, both versions sort the 
candidates first and join back only the rows they
     return, so both lock exactly `max_tis` rows (512 and 16, counted in 
`performance_schema.data_locks`). The same at
     1,000, 5,000 and 10,000 waiting: 512 and 16 rows locked in both versions. 
On very small tables the optimizer can
     instead scan `task_instance` first and lock every row it reads; that 
happens on `main` and with this PR alike (seen
     with 200 waiting task instances), and this PR does not change it.
   - MariaDB is not a supported backend (`installation/prerequisites.rst`) and 
was not tested; `with_row_locks` does not
     lock rows there.
   
   ### Measurements
   
   The measurements and benchmarks below were taken against `main` at 
bada0686ef. #77247, merged since, only adds the
   locked row's state to the outer query's columns.
   
   The query alone, 70,000 SCHEDULED and 200,000 finished task instances (100 
Dags, 7 running Dag runs each, 100 tasks
   per Dag), local containers (PostgreSQL 14 with the default configuration, 
`work_mem` 4 MB, psycopg 3; MySQL 8.0),
   warm cache, query time (median of 5); sorts and buffers from `EXPLAIN 
(ANALYZE, BUFFERS)`.
   
   | | `main` | `main` without the ranking ORDER BY | Narrow ranking, no 
`candidates` LIMIT | This PR |
   |---|---|---|---|---|
   | PostgreSQL, `max_tis=512` | 954 ms, 3 sorts on disk (76 + 28 + 26 MB), 
494,669 buffers | 853 ms, 2 sorts on disk | 620 ms, 2 sorts on disk (52 + 6.5 
MB) | 122 ms, 1 sort on disk (6.5 MB: ids, ordering and window columns), 19,005 
buffers |
   | PostgreSQL, `max_tis=16` (default) | 930 ms | 835 ms | 598 ms | 94 ms, 
4,125 buffers |
   | MySQL 8, `max_tis=512` | 1,223 ms | 974 ms | 316 ms | 296 ms |
   | MySQL 8, `max_tis=16` (default) | 986 ms | 774 ms | 276 ms | 256 ms |
   
   The third column answers "why not only narrow the ranking?": it ranks ids 
and ordering columns like this PR but keeps
   `main`'s join of every candidate and outer ORDER BY / LIMIT / `SKIP LOCKED`, 
so it locks exactly as `main` does.
   On MySQL it is about as fast as this PR, because MySQL sorts the narrow 
derived table first and joins back only the
   rows it returns. On PostgreSQL it is still 5 to 6 times slower than this PR: 
without the `candidates` LIMIT, the
   outer query joins every candidate back and sorts their full rows below 
LockRows (52 MB on disk), so the LIMIT is what
   makes the change pay off there.
   
   Middle and small backlogs, `max_tis=16`: on MySQL, 15 ms on `main` and 7 ms 
with this PR at 1,000 waiting, 56 and
   21 ms at 5,000, 108 and 40 ms at 10,000 (query time). At 100 waiting 
(`EXPLAIN ANALYZE` execution time): PostgreSQL
   1.98 ms on `main` and 1.68 ms with this PR (`max_tis=512`), 1.37 and 0.76 ms 
(16); MySQL 1.62 and 0.84 ms (512),
   1.32 and 0.59 ms (16).
   
   Prepared statements: psycopg 3 prepares a statement server-side after 5 
executions on a connection. With the
   default `plan_cache_mode = auto`, PostgreSQL keeps custom plans for this 
query (checked after 7 executions, on `main`
   and with this PR). A forced generic plan keeps the same join back to 
`task_instance` (nested loop on its primary key)
   and is slower on both, because the state filters become parameters: 1.24 s 
on `main`, 0.21 to 0.23 s with this PR.
   
   ### Benchmarks
   
   On AWS: schedulers on one c7g.8xlarge, RDS PostgreSQL 14.24 (db.m6g.xlarge) 
in the same zone, 100 Dags of 100
   tasks, `max_tis_per_query` 512.
   
   **4 schedulers, a burst of 70,000 task instances.** A test executor whose 
fleet process does the workers' database
   writes (start, heartbeats every 5 s). 7 running Dag runs per Dag (70,000 
task instances started at once) and 50
   finished ones (500,000 task instances), one pool of 1,000,000 slots, 
`parallelism` 200,000. Each run stops once all
   70,000 run; two interleaved runs each. This ran an earlier revision of this 
PR, which differs from this one only in
   comments and a guard that has no effect at the default `CANDIDATE_BATCHES`.
   
   | | `main` | This PR |
   |---|---:|---:|
   | All 70,000 running after | 262.0 s | **158.8 s** |
   | Queue rate | 273 TIs/s | 459 TIs/s |
   | `critical_section_duration` p50 / p95 | 1,408 / 1,986 ms | 838 / 1,221 ms |
   | `critical_section_busy` per run | 1,138 | 618 |
   | Scheduler loop p50 / p95 | 418 / 1,942 ms | 457 / 1,622 ms |
   | RDS CPU, average | 54 % | 52 % |
   
   With a large backlog and several schedulers, the shorter critical section 
starts the 70,000 tasks 39 % faster.
   
   **2 schedulers, real `AwsEcsExecutor` on Fargate.** 10,000 task instances (1 
running Dag run per Dag) of 120 to
   360 s each, and 50 finished Dag runs per Dag (500,000 task instances). A 
2,000-slot pool, `parallelism` 1,000 per
   scheduler. One run of this PR; `main` ran before and after it.
   
   | | `main` (2 runs) | This PR |
   |---|---:|---:|
   | Selection query (`critical_section_query_duration`) p50 / p95 | 4.9 / 
141-143 ms | 4.7 / **30 ms** |
   | `critical_section_duration` p50 / p95 | 12 / 175-176 ms | 11 / **60 ms** |
   | `critical_section_busy` per run | 39-45 | 32 |
   | All 10,000 / 99 % succeeded | 1,816-1,833 / 1,732-1,747 s | 1,831 / 1,730 
s |
   
   The selection query's p95 drops by 79 % and the critical section's by 66 %. 
The p95 comes from the first wave, when
   2,000 task instances are selected at once; after it, each loop selects only 
the few whose slots just freed, so the
   p50 does not change. End to end, the run takes as long: the task durations 
and Fargate start-up set it, and each
   scheduler loop (about 5 s) is mostly the ECS executor's sync (about 4.5 s).
   
   Earlier, on a laptop on `main` of 2026-10-22 (PostgreSQL 14 limited to 4 
CPUs, 70,000 task instances waiting,
   `max_tis_per_query=512`): starting 70,000 tasks with one scheduler took 328 
s on `main` and 129 s with this change.
   
   **Celery executor on a laptop.** A MacBook (Apple M1 Pro), PostgreSQL 17 in 
a container limited to 4 CPUs, the real
   `CeleryExecutor` (Redis broker, database result backend) and Celery workers 
whose task does the workers' database
   writes. On macOS `[celery] sync_parallelism` is 1, so each scheduler sends 
one task at a time, which limits the
   4-scheduler runs. 100 Dags of 100 tasks, 500,000 finished task instances, 
tasks that never finish; each run stops once
   all waiting task instances run. Two interleaved runs per variant (mean, 
range in parentheses); no task instance was
   queued twice in any run.
   
   | Schedulers, `max_tis_per_query`, task instances waiting | | All running 
after | Selection query p50 | `critical_section_duration` p50 / p95 |
   |---|---|---:|---:|---:|
   | 1, 512, 70,000 | `main` | 618 s (603-634) | 406 ms | 697 / 9,082 ms |
   | | This PR | **444 s** (443-445) | 96 ms | 367 / 520 ms |
   | 4, 512, 70,000 | `main` | 234 s (228-239) | 479 ms | 367 / 1,057 ms |
   | | This PR | **188 s** (186-189) | 120 ms | 41 / 761 ms |
   | 4, 16 (the default), 10,000 | `main` | 891 s (881-900) | 1,278 ms | 1,316 
/ 1,770 ms |
   | | This PR | **123 s** (122-125) | 32 ms | 71 / 168 ms |
   
   Faster in every cell: 28 % with one scheduler, 20 % with four, and 7.2 times 
faster at the default `max_tis_per_query`
   of 16, where `main`'s selection query takes over a second to return 16 rows.
   
   ### Considered and left out
   
   - A fallback that re-runs the current full-join query once when the batch 
comes back short while more candidates
     exist (with `count(*) OVER ()` from the ranking): it would remove the 
locked-row cases above, at the cost of a
     second query shape in the critical section, and is where a debug log or 
counter for short batches would go.
     Possible follow-up.
   - The window function still sorts the narrow rows (ids, ordering and window 
columns) of every waiting task instance:
     the 6.5 MB on-disk sort above. A per-Dag-run top-N (for example a LATERAL 
join on PostgreSQL) could avoid it.
     Possible follow-up.
   
   ### Query plans
   
   70,000 waiting task instances, `max_tis=512`, the database of "Measurements" 
above.
   
   <details><summary>PostgreSQL 14, main, max_tis=512 (512 rows in 954 ms 
(median of 5))</summary>
   
   ```
   Limit  (cost=38906.08..38912.48 rows=512 width=7243) (actual 
time=995.567..996.696 rows=512 loops=1)
     Buffers: shared hit=494669, temp read=13142 written=22310
     ->  LockRows  (cost=38906.08..38931.29 rows=2017 width=7243) (actual 
time=995.566..996.661 rows=512 loops=1)
           Buffers: shared hit=494669, temp read=13142 written=22310
           ->  Sort  (cost=38906.08..38911.12 rows=2017 width=7243) (actual 
time=995.532..996.302 rows=512 loops=1)
                 Sort Key: ((- anon_1.priority_weight_for_ordering)), 
anon_1.logical_date_for_ordering, anon_1.region_index_for_ordering
                 Sort Method: external merge  Disk: 75968kB
                 Buffers: shared hit=493645, temp read=13142 written=22310
                 ->  Nested Loop  (cost=24010.41..38805.23 rows=2017 
width=7243) (actual time=301.257..705.659 rows=70000 loops=1)
                       Buffers: shared hit=493645, temp read=6686 written=6704
                       ->  Nested Loop  (cost=24010.13..38187.94 rows=2017 
width=5376) (actual time=301.238..510.840 rows=70000 loops=1)
                             Buffers: shared hit=283645, temp read=6686 
written=6704
                             ->  Subquery Scan on anon_1  
(cost=24009.71..24100.46 rows=2017 width=2731) (actual time=301.211..418.537 
rows=70000 loops=1)
                                   Filter: (anon_1.dr_max_active_tasks >= 
anon_1.row_num)
                                   Buffers: shared hit=3645, temp read=6686 
written=6704
                                   ->  Sort  (cost=24009.71..24024.84 rows=6050 
width=2687) (actual time=301.192..367.675 rows=70000 loops=1)
                                         Sort Key: ((- 
task_instance_1.priority_weight)), dag_run.logical_date, 
task_instance_1.region_index
                                         Sort Method: external merge  Disk: 
27576kB
                                         Buffers: shared hit=3645, temp 
read=6686 written=6704
                                         ->  WindowAgg  
(cost=16437.69..16619.19 rows=6050 width=2687) (actual time=119.931..192.756 
rows=70000 loops=1)
                                               Buffers: shared hit=3645, temp 
read=3239 written=3248
                                               ->  Sort  
(cost=16437.69..16452.81 rows=6050 width=2671) (actual time=119.874..149.640 
rows=70000 loops=1)
                                                     Sort Key: 
task_instance_1.dag_id, task_instance_1.run_id, ((- 
task_instance_1.priority_weight)), dag_run.logical_date, 
task_instance_1.region_index
                                                     Sort Method: external 
merge  Disk: 25912kB
                                                     Buffers: shared hit=3645, 
temp read=3239 written=3248
                                                     ->  Hash Join  
(cost=250.85..9085.67 rows=6050 width=2671) (actual time=0.884..59.103 
rows=70000 loops=1)
                                                           Hash Cond: 
((dag_run.dag_id)::text = (dag.dag_id)::text)
                                                           Join Filter: 
(COALESCE((count('*')), '0'::bigint) < dag.max_active_tasks)
                                                           Buffers: shared 
hit=3645
                                                           ->  Hash Left Join  
(cost=241.60..9012.83 rows=18149 width=2682) (actual time=0.821..45.898 
rows=70000 loops=1)
                                                                 Hash Cond: 
(((task_instance_1.dag_id)::text = (task_instance_2.dag_id)::text) AND 
((task_instance_1.run_id)::text = (task_instance_2.run_i
                                                                 Buffers: 
shared hit=3638
                                                                 ->  Hash Join  
(cost=232.67..8908.54 rows=18149 width=2674) (actual time=0.802..34.522 
rows=70000 loops=1)
                                                                       Hash 
Cond: (((task_instance_1.dag_id)::text = (dag_run.dag_id)::text) AND 
((task_instance_1.run_id)::text = (dag_run.run_id)::text))
                                                                       Buffers: 
shared hit=3632
                                                                       ->  
Index Scan using ti_state on task_instance task_instance_1  (cost=0.42..8308.46 
rows=70002 width=2655) (actual time=0.014..10.00
                                                                             
Index Cond: ((state)::text = 'scheduled'::text)
                                                                             
Buffers: shared hit=3444
                                                                       ->  Hash 
 (cost=221.75..221.75 rows=700 width=53) (actual time=0.780..0.781 rows=700 
loops=1)
                                                                             
Buckets: 1024  Batches: 1  Memory Usage: 66kB
   ```
   </details>
   
   <details><summary>PostgreSQL 14, this PR, max_tis=512 (512 rows in 122 ms 
(median of 5))</summary>
   
   ```
   Limit  (cost=15284.48..15290.88 rows=512 width=4600) (actual 
time=146.373..146.807 rows=512 loops=1)
     Buffers: shared hit=19005, temp read=807 written=809
     ->  LockRows  (cost=15284.48..15292.88 rows=672 width=4600) (actual 
time=146.372..146.766 rows=512 loops=1)
           Buffers: shared hit=19005, temp read=807 written=809
           ->  Sort  (cost=15284.48..15286.16 rows=672 width=4600) (actual 
time=146.352..146.382 rows=512 loops=1)
                 Sort Key: ((- candidates.priority_weight_for_ordering)), 
candidates.logical_date_for_ordering, candidates.region_index_for_ordering
                 Sort Method: quicksort  Memory: 2173kB
                 Buffers: shared hit=17981, temp read=807 written=809
                 ->  Nested Loop  (cost=9771.88..15252.93 rows=672 width=4600) 
(actual time=133.932..143.103 rows=2048 loops=1)
                       Buffers: shared hit=17981, temp read=807 written=809
                       ->  Nested Loop  (cost=9771.60..15047.26 rows=672 
width=2733) (actual time=133.916..137.455 rows=2048 loops=1)
                             Buffers: shared hit=11837, temp read=807 
written=809
                             ->  Subquery Scan on candidates  
(cost=9771.18..9779.58 rows=672 width=88) (actual time=133.884..134.502 
rows=2048 loops=1)
                                   Buffers: shared hit=3645, temp read=807 
written=809
                                   ->  Limit  (cost=9771.18..9772.86 rows=672 
width=36) (actual time=133.876..134.125 rows=2048 loops=1)
                                         Buffers: shared hit=3645, temp 
read=807 written=809
                                         ->  Sort  (cost=9771.18..9772.86 
rows=672 width=36) (actual time=133.875..133.987 rows=2048 loops=1)
                                               Sort Key: ((- 
anon_1.priority_weight_for_ordering)), anon_1.logical_date_for_ordering, 
anon_1.region_index_for_ordering
                                               Sort Method: top-N heapsort  
Memory: 446kB
                                               Buffers: shared hit=3645, temp 
read=807 written=809
                                               ->  Subquery Scan on anon_1  
(cost=9465.69..9739.62 rows=672 width=36) (actual time=86.343..125.522 
rows=70000 loops=1)
                                                     Filter: 
((anon_1.dr_max_active_tasks >= anon_1.row_num) AND (anon_1.row_num <= 1024))
                                                     Buffers: shared hit=3645, 
temp read=807 written=809
                                                     ->  WindowAgg  
(cost=9465.69..9647.19 rows=6050 width=93) (actual time=86.341..118.618 
rows=70000 loops=1)
                                                           Buffers: shared 
hit=3645, temp read=807 written=809
                                                           ->  Sort  
(cost=9465.69..9480.81 rows=6050 width=85) (actual time=86.302..97.750 
rows=70000 loops=1)
                                                                 Sort Key: 
task_instance_1.dag_id, task_instance_1.run_id, ((- 
task_instance_1.priority_weight)), dag_run.logical_date, task_instance_1.reg
                                                                 Sort Method: 
external merge  Disk: 6456kB
                                                                 Buffers: 
shared hit=3645, temp read=807 written=809
                                                                 ->  Hash Join  
(cost=250.85..9085.67 rows=6050 width=85) (actual time=0.826..49.690 rows=70000 
loops=1)
                                                                       Hash 
Cond: ((dag_run.dag_id)::text = (dag.dag_id)::text)
                                                                       Join 
Filter: (COALESCE((count('*')), '0'::bigint) < dag.max_active_tasks)
                                                                       Buffers: 
shared hit=3645
                                                                       ->  Hash 
Left Join  (cost=241.60..9012.83 rows=18149 width=96) (actual 
time=0.780..38.637 rows=70000 loops=1)
                                                                             
Hash Cond: (((task_instance_1.dag_id)::text = (task_instance_2.dag_id)::text) 
AND ((task_instance_1.run_id)::text = (task_inst
                                                                             
Buffers: shared hit=3638
                                                                             -> 
 Hash Join  (cost=232.67..8908.54 rows=18149 width=88) (actual 
time=0.767..29.445 rows=70000 loops=1)
                                                                                
   Hash Cond: (((task_instance_1.dag_id)::text = (dag_run.dag_id)::text) AND 
((task_instance_1.run_id)::text = (dag_run.run
                                                                                
   Buffers: shared hit=3632
                                                                                
   ->  Index Scan using ti_state on task_instance task_instance_1  
(cost=0.42..8308.46 rows=70002 width=69) (actual time=0.
   ```
   </details>
   
   <details><summary>MySQL 8.0, main, max_tis=512 (512 rows in 1223 ms (median 
of 5), 512 task_instance rows locked)</summary>
   
   ```
   -> Limit: 512 row(s)  (cost=144 rows=0) (actual time=1346..1347 rows=512 
loops=1)
       -> Nested loop inner join  (cost=144 rows=0) (actual time=1346..1347 
rows=512 loops=1)
           -> Nested loop inner join  (cost=65.9 rows=0) (actual 
time=1346..1347 rows=512 loops=1)
               -> Sort: -(anon_1.priority_weight_for_ordering), 
anon_1.logical_date_for_ordering, anon_1.region_index_for_ordering  
(cost=2.6..2.6 rows=0) (actual time=1345..1346 rows=512 loops=1)
                   -> Filter: (anon_1.dr_max_active_tasks >= anon_1.row_num)  
(cost=2.5..2.5 rows=0) (actual time=1220..1287 rows=70000 loops=1)
                       -> Table scan on anon_1  (cost=2.5..2.5 rows=0) (actual 
time=1220..1283 rows=70000 loops=1)
                           -> Materialize  (cost=0..0 rows=0) (actual 
time=1220..1220 rows=70000 loops=1)
                               -> Sort: `-(task_instance.priority_weight)`, 
dag_run.logical_date, task_instance.region_index  (actual time=1045..1069 
rows=70000 loops=1)
                                   -> Table scan on <temporary>  (cost=2.5..2.5 
rows=0) (actual time=918..982 rows=70000 loops=1)
                                       -> Temporary table  (cost=0..0 rows=0) 
(actual time=918..918 rows=70000 loops=1)
                                           -> Window aggregate: row_number() 
OVER (PARTITION BY task_instance.dag_id,task_instance.run_id ORDER BY 
`-(task_instance.priority_weight)`,dag_run.logical_date,
                                               -> Sort: task_instance.dag_id, 
task_instance.run_id, `-(task_instance.priority_weight)`, dag_run.logical_date, 
task_instance.region_index  (actual time=721.
                                                   -> Stream results  
(cost=58.9 rows=0) (actual time=281..580 rows=70000 loops=1)
                                                       -> Filter: 
(coalesce(anon_2.task_per_dr_count,0) < dag.max_active_tasks)  (cost=58.9 
rows=0) (actual time=281..482 rows=70000 loops=1)
                                                           -> Left hash join 
(anon_2.run_id = task_instance.run_id), (anon_2.dag_id = dag.dag_id)  
(cost=58.9 rows=0) (actual time=281..475 rows=70000 loop
                                                               -> Nested loop 
inner join  (cost=19437 rows=0.0246) (actual time=281..462 rows=70000 loops=1)
                                                                   -> Inner 
hash join (task_instance.dag_id = dag.dag_id)  (cost=18985 rows=0.0948) (actual 
time=281..414 rows=70000 loops=1)
                                                                       -> 
Filter: (task_instance.state = 'scheduled')  (cost=1893 rows=49.3) (actual 
time=281..398 rows=70000 loops=1)
                                                                           -> 
Table scan on task_instance  (cost=1893 rows=256614) (actual time=0.0356..377 
rows=270000 loops=1)
                                                                       -> Hash
                                                                           -> 
Filter: (dag.is_paused = 0)  (cost=13 rows=10) (actual time=0.0417..0.085 
rows=100 loops=1)
                                                                               
-> Table scan on dag  (cost=13 rows=100) (actual time=0.0404..0.0784 rows=100 
loops=1)
                                                                   -> Filter: 
(dag_run.state = 'running')  (cost=0.918 rows=0.26) (actual time=473e-6..540e-6 
rows=1 loops=70000)
                                                                       -> 
Single-row index lookup on dag_run using dag_run_dag_id_run_id_key 
(dag_id=dag.dag_id, run_id=task_instance.run_id)  (cost=0.918
                                                               -> Hash
                                                                   -> Table 
scan on anon_2  (cost=2.5..2.5 rows=0) (actual time=0.0251..0.0251 rows=0 
loops=1)
                                                                       -> 
Materialize  (cost=0..0 rows=0) (actual time=0.0248..0.0248 rows=0 loops=1)
                                                                           -> 
Table scan on <temporary>  (actual time=0.0226..0.0226 rows=0 loops=1)
                                                                               
-> Aggregate using temporary table  (actual time=0.0212..0.0212 rows=0 loops=1)
                                                                                
   -> Index range scan on task_instance using ti_state over (state = 'queued') 
OR (state = 'running'), with index condition
               -> Single-row index lookup on task_instance using PRIMARY 
(id=anon_1.id)  (cost=0.743 rows=1) (actual time=0.00242..0.00244 rows=1 
loops=512)
           -> Single-row index lookup on dag_run_1 using 
dag_run_dag_id_run_id_key (dag_id=task_instance.dag_id, 
run_id=task_instance.run_id)  (cost=0.919 rows=1) (actual time=443e-6..465e-6 
rows=1 loops
   ```
   </details>
   
   <details><summary>MySQL 8.0, this PR, max_tis=512 (512 rows in 296 ms 
(median of 5), 512 task_instance rows locked)</summary>
   
   ```
   -> Limit: 512 row(s)  (cost=909 rows=0) (actual time=367..368 rows=512 
loops=1)
       -> Nested loop inner join  (cost=909 rows=0) (actual time=367..368 
rows=512 loops=1)
           -> Nested loop inner join  (cost=321 rows=0) (actual time=367..368 
rows=512 loops=1)
               -> Sort: -(candidates.priority_weight_for_ordering), 
candidates.logical_date_for_ordering, candidates.region_index_for_ordering  
(cost=5.2..5.2 rows=0) (actual time=367..367 rows=512 loops
                   -> Table scan on candidates  (cost=5.1..5.1 rows=0) (actual 
time=367..367 rows=2048 loops=1)
                       -> Materialize  (cost=2.6..2.6 rows=0) (actual 
time=367..367 rows=2048 loops=1)
                           -> Limit: 2048 row(s)  (cost=2.6..2.6 rows=0) 
(actual time=366..367 rows=2048 loops=1)
                               -> Sort: -(anon_1.priority_weight_for_ordering), 
anon_1.logical_date_for_ordering, anon_1.region_index_for_ordering, limit input 
to 2048 row(s) per chunk  (cost=2.6..2.6 ro
                                   -> Filter: ((anon_1.dr_max_active_tasks >= 
anon_1.row_num) and (anon_1.row_num <= 1024))  (cost=2.5..2.5 rows=0) (actual 
time=341..352 rows=70000 loops=1)
                                       -> Table scan on anon_1  (cost=2.5..2.5 
rows=0) (actual time=341..346 rows=70000 loops=1)
                                           -> Materialize  (cost=0..0 rows=0) 
(actual time=341..341 rows=70000 loops=1)
                                               -> Window aggregate: 
row_number() OVER (PARTITION BY task_instance.dag_id,task_instance.run_id ORDER 
BY `-(task_instance.priority_weight)`,dag_run.logical_d
                                                   -> Sort: 
task_instance.dag_id, task_instance.run_id, `-(task_instance.priority_weight)`, 
dag_run.logical_date, task_instance.region_index  (actual time=
                                                       -> Stream results  
(cost=10611 rows=0) (actual time=0.0808..199 rows=70000 loops=1)
                                                           -> Nested loop inner 
join  (cost=10611 rows=0) (actual time=0.0752..177 rows=70000 loops=1)
                                                               -> Filter: 
(coalesce(anon_2.task_per_dr_count,0) < dag.max_active_tasks)  (cost=405 
rows=0) (actual time=0.0675..129 rows=70000 loops=1)
                                                                   -> Left hash 
join (anon_2.run_id = task_instance.run_id), (anon_2.dag_id = 
task_instance.dag_id)  (cost=405 rows=0) (actual time=0.0665.
                                                                       -> 
Nested loop inner join  (cost=66487 rows=12831) (actual time=0.0359..111 
rows=70000 loops=1)
                                                                           -> 
Index lookup on task_instance using ti_state (state='scheduled')  (cost=21579 
rows=128307) (actual time=0.0277..79.4 rows=700
                                                                           -> 
Filter: (dag.is_paused = 0)  (cost=0.25 rows=0.1) (actual time=271e-6..338e-6 
rows=1 loops=70000)
                                                                               
-> Single-row index lookup on dag using PRIMARY (dag_id=task_instance.dag_id)  
(cost=0.25 rows=1) (actual time=165e-6..188e-
                                                                       -> Hash
                                                                           -> 
Table scan on anon_2  (cost=2.5..2.5 rows=0) (actual time=0.0247..0.0247 rows=0 
loops=1)
                                                                               
-> Materialize  (cost=0..0 rows=0) (actual time=0.0243..0.0243 rows=0 loops=1)
                                                                                
   -> Table scan on <temporary>  (actual time=0.0223..0.0223 rows=0 loops=1)
                                                                                
       -> Aggregate using temporary table  (actual time=0.021..0.021 rows=0 
loops=1)
                                                                                
           -> Index range scan on task_instance using ti_state over (state = 
'queued') OR (state = 'running'), with index c
                                                               -> Filter: 
(dag_run.state = 'running')  (cost=0.398 rows=0.26) (actual time=446e-6..557e-6 
rows=1 loops=70000)
                                                                   -> 
Single-row index lookup on dag_run using dag_run_dag_id_run_id_key 
(dag_id=task_instance.dag_id, run_id=task_instance.run_id)  (cost=
               -> Single-row index lookup on task_instance using PRIMARY 
(id=candidates.id)  (cost=0.427 rows=1) (actual time=0.00166..0.00169 rows=1 
loops=512)
           -> Single-row index lookup on dag_run_1 using 
dag_run_dag_id_run_id_key (dag_id=task_instance.dag_id, 
run_id=task_instance.run_id)  (cost=0.796 rows=1) (actual time=297e-6..319e-6 
rows=1 loops
   ```
   </details>
   
   ### Tests
   
   Five of the six new tests also pass on `main`, by design: they guard what 
`main` already does (locked rows are
   replaced, the highest priorities come first) against the naive versions of 
this change, and each fails against one
   of them.
   
   - 
`test_build_schedulable_tis_query_joins_full_rows_to_a_few_batches_of_ids`: the 
ranking subquery selects only the
     ids, ordering and window columns, and the `candidates` subquery keeps 
`max_tis * CANDIDATE_BATCHES` rows. Fails on
     `main`, or if the ranking selects full rows again.
   - `test_build_schedulable_tis_query_keeps_the_highest_priority_candidates`: 
with more candidates (one per Dag run) than
     the subquery keeps, the highest-priority one is still selected. Fails 
without the subquery's ORDER BY.
   - 
`test_build_schedulable_tis_query_keeps_the_top_task_instances_of_a_dag_run`: 
one Dag run with 6 candidates,
     `max_tis=3` returns its top 3. Fails if the per-Dag-run cap is below 
`max_tis`.
   - 
`test_build_schedulable_tis_query_replaces_candidates_locked_by_other_transactions`
 (PostgreSQL, MySQL): 4 Dag runs
     of one candidate each, the 3 highest-priority ones locked by a second 
connection; `max_tis=1` returns the 4th. Fails
     if the candidates are cut to one batch before locking, or with fewer than 
4 batches.
   - 
`test_build_schedulable_tis_query_replaces_a_locked_candidate_from_the_same_dag_run`
 (PostgreSQL, MySQL): one Dag run
     with candidates at priorities 2 and 1, the first locked; `max_tis=1` 
returns the second. Fails if the per-Dag-run
     cap is `max_tis` instead of `2 * max_tis`.
   - 
`test_build_schedulable_tis_query_leaves_candidates_for_other_dag_runs_when_one_is_locked`
 (PostgreSQL, MySQL): a Dag
     run with 4 higher-priority task instances, all locked, and another Dag run 
with one; `max_tis=1` returns the other
     Dag run's. Fails without the per-Dag-run cap.
   
   The lock tests run the selection in a thread with a 10 s timeout, so a `SKIP 
LOCKED` regression fails instead of
   hanging. The existing selection tests (priority order, `max_active_tasks`, 
task concurrency limits, pools,
   starvation, refill loop, MySQL index hint) pass unchanged, and so do the two 
tests from #77247, which still fail on
   top of this query when its check of the locked rows' state is removed. The 
query also returns the same rows as `main`'s on random
   data (6 seeds, 8 Dags with `max_active_tasks` from 1 to 64, up to 3 runs 
each, `max_tis` from 1 to 512, with and
   without starvation filters), on SQLite, PostgreSQL and MySQL.
   
   `airflow-core/tests/unit/jobs/test_scheduler_job.py` in full: SQLite 628 
passed / 18 skipped, PostgreSQL 14
   (psycopg 3) 644 passed / 2 skipped, MySQL 8.0 644 passed / 2 skipped.
   
   `prek run --from-ref main --stage pre-commit` (including 
`mypy-airflow-core`) and `--stage manual`: passed.
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   - [X] Yes (please specify the tool below)
   
   Generated-by: Claude Code (Opus 5.5) following [the 
guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
   
   ---
   
   * Read the **[Pull Request 
Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)**
 for more information. Note: commit author/co-author name and email in commits 
become permanently public when merged.
   * For fundamental code changes, an Airflow Improvement Proposal 
([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals))
 is needed.
   * When adding dependency, check compliance with the [ASF 3rd Party License 
Policy](https://www.apache.org/legal/resolved.html#category-x).
   * For significant user-facing changes create newsfragment: 
`{pr_number}.significant.rst`, in 
[airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments).
 You can add this file in a follow-up commit after the PR is created so you 
know the PR number.
   


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