You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "sjyangkevin (via GitHub)" <gi...@apache.org> on 2025/08/16 03:55:26 UTC

[PR] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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

   Close: #52574 
   
   As discussed in #52574 , the outlet event extra data is empty because the task runner does not commit the asset changes to the database before calling the callbacks and the listeners. Also, every call to the `get_template_context` method create and return a new `Context` object, which might not persist the changes made during the task execution. Therefore, a method to fix this issue is to add a cache to the `get_template_context` method, ensuring all calls are operating on the same context object.
   
   Since `RuntimeTaskInstance` is a unhashable type, `@functools.cache` doesn't work in this case. As an alternative, we probably can convert the `context` into a property, and the runtime task instance will operate on the property `context`. However, this implementation breaks the pre-commit hook `check-template-context-variable-in-sync`.
   
   https://github.com/apache/airflow/blob/d4f4b22bbee25d58d56e2363bd68aaf4c9ac9093/scripts/ci/pre_commit/check_template_context_variable_in_sync.py#L81-L88
   
   Any feedback regarding how to improve the current implementation for fixing the issue would be appreciated.
   
   <!--
    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.
    -->
   
   <!--
   Thank you for contributing! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   In case of an existing issue, reference it using one of the following:
   
   closes: #ISSUE
   related: #ISSUE
   
   How to write a good git commit message:
   http://chris.beams.io/posts/git-commit/
   -->
   
   
   
   <!-- Please keep an empty line above the dashes. -->
   ---
   **^ Add meaningful description above**
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
   In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments).
   


-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #54568:
URL: https://github.com/apache/airflow/pull/54568#discussion_r2299691759


##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -2538,6 +2564,118 @@ def execute(self, context):
         assert listener.state == [TaskInstanceState.RUNNING, TaskInstanceState.FAILED]
         assert listener.error == error
 
+    def test_listener_access_outlet_event_on_running_and_success(self, mocked_parse, mock_supervisor_comms):
+        """Test listener can access outlet events through invoking get_template_context() while task running and success"""
+        listener = self.CustomOutletEventsListener()
+        get_listener_manager().add_listener(listener)
+
+        test_asset = Asset("test-asset")
+        test_key = AssetUniqueKey(name="test-asset", uri="test-asset")
+        test_extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        class Producer(BaseOperator):
+            def execute(self, context):
+                outlet_events = context["outlet_events"]
+                outlet_events[test_asset].extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        task = Producer(
+            task_id="test_listener_access_outlet_event_on_running_and_success", outlets=[test_asset]
+        )
+        dag = get_inline_dag(dag_id="test_dag", task=task)
+        ti = TaskInstance(
+            id=uuid7(),
+            task_id=task.task_id,
+            dag_id=dag.dag_id,
+            run_id="test_run",
+            try_number=1,
+            dag_version_id=uuid7(),
+        )
+
+        runtime_ti = RuntimeTaskInstance.model_construct(
+            **ti.model_dump(exclude_unset=True), task=task, start_date=timezone.utcnow()
+        )
+
+        log = mock.MagicMock()
+        context = runtime_ti.get_template_context()
+
+        with mock.patch(
+            "airflow.sdk.execution_time.task_runner._validate_task_inlets_and_outlets"

Review Comment:
   I think line 2608 is not (or should not) be properly executed. It might be worth entering it through a breakpoint and seeing what's happening there



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -2538,6 +2564,118 @@ def execute(self, context):
         assert listener.state == [TaskInstanceState.RUNNING, TaskInstanceState.FAILED]
         assert listener.error == error
 
+    def test_listener_access_outlet_event_on_running_and_success(self, mocked_parse, mock_supervisor_comms):
+        """Test listener can access outlet events through invoking get_template_context() while task running and success"""
+        listener = self.CustomOutletEventsListener()
+        get_listener_manager().add_listener(listener)
+
+        test_asset = Asset("test-asset")
+        test_key = AssetUniqueKey(name="test-asset", uri="test-asset")
+        test_extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        class Producer(BaseOperator):
+            def execute(self, context):
+                outlet_events = context["outlet_events"]
+                outlet_events[test_asset].extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        task = Producer(
+            task_id="test_listener_access_outlet_event_on_running_and_success", outlets=[test_asset]
+        )
+        dag = get_inline_dag(dag_id="test_dag", task=task)
+        ti = TaskInstance(
+            id=uuid7(),
+            task_id=task.task_id,
+            dag_id=dag.dag_id,
+            run_id="test_run",
+            try_number=1,
+            dag_version_id=uuid7(),
+        )
+
+        runtime_ti = RuntimeTaskInstance.model_construct(
+            **ti.model_dump(exclude_unset=True), task=task, start_date=timezone.utcnow()
+        )
+
+        log = mock.MagicMock()
+        context = runtime_ti.get_template_context()
+
+        with mock.patch(
+            "airflow.sdk.execution_time.task_runner._validate_task_inlets_and_outlets"

Review Comment:
   Thanks for the insightful feedback! 
   
   >As we already know, it's an activated asset (we create it and activate it), this check doesn't really needed here
   
   Yeah, from my understanding, looks like it is the case. Because we've put the asset into `outlets` when instantiating the task. This should create an asset and set that to active.
   
   However, when the patching is not included here, the listener is not triggered. As shown below, the listener's attribute `listener.outlet_events` should store the outlet events fetched during task running and at task success, but an empty list is returned.
   
   <img width="1385" height="714" alt="Screenshot from 2025-08-25 23-45-11" src="https://github.com/user-attachments/assets/9dd21bae-59b4-4336-9992-affc7ffb3083" />
   
   Probably the issue is not because of the patching. It might be related to somehow I am not running the task properly?



##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -2538,6 +2564,118 @@ def execute(self, context):
         assert listener.state == [TaskInstanceState.RUNNING, TaskInstanceState.FAILED]
         assert listener.error == error
 
+    def test_listener_access_outlet_event_on_running_and_success(self, mocked_parse, mock_supervisor_comms):
+        """Test listener can access outlet events through invoking get_template_context() while task running and success"""
+        listener = self.CustomOutletEventsListener()
+        get_listener_manager().add_listener(listener)
+
+        test_asset = Asset("test-asset")
+        test_key = AssetUniqueKey(name="test-asset", uri="test-asset")
+        test_extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        class Producer(BaseOperator):
+            def execute(self, context):
+                outlet_events = context["outlet_events"]
+                outlet_events[test_asset].extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}

Review Comment:
   Yeah. The hard-coded dictionary looks redundant here. Will update 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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -2538,6 +2564,118 @@ def execute(self, context):
         assert listener.state == [TaskInstanceState.RUNNING, TaskInstanceState.FAILED]
         assert listener.error == error
 
+    def test_listener_access_outlet_event_on_running_and_success(self, mocked_parse, mock_supervisor_comms):
+        """Test listener can access outlet events through invoking get_template_context() while task running and success"""
+        listener = self.CustomOutletEventsListener()
+        get_listener_manager().add_listener(listener)
+
+        test_asset = Asset("test-asset")
+        test_key = AssetUniqueKey(name="test-asset", uri="test-asset")
+        test_extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        class Producer(BaseOperator):
+            def execute(self, context):
+                outlet_events = context["outlet_events"]
+                outlet_events[test_asset].extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        task = Producer(
+            task_id="test_listener_access_outlet_event_on_running_and_success", outlets=[test_asset]
+        )
+        dag = get_inline_dag(dag_id="test_dag", task=task)
+        ti = TaskInstance(
+            id=uuid7(),
+            task_id=task.task_id,
+            dag_id=dag.dag_id,
+            run_id="test_run",
+            try_number=1,
+            dag_version_id=uuid7(),
+        )
+
+        runtime_ti = RuntimeTaskInstance.model_construct(
+            **ti.model_dump(exclude_unset=True), task=task, start_date=timezone.utcnow()
+        )
+
+        log = mock.MagicMock()
+        context = runtime_ti.get_template_context()
+
+        with mock.patch(
+            "airflow.sdk.execution_time.task_runner._validate_task_inlets_and_outlets"

Review Comment:
   Hi @Lee-W , I think I kind of figuring out what happens here. Let me restate the original issue in the test. When the following patch is not used, the listener is not triggered. So, the test will fail at the upcoming assertion when looking for an outlet event in the listener's attribute `listener.outlet_events`. 
   https://github.com/apache/airflow/blob/40c2c910ad02be1c6000d65585477f18bb655fa6/task-sdk/tests/task_sdk/execution_time/test_task_runner.py#L2685-L2688
   
   ### Why the listener is not triggered?
   In the task runner, the following exception is always raised during the tests because `inactive_assets_resp.inactive_assets` is a mock object, and it is always evaluated to `True`. It means that if `_validate_task_inlets_and_outlets` is not mock through the patch, the exception will always be raised.
   https://github.com/apache/airflow/blob/40c2c910ad02be1c6000d65585477f18bb655fa6/task-sdk/src/airflow/sdk/execution_time/task_runner.py#L836-L841
   
   I believe the listener invocation `get_listener_manager().hook.on_task_instance_running` is not reached when the exception is raised.
   https://github.com/apache/airflow/blob/40c2c910ad02be1c6000d65585477f18bb655fa6/task-sdk/src/airflow/sdk/execution_time/task_runner.py#L815-L823
   
   ### Can we make the test run without using the patch for the validation?
   
   Yes. In this case, what we need to do is to make `inactive_assets` an empty list for the supervisor mock fixture. In this case, the exception will not be raised, but here we assume the asset in the outlets is an valid asset.
   ```
   mock_supervisor_comms.send.return_value.inactive_assets = []
   ```
   
   Let me know if it is more suitable to use the patch for `_validate_task_inlets_and_outlets` or we should update the mock supervisor comms. Thanks!



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W merged PR #54568:
URL: https://github.com/apache/airflow/pull/54568


-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_context.py:
##########
@@ -154,6 +154,26 @@ def test_context_to_airflow_vars_all_context(self, create_runtime_ti):
             "AIRFLOW_CTX_DAG_EMAIL": "email1@test.com",
         }
 
+    def test_get_template_context_return_same_context_object(self, create_runtime_ti):

Review Comment:
   Did a test like this previously fail before you made the changes?



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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

   Hi @Lee-W , thanks for looking into it , sorry I didn't get the chance yet to make the updates suggested by @uranusjr due to very limited bandwidth in these few weeks; 
   
   I am wondering if we still need to make that change, if so, I would like to push that change by around end of the week. thanks!
   
   > Let’s add a comment on this attribute to mark this as only implementation detail for caching get_template_context. And/or maybe rename this to _cached_template_context?


-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_context.py:
##########
@@ -154,6 +154,26 @@ def test_context_to_airflow_vars_all_context(self, create_runtime_ti):
             "AIRFLOW_CTX_DAG_EMAIL": "email1@test.com",
         }
 
+    def test_get_template_context_return_same_context_object(self, create_runtime_ti):

Review Comment:
   still working on it, will push an update later this week. The followings are the things I am looking at
   * replace the test case with a test for outlet event extra
   * understand the check `_iter_template_context_keys_from_original_return` in pre-commit hook (or, prek) for `check_template_context_variable_in_sync.py`. Since the change made in this PR update the assignment from `context: Context = { ... }` to `self._context = self._context or { ... }`. The AST is different for static code analysis.
   * This is related to the second item, whether I should implement the cache in this way. Is it intended to keep that context as a variable rather than attribute. Or is it expected to create a new context object every time the function is called?
   
   Thanks,



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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

   Hi all, I would like to follow up on the PR. I think the major concern here probably is around the impact of the `context`; recently, I had very limited bandwidth, but will try to get back to this in the upcoming week or two, to further investigate the impact of the change. Thank you for the time to review the PR.


-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/src/airflow/sdk/execution_time/task_runner.py:
##########
@@ -129,6 +129,9 @@ class RuntimeTaskInstance(TaskInstance):
 
     task: BaseOperator
     bundle_instance: BaseDagBundle
+    _context: Context | None = None

Review Comment:
   Let’s add a comment on this attribute to mark this as only implementation detail for caching `get_template_context`. And/or maybe rename this to `_cached_template_context`?



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_context.py:
##########
@@ -154,6 +154,26 @@ def test_context_to_airflow_vars_all_context(self, create_runtime_ti):
             "AIRFLOW_CTX_DAG_EMAIL": "email1@test.com",
         }
 
+    def test_get_template_context_return_same_context_object(self, create_runtime_ti):

Review Comment:
   still working on it, will push an update later this week. The followings are the things I am looking at
   * replace the test case with a test for outlet event extra
   * understand the check `_iter_template_context_keys_from_original_return` in pre-commit hook (or, prek) for `check_template_context_variable_in_sync.py`. Since the change made in this PR update the assignment from `context: Context = { ... }` to `self._context = self._context or { ... }`. The AST is different for static code analysis.
   * This is related to the second item, whether I should implement the idea of cache in this way. Is it intended to keep that context as a variable rather than attribute. Or is it expected to create a new context object every time the function is called?
   
   Thanks,



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -2538,6 +2564,118 @@ def execute(self, context):
         assert listener.state == [TaskInstanceState.RUNNING, TaskInstanceState.FAILED]
         assert listener.error == error
 
+    def test_listener_access_outlet_event_on_running_and_success(self, mocked_parse, mock_supervisor_comms):
+        """Test listener can access outlet events through invoking get_template_context() while task running and success"""
+        listener = self.CustomOutletEventsListener()
+        get_listener_manager().add_listener(listener)
+
+        test_asset = Asset("test-asset")
+        test_key = AssetUniqueKey(name="test-asset", uri="test-asset")
+        test_extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        class Producer(BaseOperator):
+            def execute(self, context):
+                outlet_events = context["outlet_events"]
+                outlet_events[test_asset].extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        task = Producer(
+            task_id="test_listener_access_outlet_event_on_running_and_success", outlets=[test_asset]
+        )
+        dag = get_inline_dag(dag_id="test_dag", task=task)
+        ti = TaskInstance(
+            id=uuid7(),
+            task_id=task.task_id,
+            dag_id=dag.dag_id,
+            run_id="test_run",
+            try_number=1,
+            dag_version_id=uuid7(),
+        )
+
+        runtime_ti = RuntimeTaskInstance.model_construct(
+            **ti.model_dump(exclude_unset=True), task=task, start_date=timezone.utcnow()
+        )
+
+        log = mock.MagicMock()
+        context = runtime_ti.get_template_context()
+
+        with mock.patch(
+            "airflow.sdk.execution_time.task_runner._validate_task_inlets_and_outlets"

Review Comment:
   Actually, I wasn't quite sure why we need this patch here. Without this patch, the listener will not be triggered when `outlets` is set. Would appreciate if anyone could provide some context about it. Probably because the `test_asset` is somehow considered as an invalid asset, like not written into the DB?
   
   ```python
   task = Producer(
       task_id="test_listener_access_outlet_event_on_running_and_success", outlets=[test_asset]
   )
   ```



##########
scripts/ci/prek/check_template_context_variable_in_sync.py:
##########


Review Comment:
   the update to cache the context is not compatible with this pre-commit (or prek) check. I wasn't sure whether it is fine to update this logic. Would appreciate any feedback.



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #54568:
URL: https://github.com/apache/airflow/pull/54568#discussion_r2318310054


##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -2538,6 +2564,118 @@ def execute(self, context):
         assert listener.state == [TaskInstanceState.RUNNING, TaskInstanceState.FAILED]
         assert listener.error == error
 
+    def test_listener_access_outlet_event_on_running_and_success(self, mocked_parse, mock_supervisor_comms):
+        """Test listener can access outlet events through invoking get_template_context() while task running and success"""
+        listener = self.CustomOutletEventsListener()
+        get_listener_manager().add_listener(listener)
+
+        test_asset = Asset("test-asset")
+        test_key = AssetUniqueKey(name="test-asset", uri="test-asset")
+        test_extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        class Producer(BaseOperator):
+            def execute(self, context):
+                outlet_events = context["outlet_events"]
+                outlet_events[test_asset].extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        task = Producer(
+            task_id="test_listener_access_outlet_event_on_running_and_success", outlets=[test_asset]
+        )
+        dag = get_inline_dag(dag_id="test_dag", task=task)
+        ti = TaskInstance(
+            id=uuid7(),
+            task_id=task.task_id,
+            dag_id=dag.dag_id,
+            run_id="test_run",
+            try_number=1,
+            dag_version_id=uuid7(),
+        )
+
+        runtime_ti = RuntimeTaskInstance.model_construct(
+            **ti.model_dump(exclude_unset=True), task=task, start_date=timezone.utcnow()
+        )
+
+        log = mock.MagicMock()
+        context = runtime_ti.get_template_context()
+
+        with mock.patch(
+            "airflow.sdk.execution_time.task_runner._validate_task_inlets_and_outlets"

Review Comment:
   Both works are similar, but this one works a bit more accurately. Nice job!



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_context.py:
##########
@@ -154,6 +154,26 @@ def test_context_to_airflow_vars_all_context(self, create_runtime_ti):
             "AIRFLOW_CTX_DAG_EMAIL": "email1@test.com",
         }
 
+    def test_get_template_context_return_same_context_object(self, create_runtime_ti):

Review Comment:
   thanks for the feedback. will add the test for the outlet event extra.



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/src/airflow/sdk/execution_time/task_runner.py:
##########
@@ -129,6 +129,9 @@ class RuntimeTaskInstance(TaskInstance):
 
     task: BaseOperator
     bundle_instance: BaseDagBundle
+    _context: Context | None = None

Review Comment:
   Thanks for the feedback! Will do the update.



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -2538,6 +2564,118 @@ def execute(self, context):
         assert listener.state == [TaskInstanceState.RUNNING, TaskInstanceState.FAILED]
         assert listener.error == error
 
+    def test_listener_access_outlet_event_on_running_and_success(self, mocked_parse, mock_supervisor_comms):
+        """Test listener can access outlet events through invoking get_template_context() while task running and success"""
+        listener = self.CustomOutletEventsListener()
+        get_listener_manager().add_listener(listener)
+
+        test_asset = Asset("test-asset")
+        test_key = AssetUniqueKey(name="test-asset", uri="test-asset")
+        test_extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        class Producer(BaseOperator):
+            def execute(self, context):
+                outlet_events = context["outlet_events"]
+                outlet_events[test_asset].extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        task = Producer(
+            task_id="test_listener_access_outlet_event_on_running_and_success", outlets=[test_asset]
+        )
+        dag = get_inline_dag(dag_id="test_dag", task=task)
+        ti = TaskInstance(
+            id=uuid7(),
+            task_id=task.task_id,
+            dag_id=dag.dag_id,
+            run_id="test_run",
+            try_number=1,
+            dag_version_id=uuid7(),
+        )
+
+        runtime_ti = RuntimeTaskInstance.model_construct(
+            **ti.model_dump(exclude_unset=True), task=task, start_date=timezone.utcnow()
+        )
+
+        log = mock.MagicMock()
+        context = runtime_ti.get_template_context()
+
+        with mock.patch(
+            "airflow.sdk.execution_time.task_runner._validate_task_inlets_and_outlets"

Review Comment:
   Thanks for the insightful feedback! 
   
   >As we already know, it's an activated asset (we create it and activate it), this check doesn't really needed here
   
   Yeah, from my understanding, looks like it is the case. Because we've put the asset into `outlets` when instantiating the task. This should create an asset and set that to active.
   
   However, when the patching is not included here, the listener is not triggered. As shown below, the listener's attribute `listener.outlet_events` should store the outlet events fetched during task running and at task success, but an empty list is returned. I also attempted to put some `print` statement in the listener code, and those are not show up when the patching is not here.
   
   <img width="1385" height="714" alt="Screenshot from 2025-08-25 23-45-11" src="https://github.com/user-attachments/assets/9dd21bae-59b4-4336-9992-affc7ffb3083" />
   
   Probably the issue is not because of the patching. It might be related to somehow I am not running the task properly?



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_context.py:
##########
@@ -154,6 +154,26 @@ def test_context_to_airflow_vars_all_context(self, create_runtime_ti):
             "AIRFLOW_CTX_DAG_EMAIL": "email1@test.com",
         }
 
+    def test_get_template_context_return_same_context_object(self, create_runtime_ti):

Review Comment:
   Yes. I did revert all changes after creating the test. The test failed.



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_context.py:
##########
@@ -154,6 +154,26 @@ def test_context_to_airflow_vars_all_context(self, create_runtime_ti):
             "AIRFLOW_CTX_DAG_EMAIL": "email1@test.com",
         }
 
+    def test_get_template_context_return_same_context_object(self, create_runtime_ti):

Review Comment:
   I'd even say lets remove this tests too please. (Not _as_ certain on that, but I don't think it's all that important overall if we test the behaviour we want)



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/src/airflow/sdk/execution_time/task_runner.py:
##########
@@ -129,6 +129,9 @@ class RuntimeTaskInstance(TaskInstance):
 
     task: BaseOperator
     bundle_instance: BaseDagBundle
+    _context: Context | None = None

Review Comment:
   It feels wrong this need to be an attribute. How about just adding `functools.cache` on `get_template_context`?



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/src/airflow/sdk/execution_time/task_runner.py:
##########
@@ -129,6 +129,9 @@ class RuntimeTaskInstance(TaskInstance):
 
     task: BaseOperator
     bundle_instance: BaseDagBundle
+    _context: Context | None = None

Review Comment:
   Hi @uranusjr , thanks for the feedback. I attempted to use `functools.cache` but got the following error since `RuntimeTaskInstance` is an unhashable type. I think it is because the `self` reference to the instances of the class.
   
   <img width="902" height="252" alt="image" src="https://github.com/user-attachments/assets/46717857-39f3-49cd-927f-f45e68893348" />
   
   https://github.com/apache/airflow/issues/52574#issuecomment-3149060840



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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

   ### Backport successfully created: v3-1-test
   
   <table>
                   <tr>
                       <th>Status</th>
                       <th>Branch</th>
                       <th>Result</th>
                   </tr>
                   <tr>
                       <td>✅</td>
                       <td>v3-1-test</td>
                       <td><a href="https://github.com/apache/airflow/pull/57031"><img src="https://img.shields.io/badge/PR-57031-blue" alt="PR Link"></a></td>
                   </tr>
               </table>


-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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

   Mostly good, I would appreciate it if we could have someone more familiar with task-sdk to take another look, as this changes the behavior of context, which could have a huge impact.
   
   @amoghrajesh @kaxil @ashb 


-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #54568:
URL: https://github.com/apache/airflow/pull/54568#discussion_r2299621565


##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -2538,6 +2564,118 @@ def execute(self, context):
         assert listener.state == [TaskInstanceState.RUNNING, TaskInstanceState.FAILED]
         assert listener.error == error
 
+    def test_listener_access_outlet_event_on_running_and_success(self, mocked_parse, mock_supervisor_comms):
+        """Test listener can access outlet events through invoking get_template_context() while task running and success"""
+        listener = self.CustomOutletEventsListener()
+        get_listener_manager().add_listener(listener)
+
+        test_asset = Asset("test-asset")
+        test_key = AssetUniqueKey(name="test-asset", uri="test-asset")
+        test_extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        class Producer(BaseOperator):
+            def execute(self, context):
+                outlet_events = context["outlet_events"]
+                outlet_events[test_asset].extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        task = Producer(
+            task_id="test_listener_access_outlet_event_on_running_and_success", outlets=[test_asset]
+        )
+        dag = get_inline_dag(dag_id="test_dag", task=task)
+        ti = TaskInstance(
+            id=uuid7(),
+            task_id=task.task_id,
+            dag_id=dag.dag_id,
+            run_id="test_run",
+            try_number=1,
+            dag_version_id=uuid7(),
+        )
+
+        runtime_ti = RuntimeTaskInstance.model_construct(
+            **ti.model_dump(exclude_unset=True), task=task, start_date=timezone.utcnow()
+        )
+
+        log = mock.MagicMock()
+        context = runtime_ti.get_template_context()
+
+        with mock.patch(
+            "airflow.sdk.execution_time.task_runner._validate_task_inlets_and_outlets"

Review Comment:
   I think it's because we'll need to patch `SUPERVISOR_COMMS` due to `inactive_assets_resp = SUPERVISOR_COMMS.send(msg=ValidateInletsAndOutlets(ti_id=ti.id))` which makes things a bit more complicated. 
   
   As we already know, it's an activated asset (we create it and activate it), this check doesn't really needed here



##########
scripts/ci/prek/check_template_context_variable_in_sync.py:
##########


Review Comment:
   looks good to me if we're to merge this logic



##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -2538,6 +2564,118 @@ def execute(self, context):
         assert listener.state == [TaskInstanceState.RUNNING, TaskInstanceState.FAILED]
         assert listener.error == error
 
+    def test_listener_access_outlet_event_on_running_and_success(self, mocked_parse, mock_supervisor_comms):
+        """Test listener can access outlet events through invoking get_template_context() while task running and success"""
+        listener = self.CustomOutletEventsListener()
+        get_listener_manager().add_listener(listener)
+
+        test_asset = Asset("test-asset")
+        test_key = AssetUniqueKey(name="test-asset", uri="test-asset")
+        test_extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        class Producer(BaseOperator):
+            def execute(self, context):
+                outlet_events = context["outlet_events"]
+                outlet_events[test_asset].extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}

Review Comment:
   ```suggestion
                   outlet_events[test_asset].extra = test_extra
   ```
   
   maybe just reuse the `test_extra` variable?



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -2538,6 +2564,118 @@ def execute(self, context):
         assert listener.state == [TaskInstanceState.RUNNING, TaskInstanceState.FAILED]
         assert listener.error == error
 
+    def test_listener_access_outlet_event_on_running_and_success(self, mocked_parse, mock_supervisor_comms):
+        """Test listener can access outlet events through invoking get_template_context() while task running and success"""
+        listener = self.CustomOutletEventsListener()
+        get_listener_manager().add_listener(listener)
+
+        test_asset = Asset("test-asset")
+        test_key = AssetUniqueKey(name="test-asset", uri="test-asset")
+        test_extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        class Producer(BaseOperator):
+            def execute(self, context):
+                outlet_events = context["outlet_events"]
+                outlet_events[test_asset].extra = {"name1": "value1", "nested_obj": {"name2": "value2"}}
+
+        task = Producer(
+            task_id="test_listener_access_outlet_event_on_running_and_success", outlets=[test_asset]
+        )
+        dag = get_inline_dag(dag_id="test_dag", task=task)
+        ti = TaskInstance(
+            id=uuid7(),
+            task_id=task.task_id,
+            dag_id=dag.dag_id,
+            run_id="test_run",
+            try_number=1,
+            dag_version_id=uuid7(),
+        )
+
+        runtime_ti = RuntimeTaskInstance.model_construct(
+            **ti.model_dump(exclude_unset=True), task=task, start_date=timezone.utcnow()
+        )
+
+        log = mock.MagicMock()
+        context = runtime_ti.get_template_context()
+
+        with mock.patch(
+            "airflow.sdk.execution_time.task_runner._validate_task_inlets_and_outlets"

Review Comment:
   sure. will experiment with it, and see if I could get better understanding.



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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

   Hi @sjyangkevin,
   
   Thanks for your fix — I’ve applied it in my environment and everything is working smoothly now. Really appreciate your effort!
   
   Looking forward to seeing this included in the next Airflow release.


-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_context.py:
##########
@@ -154,6 +154,26 @@ def test_context_to_airflow_vars_all_context(self, create_runtime_ti):
             "AIRFLOW_CTX_DAG_EMAIL": "email1@test.com",
         }
 
+    def test_get_template_context_return_same_context_object(self, create_runtime_ti):

Review Comment:
   A test that actually tests that the outlet event extra is set would be better than this. This is testing the current implementation, but that isn't _strictly_ what we care about.



-- 
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] Fix Outlet Event Extra Data is Empty in Task Instance Success Listener [airflow]

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

   Hi @uranusjr , would you mind have a look whenever you have time. thanks!


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