hussein-awala commented on code in PR #76463:
URL: https://github.com/apache/airflow/pull/76463#discussion_r4719471567


##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -2856,6 +3144,124 @@ def _resolve_partition_date(
             return None
         return anchors.pop()
 
+    def _claim_pending_partition_dag_runs(self, *, session: Session) -> 
list[AssetPartitionDagRun]:
+        """
+        Lock the pending :class:`AssetPartitionDagRun` rows this tick 
evaluates, oldest first.
+
+        The rows come from the scheduler's rotation (:class:`_PartitionRing`), 
read without locks,
+        and are then locked by primary key with SKIP LOCKED up to the per-tick 
cap. The lock
+        footprint therefore does not depend on the query plan, and when an HA 
peer holds some of
+        the rows this scheduler claims the next ones instead of none. Without 
the lock, two HA
+        schedulers could both fire the same satisfied APDR and race the 
``created_dag_run_id``
+        update, orphaning whichever Dag run loses. SQLite is single-writer and 
drops ``FOR UPDATE``.
+        """
+        ring = self._partition_ring
+        cap = self._max_partition_dag_runs_per_loop
+        limit = cap * (1 + MAX_PARTITION_CLAIM_REFILLS_PER_LOOP)
+        if ring.refresh_interval is None:
+            # SQLite reuses the id of a deleted row, which the tail read below 
would miss, and at
+            # the scale SQLite is used at a full read costs little.
+            ring.refresh_interval = (
+                0.0 if get_dialect_name(session) == "sqlite" else 
_PARTITION_SNAPSHOT_REFRESH_SECONDS
+            )
+        now = time.monotonic()
+        if ring.needs_refresh(now):
+            max_id = session.scalar(select(func.max(AssetPartitionDagRun.id)))
+            ring.refresh(
+                session.execute(
+                    select(AssetPartitionDagRun.id, 
AssetPartitionDagRun.target_dag_id)
+                    .where(AssetPartitionDagRun.created_dag_run_id.is_(None))
+                    # Stream the rows rather than buffer all of them before 
the ring copies them. On
+                    # PostgreSQL a streamed read never gets a parallel plan.
+                    .execution_options(yield_per=10_000)
+                ).tuples(),
+                max_id=max_id,
+                now=now,
+            )
+        else:
+            ring.add_tail(
+                session.execute(
+                    select(
+                        AssetPartitionDagRun.id,
+                        AssetPartitionDagRun.target_dag_id,
+                        AssetPartitionDagRun.created_dag_run_id,
+                    )
+                    .where(AssetPartitionDagRun.id > ring.max_seen)
+                    .order_by(AssetPartitionDagRun.id)
+                    .limit(limit)
+                ).tuples()
+            )
+        if not (dag_ids := ring.get_dag_ids()):
+            ring.interrupt()
+            self._reset_partition_age_gauge()
+            return []
+        eligible: set[str] = set()
+        for batch in chunks(dag_ids, _PARTITION_ELIGIBILITY_CHUNK_SIZE):
+            eligible.update(
+                session.scalars(
+                    select(DagModel.dag_id).where(
+                        DagModel.dag_id.in_(batch), 
*_build_partition_eligible_dag_filters()
+                    )
+                )
+            )
+        # New rows take at most half the cap, so that the rotation keeps at 
least half of each tick.
+        candidates = ring.pick(eligible, limit=limit, fresh_limit=cap // 2)
+        if not candidates:
+            self._reset_partition_age_gauge()
+        claimed: dict[int, AssetPartitionDagRun] = {}
+        tried = 0
+        for _ in range(1 + MAX_PARTITION_CLAIM_REFILLS_PER_LOOP):
+            if not (chunk := candidates[tried : tried + cap - len(claimed)]):
+                break
+            tried += len(chunk)
+            for apdr in session.scalars(
+                with_row_locks(
+                    select(AssetPartitionDagRun).where(
+                        AssetPartitionDagRun.id.in_(chunk),
+                        AssetPartitionDagRun.created_dag_run_id.is_(None),
+                    ),

Review Comment:
   f84495c8d3 makes the lock query check `is_paused`, `is_draining` and 
`is_stale` itself, through an `EXISTS` on the Dag row. A Dag that is paused, 
draining or stale after the eligibility read now keeps its runs pending, which 
restores what `main` guarantees without locking the Dag row.
   - 
`test_partition_dag_paused_after_the_eligibility_read_keeps_its_runs_pending` 
pauses or drains the Dag between the two reads; it fails without the change.
   - The lock-footprint test now also checks that the Dag row stays unlocked, 
on PostgreSQL and MySQL.
   - Cost: about 1 ms per lock query of 500 runs on PostgreSQL (2.7 to 3.8 ms), 
and about 0.1 ms on MySQL.
   
   What is still missing to close the window completely, on `main` too: the 
flags can change after the lock query and before `create_dagrun`, because 
nothing locks the Dag row. Closing it needs a `FOR SHARE` lock on the Dag rows 
of the runs about to fire, with the flags checked in the same statement. `FOR 
KEY SHARE` is not enough, because it does not block the pause request's `FOR NO 
KEY UPDATE`. That lock has costs:
   - pause and unpause requests, and the Dag processor's updates of those rows, 
wait for the scheduler's commit; with `SKIP LOCKED` instead, a ready run that 
loses the race waits until the rotation comes back to it;
   - another scheduler's `dags_needing_dagruns` skips those Dags while the lock 
is held;
   - the fire loop has to be split into evaluate, then lock and check, then 
fire.
   
   The window exists on `main`, and its effect is mild: a run created for a Dag 
paused at that moment waits until the Dag is unpaused, and a draining Dag 
finishes draining once that run completes. So closing it fits better in a 
separate change against `main` than in this backport.
   



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