kaxil commented on code in PR #75429:
URL: https://github.com/apache/airflow/pull/75429#discussion_r4712249444


##########
providers/databricks/src/airflow/providers/databricks/operators/databricks.py:
##########
@@ -2063,7 +2063,18 @@ def _convert_to_databricks_workflow_task(
         context: Context | None = None,
     ) -> dict[str, object]:
         """Convert the operator to a Databricks workflow task that can be a 
task in a workflow."""
-        base_task_json = self._get_task_base_json()
+        if context is not None:
+            fields_to_render = [f for f in self.template_fields if f != 
"workflow_run_metadata"]
+            if fields_to_render:
+                operator_proxy = copy.copy(self)

Review Comment:
   If this starts from `operator_proxy = self` and only copies and renders when 
`context` is set, the two `else` arms go away, and `_retry_settings()` below 
can read from `operator_proxy` as well, which also fixes the templated 
`max_retries` failure raised in the PR conversation.



##########
providers/databricks/docs/operators/workflow.rst:
##########
@@ -68,3 +68,10 @@ To minimize update conflicts, we recommend that you keep 
parameters in the ``not
 ``DatabricksWorkflowTaskGroup`` and not in the ``DatabricksNotebookOperator`` 
whenever possible.
 This is because, tasks in the ``DatabricksWorkflowTaskGroup`` are passed in on 
the job trigger time and
 do not modify the job definition.
+
+Templating in workflow tasks
+----------------------------
+
+When a workflow job is created or updated in Databricks by the launch task, 
member tasks have their declared ``template_fields`` rendered against the 
launch task's execution context (e.g. ``{{ ds }}``, ``{{ dag_run }}``, ``{{ 
params }}``).
+
+Because all tasks in the workflow are defined when the launch task executes, 
task-scoped expressions that require an individual member's task instance (such 
as ``{{ ti }}`` or task-specific XCom pulls) are not supported in workflow 
member definitions. Run-scoped expressions (execution dates, run configuration, 
parameters) should be used instead.

Review Comment:
   `{{ ti }}` isn't rejected: it renders as the launch task's TI with no error, 
and `ti.xcom_pull(...)` goes through the launch TI too, so it only finds tasks 
that finished before launch. Member-level `params=` aren't in the launch 
context either, so a `{{ params.x }}` defined only on the member raises 
`UndefinedError` in the launch task. Could this and the docstring note say the 
context is the launch task's (`ti`, `task` and task-level `params` all belong 
to `launch`), rather than that member TIs don't exist yet?



##########
providers/databricks/src/airflow/providers/databricks/operators/databricks.py:
##########
@@ -2063,7 +2063,18 @@ def _convert_to_databricks_workflow_task(
         context: Context | None = None,
     ) -> dict[str, object]:
         """Convert the operator to a Databricks workflow task that can be a 
task in a workflow."""
-        base_task_json = self._get_task_base_json()
+        if context is not None:
+            fields_to_render = [f for f in self.template_fields if f != 
"workflow_run_metadata"]
+            if fields_to_render:
+                operator_proxy = copy.copy(self)
+                operator_proxy._do_render_template_fields(

Review Comment:
   Besides the `UndefinedError` for unescaped references mentioned in the PR 
conversation, Databricks' legacy `{{run_id}}` variable is also an Airflow 
context key. A member passing it in `notebook_params` or `task_config` used to 
get the Databricks run id and now silently gets the Airflow `run_id`. Can the 
changelog and the new docs section say that Databricks references in member 
fields must be wrapped in `{% raw %}...{% endraw %}`, and call out `{{run_id}}` 
as the one that changes without an error?



##########
providers/databricks/tests/unit/databricks/operators/test_databricks.py:
##########
@@ -4086,6 +4086,10 @@ def test_custom_query_tags_override_airflow_tags(self, 
db_mock_class):
 
 
 class TestDatabricksNotebookOperator:
+    def test_notebook_path_and_source_in_template_fields(self):

Review Comment:
   This only checks membership, and 
`test_create_workflow_json_renders_notebook_operator_template_fields` already 
fails if either field is dropped from `template_fields`. Can it go?



##########
providers/databricks/docs/operators/workflow.rst:
##########
@@ -68,3 +68,10 @@ To minimize update conflicts, we recommend that you keep 
parameters in the ``not
 ``DatabricksWorkflowTaskGroup`` and not in the ``DatabricksNotebookOperator`` 
whenever possible.
 This is because, tasks in the ``DatabricksWorkflowTaskGroup`` are passed in on 
the job trigger time and
 do not modify the job definition.
+
+Templating in workflow tasks
+----------------------------
+
+When a workflow job is created or updated in Databricks by the launch task, 
member tasks have their declared ``template_fields`` rendered against the 
launch task's execution context (e.g. ``{{ ds }}``, ``{{ dag_run }}``, ``{{ 
params }}``).

Review Comment:
   There's one Databricks job per Dag (`{dag_id}.{group_id}`) and launch resets 
it on every run, so a rendered `{{ ds }}` ends up in the shared job definition. 
During a backfill, or when an older run is cleared, a second launch can call 
`reset_job` before the first one gets to `run_now`, and the first run then 
executes with the other run's date. `extra_job_params` can hit this already. 
Worth a warning in this section? The group-level `notebook_params` / 
`python_params` are sent in the `run_now` call, so they stay per run.



##########
providers/databricks/tests/unit/databricks/operators/test_databricks_workflow.py:
##########
@@ -647,3 +651,269 @@ def test_downstream_set_after_with_block(self):
             tg >> end
         nb = dag.get_task("tg.nb")
         assert "end" in nb.downstream_task_ids
+
+
+class CustomWorkflowTaskOperator(DatabricksTaskBaseOperator):
+    """Custom operator subclassing DatabricksTaskBaseOperator for GH-46563 
reproduction."""
+
+    template_fields = ("application_args", "spark_conf")
+
+    def __init__(self, application_args=None, spark_conf=None, **kwargs):
+        self.application_args = application_args or []
+        self.spark_conf = spark_conf or {}
+        super().__init__(**kwargs)
+
+    def _get_task_base_json(self):
+        return {
+            "spark_jar_task": {
+                "parameters": self.application_args,
+                "spark_conf": self.spark_conf,
+            }
+        }
+
+
+class TestWorkflowTemplateFields:
+    """Tests for template field rendering in DatabricksWorkflowTaskGroup 
members (GH-46563)."""
+
+    def test_create_workflow_json_renders_task_operator_template_fields(self):
+        """Test that DatabricksTaskOperator task_config is rendered with 
execution context."""
+        with DAG(dag_id="test_dag_task_op", start_date=DEFAULT_DATE, 
schedule=None) as dag:
+            with DatabricksWorkflowTaskGroup(
+                group_id="test_tg",
+                databricks_conn_id="databricks_conn",
+            ):
+                DatabricksTaskOperator(
+                    task_id="spark_task",
+                    task_config={
+                        "spark_python_task": {
+                            "python_file": "dbfs:/script.py",
+                            "parameters": ["--date", "{{ ds }}", "--cluster", 
"{{ params.cluster_name }}"],
+                        }
+                    },
+                )
+
+        launch_op = dag.get_task("test_tg.launch")
+        context = {
+            "ds": "2025-06-15",
+            "params": {"cluster_name": "prod-cluster"},
+        }
+        workflow_json = launch_op.create_workflow_json(context=context)
+        tasks = workflow_json["tasks"]
+        assert len(tasks) == 1
+        assert tasks[0]["spark_python_task"]["parameters"] == [
+            "--date",
+            "2025-06-15",
+            "--cluster",
+            "prod-cluster",
+        ]
+
+    def 
test_create_workflow_json_renders_notebook_operator_template_fields(self):
+        """Test that DatabricksNotebookOperator path, source, and params are 
rendered."""
+        with DAG(dag_id="test_dag_nb_op", start_date=DEFAULT_DATE, 
schedule=None) as dag:
+            with DatabricksWorkflowTaskGroup(
+                group_id="test_tg",
+                databricks_conn_id="databricks_conn",
+                notebook_params={"group_param": "group_{{ ds }}"},
+            ):
+                DatabricksNotebookOperator(
+                    task_id="notebook_task",
+                    notebook_path="/notebooks/{{ ds }}/etl",
+                    source="{{ params.source_type }}",
+                    notebook_params={"task_param": "task_{{ ds }}"},
+                )
+
+        launch_op = dag.get_task("test_tg.launch")
+        context = {
+            "ds": "2025-06-15",
+            "params": {"source_type": "WORKSPACE"},
+        }
+        workflow_json = launch_op.create_workflow_json(context=context)
+        tasks = workflow_json["tasks"]
+        assert len(tasks) == 1
+        nb_task = tasks[0]["notebook_task"]
+        assert nb_task["notebook_path"] == "/notebooks/2025-06-15/etl"
+        assert nb_task["source"] == "WORKSPACE"
+        assert nb_task["base_parameters"] == {
+            "task_param": "task_2025-06-15",
+            "group_param": "group_2025-06-15",
+        }
+
+    def 
test_create_workflow_json_renders_custom_operator_template_fields(self):
+        """Test that custom DatabricksTaskBaseOperator subclasses render 
declared template_fields (GH-46563)."""
+        with DAG(dag_id="test_dag_custom_op", start_date=DEFAULT_DATE, 
schedule=None) as dag:
+            with DatabricksWorkflowTaskGroup(
+                group_id="test_tg",
+                databricks_conn_id="databricks_conn",
+            ):
+                CustomWorkflowTaskOperator(
+                    task_id="custom_task",
+                    application_args=["main.jar", "--date", "{{ ds }}"],
+                    spark_conf={"spark.app.name": "app_{{ ds }}"},
+                )
+
+        launch_op = dag.get_task("test_tg.launch")
+        context = {"ds": "2025-06-15"}
+        workflow_json = launch_op.create_workflow_json(context=context)
+        tasks = workflow_json["tasks"]
+        assert len(tasks) == 1
+        assert tasks[0]["spark_jar_task"]["parameters"] == ["main.jar", 
"--date", "2025-06-15"]
+        assert tasks[0]["spark_jar_task"]["spark_conf"] == {"spark.app.name": 
"app_2025-06-15"}
+
+    def 
test_create_workflow_json_without_context_preserves_unrendered_templates(self):
+        """Test that create_workflow_json without context leaves raw templates 
intact."""
+        with DAG(dag_id="test_dag_no_ctx", start_date=DEFAULT_DATE, 
schedule=None) as dag:
+            with DatabricksWorkflowTaskGroup(
+                group_id="test_tg",
+                databricks_conn_id="databricks_conn",
+            ):
+                DatabricksTaskOperator(
+                    task_id="spark_task",
+                    task_config={
+                        "spark_python_task": {
+                            "python_file": "dbfs:/script.py",
+                            "parameters": ["--date", "{{ ds }}"],
+                        }
+                    },
+                )
+
+        launch_op = dag.get_task("test_tg.launch")
+        workflow_json = launch_op.create_workflow_json(context=None)
+        tasks = workflow_json["tasks"]
+        assert tasks[0]["spark_python_task"]["parameters"] == ["--date", "{{ 
ds }}"]
+
+    def 
test_create_workflow_json_does_not_mutate_member_task_attributes_across_runs(self):
+        """Test that multiple workflow JSON generations with different 
contexts do not mutate operator state."""
+        with DAG(dag_id="test_dag_mutation_guard", start_date=DEFAULT_DATE, 
schedule=None) as dag:
+            with DatabricksWorkflowTaskGroup(
+                group_id="test_tg",
+                databricks_conn_id="databricks_conn",
+                notebook_params={"group_param": "group_{{ ds }}"},
+            ):
+                spark_task = DatabricksTaskOperator(
+                    task_id="spark_task",
+                    task_config={
+                        "spark_python_task": {
+                            "python_file": "dbfs:/script.py",
+                            "parameters": ["--date", "{{ ds }}"],
+                        }
+                    },
+                )
+                nb_task = DatabricksNotebookOperator(
+                    task_id="notebook_task",
+                    notebook_path="/notebooks/{{ ds }}/etl",
+                    source="WORKSPACE",
+                    notebook_params={"task_param": "task_{{ ds }}"},
+                )
+
+        launch_op = dag.get_task("test_tg.launch")
+
+        # First call with date 1
+        wf1 = launch_op.create_workflow_json(context={"ds": "2025-06-15"})
+        tasks1 = {t["task_key"]: t for t in wf1["tasks"]}
+        assert 
tasks1[spark_task.databricks_task_key]["spark_python_task"]["parameters"] == [
+            "--date",
+            "2025-06-15",
+        ]
+        assert (
+            
tasks1[nb_task.databricks_task_key]["notebook_task"]["notebook_path"]
+            == "/notebooks/2025-06-15/etl"
+        )
+        assert 
tasks1[nb_task.databricks_task_key]["notebook_task"]["base_parameters"] == {
+            "task_param": "task_2025-06-15",
+            "group_param": "group_2025-06-15",
+        }
+
+        # Second call with date 2
+        wf2 = launch_op.create_workflow_json(context={"ds": "2025-06-16"})
+        tasks2 = {t["task_key"]: t for t in wf2["tasks"]}
+        assert 
tasks2[spark_task.databricks_task_key]["spark_python_task"]["parameters"] == [
+            "--date",
+            "2025-06-16",
+        ]
+        assert (
+            
tasks2[nb_task.databricks_task_key]["notebook_task"]["notebook_path"]
+            == "/notebooks/2025-06-16/etl"
+        )
+        assert 
tasks2[nb_task.databricks_task_key]["notebook_task"]["base_parameters"] == {
+            "task_param": "task_2025-06-16",
+            "group_param": "group_2025-06-16",
+        }
+
+        # Verify the task operators on the DAG were not mutated in place with 
rendered values
+        assert spark_task.task_config["spark_python_task"]["parameters"] == 
["--date", "{{ ds }}"]
+        assert nb_task.notebook_path == "/notebooks/{{ ds }}/etl"
+        assert nb_task.notebook_params["task_param"] == "task_{{ ds }}"

Review Comment:
   This checks one key, so merging the group params back into 
`self.notebook_params` would still pass. Comparing the whole dict (`== 
{"task_param": "task_{{ ds }}"}`) covers that, and then 
`test_create_workflow_json_does_not_mutate_notebook_params_with_task_group` 
repeats this test.



##########
providers/databricks/src/airflow/providers/databricks/operators/databricks.py:
##########
@@ -2063,7 +2063,18 @@ def _convert_to_databricks_workflow_task(
         context: Context | None = None,
     ) -> dict[str, object]:
         """Convert the operator to a Databricks workflow task that can be a 
task in a workflow."""
-        base_task_json = self._get_task_base_json()
+        if context is not None:
+            fields_to_render = [f for f in self.template_fields if f != 
"workflow_run_metadata"]

Review Comment:
   Only `workflow_run_metadata` is skipped, so an XComArg in a member field 
(`notebook_params={"x": producer.output}`) now resolves through the launch TI. 
Launch isn't downstream of `producer` (only the group roots get launch as 
upstream), so if launch runs first the job definition gets `None` with no 
error, where before the XComArg reached `json.dumps` and failed loudly. Should 
XComArgs in member fields be rejected here, or is there a way to make launch 
wait for their producers?



##########
providers/databricks/tests/unit/databricks/operators/test_databricks_workflow.py:
##########
@@ -647,3 +651,269 @@ def test_downstream_set_after_with_block(self):
             tg >> end
         nb = dag.get_task("tg.nb")
         assert "end" in nb.downstream_task_ids
+
+
+class CustomWorkflowTaskOperator(DatabricksTaskBaseOperator):
+    """Custom operator subclassing DatabricksTaskBaseOperator for GH-46563 
reproduction."""

Review Comment:
   Can the `GH-46563` references in these docstrings (also 676 and 742) go? The 
PR already links the issue.



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