seunggabi opened a new pull request, #77604: URL: https://github.com/apache/airflow/pull/77604
With multiple schedulers, `_start_queued_dagruns` can start more runs of a Dag than `max_active_runs` allows. **Why** - `DagRun.get_queued_dag_runs_to_set_running` selects queued runs with `FOR UPDATE SKIP LOCKED`, so two schedulers get *different* queued runs of the same Dag. - `_start_queued_dagruns` then counts running runs per Dag from committed data. Neither scheduler has committed yet, so both see `0` running and both start a run. - Example: Dag with `max_active_runs=1` and queued runs D1, D2, D3. Scheduler A locks D1/D2 and starts D1; scheduler B gets D3, sees 0 running, starts D3 → 2 running. - With `depends_on_past=True` this can deadlock: D3 is running and waits for D2, while D2 stays queued because the Dag is at its limit. - It rarely shows up in steady state (a Dag seldom has several queued runs), but it happens after clearing / re-queueing many runs at once. We saw it on 2.8.1 with two schedulers: after a large re-queue, ~400 Dags ended up stuck this way. **Fix** Backfill runs are already protected against this: `_lock_backfills` locks the `Backfill` rows with `SKIP LOCKED` before counting, and runs of a backfill locked by another scheduler are skipped. This PR does the same for non-backfill runs: `_lock_dags` locks the `dag` rows of the candidate runs with `SKIP LOCKED` before the running-count query, and runs of a Dag locked by another scheduler are skipped for this loop. The lock is held only within the existing scheduling transaction. A Dag whose row is locked elsewhere (e.g. by the other scheduler's `dags_needing_dagruns`) only has its queued runs delayed to a later loop; nothing is dropped. On databases without row locking `with_row_locks` is a no-op, as before. Related: #77603 (another cause of the same depends_on_past deadlock) **Tests** - `test_concurrent_schedulers_respect_max_active_runs` (postgres/mysql): two sessions act as two schedulers, each examining one queued run (`DEFAULT_DAGRUNS_TO_EXAMINE=1`) of a Dag with `max_active_runs=1`, and neither commits before the other has decided. On `main` this ends with 2 running runs (`assert 2 == 1`); with this change, 1. - `test_queued_runs_skipped_when_dag_lock_held_by_another_scheduler`: mirrors the existing backfill lock test; runs of a Dag whose row is locked elsewhere are skipped and started in the next loop. --- ##### Was generative AI tooling used to co-author this PR? - [X] Yes (please specify the tool below) Generated-by: Claude Code following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions) -- 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]
