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


##########
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:
   Thanks, good catch. With a single-connection pool 
(`SingletonThreadPool`/`StaticPool`), the alerts now use the caller's own 
session, so the pending Dag run is no longer rolled back. Covered by 
`test_deadline_alert_session_is_callers_session_when_the_pool_has_one_connection`.
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by `xchwan` before posting
   



##########
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:
   Agreed, thanks. On `DagRunDiscardedError` the scheduler now rolls back and 
creates no more Dag runs in that loop, so nothing is created after the locks 
are gone. The next loop takes the locks again and recreates the runs that were 
discarded, since their `next_dagrun` was rolled back too. `_create_dag_runs` 
re-raises the error and the asset paths don't catch it. The handler uses the 
`dag_id` from the error, so it never reads a detached instance. Covered by 
`test_do_scheduling_ends_dag_run_creation_when_deadline_alert_discards_dag_run`,
 and checked with 2 schedulers on kind: no duplicate runs. The update above 
describes how the Dag is then left out, so it doesn't end every loop.
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by `xchwan` before posting
   



##########
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:
   Thanks, fixed. The check now runs before the Deadline is added. It checks 
that the session is still active and that the Dag run's row still exists, which 
also catches a rollback by the database itself. Covered by 
`test_dagrun_deadline_alert_silently_rolling_back_callers_session_creates_no_deadline`.
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by `xchwan` before posting
   



##########
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:
   Thanks, done as suggested. The `except` block rolls back the alert session, 
and the `after_begin` listener makes the next transaction read-only again. 
`test_dagrun_deadline_alert_failing_statement_does_not_fail_later_alerts` uses 
a second alert that queries the database, and it passes on PostgreSQL.
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by `xchwan` before posting
   



##########
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:
   Thanks, replaced. `_create_dag_runs` now re-raises the error, and 
`test_dag_run_discarded_by_deadline_alert_propagates` fails without that 
re-raise.
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by `xchwan` 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