Copilot commented on code in PR #76463:
URL: https://github.com/apache/airflow/pull/76463#discussion_r4719254272


##########
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:
   If a Dag is paused, starts draining, or becomes stale between the 
eligibility read and this locking query, the cached `eligible` set still allows 
its pending partitions to be consumed and Dag runs to be created. Restore the 
eligibility predicates in the claim itself using a subquery, while keeping the 
bounded primary-key filter. Add a regression test that changes eligibility 
between discovery and claim, and retain the PostgreSQL/MySQL lock-footprint 
checks.



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