ramitkataria commented on code in PR #71214:
URL: https://github.com/apache/airflow/pull/71214#discussion_r4331611151


##########
airflow-core/src/airflow/models/callback.py:
##########
@@ -143,10 +143,17 @@ class Callback(Base, BaseWorkload):
     # Creation time of the callback
     created_at: Mapped[datetime] = mapped_column(UtcDateTime, 
default=timezone.utcnow, nullable=False)
 
+    dagrun_id: Mapped[int | None] = mapped_column(
+        Integer, ForeignKey("dag_run.id", ondelete="CASCADE"), nullable=True

Review Comment:
   `db_cleanup.py` isn't in the diff so commenting here: Should `callback` be 
added to `dag_run`'s `dependent_tables` in `db_cleanup.py`, like 
`task_state_store` was in #68218 and `task_reschedule` in #71990? With this 
CASCADE, I think `db clean -t dag_run` would delete the run's callbacks without 
archiving them



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -1366,25 +1367,19 @@ def _enqueue_executor_callbacks(self, session: Session) 
-> None:
                     # Can't happen since we queried ExecutorCallback, but 
satisfies mypy.
                     continue
 
-                # TODO: Add dagrun_id as a proper ORM foreign key on the 
callback table instead of storing in data dict.
-                #       This would eliminate this reconstruction step. For 
now, all ExecutorCallbacks
-                #       are expected to have dag_run_id set in their data dict 
(e.g., by Deadline.handle_miss).
-                if not isinstance(callback.data, dict) or "dag_run_id" not in 
callback.data:
-                    self.log.error(
-                        "ExecutorCallback %s is missing required 'dag_run_id' 
in data dict. "
-                        "This indicates a bug in callback creation. Skipping 
callback.",
-                        callback.id,
+                if callback.dagrun_id is None:
+                    self.log.warning(

Review Comment:
   Thanks for switching to error. I don't think anything fills `dagrun_id` in 
later, so the callback stays PENDING and gets fetched and logged again every 
loop. With the query taking the top `max_callbacks` by `priority_weight`, 
enough of these could crowd out valid callbacks. Maybe we should mark it 
`FAILED` with an `output`, similar to how the scheduler fails task instances 
whose serialized Dag is missing?
   
   Separately, maybe we should also have `Deadline.__init__` set `dagrun_id` 
next to `bundle_name` to avoid running into this?



##########
airflow-core/src/airflow/migrations/versions/0149_3_5_0_add_dagrun_id_to_callback.py:
##########
@@ -0,0 +1,167 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Add dagrun_id foreign key to callback.
+
+Revision ID: 0f4c9a2b8e1d
+Revises: c71065a1b14f
+Create Date: 2026-08-06 00:00:00.000000
+
+"""
+
+from __future__ import annotations
+
+import json
+
+import sqlalchemy as sa
+from alembic import context, op
+
+from airflow.configuration import conf
+
+# revision identifiers, used by Alembic.
+revision = "0f4c9a2b8e1d"
+down_revision = "c71065a1b14f"
+branch_labels = None
+depends_on = None
+airflow_version = "3.5.0"
+
+
+def _deserialize_data(data):
+    if isinstance(data, str):
+        try:
+            data = json.loads(data)
+        except json.JSONDecodeError:
+            return {}
+    return data.get("__var", data) if isinstance(data, dict) else {}
+
+
+def _extract_dagrun_id(data) -> int | None:
+    dagrun_id = _deserialize_data(data).get("dag_run_id")
+    if dagrun_id is None:
+        return None
+    try:
+        return int(dagrun_id)
+    except (TypeError, ValueError):
+        return None
+
+
+def _backfill_dagrun_id_from_deadline(conn, batch_size: int) -> None:
+    callback = sa.table(
+        "callback",
+        sa.column("id", sa.Uuid()),
+        sa.column("type", sa.String(20)),
+        sa.column("dagrun_id", sa.Integer()),
+    )
+    deadline = sa.table(
+        "deadline",
+        sa.column("callback_id", sa.Uuid()),
+        sa.column("dagrun_id", sa.Integer()),
+    )
+    dag_run = sa.table("dag_run", sa.column("id", sa.Integer()))
+
+    last_id = None
+    while True:
+        query = (
+            sa.select(callback.c.id, deadline.c.dagrun_id)
+            .select_from(
+                callback.join(deadline, callback.c.id == 
deadline.c.callback_id).join(
+                    dag_run, deadline.c.dagrun_id == dag_run.c.id
+                )
+            )
+            .where(callback.c.type == "executor", 
callback.c.dagrun_id.is_(None))
+            .order_by(callback.c.id)
+            .limit(batch_size)
+        )
+        if last_id is not None:
+            query = query.where(callback.c.id > last_id)
+
+        rows = conn.execute(query).fetchall()
+        if not rows:
+            return
+
+        for callback_id, dagrun_id in rows:
+            conn.execute(callback.update().where(callback.c.id == 
callback_id).values(dagrun_id=dagrun_id))
+
+        last_id = rows[-1].id
+
+
+def _backfill_dagrun_id(conn, batch_size: int) -> None:
+    callback = sa.table(
+        "callback",
+        sa.column("id", sa.Uuid()),
+        sa.column("type", sa.String(20)),
+        sa.column("data", sa.Text()),
+        sa.column("dagrun_id", sa.Integer()),
+    )
+    dag_run = sa.table("dag_run", sa.column("id", sa.Integer()))
+
+    last_id = None
+    while True:
+        query = (
+            sa.select(callback.c.id, callback.c.data)
+            .where(callback.c.type == "executor", 
callback.c.dagrun_id.is_(None))
+            .order_by(callback.c.id)
+            .limit(batch_size)
+        )
+        if last_id is not None:
+            query = query.where(callback.c.id > last_id)
+
+        rows = conn.execute(query).fetchall()
+        if not rows:
+            return
+
+        for callback_id, data in rows:
+            dagrun_id = _extract_dagrun_id(data)
+            if dagrun_id is None:
+                continue
+
+            dagrun_exists = conn.execute(
+                sa.select(dag_run.c.id).where(dag_run.c.id == 
dagrun_id).limit(1)
+            ).first()
+            if dagrun_exists:
+                conn.execute(
+                    callback.update().where(callback.c.id == 
callback_id).values(dagrun_id=dagrun_id)
+                )
+
+        last_id = rows[-1].id
+
+
+def upgrade():
+    """Add callback.dagrun_id and backfill it from legacy callback.data."""
+    with op.batch_alter_table("callback") as batch_op:
+        batch_op.add_column(sa.Column("dagrun_id", sa.Integer(), 
nullable=True))
+
+    if not context.is_offline_mode():
+        conn = op.get_bind()
+        batch_size = conf.getint("database", "migration_batch_size")
+        _backfill_dagrun_id_from_deadline(conn, batch_size)
+        _backfill_dagrun_id(conn, batch_size)
+
+    with op.batch_alter_table("callback") as batch_op:
+        batch_op.create_index("callback_dagrun_id_idx", ["dagrun_id"], 
unique=False)
+        batch_op.create_foreign_key(
+            batch_op.f("callback_dagrun_id_fkey"), "dag_run", ["dagrun_id"], 
["id"], ondelete="CASCADE"
+        )
+
+
+def downgrade():

Review Comment:
   We might want to write `dagrun_id` back into `data["dag_run_id"]` before 
dropping the column. The scheduler code before this change reads that key and 
skips the callback without it, so executor callbacks still PENDING at downgrade 
time might never run



##########
airflow-core/src/airflow/migrations/versions/0149_3_5_0_add_dagrun_id_to_callback.py:
##########
@@ -0,0 +1,167 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Add dagrun_id foreign key to callback.
+
+Revision ID: 0f4c9a2b8e1d
+Revises: c71065a1b14f
+Create Date: 2026-08-06 00:00:00.000000
+
+"""
+
+from __future__ import annotations
+
+import json
+
+import sqlalchemy as sa
+from alembic import context, op
+
+from airflow.configuration import conf
+
+# revision identifiers, used by Alembic.
+revision = "0f4c9a2b8e1d"
+down_revision = "c71065a1b14f"
+branch_labels = None
+depends_on = None
+airflow_version = "3.5.0"
+
+
+def _deserialize_data(data):
+    if isinstance(data, str):
+        try:
+            data = json.loads(data)
+        except json.JSONDecodeError:
+            return {}
+    return data.get("__var", data) if isinstance(data, dict) else {}
+
+
+def _extract_dagrun_id(data) -> int | None:
+    dagrun_id = _deserialize_data(data).get("dag_run_id")
+    if dagrun_id is None:
+        return None
+    try:
+        return int(dagrun_id)
+    except (TypeError, ValueError):
+        return None
+
+
+def _backfill_dagrun_id_from_deadline(conn, batch_size: int) -> None:
+    callback = sa.table(
+        "callback",
+        sa.column("id", sa.Uuid()),
+        sa.column("type", sa.String(20)),
+        sa.column("dagrun_id", sa.Integer()),
+    )
+    deadline = sa.table(
+        "deadline",
+        sa.column("callback_id", sa.Uuid()),
+        sa.column("dagrun_id", sa.Integer()),
+    )
+    dag_run = sa.table("dag_run", sa.column("id", sa.Integer()))
+
+    last_id = None
+    while True:
+        query = (
+            sa.select(callback.c.id, deadline.c.dagrun_id)
+            .select_from(
+                callback.join(deadline, callback.c.id == 
deadline.c.callback_id).join(
+                    dag_run, deadline.c.dagrun_id == dag_run.c.id
+                )
+            )
+            .where(callback.c.type == "executor", 
callback.c.dagrun_id.is_(None))
+            .order_by(callback.c.id)
+            .limit(batch_size)
+        )
+        if last_id is not None:
+            query = query.where(callback.c.id > last_id)
+
+        rows = conn.execute(query).fetchall()
+        if not rows:
+            return
+
+        for callback_id, dagrun_id in rows:
+            conn.execute(callback.update().where(callback.c.id == 
callback_id).values(dagrun_id=dagrun_id))
+
+        last_id = rows[-1].id
+
+
+def _backfill_dagrun_id(conn, batch_size: int) -> None:
+    callback = sa.table(
+        "callback",
+        sa.column("id", sa.Uuid()),
+        sa.column("type", sa.String(20)),
+        sa.column("data", sa.Text()),
+        sa.column("dagrun_id", sa.Integer()),
+    )
+    dag_run = sa.table("dag_run", sa.column("id", sa.Integer()))
+
+    last_id = None
+    while True:
+        query = (
+            sa.select(callback.c.id, callback.c.data)
+            .where(callback.c.type == "executor", 
callback.c.dagrun_id.is_(None))
+            .order_by(callback.c.id)
+            .limit(batch_size)
+        )
+        if last_id is not None:
+            query = query.where(callback.c.id > last_id)
+
+        rows = conn.execute(query).fetchall()
+        if not rows:
+            return
+
+        for callback_id, data in rows:
+            dagrun_id = _extract_dagrun_id(data)
+            if dagrun_id is None:
+                continue
+
+            dagrun_exists = conn.execute(
+                sa.select(dag_run.c.id).where(dag_run.c.id == 
dagrun_id).limit(1)
+            ).first()
+            if dagrun_exists:
+                conn.execute(
+                    callback.update().where(callback.c.id == 
callback_id).values(dagrun_id=dagrun_id)
+                )
+
+        last_id = rows[-1].id
+
+
+def upgrade():
+    """Add callback.dagrun_id and backfill it from legacy callback.data."""
+    with op.batch_alter_table("callback") as batch_op:
+        batch_op.add_column(sa.Column("dagrun_id", sa.Integer(), 
nullable=True))
+
+    if not context.is_offline_mode():
+        conn = op.get_bind()
+        batch_size = conf.getint("database", "migration_batch_size")
+        _backfill_dagrun_id_from_deadline(conn, batch_size)
+        _backfill_dagrun_id(conn, batch_size)
+
+    with op.batch_alter_table("callback") as batch_op:
+        batch_op.create_index("callback_dagrun_id_idx", ["dagrun_id"], 
unique=False)
+        batch_op.create_foreign_key(

Review Comment:
   On SQLite I think this empties the deadline table: adding the FK makes 
Alembic rebuild `callback`, and with `PRAGMA foreign_keys=ON` the `DROP TABLE` 
cascades through `deadline.callback_id`. In my local testing, `upgradedb` took 
`deadline` from 2 rows to 0, and `downgrade()` did the same. I think there's 
some guidelines on dealing with this in 
`contributing-docs/26_migration_round_trip_check.rst`. The round-trip CI job 
doesn't seed `callback`/`deadline`, so I don't think it would catch this



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