o-nikolas commented on code in PR #77653:
URL: https://github.com/apache/airflow/pull/77653#discussion_r4714269268


##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/executors/kubernetes_executor_utils.py:
##########
@@ -189,29 +203,35 @@ def _run(
             if event["type"] == "ERROR":
                 return self.process_error(event)
             annotations = task.metadata.annotations
-            task_instance_related_annotations = {
-                "dag_id": annotations["dag_id"],
-                "task_id": annotations["task_id"],
-                logical_date_key: annotations.get(logical_date_key),
-                "run_id": annotations.get("run_id"),
-                "try_number": annotations["try_number"],
-            }
-            if TASK_INSTANCE_ID_ANNOTATION in annotations:
-                task_instance_related_annotations[TASK_INSTANCE_ID_ANNOTATION] 
= annotations[
-                    TASK_INSTANCE_ID_ANNOTATION
-                ]
-            elif self.supports_task_instance_uuid:
-                if identity := task_instance_id_from_pod(task):
-                    
task_instance_related_annotations[TASK_INSTANCE_ID_ANNOTATION] = str(identity)
-            map_index = annotations.get("map_index")
-            if map_index is not None:
-                task_instance_related_annotations["map_index"] = map_index
+            if CALLBACK_POD_ANNOTATION_KEY in annotations:

Review Comment:
   Small robustness thing: this check (and the ones in `process_status`, 
`_format_pod_log_key`, `process_watcher_task`, and `_adopt_completed_pods` in 
the executor) keys off the bare `callback_id` annotation without the 
`AIRFLOW_V_3_3_PLUS` gate that `_is_callback_key` has. On Airflow < 3.3 a task 
pod that picks up a `callback_id` annotation from a pod template or 
`pod_override` would hit a `NameError` on `CallbackKey`/`CallbackState`. 
Unlikely, but a tiny `_is_callback_pod(annotations)` helper that also checks 
the version flag would close it.



##########
kubernetes-tests/tests/kubernetes_tests/test_kubernetes_executor.py:
##########
@@ -244,3 +248,177 @@ def test_pod_failure_logging_non_failed_state(self, 
mock_log, executor_task_key)
         mock_log.warning.assert_not_called()
 
         executor.kube_client.read_namespaced_pod.assert_not_called()
+
+
[email protected](EXECUTOR != "KubernetesExecutor", reason="Only runs on 
KubernetesExecutor")
+class TestKubernetesExecutorCallbacks(BaseK8STest):
+    """
+    Integration tests for deadline callbacks run as pods on the Kubernetes 
executor.
+
+    Each test triggers its own Dag run and follows the callback that run 
created, so other callback pods in
+    the namespace cannot satisfy it.  No public API exposes executor callback 
rows, so the callback is looked
+    up in the metadata database from inside the scheduler pod.
+
+    Prerequisites:
+      - The ``example_deadline_callback`` Dag must be loaded in the cluster.
+    """
+
+    _DAG_ID = "example_deadline_callback"
+    _CALLBACK_LABEL = "airflow-workload-type=callback"
+    _CALLBACK_ANNOTATION_KEY = "callback_id"
+    _TERMINAL_STATES = ("success", "failed")
+
+    _QUERY_CALLBACK_SCRIPT = dedent(
+        """\
+        import json
+        import sys
+
+        from sqlalchemy import select
+
+        from airflow.models.callback import Callback
+        from airflow.models.dagrun import DagRun
+        from airflow.models.deadline import Deadline
+        from airflow.utils.session import create_session
+
+        dag_id, run_id = sys.argv[1:3]
+        with create_session() as session:
+            row = session.execute(
+                select(Callback.id, Callback.state)
+                .join(Deadline, Deadline.callback_id == Callback.id)
+                .join(DagRun, DagRun.id == Deadline.dagrun_id)
+                .where(DagRun.dag_id == dag_id, DagRun.run_id == run_id)
+            ).first()
+        print("CALLBACK_ROW " + json.dumps(None if row is None else 
[str(row[0]), row[1]]))
+        """
+    )
+
+    @classmethod
+    def _find_callback(cls, dag_id: str, run_id: str, namespace: str = 
"airflow") -> tuple[str, str] | None:
+        """Return ``(callback_id, state)`` of the callback created for a Dag 
run, if it exists yet."""
+        output = check_output(
+            [
+                "kubectl",
+                "exec",
+                "-n",
+                namespace,
+                "deploy/airflow-scheduler",
+                "-c",
+                "scheduler",
+                "--",
+                "python",
+                "-c",
+                cls._QUERY_CALLBACK_SCRIPT,
+                dag_id,
+                run_id,
+            ]
+        )
+        # Airflow logs to stdout before and after the result, at interpreter 
exit included, so find it by
+        # its marker rather than its position.
+        line = next(line for line in output.decode().splitlines() if 
line.startswith("CALLBACK_ROW "))
+        row = json.loads(line.removeprefix("CALLBACK_ROW "))
+        return None if row is None else (row[0], row[1])
+
+    @classmethod
+    def _wait_for_callback_state(
+        cls, dag_id: str, run_id: str, states: tuple[str, ...], timeout: int = 
180
+    ) -> tuple[str, str]:
+        deadline = time.monotonic() + timeout
+        found = None
+        while time.monotonic() < deadline:
+            found = cls._find_callback(dag_id, run_id)
+            if found is not None and found[1] in states:
+                return found
+            time.sleep(2)
+        raise AssertionError(
+            f"Callback for {dag_id}/{run_id} did not reach one of {states} 
within {timeout}s (last seen: {found})"
+        )
+
+    @classmethod
+    def _find_callback_pod(cls, callback_id: str, namespace: str = "airflow") 
-> dict | None:
+        raw = check_output(
+            ["kubectl", "get", "pods", "-n", namespace, "-l", 
cls._CALLBACK_LABEL, "-o", "json"]
+        )
+        return next(
+            (
+                pod
+                for pod in json.loads(raw)["items"]
+                if pod["metadata"].get("annotations", 
{}).get(cls._CALLBACK_ANNOTATION_KEY) == callback_id
+            ),
+            None,
+        )
+
+    @classmethod
+    def _wait_for_callback_pod(cls, callback_id: str, timeout: int = 120) -> 
dict:
+        deadline = time.monotonic() + timeout
+        while time.monotonic() < deadline:
+            if pod := cls._find_callback_pod(callback_id):
+                return pod
+            time.sleep(0.5)
+        raise AssertionError(f"No pod for callback {callback_id} appeared 
within {timeout}s")
+
+    @classmethod
+    def _wait_for_callback_pod_gone(cls, callback_id: str, timeout: int = 120) 
-> None:
+        deadline = time.monotonic() + timeout
+        while time.monotonic() < deadline:
+            if cls._find_callback_pod(callback_id) is None:
+                return
+            time.sleep(2)
+        raise AssertionError(f"Pod for callback {callback_id} was not deleted 
within {timeout}s")
+
+    def _trigger_dag_run(self, dag_id: str) -> str:
+        result_json = self.start_dag(dag_id=dag_id, host=self.host)
+        dag_runs = result_json.get("dag_runs", [])
+        matching = [r for r in dag_runs if r["dag_id"] == dag_id]
+        assert matching, f"No dag runs returned for dag_id={dag_id!r}"
+        newest = max(matching, key=lambda r: r["queued_at"])
+        return newest["dag_run_id"]
+
+    @pytest.mark.execution_timeout(300)
+    def test_deadline_callback_executes_on_kubernetes(self):
+        run_id = self._trigger_dag_run(self._DAG_ID)
+
+        callback_id, state = self._wait_for_callback_state(self._DAG_ID, 
run_id, self._TERMINAL_STATES)
+
+        assert state == "success", f"Callback {callback_id} ended in state 
{state!r}"
+
+    @pytest.mark.execution_timeout(300)
+    def test_callback_pod_annotations_and_labels(self):
+        run_id = self._trigger_dag_run(self._DAG_ID)
+        callback_id, _ = self._wait_for_callback_state(
+            self._DAG_ID, run_id, ("queued", "running", *self._TERMINAL_STATES)
+        )
+
+        pod = self._wait_for_callback_pod(callback_id)

Review Comment:
   I think this one could flake: if the first DB poll that finds the callback 
already sees `success`, the pod may already be deleted before 
`_wait_for_callback_pod` starts looking, and the test fails after 120s. Each 
poll is a `kubectl exec` that imports Airflow, so the queued/running window is 
easy to miss. Maybe collect the `airflow-workload-type=callback` pods while 
polling the DB and match on `callback_id` afterwards?



##########
providers/cncf/kubernetes/docs/kubernetes_executor.rst:
##########
@@ -279,6 +279,21 @@ Finally, note that it does not have to be either-or; using 
the `Multiple Executo
 
<https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/executor/index.html#using-multiple-executors-concurrently>`_,
 it is possible to use both CeleryExecutor and KubernetesExecutor 
simultaneously on the same cluster.
 
+Running callbacks
+-----------------
+
+On Airflow 3.3 and later, the KubernetesExecutor also runs executor callbacks, 
such as the callback of a
+:class:`~airflow.sdk.DeadlineAlert` defined with a 
:class:`~airflow.sdk.SyncCallback`.  Each callback runs in its own
+pod, built from the same ``pod_template_file`` and image as task pods.  The 
pod is labeled
+``airflow-workload-type=callback`` and carries a ``callback_id`` annotation 
instead of task annotations.

Review Comment:
   Could we add a line here that `pod_mutation_hook` also runs on callback 
pods, and that they carry no `dag_id`/`task_id`/`run_id` labels or annotations? 
A hook that does `pod.metadata.labels["dag_id"]` would fail every callback with 
a `PodMutationHookException`, so it's a useful heads-up for people turning this 
on.



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