uranusjr commented on code in PR #76303:
URL: https://github.com/apache/airflow/pull/76303#discussion_r4685396870


##########
airflow-core/src/airflow/executors/base_executor.py:
##########
@@ -208,6 +209,8 @@ class BaseExecutor(LoggingMixin):
     supports_ad_hoc_ti_run: bool = False
     supported_workload_types: frozenset[WorkloadType] = 
frozenset({WorkloadType.EXECUTE_TASK})
     supports_callbacks = _LegacyWorkloadFlag(WorkloadType.EXECUTE_CALLBACK)
+    # Older executors may support deadline alerts without preserving a routed 
task's launch settings.
+    supports_routed_callbacks: bool = False

Review Comment:
   This is a second capability flag next to `supported_workload_types` and 
`supports_callbacks` (`_LegacyWorkloadFlag`). The scheduler then checks both 
(`scheduler_job_runner.py:513-519`, `1748-1752`). This can be done through the 
existing workload-type capability mechanism, or by explaining why "supports 
callbacks but not routed callbacks" has to be a separate state.



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -365,6 +394,37 @@ def _build_pending_partitioned_apdr_filters() -> 
tuple[ColumnElement[bool], ...]
     )
 
 
+@dataclass(frozen=True)
+class _CallbackExecutorRef(BaseWorkload):
+    """The Dag and executor name a Dag processor callback is routed by, to 
look its executor up."""
+
+    dag_id: str
+    executor: str | None
+
+    def get_dag_id(self) -> str | None:
+        return self.dag_id
+
+    def get_executor_name(self) -> str | None:
+        return self.executor

Review Comment:
   This exists only to satisfy `_try_to_load_executor`. Maybe it’s better to 
split executor resolution into a function called by the workload overload.



##########
airflow-core/src/airflow/models/trigger.py:
##########
@@ -931,19 +932,24 @@ def _submit_callback_if_necessary() -> None:
             TaskInstanceState.FAILED,
             TaskInstanceState.UP_FOR_RETRY,
         ):
-            if task_instance.dag_model.relative_fileloc is None:
+            callback_filepath = (
+                dag.relative_fileloc if dag is not None else None
+            ) or task_instance.dag_model.relative_fileloc
+            if callback_filepath is None:
                 raise RuntimeError("relative_fileloc should not be None for a 
finished task")
             from airflow.models.dag_version import 
_resolve_ti_callback_bundle_info
 
             bundle_name, bundle_version, version_data = 
_resolve_ti_callback_bundle_info(task_instance)
             request = TaskCallbackRequest(
-                filepath=task_instance.dag_model.relative_fileloc,
+                filepath=callback_filepath,
                 ti=task_instance_to_runtime(
                     task_instance,
                     model=TIDataModel,
                     map_index=TaskCoordinateResolver(dag_bag, 
session).public_map_index(task_instance),
                 ),
                 task_callback_type=callback_type,
+                # Only a worker running the task sets it, and ``defer_task`` 
clears it.
+                task_started=task_instance.last_heartbeat_at is not None,

Review Comment:
   How is this different from `task_instance.state == 
TaskInstanceState.RUNNING`? Different parts of the code uses this flag instead.



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -2181,6 +2734,11 @@ def _run_scheduler_loop(self) -> None:
             # are picked up each iteration without requiring a scheduler 
restart.
             self._dag_id_to_team_name = {}
             with stats.timer("scheduler.scheduler_loop_duration") as timer:
+                if self._route_dag_processor_callbacks_enabled:
+                    with create_session() as session:
+                        # Ahead of the tasks that would take the free executor 
slots.
+                        self._route_dag_processor_callbacks(session=session)

Review Comment:
   Routing runs in its own transaction with `FOR UPDATE SKIP LOCKED` on every 
loop. The benchmark only covers routing disabled. Since this is on the hot 
path, we probably should have numbers measuring with routing enabled.



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -1496,10 +1570,437 @@ def _enqueue_executor_callbacks(self, session: 
Session) -> None:
                     generator=executor.jwt_generator,
                 )
 
-                executor.queue_workload(workload, session=session)
-                callback.state = CallbackState.QUEUED
+                try:
+                    executor.queue_workload(workload, session=session)
+                except NotImplementedError as e:
+                    # Some executors run callbacks without declaring it, so 
ask the executor itself.
+                    self.log.error("Failing callback %s: %s", callback.id, e)
+                    callback.state = CallbackState.FAILED
+                    callback.output = str(e)
+                else:
+                    callback.state = CallbackState.QUEUED
+                    if callback.fetch_method == 
CallbackFetchMethod.IMPORT_PATH:
+                        callback.data = {**callback.data, 
HEARTBEAT_SUPPORTED_KEY: True}

Review Comment:
   This changes the existing deadline path regardless of the flag. A 
NotImplementedError from `queue_workload` now fails the callback; it would 
propagate previously. The comment says the capability declaration can't be 
trusted, but why not fix the declaration?



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -2145,6 +2675,29 @@ def _run_scheduler_loop(self) -> None:
             self._handle_tasks_stuck_in_queued,
         )
 
+        # Runs even with routing turned off, to settle callbacks routed before 
it was.
+        timers.call_regular_interval(
+            conf.getfloat("scheduler", "task_queued_timeout_check_interval"),
+            self._reap_routed_callbacks,
+            non_fatal=True,
+        )
+        callback_check_interval = conf.getfloat("scheduler", 
"task_queued_timeout_check_interval")
+        if self._route_dag_processor_callbacks_enabled:
+            # Forgets callbacks other schedulers settled, and has the rest 
wait on their current team's
+            # executor.
+            timers.call_regular_interval(callback_check_interval, 
self._waiting_callback_executors.clear)
+        else:
+            # The loop doesn't look for callbacks to route then. Ones stored 
while routing was on, or by
+            # a component that still has it on, are handed back at startup and 
then on this interval.
+            try:
+                self._hand_back_waiting_callbacks()
+            except Exception:
+                # Not worth failing startup for: the timer tries again.
+                self.log.exception("Failed to hand back waiting callbacks")
+            timers.call_regular_interval(
+                callback_check_interval, self._hand_back_waiting_callbacks, 
non_fatal=True
+            )

Review Comment:
   With routing **off** (the default), every scheduler now runs 
`_reap_routed_callbacks` and `_hand_back_waiting_callbacks` on each 
`task_queued_timeout_check_interval` at startup too. That's two extra queries 
per interval for every user not covered by the benchmark. Also, 
`callback_check_interval` is read right after the same value was passed inline.



##########
airflow-core/src/airflow/callbacks/database_callback_sink.py:
##########
@@ -41,5 +49,10 @@ def send(self, callback: CallbackRequest, *, session: 
Session | None = None) ->
         """
         if session is None:
             session = settings.get_session()()
-        db_callback = DbCallbackRequest(callback=callback, priority_weight=1)
-        session.add(db_callback)
+        if self.route_to_executors:

Review Comment:
   Branching on config inside `send()` means a second sink is living inside 
this one. Make it a separate `ExecutorCallbackSink(BaseCallbackSink)` and pick 
the sink once where it's constructed. That's also the natural place to plug in 
custom sinks. The `isinstance(callback, TaskCallbackRequest) and not 
callback.is_failure_callback` filter (L53) should be a property of the request, 
e.g. `request.needs_execution`, not a type check here.



##########
airflow-core/src/airflow/models/callback.py:
##########
@@ -229,10 +251,94 @@ def get_dag_id(self) -> str | None:
         """Return the DAG ID for scheduler routing."""
         return self.data.get("dag_id")
 
+    def get_dag_run(self, *, session: Session) -> DagRun | None:
+        """Resolve the original run even if SQLite has reused its integer 
primary key."""
+        from airflow.callbacks.callback_requests import DagCallbackRequest
+        from airflow.models.dagrun import DagRun
+
+        try:
+            # Deadline.handle_miss stores this integer as a string; routed 
requests store an integer.
+            dag_run_id = int(self.data["dag_run_id"])
+        except (KeyError, TypeError, ValueError):
+            return None
+        request = self.get_callback_request()
+        if request is None:
+            # Deadline.handle_miss snapshots the Dag run before queueing the 
callback.
+            run = ((self.data.get("kwargs") or {}).get("context") or 
{}).get("dag_run") or {}
+            dag_id, run_id = run.get("dag_id"), run.get("dag_run_id")
+            if not dag_id or not run_id:
+                # A deadline row still links a legacy callback to its run via 
foreign keys.
+                from airflow.models.deadline import Deadline
+
+                return session.scalar(
+                    select(DagRun)
+                    .join(Deadline, Deadline.dagrun_id == DagRun.id)
+                    .where(Deadline.callback_id == self.id, DagRun.id == 
dag_run_id)
+                )
+        elif isinstance(request, DagCallbackRequest):
+            dag_id, run_id = request.dag_id, request.run_id
+        else:
+            dag_id, run_id = request.ti.dag_id, request.ti.run_id
+        return session.scalar(
+            select(DagRun).where(DagRun.id == dag_run_id, DagRun.dag_id == 
dag_id, DagRun.run_id == run_id)
+        )

Review Comment:
   At this scale, it might be easier to just do what the TODO comment here was 
leaning toward
   
   
https://github.com/astronomer/airflow/blob/e494b868cf7aca91720031a973c7080b1cf2f661/airflow-core/src/airflow/jobs/scheduler_job_runner.py#L1471-L1473
   
   Since we need to add a migration anyway, adding a proper fk can solve a lot 
of things. (This is similar in principle to the storing flags in `data` point 
raised earlier—we should just make use of database features when they make 
sense.)



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -1496,10 +1570,437 @@ def _enqueue_executor_callbacks(self, session: 
Session) -> None:
                     generator=executor.jwt_generator,
                 )
 
-                executor.queue_workload(workload, session=session)
-                callback.state = CallbackState.QUEUED
+                try:
+                    executor.queue_workload(workload, session=session)
+                except NotImplementedError as e:
+                    # Some executors run callbacks without declaring it, so 
ask the executor itself.
+                    self.log.error("Failing callback %s: %s", callback.id, e)
+                    callback.state = CallbackState.FAILED
+                    callback.output = str(e)
+                else:
+                    callback.state = CallbackState.QUEUED
+                    if callback.fetch_method == 
CallbackFetchMethod.IMPORT_PATH:
+                        callback.data = {**callback.data, 
HEARTBEAT_SUPPORTED_KEY: True}
                 session.add(callback)
 
+    def _route_dag_processor_callbacks(self, *, session: Session) -> None:
+        """
+        Queue Dag processor callbacks on executors.
+
+        With routing on, callback sinks store Dag processor callbacks as 
executor callbacks waiting
+        SCHEDULED (see ``ExecutorCallback.from_dag_processor_request``). A 
routed callback is marked
+        QUEUED in the transaction that queues it. One that no executor can run 
is failed with the
+        reason, and one that fails to route is tried again in a later loop, up 
to
+        ``MAX_ROUTED_CALLBACK_TRIES``.
+
+        Each scheduler admits callbacks per loop into at most half its free 
logical slots and half
+        each of its executor instances' free slots, rounded down, with at 
least one when a slot is
+        free. This leaves local capacity for tasks when more than one slot is 
free; it does not
+        reserve shared workers or limit callback concurrency across 
schedulers. Executors send
+        callbacks first, and one left waiting in an executor for a slot would 
age toward its start
+        deadline. Callbacks that could be routed but find no free slot wait 
for a later loop, while
+        those no executor can run are failed without waiting for one.
+        """
+        free_slots = self._parallelism - sum(executor.slots_occupied for 
executor in self.executors)
+        budget = min(self._max_routed_callbacks_per_loop, max(1, free_slots // 
2)) if free_slots > 0 else 0
+        executor_budgets = {
+            executor: max(1, executor.slots_available // 2) if 
executor.slots_available > 0 else 0
+            for executor in self.executors
+        }
+        now = timezone.utcnow()
+        examined: set[UUID] = set()
+        if budget > 0:
+            # Oldest first, so callbacks are routed in the order they were 
requested.
+            oldest = self._select_waiting_callbacks(session=session)
+            for callback in oldest:
+                examined.add(callback.id)
+                if executor := self._settle_waiting_callback(
+                    callback,
+                    now=now,
+                    can_queue=budget > 0,
+                    executor_budgets=executor_budgets,
+                    session=session,
+                ):
+                    budget -= 1
+                    executor_budgets[executor] -= 1
+            if len(oldest) < self._max_routed_callbacks_per_loop:
+                # That was every waiting callback no other scheduler is 
locking.
+                return
+
+        # After a full oldest window, or none for lack of a free slot, the 
next window is checked too,
+        # resuming after the last one checked, so callbacks waiting for a slot 
don't keep the rest from
+        # being routed or failed.
+        swept = self._select_waiting_callbacks(
+            session=session, after=self._callback_sweep_cursor, 
exclude=examined
+        )
+        self._callback_sweep_cursor = (
+            swept[-1].id if len(swept) == self._max_routed_callbacks_per_loop 
else None
+        )
+        for callback in swept:
+            if executor := self._settle_waiting_callback(
+                callback,
+                now=now,
+                can_queue=budget > 0,
+                executor_budgets=executor_budgets,
+                session=session,
+            ):
+                budget -= 1
+                executor_budgets[executor] -= 1
+
+    def _select_waiting_callbacks(
+        self, *, session: Session, after: UUID | None = None, exclude: 
set[UUID] | None = None
+    ) -> Sequence[ExecutorCallback]:
+        query = (
+            select(ExecutorCallback)
+            .where(
+                ExecutorCallback.fetch_method == 
CallbackFetchMethod.DAG_ATTRIBUTE,
+                ExecutorCallback.state == CallbackState.SCHEDULED,
+            )
+            .order_by(ExecutorCallback.id)
+            .limit(self._max_routed_callbacks_per_loop)
+        )
+        if after is not None:
+            query = query.where(ExecutorCallback.id > after)
+        if exclude:
+            query = query.where(ExecutorCallback.id.not_in(exclude))
+        return session.scalars(with_row_locks(query, session, 
of=ExecutorCallback, skip_locked=True)).all()
+
+    def _settle_waiting_callback(
+        self,
+        callback: ExecutorCallback,
+        *,
+        now: datetime,
+        can_queue: bool,
+        executor_budgets: dict[BaseExecutor, int],
+        session: Session,
+    ) -> BaseExecutor | None:
+        """
+        Route a waiting callback, fail it if no executor can run it, or leave 
it waiting.
+
+        A callback left waiting is only looked up again once its executor has 
a free slot: waiting costs
+        no queries, and the callback is queued by its current Dag run and team.
+
+        :return: The executor it was queued on, or ``None`` if it wasn't 
queued.
+        """
+
+        def has_free_slot(executor: BaseExecutor) -> bool:
+            return can_queue and executor_budgets[executor] > 0 and 
executor.slots_available > 0
+
+        try:
+            executor = self._waiting_callback_executors.pop(callback.id, None)
+            if executor is not None and not has_free_slot(executor):
+                self._waiting_callback_executors[callback.id] = executor
+                return None
+            with session.begin_nested():
+                target = self._get_callback_target(callback, session=session)
+                if has_free_slot(target.executor):
+                    self._queue_routed_callback(callback, target, now=now, 
session=session)
+                    return target.executor
+            self._waiting_callback_executors[callback.id] = target.executor
+        except _UnroutableCallbackError as e:
+            self.log.warning("Failing callback %s, which no executor can run: 
%s", callback.id, e)
+            callback.state = CallbackState.FAILED
+            callback.output = str(e)
+        except Exception as e:
+            self.log.exception("Failed to route callback %s", callback.id)
+            try_number = callback.data.get(TRY_NUMBER_KEY, 1)
+            if try_number < MAX_ROUTED_CALLBACK_TRIES:
+                callback.data = {**callback.data, TRY_NUMBER_KEY: try_number + 
1}
+            else:
+                callback.state = CallbackState.FAILED
+                callback.output = f"Could not be routed in {try_number} tries: 
{e}"
+        return None
+
+    def _get_callback_target(self, callback: ExecutorCallback, *, session: 
Session) -> _CallbackTarget:
+        """
+        Return where a waiting Dag processor callback runs.
+
+        :raises _UnroutableCallbackError: If no executor can run it.
+        """
+        request = callback.get_callback_request()
+        if request is None:
+            raise _UnroutableCallbackError("It stores no callback request")
+        executor_name: str | None = None
+        queue: str | None = None
+        executor_config: dict | None = None
+        if isinstance(request, DagCallbackRequest):
+            dag_id, run_id = request.dag_id, request.run_id
+        else:
+            dag_id, run_id = request.ti.dag_id, request.ti.run_id

Review Comment:
   There are several of this kind of branches. This probably should live on 
each request type as a function instead.



##########
airflow-core/src/airflow/api_fastapi/execution_api/routes/callbacks.py:
##########
@@ -58,39 +110,207 @@ def run_callback(
     response: Response,
     session: SessionDep,
     services=DepContainer,
+    body: CallbackRunPayload | None = None,
+    prefer: Annotated[str | None, Header()] = None,
 ) -> None:
-    """Exchange a single-use callback token for a short-lived execution 
token."""
-    callback = session.get(Callback, callback_id, with_for_update=True)
-    if callback is None:
+    """
+    Exchange a single-use callback token for a short-lived execution token.
+
+    An attempt that identifies itself can repeat its own exchange, as when it 
never got the response,
+    and gets a new execution token. Any other exchange of a callback that 
already started is refused,
+    including a second delivery of its workload.
+
+    A deadline worker can request heartbeats with ``Prefer: 
callback-heartbeat``. When enabled,
+    the response returns its worker timeout in seconds in 
``Airflow-Callback-Heartbeat-Timeout``.
+    """
+    callback = _get_callback(callback_id, session=session, for_update=True)
+    started_by = body.model_dump(mode="json") if body is not None else None
+    heartbeat_timeout = (
+        _get_callback_heartbeat_timeout()
+        if (
+            started_by is not None
+            and prefer == "callback-heartbeat"
+            and callback.fetch_method == CallbackFetchMethod.IMPORT_PATH
+            and callback.data.get(HEARTBEAT_SUPPORTED_KEY)
+        )
+        else None
+    )
+    if not callback.try_start(
+        timezone.utcnow(), started_by=started_by, 
heartbeat_timeout=heartbeat_timeout, session=session
+    ):
+        callback = _get_callback(callback_id, session=session, for_update=True)
+        if callback.state == CallbackState.QUEUED and callback.state_deadline 
is not None:
+            raise HTTPException(
+                status_code=status.HTTP_409_CONFLICT,
+                detail={
+                    "reason": "start_deadline_passed",
+                    "message": f"Callback {callback_id} had to start by 
{callback.state_deadline.isoformat()}",
+                },
+            )
+        if callback.state != CallbackState.RUNNING or started_by is None or 
callback.started_by != started_by:
+            raise HTTPException(
+                status_code=status.HTTP_409_CONFLICT,
+                detail={
+                    "reason": "invalid_state",
+                    "message": (
+                        f"Callback {callback_id} is in state {callback.state}; 
its token can only be "
+                        "exchanged once while QUEUED."
+                    ),
+                    "previous_state": callback.state,
+                    "worker_is_monitored": callback.state_deadline is not None,
+                },
+            )
+        # A retry whose first response was lost repeats the original 
negotiation.
+        if callback.fetch_method == CallbackFetchMethod.IMPORT_PATH and 
callback.state_deadline is not None:
+            heartbeat_timeout = _get_callback_heartbeat_timeout()
+            _renew_callback_heartbeat(callback_id, heartbeat_timeout, 
session=session)
+        else:
+            heartbeat_timeout = None
+
+    if heartbeat_timeout is not None:
+        response.headers["Airflow-Callback-Heartbeat-Timeout"] = 
str(int(heartbeat_timeout.total_seconds()))
+    # A routed callback doesn't heartbeat, so its token must last until it 
reports its outcome.
+    timeout = callback.data.get(EXECUTION_TIMEOUT_KEY)
+    issue_execution_token(
+        services,
+        response,
+        sub=str(callback.id),
+        claims=_get_identity_claims(callback, session=session),
+        min_valid_for=get_callback_report_window(timeout) if timeout else None,
+    )

Review Comment:
   Why not heartbeat routed callbacks as well, like tasks? Then the token 
validity hack (`min_valid_for`) and `get_callback_report_window` go away.



##########
airflow-core/src/airflow/api_fastapi/execution_api/versions/v2027_02_28.py:
##########
@@ -103,3 +103,27 @@ class AddCallbackStateEndpoint(VersionChange):
     instructions_to_migrate_to_previous_version = (
         endpoint("/callbacks/{callback_id}/state", ["PATCH"]).didnt_exist,
     )
+
+
+class AddCallbackContextEndpoint(VersionChange):
+    """
+    Add the endpoint a routed Dag processor callback reads its context from.
+
+    It can also read its Dag's previous successful run. An attempt to run a 
callback can also identify
+    itself when it exchanges the callback's token, so it can repeat its own 
exchange. Requests of
+    earlier versions keep the single-use exchange.
+    """

Review Comment:
   This should mention `/heartbeat` and the header protocol.



##########
airflow-core/src/airflow/models/callback.py:
##########
@@ -321,26 +427,55 @@ class ExecutorCallback(Callback):
     __mapper_args__ = {"polymorphic_identity": CallbackType.EXECUTOR}
 
     def __init__(
-        self, callback_def: ImportPathExecutorCallbackDefProtocol, 
fetch_method: CallbackFetchMethod, **kwargs
+        self,
+        callback_def: ImportPathExecutorCallbackDefProtocol | None,
+        fetch_method: CallbackFetchMethod,
+        *,
+        request: CallbackRequest | None = None,
+        **kwargs,
     ):
         """
-        Initialize an ExecutorCallback from a callback definition and fetch 
method.
+        Initialize an ExecutorCallback from a callback definition, or from a 
Dag processor callback request.
 
-        :param callback_def: Callback definition with path, kwargs, and 
executor
+        :param callback_def: Callback definition with path, kwargs, and 
executor; ``None`` with ``request``
         :param fetch_method: Method to fetch the callback at runtime
+        :param request: Dag processor callback request, for a callback the 
scheduler routes to an executor
         :param kwargs: Passed to parent Callback.__init__ (see base class for 
details)
         """
         from airflow.serialization.encoders import 
encode_stored_callback_kwargs
 
         super().__init__(**kwargs)
         self.fetch_method = fetch_method
+        if request is not None:
+            self.bundle_name = request.bundle_name
+            self.data |= _get_request_data(request)
+            return

Review Comment:
   I suspect it’d be better if this case builds a subclass. The branching can 
be done in  `from_dag_processor_request`.



##########
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/token.py:
##########
@@ -48,6 +48,11 @@ class TIClaims(_JWTClaims):
     scope: TaskTokenScope = "execution"
     # Trusted in-process callers construct task identities without a JWT or 
expiry.
     exp: float | None = None
+    # Signed into the execution token a callback exchanges for: a callback has 
no task instance
+    # to resolve its Dag, run, bundle or team from.
+    dag_id: str | None = None
+    run_id: str | None = None
+    bundle_name: str | None = None

Review Comment:
   Probably better to have a separate `CallbackClaims` model, and let the claim 
type decide how the team is resolved. This avoids field checks in 
`_team_name_for_requester_stmt`.



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -1496,10 +1570,437 @@ def _enqueue_executor_callbacks(self, session: 
Session) -> None:
                     generator=executor.jwt_generator,
                 )
 
-                executor.queue_workload(workload, session=session)
-                callback.state = CallbackState.QUEUED
+                try:
+                    executor.queue_workload(workload, session=session)
+                except NotImplementedError as e:
+                    # Some executors run callbacks without declaring it, so 
ask the executor itself.
+                    self.log.error("Failing callback %s: %s", callback.id, e)
+                    callback.state = CallbackState.FAILED
+                    callback.output = str(e)
+                else:
+                    callback.state = CallbackState.QUEUED
+                    if callback.fetch_method == 
CallbackFetchMethod.IMPORT_PATH:
+                        callback.data = {**callback.data, 
HEARTBEAT_SUPPORTED_KEY: True}

Review Comment:
   Also, I wonder if whether heartbeat is supported should just be a regular 
column instead of stored in `data`, as raised in 
https://github.com/apache/airflow/pull/76303#pullrequestreview-5967389319



##########
task-sdk/src/airflow/sdk/execution_time/callback_supervisor.py:
##########
@@ -80,11 +106,44 @@ class _BundleInfoLike(Protocol):
 log: FilteringBoundLogger = 
structlog.get_logger(logger_name="callback_supervisor")
 
 
-# The set of messages that a callback subprocess can send to the supervisor.
-# This is a minimal subset of ToSupervisor: read-only access to Connections,
-# Variables, and XCom values, plus MaskSecret for the secrets masker.
+# The set of messages that a callback subprocess can send to the supervisor: 
the requests a Dag
+# processor answers for the callbacks it runs, so a Dag or task callback has 
the same context on a
+# worker, plus asset alias resolution during context construction and 
MaskSecret for the secrets masker.
+_CALLBACK_REQUEST_TYPES: tuple[type[BaseModel], ...] = (
+    DeleteVariable,
+    GetAssetsByAlias,
+    GetConnection,
+    GetPrevSuccessfulDagRun,
+    GetPreviousDagRun,
+    GetPreviousTI,
+    GetTICount,
+    GetTaskStates,
+    GetVariable,
+    GetVariableKeys,
+    GetXCom,
+    GetXComCount,
+    GetXComSequenceItem,
+    GetXComSequenceSlice,
+    MaskSecret,
+    PutVariable,
+)
 CallbackToSupervisor = Annotated[
-    GetConnection | GetVariable | GetVariableKeys | GetXCom | MaskSecret,
+    DeleteVariable
+    | GetAssetsByAlias
+    | GetConnection
+    | GetPrevSuccessfulDagRun
+    | GetPreviousDagRun
+    | GetPreviousTI
+    | GetTICount
+    | GetTaskStates
+    | GetVariable
+    | GetVariableKeys
+    | GetXCom
+    | GetXComCount
+    | GetXComSequenceItem
+    | GetXComSequenceSlice
+    | MaskSecret
+    | PutVariable,
     Field(discriminator="type"),
 ]

Review Comment:
   Would it be a good idea to gate the extra request types on `fetch_method` 
instead of widening the shared union?



##########
task-sdk/src/airflow/sdk/execution_time/execute_workload.py:
##########
@@ -99,7 +102,11 @@ def main():
             log.error("Failed to parse input JSON string", error=str(e))
             sys.exit(1)
 
-    execute_workload(workload)
+    try:
+        execute_workload(workload)
+    except CallbackAlreadyStartedError:
+        # A container executor must distinguish a duplicate delivery from the 
admitted worker's failure.
+        sys.exit(os.EX_TEMPFAIL)

Review Comment:
   `os.EX_TEMPFAIL` becomes an implicit protocol that ECS and Batch executors 
match on. This should be defined and documented explicitly as part of the 
executor contract. A hook on `BaseExecutor` hook covering this (that the 
callback path overrides) would also be better than doing `isinstance` and 
`hasattr` checks in every provider.



##########
task-sdk/src/airflow/sdk/execution_time/dag_attribute_callbacks.py:
##########
@@ -0,0 +1,252 @@
+# 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.
+"""
+Run the Dag and task callbacks, and task emails, that the scheduler routes to 
executors.
+
+These are the callbacks a Dag processor otherwise runs inside a parse of the 
Dag file. The worker
+parses the file at the Dag run's bundle version, finds the callbacks on the 
Dag or task, and runs
+them with the context the scheduler recorded when it requested them. Changes 
to callback selection
+or context also apply to 
``airflow.dag_processing.processor._execute_callbacks``.
+"""
+
+from __future__ import annotations
+
+import os
+from collections.abc import Sequence
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from airflow.dag_processing.bundles.base import BundleVersionLock  # noqa: 
SDK002
+from airflow.sdk._shared.observability.metrics import stats
+from airflow.sdk.api.datamodels._generated import (
+    DagCallbackContext,
+    EmailCallbackContext,
+    TaskCallbackContext,
+    TaskInstanceState,
+    TIRunContext,
+)
+from airflow.sdk.definitions.context import CallbackMeta, CallbackSource
+from airflow.sdk.definitions.dag import DAG
+from airflow.sdk.exceptions import TaskNotFound
+
+if TYPE_CHECKING:
+    from structlog.typing import FilteringBoundLogger
+
+    from airflow.sdk.api.datamodels._generated import BundleInfo
+    from airflow.sdk.definitions.context import Context
+
+    CallbackContext = DagCallbackContext | TaskCallbackContext | 
EmailCallbackContext
+
+__all__ = ["run_dag_attribute_callbacks"]
+
+_FAILURE_CALLBACK_TYPES = frozenset(
+    (TaskInstanceState.FAILED, TaskInstanceState.UP_FOR_RETRY, 
TaskInstanceState.UPSTREAM_FAILED)
+)
+
+
+def run_dag_attribute_callbacks(
+    context: CallbackContext,
+    *,
+    dag_rel_path: os.PathLike[str],
+    bundle_info: BundleInfo,
+    log: FilteringBoundLogger,
+) -> list[str]:
+    """
+    Parse the callback's Dag file and run its callbacks, returning one message 
per failure.
+
+    Each callback runs even if an earlier one failed, as in the Dag processor.
+    """
+    from airflow.sdk.execution_time.bundles import initialize_ti_bundle
+
+    try:
+        bundle = initialize_ti_bundle(bundle_info)
+        with BundleVersionLock(bundle_name=bundle.name, 
bundle_version=bundle.version):
+            dag = _load_dag(_get_dag_id(context), Path(bundle.path, 
dag_rel_path), bundle.path, bundle.name)
+            if isinstance(context, DagCallbackContext):
+                return _run_dag_callbacks(context, dag, log)
+            if isinstance(context, TaskCallbackContext):
+                return _run_task_callbacks(context, dag, log)
+            return _send_task_email(context, dag, log)

Review Comment:
   Use a mapping from context type to runner, or `functools.singledispatch`.



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