This is an automated email from the ASF dual-hosted git repository.

dabla pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new ff812b65b93 Make the in-process supervisor safe to call from several 
threads (#74074)
ff812b65b93 is described below

commit ff812b65b93ce2059378a797eaf1378c6154592f
Author: David Blain <[email protected]>
AuthorDate: Fri Nov 20 07:25:07 2026 +0100

    Make the in-process supervisor safe to call from several threads (#74074)
    
    * Make the in-process supervisor safe to call from several threads
    
    InProcessSupervisorComms served a request by removing
    task_runner.SUPERVISOR_COMMS from the whole process, so that the code
    serving it acted as the server side. A task calling the SDK from several
    threads under dag.test() failed with ImportError, or took its Variable
    and Connection lookups for the server side, while another thread's
    request was served.
    
    Instead of removing SUPERVISOR_COMMS, a ContextVar marks the code serving
    a request: the sender sets it around _handle_request, and the in-process
    execution API sets it around each request it serves, next to
    force_server_context(), so its event loop task and the worker threads of
    sync routes inherit it. The task's other threads keep their comms. Mask
    forwarding and the secrets backend choice read it through
    task_runner.supervisor_comms(), airflow-core through
    should_use_task_sdk_api_path().
    
    * Keep removing the comms for an older airflow-core
    
    An airflow-core from before airflow.process_context decides from the
    presence of task_runner.SUPERVISOR_COMMS alone whether it runs in a
    task. With the attribute left in place while a request is served, its
    Variable and Connection lookups in the in-process API went back through
    the comms. InProcessSupervisorComms.send therefore removes the attribute
    for the whole process there, as before, and hides the comms per request
    only when the core has airflow.process_context.
    
    Also renames the helpers to get_supervisor_comms() and
    hide_supervisor_comms(), keeps their explanation in one place, and moves
    the threaded DB tests next to the dag.test() tests, where they call
    dag.test() itself.
    
    * Read get_supervisor_comms with a getattr guard and name the core check as 
a predicate
    
    _supervisor_comms() in sdk/log.py now looks up get_supervisor_comms with
    the same getattr guard as airflow.process_context, so a secret masked
    while task_runner is still importing gets None instead of an
    AttributeError. _core_decides_server_side_per_request is renamed to
    _has_per_request_server_context, and its patch in the test gets autospec.
---
 .../api_fastapi/execution_api/in_process.py        |  15 +++-
 airflow-core/src/airflow/process_context.py        |   8 +-
 .../unit/api_fastapi/execution_api/test_app.py     |  44 +++++++++
 .../tests/unit/core/test_process_context.py        |  59 ++++++++++++
 airflow-core/tests/unit/models/test_dag.py         |  62 +++++++++++++
 .../src/airflow/sdk/execution_time/supervisor.py   |  35 ++++++--
 .../src/airflow/sdk/execution_time/task_runner.py  |  28 ++++++
 task-sdk/src/airflow/sdk/log.py                    |   8 +-
 .../task_sdk/execution_time/test_supervisor.py     | 100 +++++++++++++++++++++
 9 files changed, 349 insertions(+), 10 deletions(-)

diff --git a/airflow-core/src/airflow/api_fastapi/execution_api/in_process.py 
b/airflow-core/src/airflow/api_fastapi/execution_api/in_process.py
index 4405e387b76..60bfe223f88 100644
--- a/airflow-core/src/airflow/api_fastapi/execution_api/in_process.py
+++ b/airflow-core/src/airflow/api_fastapi/execution_api/in_process.py
@@ -19,9 +19,10 @@
 from __future__ import annotations
 
 import asyncio
+import sys
 import threading
 import weakref
-from contextlib import AsyncExitStack
+from contextlib import AsyncExitStack, nullcontext
 from functools import cached_property
 from typing import TYPE_CHECKING, cast
 
@@ -94,13 +95,21 @@ def _configure_in_process_auth(app: FastAPI, *, 
triggerer_id: int | None = None)
 
 
 class _RequestScopedServerContextApp:
-    """Wrap an ASGI app so in-process requests behave like server-side API 
handling."""
+    """
+    Wrap an ASGI app so in-process requests behave like server-side API 
handling.
+
+    ``force_server_context`` covers airflow-core's readers and the Task SDK's 
``hide_supervisor_comms``
+    its own; the event loop task and the worker threads of sync routes inherit 
both.
+    """
 
     def __init__(self, app: FastAPI) -> None:
         self.app = app
 
     async def __call__(self, scope: Scope, receive: Receive, send: Send) -> 
None:
-        with force_server_context():
+        task_runner = sys.modules.get("airflow.sdk.execution_time.task_runner")
+        # No task runs in this process, or a Task SDK from before the flag: 
nothing to hide.
+        hide_supervisor_comms = getattr(task_runner, "hide_supervisor_comms", 
nullcontext)
+        with force_server_context(), hide_supervisor_comms():
             await self.app(scope, receive, send)
 
 
diff --git a/airflow-core/src/airflow/process_context.py 
b/airflow-core/src/airflow/process_context.py
index af506bc00a2..ee5ef6d4bf9 100644
--- a/airflow-core/src/airflow/process_context.py
+++ b/airflow-core/src/airflow/process_context.py
@@ -50,4 +50,10 @@ def should_use_task_sdk_api_path() -> bool:
         return False
 
     task_runner_module = 
sys.modules.get("airflow.sdk.execution_time.task_runner")
-    return bool(getattr(task_runner_module, "SUPERVISOR_COMMS", None))
+    if task_runner_module is None:
+        return False
+    get_supervisor_comms = getattr(task_runner_module, "get_supervisor_comms", 
None)
+    if get_supervisor_comms is None:
+        # A Task SDK from before ``get_supervisor_comms()``.
+        return bool(getattr(task_runner_module, "SUPERVISOR_COMMS", None))
+    return get_supervisor_comms() is not None
diff --git a/airflow-core/tests/unit/api_fastapi/execution_api/test_app.py 
b/airflow-core/tests/unit/api_fastapi/execution_api/test_app.py
index a95448fa06f..782726de7f7 100644
--- a/airflow-core/tests/unit/api_fastapi/execution_api/test_app.py
+++ b/airflow-core/tests/unit/api_fastapi/execution_api/test_app.py
@@ -582,3 +582,47 @@ class TestTraceContextPropagation:
                 await gen.asend(None)  # resume past the yield -> else branch 
-> detach
 
         detach_spy.assert_called_once()
+
+
+def test_in_process_execution_api_serves_requests_as_the_server_side():
+    """
+    Under dag.test() the task, its supervisor and the in-process API share one 
process.
+
+    The code serving a request, on the API's event loop or in the worker 
thread of a sync route, must
+    act as the server side and not see the task's comms. A thread of the task 
that is not serving the
+    request keeps them meanwhile, so its own Variable or Connection lookups 
still go to the supervisor.
+    """
+    from airflow.sdk.execution_time import task_runner
+
+    comms = object()
+    seen: dict[str, object] = {}
+    route_entered = threading.Event()
+    task_thread_read = threading.Event()
+
+    def task_thread():
+        route_entered.wait(5)
+        seen["task thread"] = task_runner.get_supervisor_comms()
+        task_thread_read.set()
+
+    async def probe_async():
+        seen["async route"] = task_runner.get_supervisor_comms()
+
+    def probe_sync():
+        route_entered.set()
+        task_thread_read.wait(5)
+        seen["sync route"] = task_runner.get_supervisor_comms()
+
+    api = InProcessExecutionAPI()
+    api.app.add_api_route("/probe-async", probe_async, methods=["GET"])
+    api.app.add_api_route("/probe-sync", probe_sync, methods=["GET"])
+
+    with mock.patch.object(task_runner, "SUPERVISOR_COMMS", comms, 
create=True):
+        thread = threading.Thread(target=task_thread)
+        thread.start()
+        with httpx2.Client(transport=api.transport, 
base_url="http://localhost";) as client:
+            assert client.get("/probe-async").status_code == 200
+            assert client.get("/probe-sync").status_code == 200
+        thread.join(5)
+        seen["after"] = task_runner.get_supervisor_comms()
+
+    assert seen == {"async route": None, "sync route": None, "task thread": 
comms, "after": comms}
diff --git a/airflow-core/tests/unit/core/test_process_context.py 
b/airflow-core/tests/unit/core/test_process_context.py
new file mode 100644
index 00000000000..ba4dd1a0180
--- /dev/null
+++ b/airflow-core/tests/unit/core/test_process_context.py
@@ -0,0 +1,59 @@
+#
+# 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.
+from __future__ import annotations
+
+import sys
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from airflow.process_context import should_use_task_sdk_api_path
+
+TASK_RUNNER = "airflow.sdk.execution_time.task_runner"
+
+
+class TestShouldUseTaskSdkApiPath:
+    """Whether models.Variable/Connection take the Execution API path, per 
thread."""
+
+    @pytest.mark.parametrize(("comms", "expected"), [("comms", True), (None, 
False)])
+    def test_follows_the_task_runners_answer_for_this_thread(self, 
monkeypatch, comms, expected):
+        monkeypatch.setitem(sys.modules, TASK_RUNNER, 
SimpleNamespace(get_supervisor_comms=lambda: comms))
+        assert should_use_task_sdk_api_path() is expected
+
+    @pytest.mark.parametrize(
+        ("module_attrs", "expected"), [({"SUPERVISOR_COMMS": "comms"}, True), 
({}, False)]
+    )
+    def test_falls_back_to_the_attribute_for_an_older_task_sdk(self, 
monkeypatch, module_attrs, expected):
+        monkeypatch.setitem(sys.modules, TASK_RUNNER, 
SimpleNamespace(**module_attrs))
+        assert should_use_task_sdk_api_path() is expected
+
+    @pytest.mark.parametrize("name", ["get_supervisor_comms", 
"hide_supervisor_comms"])
+    def test_the_task_sdk_has_the_names_looked_up_with_getattr(self, name):
+        """airflow-core falls back silently when a name is missing, so a 
rename must fail here."""
+        from airflow.sdk.execution_time import task_runner
+
+        assert callable(getattr(task_runner, name))
+
+    def test_the_thread_serving_an_in_process_request_is_the_server_side(self):
+        from airflow.sdk.execution_time import task_runner
+
+        with patch.object(task_runner, "SUPERVISOR_COMMS", "comms", 
create=True):
+            assert should_use_task_sdk_api_path() is True
+            with task_runner.hide_supervisor_comms():
+                assert should_use_task_sdk_api_path() is False
diff --git a/airflow-core/tests/unit/models/test_dag.py 
b/airflow-core/tests/unit/models/test_dag.py
index 0bb313664e9..f94a8a0c92e 100644
--- a/airflow-core/tests/unit/models/test_dag.py
+++ b/airflow-core/tests/unit/models/test_dag.py
@@ -23,6 +23,7 @@ import os
 import pickle
 import re
 import time
+from concurrent.futures import ThreadPoolExecutor
 from contextlib import nullcontext
 from datetime import timedelta
 from pathlib import Path
@@ -68,6 +69,8 @@ from airflow.models.hitl import HITLDetail
 from airflow.models.serialized_dag import SerializedDagModel
 from airflow.models.taskinstance import TaskInstance as TI
 from airflow.models.trigger import handle_event_submit
+from airflow.models.variable import Variable
+from airflow.models.xcom import XComModel
 from airflow.providers.standard.operators.bash import BashOperator
 from airflow.providers.standard.operators.empty import EmptyOperator
 from airflow.providers.standard.operators.python import PythonOperator
@@ -77,6 +80,7 @@ from airflow.sdk import (
     CronPartitionTimetable,
     PartitionedAtRuntime,
     TaskGroup,
+    Variable as SdkVariable,
     setup,
     task as task_decorator,
     task_group,
@@ -1946,6 +1950,64 @@ class TestDag:
         dag.test()
         mock_object.assert_called_with("output of first task")
 
+    def test_dag_test_threads_of_a_task_push_and_read_xcoms(self, 
testing_dag_bundle, session):
+        """A task's own threads make SDK calls while others are served: each 
gets its own answer."""
+        dag = DAG(dag_id="test_dag_test_xcoms_from_threads", schedule=None, 
start_date=DEFAULT_DATE)
+
+        @task_decorator
+        def produce(ti=None):
+            def work(x):
+                for n in range(5):
+                    ti.xcom_push(key=f"k{n}_{x}", value=x)
+                    assert ti.xcom_pull(task_ids="produce", key=f"k{n}_{x}") 
== x
+                return x
+
+            with ThreadPoolExecutor(max_workers=4) as pool:
+                return sorted(pool.map(work, range(8)))
+
+        with dag:
+            produce()
+        sync_dag_to_db(dag)
+
+        dr = dag.test()
+
+        assert dr.state == DagRunState.SUCCESS
+        keys = set(
+            session.scalars(
+                select(XComModel.key).where(XComModel.dag_id == dag.dag_id, 
XComModel.run_id == dr.run_id)
+            )
+        )
+        assert {f"k{n}_{x}" for n in range(5) for x in range(8)} <= keys
+
+    def test_dag_test_threads_of_a_task_read_variables_while_another_is_served(
+        self, testing_dag_bundle, session
+    ):
+        """
+        A Variable lookup must not miss while another thread's request is 
served: hiding the comms
+        from the whole process sent it to the fallback secrets backends, which 
do not have a
+        Variable stored in the metadata database.
+        """
+        Variable.set(key="in_process_db_variable", value="v", session=session)
+        session.commit()
+        dag = DAG(dag_id="test_dag_test_variables_from_threads", 
schedule=None, start_date=DEFAULT_DATE)
+
+        @task_decorator
+        def read(ti=None):
+            def work(x):
+                for _ in range(25):
+                    assert SdkVariable.get("in_process_db_variable") == "v"
+                    ti.xcom_push(key=f"k_{x}", value=x)
+                return x
+
+            with ThreadPoolExecutor(max_workers=4) as pool:
+                return sorted(pool.map(work, range(8)))
+
+        with dag:
+            read()
+        sync_dag_to_db(dag)
+
+        assert dag.test().state == DagRunState.SUCCESS
+
     @pytest.mark.parametrize("callback_error", [None, RuntimeError])
     def test_dag_test_retry_callback_keeps_attempt_live(self, 
testing_dag_bundle, callback_error):
         observed = []
diff --git a/task-sdk/src/airflow/sdk/execution_time/supervisor.py 
b/task-sdk/src/airflow/sdk/execution_time/supervisor.py
index 6fd90a0785c..ea53e73f602 100644
--- a/task-sdk/src/airflow/sdk/execution_time/supervisor.py
+++ b/task-sdk/src/airflow/sdk/execution_time/supervisor.py
@@ -22,6 +22,7 @@ from __future__ import annotations
 import atexit
 import contextlib
 import functools
+import importlib.util
 import io
 import logging
 import math
@@ -2545,6 +2546,17 @@ to the socket.
 """
 
 
[email protected]
+def _has_per_request_server_context() -> bool:
+    """
+    Whether the installed airflow-core has ``airflow.process_context``.
+
+    An older core decides from the presence of 
``task_runner.SUPERVISOR_COMMS`` alone, so the
+    attribute has to go while a request is served there.
+    """
+    return importlib.util.find_spec("airflow.process_context") is not None
+
+
 @attrs.define(kw_only=True)
 class InProcessSupervisorComms:
     """In-process communication handler that returns each response directly to 
its caller."""
@@ -2553,13 +2565,25 @@ class InProcessSupervisorComms:
     supervisor: InProcessTestSupervisor
 
     def send(self, msg: BaseModel) -> BaseModel | None:
-        """Send a request to the supervisor and return its response."""
+        """
+        Send a request to the supervisor and return its response.
+
+        Safe to call from several threads: each call gets its own response 
sink, and the comms are
+        hidden from the code serving the request only 
(``task_runner.hide_supervisor_comms``). With an
+        airflow-core from before ``airflow.process_context`` they are removed 
for the whole process
+        instead, as before, so there only one thread of a task may make SDK 
calls at a time.
+        """
+        from airflow.sdk.execution_time.task_runner import 
hide_supervisor_comms
+
         self.log.debug("Sending request", msg=msg)
+        hidden_comms = (
+            hide_supervisor_comms() if _has_per_request_server_context() else 
set_supervisor_comms(None)
+        )
 
         responses: deque[BaseModel | None] = deque()
         token = _IN_PROCESS_RESPONSE_SINK.set(responses)
         try:
-            with set_supervisor_comms(None):
+            with hidden_comms:
                 self.supervisor._handle_request(msg, log, 0)  # type: 
ignore[arg-type]
         finally:
             _IN_PROCESS_RESPONSE_SINK.reset(token)
@@ -2795,9 +2819,10 @@ def set_supervisor_comms(temp_comms):
     by injecting a test Comms implementation (e.g. `InProcessSupervisorComms`)
     in place of the real inter-process communication layer.
 
-    Some parts of the code (e.g. models.Variable.get) check for the presence
-    of `task_runner.SUPERVISOR_COMMS` to determine if the code is running in a 
Task SDK execution context.
-    This override ensures those code paths behave correctly during in-process 
tests.
+    Some parts of the code (e.g. models.Variable.get) ask 
`task_runner.get_supervisor_comms()`, in
+    airflow-core through 
`airflow.process_context.should_use_task_sdk_api_path()`, to determine if the 
code
+    is running in a Task SDK execution context. That reads the comms set here, 
so this override ensures
+    those code paths behave correctly during in-process tests.
     """
     from airflow.sdk.execution_time import task_runner
 
diff --git a/task-sdk/src/airflow/sdk/execution_time/task_runner.py 
b/task-sdk/src/airflow/sdk/execution_time/task_runner.py
index 33590b4d1b7..8bee11cefb9 100644
--- a/task-sdk/src/airflow/sdk/execution_time/task_runner.py
+++ b/task-sdk/src/airflow/sdk/execution_time/task_runner.py
@@ -1242,6 +1242,34 @@ def parse(what: StartupDetails, log: Logger) -> 
RuntimeTaskInstance:
 #   accessible wherever needed during task execution without modifying every 
layer of the call stack.
 SUPERVISOR_COMMS: CommsDecoder[ToTask, ToSupervisor]
 
+# True while code serves an in-process supervisor request (dag.test()). That 
code acts as
+# the server side, so get_supervisor_comms() returns None there. Other task 
threads are unaffected.
+_supervisor_comms_hidden: contextvars.ContextVar[bool] = 
contextvars.ContextVar(
+    "_supervisor_comms_hidden", default=False
+)
+
+
+def get_supervisor_comms() -> CommsDecoder[ToTask, ToSupervisor] | None:
+    """
+    Return the comms to the supervisor, or ``None``.
+
+    ``None`` outside a task execution context and inside 
:func:`hide_supervisor_comms`. Code that
+    decides whether it runs inside a task should ask this instead of checking 
for ``SUPERVISOR_COMMS``.
+    """
+    if _supervisor_comms_hidden.get():
+        return None
+    return globals().get("SUPERVISOR_COMMS")
+
+
+@contextmanager
+def hide_supervisor_comms() -> Iterator[None]:
+    """Hide the comms from the code run inside this block, and only from it."""
+    token = _supervisor_comms_hidden.set(True)
+    try:
+        yield
+    finally:
+        _supervisor_comms_hidden.reset(token)
+
 
 # State machine!
 # 1. Start up (receive details from supervisor)
diff --git a/task-sdk/src/airflow/sdk/log.py b/task-sdk/src/airflow/sdk/log.py
index efacfde33c2..128ec6e686d 100644
--- a/task-sdk/src/airflow/sdk/log.py
+++ b/task-sdk/src/airflow/sdk/log.py
@@ -267,9 +267,15 @@ def _supervisor_comms() -> CommsDecoder[ToTask, 
ToSupervisor] | None:
     Every process that sets ``SUPERVISOR_COMMS`` has already imported 
``task_runner``, so it is read
     from ``sys.modules`` rather than imported: importing it here would load 
the whole task runtime
     into every other process (CLI, scheduler, API server) that masks a config 
value at startup.
+    Asked through ``task_runner.get_supervisor_comms()``, which also answers 
``None`` where the comms
+    are hidden.
     """
     task_runner = sys.modules.get("airflow.sdk.execution_time.task_runner")
-    return getattr(task_runner, "SUPERVISOR_COMMS", None)
+    # ``task_runner`` may still be importing and not define the function yet.
+    get_supervisor_comms = getattr(task_runner, "get_supervisor_comms", None)
+    if get_supervisor_comms is None:
+        return None
+    return get_supervisor_comms()
 
 
 def mask_secret(secret: JsonValue, name: str | None = None) -> None:
diff --git a/task-sdk/tests/task_sdk/execution_time/test_supervisor.py 
b/task-sdk/tests/task_sdk/execution_time/test_supervisor.py
index d9d1db6587d..2e831af490e 100644
--- a/task-sdk/tests/task_sdk/execution_time/test_supervisor.py
+++ b/task-sdk/tests/task_sdk/execution_time/test_supervisor.py
@@ -176,6 +176,7 @@ from airflow.sdk.execution_time.comms import (
 )
 from airflow.sdk.execution_time.coordinator import BaseCoordinator, 
TaskLaunchError
 from airflow.sdk.execution_time.supervisor import (
+    _IN_PROCESS_RESPONSE_SINK,
     SERVER_TERMINATED,
     ActivitySubprocess,
     InProcessSupervisorComms,
@@ -5374,6 +5375,105 @@ class TestInProcessTestSupervisor:
         assert isinstance(collected[0], _Failure)
 
 
+class TestInProcessSupervisorCommsAcrossThreads:
+    """
+    dag.test() serves a task's requests in the task's own process, possibly 
for several of the task's
+    threads at once. While a request is served, the code serving it stops 
seeing the comms, and only
+    that code: the task's other threads keep theirs. The in-process API 
server's side is covered in the
+    execution API's test_app.py.
+    """
+
+    @staticmethod
+    def _comms(serve):
+        """In-process comms whose supervisor answers each request with 
``serve(msg)``."""
+        comms = 
InProcessSupervisorComms(supervisor=mock.Mock(spec=InProcessTestSupervisor))
+
+        def handle_request(msg, log, req_id):
+            sink = _IN_PROCESS_RESPONSE_SINK.get()
+            assert sink is not None
+            sink.append(serve(msg))
+
+        comms.supervisor._handle_request.side_effect = handle_request
+        return comms
+
+    def test_only_the_code_serving_a_request_stops_seeing_the_comms(self):
+        """
+        While one thread's request is served, the task's other threads must 
keep their comms: seeing
+        none, they would take their Variable and Connection lookups for the 
server side and find nothing.
+        """
+        seen: dict[str, object] = {}
+        serving = threading.Event()
+        sibling_read = threading.Event()
+
+        def serve(msg):
+            seen["serving"] = task_runner.get_supervisor_comms()
+            serving.set()
+            sibling_read.wait(5)
+            return "done"
+
+        def sibling():
+            serving.wait(5)
+            seen["sibling"] = task_runner.get_supervisor_comms()
+            sibling_read.set()
+
+        comms = self._comms(serve)
+        with patch.object(task_runner, "SUPERVISOR_COMMS", comms, create=True):
+            threads = [
+                threading.Thread(target=comms.send, args=("request",)),
+                threading.Thread(target=sibling),
+            ]
+            for thread in threads:
+                thread.start()
+            for thread in threads:
+                thread.join(5)
+            # Once answered, the sender sees its comms again, and the module 
attribute never went
+            # away, which is what `from task_runner import SUPERVISOR_COMMS` 
needs.
+            seen["after"] = task_runner.get_supervisor_comms()
+            seen["attribute"] = hasattr(task_runner, "SUPERVISOR_COMMS")
+
+        assert seen == {"serving": None, "sibling": comms, "after": comms, 
"attribute": True}
+
+    def test_hide_supervisor_comms_restores_the_previous_state(self):
+        with patch.object(task_runner, "SUPERVISOR_COMMS", "comms", 
create=True):
+            with task_runner.hide_supervisor_comms():
+                with task_runner.hide_supervisor_comms():
+                    assert task_runner.get_supervisor_comms() is None
+                assert task_runner.get_supervisor_comms() is None
+            assert task_runner.get_supervisor_comms() == "comms"
+
+    @pytest.mark.parametrize("serving", [False, True], ids=["task-code", 
"serving-a-request"])
+    def test_mask_secret_is_forwarded_only_from_task_code(self, serving):
+        from airflow.sdk.log import mask_secret
+
+        comms = mock.Mock(spec=InProcessSupervisorComms)
+        with patch.object(task_runner, "SUPERVISOR_COMMS", comms, create=True):
+            with task_runner.hide_supervisor_comms() if serving else 
nullcontext():
+                mask_secret("s3cr3t-value", "key")
+
+        assert comms.send.called is not serving
+
+    def 
test_with_an_older_core_the_comms_are_removed_while_a_request_is_served(self):
+        """
+        An airflow-core without ``airflow.process_context`` only checks 
whether ``SUPERVISOR_COMMS``
+        exists, so its code serving the request must not find the attribute.
+        """
+        seen: dict[str, object] = {}
+
+        def serve(msg):
+            seen["serving"] = hasattr(task_runner, "SUPERVISOR_COMMS")
+            return "done"
+
+        comms = self._comms(serve)
+        with (
+            patch.object(task_runner, "SUPERVISOR_COMMS", comms, create=True),
+            patch.object(supervisor, "_has_per_request_server_context", 
autospec=True, return_value=False),
+        ):
+            assert comms.send("request") == "done"
+            seen["after"] = task_runner.get_supervisor_comms()
+
+        assert seen == {"serving": False, "after": comms}
+
+
 class TestInProcessClient:
     def test_no_retries(self):
         called = 0

Reply via email to