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


##########
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:
   This window is real, but this PR does not introduce it: `main` has it too. 
On `main`, the claim checks `is_paused`, `is_draining` and `is_stale` in the 
locking statement, but it locks only the `asset_partition_dag_run` rows, not 
the Dag row, and nothing reads the flags again before `create_dagrun`. So on 
`main` too, a Dag paused while the loop runs can still get a Dag run. This PR 
adds only the few milliseconds between the eligibility query and the lock 
query, and it reads eligibility again on every loop.
   
   I'm taking a look to check whether we can fix it easily. Putting the check 
back in the lock query would only match `main`; closing the window needs the 
Dag rows locked, as `dags_needing_dagruns` does for schedule-driven runs.
   
   ---
   Drafted-by: Claude Code (Opus 5.5) (no human review before posting)
   



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