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


##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -2753,8 +2759,9 @@ def _create_dagruns_for_partitioned_asset_dags(self, 
session: Session) -> set[st
                     creating_job_id=self.job.id,
                     session=session,
                 )
-            except ParamValidationError:
+            except (DagRunRolledBackError, ParamValidationError):

Review Comment:
   **For bug-fix PRs, flag if there is no regression test**
   
   > **For bug-fix PRs, flag if there is no regression test** — a test that 
fails without the fix and passes with it.
   
   `DagRunRolledBackError` means the scheduler's session was rolled back, which 
also releases every `FOR UPDATE SKIP LOCKED` lock taken earlier in the tick 
(the APDR batch here, and the DagModel rows from `dags_needing_dagruns`). 
`continue` then creates runs for the rest of the already-selected rows without 
holding their locks, so in HA another scheduler can claim the same 
APDR/DagModel and both create runs. That is the race the comment above the APDR 
query says the lock prevents. If the rogue reference went through 
`create_session()` (rollback + `close()`), the instances are also detached, and 
the `dag_id=apdr.target_dag_id` / `dag_model.dag_id` log calls raise 
`DetachedInstanceError` in the handler itself, so the scheduler still crashes 
in the scenario 
`test_dagrun_deadline_failure_that_detaches_orm_objects_still_skips` simulates.
   
   Since everything created earlier in the tick is gone anyway, I'd stop 
processing for this tick on `DagRunRolledBackError` (break out of the three 
creation loops, log with a dag_id captured before `create_dagrun`) instead of 
`continue`. Same pattern at line 3217 and in `_create_dag_runs` (line 2983). 
The scheduler tests mock `create_dagrun` without rolling the session back, so 
they do not cover this.
   
   *Flagged by antigravity and codex (adversarial review); cross-checked.*



##########
airflow-core/src/airflow/serialization/definitions/dag.py:
##########
@@ -92,6 +96,63 @@
 }
 
 
[email protected](frozen=True)
+class _DagRunSnapshot:
+    """The fields of ``DeadlineDagRunProtocol``, read off the pending Dag 
run."""
+
+    dag_id: str
+    logical_date: datetime.datetime | None
+    queued_at: datetime.datetime | None
+
+
+_READ_ONLY_TRANSACTION_STATEMENTS = {
+    "postgresql": "SET TRANSACTION READ ONLY",
+    "mysql": "SET TRANSACTION READ ONLY",
+}
+
+
[email protected]
+def _create_sqlite_alert_session(engine: Engine, session_maker: 
sessionmaker[Session]) -> Iterator[Session]:
+    # query_only belongs to the connection, not the transaction. The session 
is bound to a connection
+    # owned here so it is switched off on that same connection before it 
returns to the pool, even if
+    # the alert closes the session.
+    with engine.connect() as connection:
+        connection.exec_driver_sql("PRAGMA query_only = ON")
+        try:
+            with session_maker(bind=connection) as alert_session:
+                yield alert_session
+        finally:
+            connection.rollback()

Review Comment:
   **Flag any database-specific SQL ... without cross-DB handling**
   
   > **Flag any database-specific SQL** (e.g., `LATERAL` joins, PostgreSQL-only 
functions, MySQL-only syntax) without cross-DB handling. SQL must work on 
PostgreSQL, MySQL, and SQLite.
   
   In-memory SQLite (`sqlite://`) is still supported by 
`settings.prepare_engine_args` and uses `SingletonThreadPool`, so 
`engine.connect()` here hands back the *same* DBAPI connection the caller's 
session holds. The `connection.rollback()` in `finally` then rolls back the 
caller's flushed-but-uncommitted DagRun (and its TIs) on every run with a 
deadline alert, even when every alert succeeds. `orm_dagrun not in session` 
stays False, so the backstop does not see it and `create_dagrun` returns a run 
that was never stored. I reproduced the pattern with plain SQLAlchemy: with 
`sqlite://` the two sessions share the DBAPI connection and the row is gone 
after the caller's `commit()`; with a file-based SQLite URL the row survives.
   
   Suggest detecting the in-memory case 
(`settings._is_sqlite_in_memory(str(engine.url))`, or `isinstance(engine.pool, 
SingletonThreadPool)`) and falling back to a SAVEPOINT on the caller's session 
(`session.begin_nested()`) or the previous behaviour, plus a test for that 
branch.
   
   *Flagged by both the primary and adversarial reviewers.*



##########
airflow-core/src/airflow/serialization/definitions/dag.py:
##########
@@ -799,69 +860,89 @@ def _process_dagrun_deadline_alerts(
         dagrun_id = orm_dagrun.id
         dagrun_dag_id = orm_dagrun.dag_id
         bundle_name = orm_dagrun.dag_model.bundle_name
+        dagrun_snapshot = _DagRunSnapshot(
+            dag_id=dagrun_dag_id,
+            logical_date=orm_dagrun.logical_date,
+            queued_at=orm_dagrun.queued_at,
+        )
         stored_alerts = [
             (alert.id, alert.name, alert.reference, alert.interval, 
alert.callback_def)
             for alert in deadline_alert_records
             if alert
         ]
 
-        for alert_id, alert_name, alert_reference, alert_interval, 
alert_callback_def in stored_alerts:
-            # Deadline creation is best-effort. Catch per alert so one bad 
alert cannot starve the rest or abort the DagRun.
-            try:
-                deserialized_deadline_alert = decode_deadline_alert(
-                    {
-                        DeadlineAlertFields.NAME: alert_name,
-                        DeadlineAlertFields.REFERENCE: alert_reference,
-                        DeadlineAlertFields.INTERVAL: alert_interval,
-                        DeadlineAlertFields.CALLBACK: alert_callback_def,
-                    }
-                )
-                interval = 
resolve_deadline_alert_interval(deserialized_deadline_alert, session=session)
-
-                if isinstance(deserialized_deadline_alert.reference, 
SerializedReferenceModels.TYPES.DAGRUN):
-                    deadline_time = 
deserialized_deadline_alert.reference.evaluate_with(
-                        session=session,
-                        interval=interval,
-                        dagrun=orm_dagrun,
-                        dag_id=self.dag_id,
-                        run_id=run_id,
+        with _create_alert_session() as alert_session:
+            for alert_id, alert_name, alert_reference, alert_interval, 
alert_callback_def in stored_alerts:
+                # Deadline creation is best-effort. Catch per alert so one bad 
alert cannot starve the rest or abort the DagRun.
+                try:
+                    deserialized_deadline_alert = decode_deadline_alert(
+                        {
+                            DeadlineAlertFields.NAME: alert_name,
+                            DeadlineAlertFields.REFERENCE: alert_reference,
+                            DeadlineAlertFields.INTERVAL: alert_interval,
+                            DeadlineAlertFields.CALLBACK: alert_callback_def,
+                        }
+                    )
+                    interval = resolve_deadline_alert_interval(
+                        deserialized_deadline_alert, session=alert_session
                     )
 
-                    if deadline_time is not None:
-                        session.add(
-                            Deadline(
-                                deadline_time=deadline_time,
-                                callback=deserialized_deadline_alert.callback,
-                                dagrun_id=dagrun_id,
-                                deadline_alert_id=alert_id,
-                                dag_id=dagrun_dag_id,
-                                bundle_name=bundle_name,
-                            )
-                        )
-                        stats.incr("deadline_alerts.deadline_created", 
tags=metrics_tags)
-                    elif required_dagrun_column := 
_DAGRUN_REFERENCE_REQUIRED_COLUMNS.get(
-                        type(deserialized_deadline_alert.reference)
+                    if isinstance(
+                        deserialized_deadline_alert.reference, 
SerializedReferenceModels.TYPES.DAGRUN
                     ):
-                        log.warning(
-                            "skipping deadline alert because the deadline 
reference evaluated to None",
+                        deadline_time = 
deserialized_deadline_alert.reference.evaluate_with(
+                            session=alert_session,
+                            interval=interval,
+                            dagrun=dagrun_snapshot,
                             dag_id=self.dag_id,
                             run_id=run_id,
-                            deadline_alert_id=alert_id,
-                            
reference_type=deserialized_deadline_alert.reference.reference_name,
-                            required_dagrun_column=required_dagrun_column,
                         )
-            except Exception as exc:
-                if isinstance(exc, RuntimeError) and 
PROHIBIT_COMMIT_ERROR_MESSAGE in str(exc):
-                    # A rejected commit means the scheduler's HA locking is 
already broken. Recording
-                    # that as a skipped alert would hide it, so let it escape 
instead.
-                    raise
-                log.exception(
-                    "skipping deadline alert because creating its deadline 
failed",
-                    dag_id=self.dag_id,
-                    run_id=run_id,
-                    deadline_alert_id=alert_id,
-                )
-                stats.incr("deadline_alerts.deadline_creation_failed", 
tags=metrics_tags)
+
+                        if deadline_time is not None:
+                            session.add(
+                                Deadline(
+                                    deadline_time=deadline_time,
+                                    
callback=deserialized_deadline_alert.callback,
+                                    dagrun_id=dagrun_id,
+                                    deadline_alert_id=alert_id,
+                                    dag_id=dagrun_dag_id,
+                                    bundle_name=bundle_name,
+                                )
+                            )
+                            stats.incr("deadline_alerts.deadline_created", 
tags=metrics_tags)
+                        elif required_dagrun_column := 
_DAGRUN_REFERENCE_REQUIRED_COLUMNS.get(
+                            type(deserialized_deadline_alert.reference)
+                        ):
+                            log.warning(
+                                "skipping deadline alert because the deadline 
reference evaluated to None",
+                                dag_id=self.dag_id,
+                                run_id=run_id,
+                                deadline_alert_id=alert_id,
+                                
reference_type=deserialized_deadline_alert.reference.reference_name,
+                                required_dagrun_column=required_dagrun_column,
+                            )
+                except Exception as exc:

Review Comment:
   **For bug-fix PRs, flag if there is no regression test**
   
   > **For bug-fix PRs, flag if there is no regression test** — a test that 
fails without the fix and passes with it.
   
   One `alert_session` is shared by every alert of the run. When an alert's 
statement is rejected, e.g. by the new read-only transaction, PostgreSQL leaves 
the transaction aborted (`InFailedSqlTransaction`) and SQLAlchemy needs a 
rollback (`PendingRollbackError`). Every later alert that queries the session 
(`VariableInterval`, `AVERAGE_RUNTIME`, custom references) is then skipped too. 
`test_dagrun_deadline_alert_writing_through_its_session_is_skipped` misses it 
because its second alert is `DAGRUN_LOGICAL_DATE`, which does no query. Calling 
`alert_session.rollback()` in the `except` block fixes it: the `after_begin` 
listener makes the next transaction read-only again. Using a DB-reading second 
alert (e.g. another `VariableInterval`) in that test would cover it.
   
   *Flagged by antigravity and codex (adversarial review); cross-checked.*



##########
airflow-core/src/airflow/serialization/definitions/dag.py:
##########
@@ -799,69 +860,89 @@ def _process_dagrun_deadline_alerts(
         dagrun_id = orm_dagrun.id
         dagrun_dag_id = orm_dagrun.dag_id
         bundle_name = orm_dagrun.dag_model.bundle_name
+        dagrun_snapshot = _DagRunSnapshot(
+            dag_id=dagrun_dag_id,
+            logical_date=orm_dagrun.logical_date,
+            queued_at=orm_dagrun.queued_at,
+        )
         stored_alerts = [
             (alert.id, alert.name, alert.reference, alert.interval, 
alert.callback_def)
             for alert in deadline_alert_records
             if alert
         ]
 
-        for alert_id, alert_name, alert_reference, alert_interval, 
alert_callback_def in stored_alerts:
-            # Deadline creation is best-effort. Catch per alert so one bad 
alert cannot starve the rest or abort the DagRun.
-            try:
-                deserialized_deadline_alert = decode_deadline_alert(
-                    {
-                        DeadlineAlertFields.NAME: alert_name,
-                        DeadlineAlertFields.REFERENCE: alert_reference,
-                        DeadlineAlertFields.INTERVAL: alert_interval,
-                        DeadlineAlertFields.CALLBACK: alert_callback_def,
-                    }
-                )
-                interval = 
resolve_deadline_alert_interval(deserialized_deadline_alert, session=session)
-
-                if isinstance(deserialized_deadline_alert.reference, 
SerializedReferenceModels.TYPES.DAGRUN):
-                    deadline_time = 
deserialized_deadline_alert.reference.evaluate_with(
-                        session=session,
-                        interval=interval,
-                        dagrun=orm_dagrun,
-                        dag_id=self.dag_id,
-                        run_id=run_id,
+        with _create_alert_session() as alert_session:
+            for alert_id, alert_name, alert_reference, alert_interval, 
alert_callback_def in stored_alerts:
+                # Deadline creation is best-effort. Catch per alert so one bad 
alert cannot starve the rest or abort the DagRun.
+                try:
+                    deserialized_deadline_alert = decode_deadline_alert(
+                        {
+                            DeadlineAlertFields.NAME: alert_name,
+                            DeadlineAlertFields.REFERENCE: alert_reference,
+                            DeadlineAlertFields.INTERVAL: alert_interval,
+                            DeadlineAlertFields.CALLBACK: alert_callback_def,
+                        }
+                    )
+                    interval = resolve_deadline_alert_interval(
+                        deserialized_deadline_alert, session=alert_session
                     )
 
-                    if deadline_time is not None:
-                        session.add(
-                            Deadline(
-                                deadline_time=deadline_time,
-                                callback=deserialized_deadline_alert.callback,
-                                dagrun_id=dagrun_id,
-                                deadline_alert_id=alert_id,
-                                dag_id=dagrun_dag_id,
-                                bundle_name=bundle_name,
-                            )
-                        )
-                        stats.incr("deadline_alerts.deadline_created", 
tags=metrics_tags)
-                    elif required_dagrun_column := 
_DAGRUN_REFERENCE_REQUIRED_COLUMNS.get(
-                        type(deserialized_deadline_alert.reference)
+                    if isinstance(
+                        deserialized_deadline_alert.reference, 
SerializedReferenceModels.TYPES.DAGRUN
                     ):
-                        log.warning(
-                            "skipping deadline alert because the deadline 
reference evaluated to None",
+                        deadline_time = 
deserialized_deadline_alert.reference.evaluate_with(
+                            session=alert_session,
+                            interval=interval,
+                            dagrun=dagrun_snapshot,
                             dag_id=self.dag_id,
                             run_id=run_id,
-                            deadline_alert_id=alert_id,
-                            
reference_type=deserialized_deadline_alert.reference.reference_name,
-                            required_dagrun_column=required_dagrun_column,
                         )
-            except Exception as exc:
-                if isinstance(exc, RuntimeError) and 
PROHIBIT_COMMIT_ERROR_MESSAGE in str(exc):
-                    # A rejected commit means the scheduler's HA locking is 
already broken. Recording
-                    # that as a skipped alert would hide it, so let it escape 
instead.
-                    raise
-                log.exception(
-                    "skipping deadline alert because creating its deadline 
failed",
-                    dag_id=self.dag_id,
-                    run_id=run_id,
-                    deadline_alert_id=alert_id,
-                )
-                stats.incr("deadline_alerts.deadline_creation_failed", 
tags=metrics_tags)
+
+                        if deadline_time is not None:
+                            session.add(

Review Comment:
   **For bug-fix PRs, flag if there is no regression test**
   
   > **For bug-fix PRs, flag if there is no regression test** — a test that 
fails without the fix and passes with it.
   
   The backstop runs after `session.add(Deadline(...))`. A reference that rolls 
back the scheduler's session but then returns a timestamp (e.g. it catches the 
error and falls back) still gets its Deadline added with the discarded 
`dagrun_id`. `DagRunRolledBackError` is then caught by the scheduler, which 
does not expunge it, so `guard.commit()` hits the `deadline.dagrun_id` foreign 
key violation the comment says this check prevents. Checking `orm_dagrun not in 
session` right after `evaluate_with` returns, before `session.add`, closes it. 
Raise it past the per-alert `except`, the same way the prohibit-commit error is 
re-raised.
   
   *Flagged by antigravity and codex (adversarial review); cross-checked.*



##########
airflow-core/tests/unit/jobs/test_scheduler_job.py:
##########
@@ -11041,6 +11041,56 @@ def 
test_misconfigured_dags_doesnt_crash_scheduler(self, mock_create, session, d
         job_runner._create_dag_runs([dm1], session)
         assert "Failed creating DagRun" in caplog.text
 
+    
@patch("airflow.serialization.serialized_objects.SerializedDAG.create_dagrun")
+    def test_dag_run_rolled_back_by_deadline_alert_does_not_advance_schedule(

Review Comment:
   **flag tests that a reviewer cannot fail by reverting the PR's change**
   
   > **Flag any changed or added behaviour without a corresponding test, and 
flag tests that a reviewer cannot fail by reverting the PR's change.** The 
target is exactly 100% coverage of what the PR changes — no more, no less. 
Tests for pre-existing logic or standard-library/third-party functions are 
padding; missing tests for changed behaviour are gaps. Exception: deliberate 
behaviour or integration tests may cross those boundaries by design.
   
   `_create_dag_runs` already catches every `Exception` (unchanged by this PR), 
so this test passes against the pre-existing handler. The PR doesn't change 
that path. Drop it, or turn it into the rolled-back-session case raised on 
`scheduler_job_runner.py:2762`.



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