potiuk commented on code in PR #72378:
URL: https://github.com/apache/airflow/pull/72378#discussion_r4752363297


##########
airflow-core/src/airflow/models/dag.py:
##########
@@ -922,6 +939,52 @@ def get_dag_id_to_team_name_mapping(
         return {dag_id: team_name for dag_id, team_name in 
session.execute(stmt)}
 
 
+def _is_within(transaction: SessionTransaction | None, ancestor: 
SessionTransaction) -> bool:
+    if ancestor.parent is None:
+        return True
+    while transaction is not None:
+        if transaction is ancestor:
+            return True
+        transaction = transaction.parent
+    return False
+
+
[email protected]_for(Session, "after_soft_rollback")
+def _discard_rolled_back_scheduling_state_changes(
+    session: Session, previous_transaction: SessionTransaction
+) -> None:
+    changes = session.info.get(_SCHEDULING_STATE_CHANGES_KEY)
+    if changes:
+        changes[:] = [change for change in changes if not 
_is_within(change[0], previous_transaction)]
+
+
[email protected]_for(Session, "after_transaction_end")
+def _forget_scheduling_state_changes(session: Session, transaction: 
SessionTransaction) -> None:
+    if transaction.parent is None:
+        session.info.pop(_SCHEDULING_STATE_CHANGES_KEY, None)
+
+
[email protected]_for(Session, "after_commit")
+def _notify_scheduling_state_changes(session: Session) -> None:

Review Comment:
   **The listener runs inside the commit**
   
   `_notify_scheduling_state_changes` calls the hook from `after_commit`, while 
the committing transaction is still on the stack. The hook passes only 
`dag_id`, so a listener that wants more will read it with `@provide_session` / 
`create_session()`, which default to the thread-local scoped session. The 
scheduler, the CLI and backfill commit on that same scoped session, so there 
the listener's query hits a session that cannot emit SQL in `after_commit`, and 
`create_session()`'s error handling rolls back and closes the caller's session 
in the middle of its `commit()` (the scheduler keeps using its instances after 
`guard.commit()`). Through the REST API the request session is not the scoped 
one, so this does not show up in API tests. Dispatch the queued changes after 
the commit has returned rather than from the commit event (e.g. collect in 
`after_commit` and fire from the callers' post-commit point, or hand them to 
the listener manager outside the session), or at least run them against
  no session and document that listeners must not use the caller's session.
   
   *Flagged by antigravity (adversarial review); cross-checked.*
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting



##########
airflow-core/src/airflow/models/dag.py:
##########
@@ -507,9 +512,21 @@ def scheduling_state(self) -> DagSchedulingState:
         return DagSchedulingState.ACTIVE
 
     def set_scheduling_state(self, state: DagSchedulingState) -> None:
-        """Set the Dag's scheduling state."""
+        """
+        Set the Dag's scheduling state.
+
+        Writers must call this instead of assigning the flags or running a 
bulk UPDATE: a change of a
+        persistent Dag is queued here for the 
``on_dag_scheduling_state_change`` listener hook, which
+        fires once the outermost transaction commits.
+        """
+        old_state = self.scheduling_state
         self.is_paused = state == DagSchedulingState.PAUSED
         self.is_draining = state == DagSchedulingState.DRAINING
+        instance_state: InstanceState = sa_inspect(self)
+        if old_state != state and instance_state.persistent and (session := 
instance_state.session):
+            session.info.setdefault(_SCHEDULING_STATE_CHANGES_KEY, []).append(

Review Comment:
   **A change queued outside a transaction can leak into a later commit**
   
   With `expire_on_commit=False`, a `DagModel` loaded before a commit is still 
persistent and readable afterwards, so `set_scheduling_state` can run while the 
session has no transaction and queues `(None, dag_id, old, new)`. If the 
session is then rolled back or closed before anything starts a transaction, 
neither `after_soft_rollback` nor `after_transaction_end` fires, `session.info` 
survives `close()`, and with the scoped session the next unrelated commit on 
that thread reports a change that never reached the database. 
`test_set_scheduling_state_is_not_notified_when_the_session_closes_uncommitted` 
passes only because its second change to the same Dag coalesces with the leaked 
one. Clear the queue on `after_rollback` / when the session is closed 
(`after_transaction_end` does not cover a session without a transaction), or 
record the change at flush time (`before_flush` / `after_flush`), when it is 
certain to be in a transaction; adjust the test to use two different Dags.
   
   *Flagged by antigravity (adversarial review); cross-checked.*
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/dags.py:
##########
@@ -443,15 +443,14 @@ def patch_dags(
     ).subquery()
 
     scheduling_state = get_scheduling_state(patch_body)
-    session.execute(
-        update(DagModel)
-        .where(DagModel.dag_id.in_(select(filtered_dag_ids.c.dag_id)))
-        .values(
-            is_paused=scheduling_state == DagSchedulingState.PAUSED,
-            is_draining=scheduling_state == DagSchedulingState.DRAINING,
+    for dag in session.scalars(

Review Comment:
   **Bulk patch reuses unlocked, possibly stale Dag rows**
   
   `dags = session.scalars(dags_select).all()` loads the Dags without a lock, 
and the locking query that follows has no `populate_existing`, so SQLAlchemy 
keeps the attributes read before the lock. If another transaction changed a Dag 
in between, `set_scheduling_state` compares and assigns against stale flags: 
requesting the state the stale copy already shows writes nothing (the request 
reports success while the row keeps the other state, and no event fires), and 
requesting DRAINING over a stale ACTIVE after a concurrent pause updates only 
`is_draining`, violating `dag_pause_state_valid`. The previous bulk UPDATE 
wrote both flags unconditionally. `start_drain` and the new auto-pause path use 
`populate_existing=True` for this reason. The lock query also has no `ORDER BY 
dag_id`, unlike the other multi-row `DagModel` locks (`collection.py`, 
`scheduler_job_runner.py`), so overlapping bulk patches can deadlock. Add 
`.execution_options(populate_existing=True)` and `.order_by(DagModel.dag_
 id)` to the locking select (or lock before loading the response list).
   
   *Flagged by both the primary and adversarial reviewers.*
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting



##########
airflow-core/src/airflow/models/dagrun.py:
##########
@@ -1144,15 +1144,13 @@ def _check_last_n_dagruns_failed(self, dag_id, 
max_consecutive_failed_dag_runs,
                 self.dag_id,
                 max_consecutive_failed_dag_runs,
             )
-            filter_query = [
-                DagModel.dag_id == self.dag_id,
-            ]
-            session.execute(
-                update(DagModel)
-                .where(or_(*filter_query))
-                .values(is_paused=True, is_draining=False)
-                .execution_options(synchronize_session="fetch")
-            )
+            dag_model = session.scalars(

Review Comment:
   **`populate_existing` on auto-pause can drop unflushed DagModel changes**
   
   Sessions run with `autoflush=False`, and the scheduler processes several 
runs of a Dag in one transaction. `populate_existing=True` reloads every column 
of that `DagModel`, so an unflushed change made earlier in the same transaction 
(e.g. `exceeds_max_non_backfill` set by `_set_exceeds_max_active_runs`) is 
overwritten with the database value. The old bulk UPDATE touched only the two 
flags. Flush before the locking select (or lock with `with_for_update` and 
refresh only the two flag columns).
   
   *Flagged by antigravity (adversarial review); cross-checked.*
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk 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