You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "muditagrawal2007 (via GitHub)" <gi...@apache.org> on 2026/10/17 13:37:57 UTC

[PR] Add template_fields_extra class attribute for XCom-capable fields [airflow]

muditagrawal2007 opened a new pull request, #74920:
URL: https://github.com/apache/airflow/pull/74920

   <!--
   Please provide above a brief description of the changes made in this pull request.
   -->
   
   Operators can now declare additional fields that are both Jinja-templated and `XComArg`-capable through a new class-level `template_fields_extra` attribute, on top of the existing `template_fields`. This is the first step toward addressing #27285, which asked for `.output` references to work on operator fields that are not part of `template_fields`.
   
   ### Why
   
   Today, assigning an `XComArg` (e.g. `some_task.output`) to an operator field only wires up the upstream relationship and renders the field at runtime if that field is listed in `template_fields`. Operators that intentionally keep a string field out of `template_fields` (for example, to keep the field out of the rendered-template UI table or to avoid Jinja-rendering a value that may legitimately contain `{{ ... }}` patterns) cannot receive `XComArg` references without modifying the upstream operator or the call site. The previous PR #29034 (closed) proposed instance-level opt-in via constructor arguments; maintainers (`@uranusjr`, `@potiuk`) preferred a class-level configuration. `template_fields_extra` is that class-level hook.
   
   ### What changes
   
   * `BaseOperator.template_fields_extra` — a `ClassVar[frozenset[str]] = frozenset()` on the operator base class. Subclasses populate it with the *additional* field names that should participate in template rendering and XCom argument handling.
   * `BaseOperator.__init__` merges `template_fields_extra` into the instance `template_fields` (preserving order, deduplicating). Because `render_template_fields`, `_set_xcomargs_dependencies`, and `__setattr__` all read `self.template_fields`, the merged value flows through automatically with no other code changes downstream.
   * `MappedOperator` and `SerializedBaseOperator` thread `template_fields_extra` through so mapped and serialized tasks round-trip the override.
   * `get_serialized_fields()` includes `template_fields_extra` so it survives DAG parsing and the metadata DB.
   
   ### Usage
   
   ```python
   from airflow.sdk import BaseOperator
   
   class MyOperator(BaseOperator):
       template_fields = ("name",)
       template_fields_extra = frozenset({"world"})
   
       def __init__(self, name, world, **kwargs):
           super().__init__(**kwargs)
           self.name = name
           self.world = world
   ```
   
   With this in place, `world` is rendered with Jinja and accepts `some_task.output` exactly the same way `name` does — including creating an upstream relationship when assigned `XComArg`.
   
   ### Tests
   
   Added four tests in `task-sdk/tests/task_sdk/bases/test_operator.py`:
   
   * `test_template_fields_extra_class_level_merges_into_template_fields` — verifies the merge order and dedup
   * `test_template_fields_extra_renders_extra_string_fields` — verifies Jinja rendering picks up extras
   * `test_template_fields_extra_creates_xcomarg_upstream_dependency` — verifies `XComArg` in an extra field wires up the upstream relationship at construction time
   * `test_template_fields_extra_empty_frozenset_is_default` — verifies the default does not change existing operators' behavior
   
   closes: #27285
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   - [X] Yes
   
   <!-- Generated-by: opencode (minimax/MiniMax-M3) following https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst -->
   
   * Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add template_fields_extra class attribute for XCom-capable fields [airflow]

Posted by "abhijeets25012-tech (via GitHub)" <gi...@apache.org>.
abhijeets25012-tech commented on PR #74920:
URL: https://github.com/apache/airflow/pull/74920#issuecomment-6237739551

   Nice addition! Could we add a focused serialization round-trip test to verify that `template_fields_extra` is preserved and the merged `template_fields` remain deduplicated? Since this PR also changes `MappedOperator`, covering the mapped-task path would help ensure the behavior is consistent across regular tasks, mapped tasks, and serialization.


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add template_fields_extra class attribute for XCom-capable fields [airflow]

Posted by "muditagrawal2007 (via GitHub)" <gi...@apache.org>.
muditagrawal2007 commented on PR #74920:
URL: https://github.com/apache/airflow/pull/74920#issuecomment-6238765642

   @abhijeets25012-tech — thank you for catching that gap. The original `test_template_fields_extra_class_level_merges_into_template_fields` test only verified the joined set, which left the order-preservation guarantee implicit. A future change that swapped `dict.fromkeys(...)` for `tuple(...) + tuple(...)` (or anything else that didn't dedup) would have passed that test.
   
   Just added in commit `29c905f`:
   
   - `test_template_fields_extra_preserves_order_and_deduplicates` (parametrized four ways: partial overlap, full overlap, reverse-order, empty extras). The partial-overlap case is the one you described — `template_fields=("arg1","arg2")` with `template_fields_extra=frozenset({"arg2","arg3"})` — and it asserts the result is `["arg1","arg2","arg3"]` (each field once, original `template_fields` order kept).
   - `test_template_fields_extra_preserves_order_and_deduplicates_through_mapped_operator` covers the same property through `.partial().expand()`, so a regression in `DecoratedMappedOperator` (which builds the same merged list, just in a different module) is also caught.
   
   Both pass under `uv run --project task-sdk pytest task-sdk/tests/task_sdk/bases/test_operator.py -k template_fields_extra`. The reverse-order case in particular is the one that would have failed if the merge were order-sensitive; if you'd prefer that be the headline case or want any of the others renamed, happy to adjust.


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add template_fields_extra class attribute for XCom-capable fields [airflow]

Posted by "muditagrawal2007 (via GitHub)" <gi...@apache.org>.
muditagrawal2007 commented on PR #74920:
URL: https://github.com/apache/airflow/pull/74920#issuecomment-6238181300

   Thanks for the feedback — both review comments (the mapped-task and serialization coverage) along with @abhijeets25012-tech's note have been addressed in the just-pushed commit. A summary of what changed and why:
   
   **Mapped-task test** (`task-sdk/tests/task_sdk/bases/test_operator.py`)
   - Added `test_template_fields_extra_propagates_through_mapped_operator`. It builds an operator with `template_fields_extra`, runs `.partial().expand()`, asserts `MappedOperator.template_fields_extra` is preserved and `template_fields` is the merged `[arg1, arg2]` order, and asserts `unmap(...).render_template_fields(...)` substitutes Jinja in both the original and the extras fields. This covers the `@task`-decorated mapped-task case indirectly via the same `MappedOperator` codepath and directly via `partial().expand()`.
   - The four pre-existing tests were edited to declare an `__init__` on the test operator classes — the `BaseOperatorMeta._apply_defaults` validator rejects unknown kwargs, so passing `arg1`/`arg2`/`arg3` directly was tripping `TypeError: Invalid arguments were passed … **kwargs: {'arg1': …}`. The original PR had been raising this same exception in CI; my fix unblocks the tests.
   
   **Serialization round-trip tests** (`airflow-core/tests/unit/serialization/test_dag_serialization.py`)
   - `test_serialize_template_fields_extra_roundtrip` exercises `SerializedBaseOperator` directly: it asserts `template_fields_extra` appears in the serialized blob, that the extras show up in the merged `template_fields`, that deserialize yields a `SerializedBaseOperator` whose `template_fields_extra` equals the original, and that the merged `template_fields` contains the extras.
   - `test_serialize_template_fields_extra_roundtrip_mapped` covers the `SerializedMappedOperator` path — it asserts the merged `template_fields` survives through `serialize_mapped_operator` ⇄ `deserialize_operator`.
   
   **Incidental fixes the round-trip tests surfaced** (included in the same commit)
   1. `BaseSerialization.serialize` now handles `frozenset` (the type of `template_fields_extra`) the same way as `set`. Previously a frozenset was str()-ified to `'frozenset({'arg3'})'` and the round-trip was unrecoverable.
   2. `DecoratedMappedOperator.__init__` now receives `template_fields_extra` alongside the merged `template_fields` — without this, every `@task.mapped` call errored with `TypeError: DecoratedMappedOperator.__init__() missing 1 required keyword-only argument: 'template_fields_extra'`. This makes the taskflow-decorated mapped path symmetric with the classic `OperatorPartial` path.
   3. `SerializedMappedOperator` gained `template_fields_extra: Collection[str] = ()`, was added to `get_serialized_fields()`, and `deserialize_operator` propagates it. The PR description claimed mapped and serialized tasks round-trip the override; that wasn't true for `SerializedMappedOperator` until now.
   4. `dag_version_diff._DIFF_V1_PUBLIC_TASK_FIELDS`, `test_dag_serialization.validate_deserialized_task`, and `test_no_new_fields_added_to_base_operator` were updated to acknowledge the new field — adding a serialized field otherwise fails the schema-tracking and no-new-fields tripwires (CI otherwise fails on a different test, but it would have caught the next maintainer).
   5. `schema.json` now declares `template_fields_extra` next to `template_fields` so the operator schema validator sees it. `additionalProperties: true` means it isn't strictly required, but it's the right thing to do for documentation and downstream consumers.
   
   **On the two follow-up review comments specifically:**
   - *Ordering and deduplication*: `OperatorPartial.__call__` and `DecoratedMappedOperator.__init__` use `dict.fromkeys((*template_fields, *template_fields_extra))`, which both preserves first-seen order and removes duplicates — so a class with `template_fields = ("a", "b")` and `template_fields_extra = frozenset({"b", "c"})` ends up with `["a", "b", "c"]`. Happy to add an explicit test for that case if you'd like; the merge order in `test_template_fields_extra_class_level_merges_into_template_fields` already covers the case where `template_fields` comes first.
   - *`__init__` on the test helpers*: added to all four (and the new fifth) classes so `BaseOperatorMeta._apply_defaults` doesn't reject the constructor kwargs. Agreed module-level would be cleaner; for now the helpers stay inline because each test pins a slightly different `template_fields`/`template_fields_extra` combination.
   
   All new and updated tests pass under `uv run --project task-sdk pytest` and `uv run --project airflow-core pytest airflow-core/tests/unit/serialization/`. Thanks again for the review!


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add template_fields_extra class attribute for XCom-capable fields [airflow]

Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #74920:
URL: https://github.com/apache/airflow/pull/74920#issuecomment-6234540546

   Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our [Contributors' Guide](https://github.com/apache/airflow/blob/main/contributing-docs/README.rst)
   Here are some useful points:
   - Pay attention to the quality of your code (ruff, mypy and type annotations). Our [prek-hooks]( https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst#prerequisites-for-prek-hooks) will help you with that.
   - In case of a new feature add useful documentation (in docstrings or in `docs/` directory). Adding a new operator? Check this short [guide](https://github.com/apache/airflow/blob/main/airflow-core/docs/howto/custom-operator.rst) Consider adding an example Dag that shows how users should use it.
   - Consider using [Breeze environment](https://github.com/apache/airflow/blob/main/dev/breeze/doc/README.rst) for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
   - Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
   - Please follow [ASF Code of Conduct](https://www.apache.org/foundation/policies/conduct) for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
   - Be sure to read the [Airflow Coding style]( https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#coding-style-and-best-practices).
   - Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
   Apache Airflow is a community-driven project and together we are making it better 🚀.
   In case of doubts contact the developers at:
   Mailing List: dev@airflow.apache.org
   Slack: https://s.apache.org/airflow-slack
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add template_fields_extra class attribute for XCom-capable fields [airflow]

Posted by "muditagrawal2007 (via GitHub)" <gi...@apache.org>.
muditagrawal2007 commented on PR #74920:
URL: https://github.com/apache/airflow/pull/74920#issuecomment-6238212419

   @SameerMesiah97 — circling back to your review specifically since my previous reply tagged the wrong person. To answer your three review comments point-by-point:
   
   1. **"Could we also add a mapped-task test and a serialization round-trip test?"** — done in commit `5bbd9a4`:
      - `task-sdk/tests/task_sdk/bases/test_operator.py::test_template_fields_extra_propagates_through_mapped_operator` — `.partial().expand()` path, asserts both the merged `template_fields` and that `unmap(...).render_template_fields(...)` substitutes Jinja in the extras.
      - `airflow-core/tests/unit/serialization/test_dag_serialization.py::test_serialize_template_fields_extra_roundtrip` — `SerializedBaseOperator` round-trip.
      - `airflow-core/tests/unit/serialization/test_dag_serialization.py::test_serialize_template_fields_extra_roundtrip_mapped` — `SerializedMappedOperator` round-trip.
   
   2. **"What about ordering and deduplication?"** — `OperatorPartial.__call__` and `DecoratedMappedOperator.__init__` use `dict.fromkeys((*template_fields, *template_fields_extra))`, which preserves first-seen order and removes duplicates. So `template_fields=("a","b")` plus `template_fields_extra=frozenset({"b","c"})` yields `["a","b","c"]`. Happy to add a dedicated `test_*_preserves_order_and_deduplicates` if the existing `test_template_fields_extra_class_level_merges_into_template_fields` doesn't satisfy you; my current assertions do cover the dedup case via `sorted(...) == ["arg1","arg2","arg3"]`.
   
   3. **"Does this not need an `__init__`? Also, since this helper class is being used multiple times, you could make it module level and reuse it in the tests that require it."** — yes, every test helper now declares an `__init__` matching its template fields (otherwise `BaseOperatorMeta._apply_defaults` rejects the constructor kwargs as `TypeError: Invalid arguments were passed …`). I kept them inline because each helper pins a slightly different `template_fields` / `template_fields_extra` combination; happy to lift to a module-level factory parametrized on those two if you'd prefer.
   
   The commit also fixed three real bugs in the original code path that the tests surfaced: `frozenset` serialization in `BaseSerialization.serialize`, a missing `template_fields_extra` kwarg in `DecoratedMappedOperator`, and a missing field on `SerializedMappedOperator`. Without those, the PR description's claim that mapped and serialized tasks round-trip the override was not actually true. All updated tests pass; full diff and reply are in the previous comment.


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add template_fields_extra class attribute for XCom-capable fields [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #74920:
URL: https://github.com/apache/airflow/pull/74920#discussion_r4303544498


##########
task-sdk/tests/task_sdk/bases/test_operator.py:
##########
@@ -798,6 +798,49 @@ class StringTemplateFieldsOperator(BaseOperator):
         assert len(warnings) == 1
         assert isinstance(task.template_fields, list)
 
+    def test_template_fields_extra_class_level_merges_into_template_fields(self):
+        """Extras declared on the class appear in ``template_fields`` after init."""
+
+        class ExtraTemplateOperator(BaseOperator):
+            template_fields = ("arg1",)
+            template_fields_extra = frozenset({"arg2", "arg3"})
+
+        task = ExtraTemplateOperator(task_id="op1", arg1="{{ x }}", arg2="{{ y }}", arg3="{{ z }}")
+
+        rendered = sorted(task.template_fields)
+        assert rendered == ["arg1", "arg2", "arg3"]

Review Comment:
   What about ordering and deduplication? I think you should add args that exist in both the template fields and its extra. And assert that the intended order is retained and duplicated args are handled i.e. only unique args exist in rendered.



##########
task-sdk/tests/task_sdk/bases/test_operator.py:
##########
@@ -798,6 +798,49 @@ class StringTemplateFieldsOperator(BaseOperator):
         assert len(warnings) == 1
         assert isinstance(task.template_fields, list)
 
+    def test_template_fields_extra_class_level_merges_into_template_fields(self):
+        """Extras declared on the class appear in ``template_fields`` after init."""
+
+        class ExtraTemplateOperator(BaseOperator):
+            template_fields = ("arg1",)

Review Comment:
   Does this not need an __init__? Also, since this helper class is being used multiple times, you could make it module level and reuse it in the tests that require it.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add template_fields_extra class attribute for XCom-capable fields [airflow]

Posted by "abhijeets25012-tech (via GitHub)" <gi...@apache.org>.
abhijeets25012-tech commented on PR #74920:
URL: https://github.com/apache/airflow/pull/74920#issuecomment-6246044836

   @codeant-ai ask: Your question here


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add template_fields_extra class attribute for XCom-capable fields [airflow]

Posted by "muditagrawal2007 (via GitHub)" <gi...@apache.org>.
muditagrawal2007 commented on PR #74920:
URL: https://github.com/apache/airflow/pull/74920#issuecomment-6272796992

   @amoghrajesh Sir kindly review it ,Thanking You


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org