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


##########
airflow-core/src/airflow/jobs/triggerer_job_runner.py:
##########
@@ -1050,13 +1055,41 @@ def _create_workload(
             if trigger.assets:
                 watched_assets = {a.name: a.uri for a in trigger.assets}
 
+            dag_run_data = dag_data = None
             if callback := getattr(trigger, "callback", None):
-                # Log callback triggers to a file the UI callback logs 
endpoint can read.
                 callback_data = callback.data or {}
-                context = (callback_data.get("kwargs") or {}).get("context") 
or {}
-                dag_run_data = context.get("dag_run") or {}
-                dag_id = callback_data.get("dag_id") or 
dag_run_data.get("dag_id") or "unknown"
-                run_id = dag_run_data.get("dag_run_id") or "unknown"
+                dag_run = self._fetch_callback_dag_run(callback_data, 
session=session)
+                if dag_run is not None:
+                    # Send the Dag run and the serialized Dag, as for 
start_from_trigger tasks below.
+                    dag_run_data = 
dag_run.dag_run_data.model_dump(exclude_unset=True)
+                    dag_run_data["_deadline"] = {

Review Comment:
   Nit: putting `_deadline` inside `dag_run_data` means anything reading that 
field as a Dag run has to know to pop it first. Since `RunTrigger` is internal 
to the triggerer, a separate field for the deadline could be cleaner.



##########
task-sdk/src/airflow/sdk/execution_time/callback_supervisor.py:
##########
@@ -198,6 +214,10 @@ def execute_callback(
             module = import_module(module_path)
         callback_callable = getattr(module, function_name)
         callback_kwargs = decode_callback_kwargs(callback_kwargs, 
callback_kwargs_encoding)
+        if render_kwargs and not inspect.isclass(callback_callable):
+            from airflow.sdk.execution_time.context import 
render_callback_kwargs
+
+            callback_kwargs = render_callback_kwargs(callback_kwargs, 
callback_kwargs["context"])

Review Comment:
   If a function callback returns a notifier instance, its kwargs get rendered 
here and then again in `BaseNotifier.__call__` via `result(context)`, so a 
`dag_run.conf` value with braces in it would be evaluated on the second pass. 
Is returning a notifier from a function something we support? If yes, maybe 
skip the `result(context)` call unless the callback was a class, or document it.
   



##########
task-sdk/src/airflow/sdk/definitions/context.py:
##########
@@ -76,6 +77,8 @@ class Context(TypedDict, total=False):
     dag_run: DagRunProtocol
     data_interval_end: NotRequired[DateTime | None]
     data_interval_start: NotRequired[DateTime | None]
+    # Only in deadline callbacks: ``{"id": ..., "deadline_time": ...}``.
+    deadline: NotRequired[dict[str, Any]]

Review Comment:
   +1 to leaving `deadline` out of `KNOWN_CONTEXT_KEYS`. `callback` from #76110 
has the same problem: it's only set in callback contexts, but it's reserved as 
a `@task` argument name too. It isn't in 3.4.0, so if we exclude both now (here 
or in a quick follow-up), neither reservation ever ships.



##########
airflow-core/src/airflow/jobs/triggerer_job_runner.py:
##########
@@ -1050,13 +1055,41 @@ def _create_workload(
             if trigger.assets:
                 watched_assets = {a.name: a.uri for a in trigger.assets}
 
+            dag_run_data = dag_data = None
             if callback := getattr(trigger, "callback", None):
-                # Log callback triggers to a file the UI callback logs 
endpoint can read.
                 callback_data = callback.data or {}
-                context = (callback_data.get("kwargs") or {}).get("context") 
or {}
-                dag_run_data = context.get("dag_run") or {}
-                dag_id = callback_data.get("dag_id") or 
dag_run_data.get("dag_id") or "unknown"
-                run_id = dag_run_data.get("dag_run_id") or "unknown"
+                dag_run = self._fetch_callback_dag_run(callback_data, 
session=session)
+                if dag_run is not None:
+                    # Send the Dag run and the serialized Dag, as for 
start_from_trigger tasks below.
+                    dag_run_data = 
dag_run.dag_run_data.model_dump(exclude_unset=True)
+                    dag_run_data["_deadline"] = {
+                        "id": callback_data.get("deadline_id"),
+                        "deadline_time": callback_data.get("deadline_time"),
+                    }
+                    if serialized_dag_model := 
dag_bag.get_serialized_dag_model_for_run(
+                        dag_run, session=session
+                    ):
+                        dag_data = serialized_dag_model.data
+                elif callback_data.get("run_id"):
+                    from airflow.models.callback import CallbackState

Review Comment:
   Can these imports go at the top of the file. I don't see a circular import?



##########
task-sdk/src/airflow/sdk/execution_time/context.py:
##########
@@ -1793,3 +1794,125 @@ def context_get_outlet_events(context: Context) -> 
OutletEventAccessorsProtocol:
     except KeyError:
         outlet_events = context["outlet_events"] = OutletEventAccessors()
     return outlet_events
+
+
+def build_dag_run_context(
+    dag_run: DagRunProtocol, dag: DAG | None = None, *, multi_team: bool = 
False
+) -> Context:
+    """
+    Build the part of a task's template context that comes from its Dag run.
+
+    ``RuntimeTaskInstance.get_template_context`` adds the task keys to it, and 
deadline callbacks,
+    which have a Dag run but no task, use it as their context. With ``dag``, 
it also has ``dag``
+    and the Dag's ``params`` with the Dag run's ``conf`` applied.
+    """
+    from airflow.sdk.definitions.param import process_params
+    from airflow.sdk.execution_time.comms import 
AssetEventDagRunReferenceResult
+    from airflow.sdk.plugins_manager import integrate_macros_plugins
+    from airflow.sdk.timezone import coerce_datetime
+
+    integrate_macros_plugins()
+
+    context: Context = {
+        "dag_run": dag_run,
+        "run_id": dag_run.run_id,
+        "partition_key": dag_run.partition_key,
+        "partition_date": coerce_datetime(dag_run.partition_date),
+        "triggering_asset_events": TriggeringAssetEventsAccessor.build(

Review Comment:
   I'd rather we fix this one than document it. Could we carry the run's 
team_name into dag_run_data here, with a small test? The asset events and the 
other missing fields are fine in the docs for me.



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