Copilot commented on code in PR #76463:
URL: https://github.com/apache/airflow/pull/76463#discussion_r4695179179
##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -341,6 +363,264 @@ def _get_current_dr_task_concurrency(states:
Iterable[TaskInstanceState]) -> Sub
)
+class _PartitionPass(NamedTuple):
+ """A completed pass of a :class:`_PartitionRing` over the pending rows of
eligible Dags."""
+
+ loops: int
+ seconds: float
+ oldest_created_at: datetime | None
+
+
+class _RingProgress(NamedTuple):
+ """The part of a :class:`_PartitionRing` that a rolled-back tick must
undo."""
+
+ cursor: int | None
+ fresh: list[int]
+ gone: set[int]
+ pass_started_at: float | None
+ pass_loops: int
+ pass_oldest: datetime | None
+
+
+class _PartitionRing:
+ """
+ Order in which one scheduler visits pending :class:`AssetPartitionDagRun`
rows: a rotation by id.
+
+ Pending rows that stay unsatisfied for long are normal (a rollup waiting
for its window, an AND
+ condition missing an input). Taking the oldest rows up to the per-tick cap
would re-evaluate the
+ same unsatisfied rows on every tick and never reach newer ones, in any
Dag. The ring visits every
+ pending row of an eligible Dag once per pass instead. Rows it has not seen
before, up to a limit
+ the caller sets, are claimed ahead of the rotation in the tick that finds
them.
+
+ The pending ids are read in full every ``refresh_interval`` seconds and,
in between, only the rows
+ inserted since the last read. The state is in memory only. Progress made
in a tick is kept by
+ :meth:`commit` and undone by :meth:`rewind`, so a tick retried after a
database error skips no row
+ that the rolled-back attempt claimed.
+ """
+
+ def __init__(self, rng: random.Random | None = None) -> None:
+ self._rng = rng or random.Random()
+ # Set on the first claim, from the database dialect.
+ self.refresh_interval: float | None = None
+ self._refreshed_at: float | None = None
+ # Highest id of the table read so far; the tail read returns the rows
above it.
+ self.max_seen = 0
+ self._dag_by_id: dict[int, str] = {}
+ self._ids_by_dag: dict[str, list[int]] = {}
+ self._ring: list[int] = []
+ # The Dags whose rows _ring holds; None after a full read, so that
pick() rebuilds it.
+ self._ring_dags: frozenset[str] | None = None
+ self._last_pick: tuple[list[int], list[int], int | None] = ([], [],
None)
+ self._fresh_added: list[int] = []
+ self._ended: _PartitionPass | None = None
+ # Progress, saved by commit() and restored by rewind().
+ # Rows with a greater id come next; None until the rotation starts.
+ self.cursor: int | None = None
+ # Pending rows not seen before, claimed ahead of the rotation.
+ self.fresh: list[int] = []
+ # Rows fired or deleted since the last full read.
+ self.gone: set[int] = set()
+ # None while the pass in progress is partial: the first one of this
process, or one interrupted
+ # by a tick with nothing to rotate over.
+ self._pass_started_at: float | None = None
+ self._pass_loops = 0
+ self._pass_oldest: datetime | None = None
+ self._committed = self._capture_progress()
+
+ def _capture_progress(self) -> _RingProgress:
+ return _RingProgress(
+ self.cursor,
+ list(self.fresh),
+ set(self.gone),
+ self._pass_started_at,
+ self._pass_loops,
+ self._pass_oldest,
+ )
+
+ def commit(self) -> _PartitionPass | None:
+ """
+ Keep the progress made since the last commit, once its transaction is
committed.
+
+ :return: the pass that ended in the committed tick, unless it is
partial.
+ """
+ ended, self._ended = self._ended, None
+ self._committed = self._capture_progress()
+ self._fresh_added = []
+ return ended
+
+ def rewind(self) -> None:
+ """Undo the progress made since the last commit, so a retried tick
skips no row."""
+ self.cursor, fresh, gone, self._pass_started_at, self._pass_loops,
self._pass_oldest = self._committed
+ # Reading new rows is not undone by a rollback, so they stay new.
+ self.fresh = sorted(
+ apdr_id for apdr_id in set(fresh).union(self._fresh_added) if
apdr_id in self._dag_by_id
+ )
+ self.gone = set(gone)
+ self._ended = None
+
+ def needs_refresh(self, now: float) -> bool:
+ return self._refreshed_at is None or now - self._refreshed_at >=
(self.refresh_interval or 0.0)
+
+ def refresh(self, rows: Iterable[tuple[int, str]], *, max_id: int | None,
now: float) -> None:
+ """
+ Replace the pending ids with a full read of *rows*.
+
+ :param max_id: the highest id in the table, read before *rows*, so
that the rows committed in
+ between are returned by both reads rather than by neither.
+ """
+ # One string per Dag rather than one per row.
+ shared: dict[str, str] = {}
+ dag_by_id: dict[int, str] = {}
+ ids_by_dag: dict[str, list[int]] = {}
+ for apdr_id, dag_id in rows:
+ shared_dag_id = shared.setdefault(dag_id, dag_id)
+ dag_by_id[apdr_id] = shared_dag_id
+ ids_by_dag.setdefault(shared_dag_id, []).append(apdr_id)
+ for ids in ids_by_dag.values():
+ ids.sort()
+ # Swapped in once every row is read: the rows are streamed, and a read
that fails part way must
+ # leave the previous full read, or the retry would take every row it
had not read as new.
+ known, self._dag_by_id, self._ids_by_dag = self._dag_by_id, dag_by_id,
ids_by_dag
+ new = [] if self._refreshed_at is None else
sorted(self._dag_by_id.keys() - known.keys())
+ self.fresh =
sorted(set(self.fresh).intersection(self._dag_by_id).union(new))
+ self._fresh_added.extend(new)
+ self.gone = set()
+ self.max_seen = max_id or 0
+ self._refreshed_at = now
+ self._ring_dags = None
+
+ def add_tail(self, rows: Iterable[tuple[int, str, int | None]]) -> None:
+ """Add the pending rows among *rows*, the rows inserted since the last
read."""
+ ring_dags = self._ring_dags or frozenset()
+ for apdr_id, dag_id, created_dag_run_id in rows:
+ self.max_seen = max(self.max_seen, apdr_id)
+ if created_dag_run_id is not None or apdr_id in self._dag_by_id:
+ continue
+ self._dag_by_id[apdr_id] = dag_id
+ # Insert in order: a full read can return rows committed after it
read max_id, so a row of
+ # the tail read is not always the highest id.
+ insort(self._ids_by_dag.setdefault(dag_id, []), apdr_id)
+ insort(self.fresh, apdr_id)
+ self._fresh_added.append(apdr_id)
+ if dag_id in ring_dags:
+ insort(self._ring, apdr_id)
+
+ def get_dag_ids(self) -> list[str]:
+ return list(self._ids_by_dag)
+
+ def discard(self, apdr_ids: Iterable[int]) -> None:
+ """Skip rows fired or deleted in this tick until the next full read."""
+ self.gone.update(apdr_ids)
+
+ def interrupt(self) -> None:
+ """Make the pass in progress partial: a tick with nothing to rotate
over is not part of a pass."""
+ self._pass_started_at = None
+ # A rollback does not undo the read that found nothing to rotate over,
so it keeps this too.
+ self._committed = self._committed._replace(pass_started_at=None)
+
+ def pick(self, eligible: Collection[str], *, limit: int, fresh_limit: int)
-> list[int]:
+ """
+ Return up to *limit* distinct ids to claim: up to *fresh_limit* rows
not seen before, then the rotation.
+
+ Rows of Dags that are not *eligible* are skipped without counting
towards *limit*.
+ """
+ dags = frozenset(eligible)
+ if dags != self._ring_dags:
+ self._update_ring(dags)
+ ring = self._ring
+ fresh: list[int] = []
+ kept: list[int] = []
+ for apdr_id in self.fresh:
Review Comment:
When a periodic full refresh discovers a large burst of new pending runs,
each subsequent tick scans and copies the entire remaining `fresh` backlog
despite selecting at most half a batch from it. `advance()`, `rewind()`, and
`commit()` also traverse or copy that backlog, so steady-loop work grows with
the burst and can delay unrelated scheduling and heartbeats. Use an ordered
queue with a cursor and rollback bookkeeping to retain the unconsumed suffix
without rebuilding it each tick, checking eligibility as entries are visited.
--
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]