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 ca7ddee2eec Let a sync send() wait for the supervisor channel during 
an asend() (#76545)
ca7ddee2eec is described below

commit ca7ddee2eeca5d1ea6be7fae6f624c0149f67e47
Author: David Blain <[email protected]>
AuthorDate: Tue Nov 24 23:58:56 2026 +0100

    Let a sync send() wait for the supervisor channel during an asend() (#76545)
    
    * Let a sync send() wait for the supervisor channel instead of raising 
while an asend() is in flight
    
    CommsDecoder.asend() held the channel's thread lock while it awaited the
    event loop for its socket I/O, so a sync send() on that loop's thread
    could never get the lock: it raised DeadlockImminentError. Its asyncio.Lock
    also bound to the first event loop that waited on it, so asyncio.run() on a
    worker thread, or any later loop, failed with "bound to a different event
    loop" while another loop had calls in flight. And a cancelled asend()
    released the lock before reading its response, which the next request
    then read as its own.
    
    asend() now runs the whole request (write and read) on a worker thread
    that needs no loop, behind one queue per event loop; send() waits for the
    reentrant channel lock. Only a send() on a thread already in the middle of
    a request (a signal handler such as on_kill interrupting it) still raises.
    A cancelled asend() marks its request abandoned: it is not sent if it had
    not been yet, and once sent its response is always drained.
    
    Extracted from #62922 (AIP-104), which needs it for indexed tasks that mix
    sync and async SDK calls.
    
    * Wrap the autospec patch of _get_response to the line length ruff format 
expects
    
    * Run asend() requests on one worker thread owned by the decoder
    
    asend() ran its request on a thread of the calling loop's default executor,
    behind one queue per event loop (_LoopQueue/_LoopQueues, held weakly so a
    closed loop was not kept). The decoder now owns a single worker thread
    (_RequestWorker) and every loop's requests queue for it, in the order they
    were made. The per-loop queues, their weak references and the bookkeeping of
    which calls waited for each other are gone, and nothing in the decoder
    refers to an event loop any more.
    
    Two things are kept on purpose:
    
    - The abandoned marker. The pool drops a cancelled request it has not picked
      up, but one it has picked up and that waits for the channel behind a sync
      send() on another thread can no longer be cancelled, and would still be
      written.
    - A worker per process. Threads do not survive a fork, so the worker is
      started by the first asend() of a process; created with the decoder, an
      asend() in a forked child waited for a thread that no longer existed.
    
    Measured against the previous commit (callgrind instructions): asend round
    trip 398.1k-399.4k -> 380.4k (-4.7 %), 50 concurrent asends 16.34M-16.37M ->
    14.85M (-9.2 %), send unchanged. Wall clock per request: unchanged on one
    loop, 426-468 us -> 295-320 us with four loops, 918-952 us -> 419-471 us
    with one asyncio.run() per call.
    
    * Rename the comms channel helpers, share the test frame helpers and link 
the stale-response issue
    
    - `_RequestWorker.get_executor()`, `_is_exchanging` and 
`_acquire_and_exchange` name what they
      return or do; the worker field takes the class itself as its attrs 
factory.
    - The `_exchange` docstring points to #77240 instead of describing the bug 
it does not fix.
    - The tests read and answer frames through module-level `_read_request` / 
`_respond`, imports
      sit at the module top, the two tests that could hang on a regression have 
a timeout, and the
      failed-request test fails the decode after the frame is read, so it can 
check that the next
      call gets its own response.
    
    * Keep the execution_timeout comment once in the comms tests
---
 task-sdk/src/airflow/sdk/execution_time/comms.py   | 188 ++++---
 .../tests/task_sdk/execution_time/test_comms.py    | 582 ++++++++++++++++-----
 2 files changed, 555 insertions(+), 215 deletions(-)

diff --git a/task-sdk/src/airflow/sdk/execution_time/comms.py 
b/task-sdk/src/airflow/sdk/execution_time/comms.py
index 6b7fbf95c95..b0c0c6b3a6d 100644
--- a/task-sdk/src/airflow/sdk/execution_time/comms.py
+++ b/task-sdk/src/airflow/sdk/execution_time/comms.py
@@ -50,10 +50,11 @@ from __future__ import annotations
 
 import asyncio
 import itertools
+import os
 import threading
 import traceback
 from collections.abc import Iterator
-from contextlib import suppress
+from concurrent.futures import ThreadPoolExecutor
 from datetime import datetime
 from functools import cached_property
 from pathlib import Path
@@ -126,13 +127,13 @@ ReceiveMsgType = TypeVar("ReceiveMsgType", 
bound=BaseModel)
 
 class DeadlockImminentError(BaseException):
     """
-    Raised when ``send()`` is called from the event loop thread while an 
``asend()`` is in flight.
+    Raised when ``send()`` is called on a thread that is itself in the middle 
of a request.
 
-    An in-flight ``asend()`` holds (or is waiting to take) the channel's 
thread lock and can only
-    release it once its event loop runs again. That loop runs on the calling 
thread, so a blocking
-    ``send()`` there can never be satisfied: the loop cannot run while the 
thread is blocked. This
-    holds whether the loop is currently running (a sync SDK call from inside a 
coroutine) or paused
-    between two ``run_until_complete`` calls (a sync SDK call from the code 
that drives the loop).
+    That thread holds the supervisor channel, and its request can only finish 
once the new call
+    returns, so waiting would freeze it: typically a signal handler, such as 
the one that runs an
+    operator's ``on_kill``, making a synchronous SDK call while the code it 
interrupted was making
+    one. Any other caller waits for the channel instead: the request in flight 
finishes on its own
+    thread, ``asend()``'s included, which needs no event loop to do so.
 
     Inherits from :class:`BaseException` so it escapes 
``contextlib.suppress(Exception)``
     and always surfaces to the caller.
@@ -145,14 +146,11 @@ class DeadlockImminentError(BaseException):
 
     def __str__(self) -> str:
         return (
-            f"comms.send() called from the event loop thread for message 
'{self.msg_type}' "
-            "— deadlock is imminent (asend() is concurrently in-flight and can 
only complete once "
-            "the event loop runs again on this thread). "
-            "Likely cause: BaseHook.get_hook() or BaseHook.get_connection() 
was called "
-            "from inside an async task, or a synchronous SDK call was made 
from the thread driving "
-            "the event loop while it was paused between two 
run_until_complete() calls. "
-            "Use the async equivalents instead: "
-            "await BaseHook.aget_hook() or await BaseHook.aget_connection()."
+            f"comms.send() called for message '{self.msg_type}' on a thread 
that is already in the "
+            "middle of a request to the supervisor — deadlock is imminent 
(that request can only "
+            "finish once this call returns). Likely cause: a synchronous SDK 
call from a signal "
+            "handler, such as an operator's on_kill(), interrupting another 
SDK call on the same "
+            "thread."
             f"\nOffending call stack:\n{self.stack}"
         )
 
@@ -228,6 +226,34 @@ class _ResponseFrame(_FrameMixin, msgspec.Struct, 
array_like=True, frozen=True,
     error: dict[str, Any] | None = None
 
 
+class _RequestWorker:
+    """
+    The one thread that makes a decoder's ``asend()`` requests, whichever 
event loop they come from.
+
+    Requests queue for it in the order they were made, and it needs no loop to 
finish one. The
+    first request of a process starts it: threads do not survive a fork, so a 
forked child gets
+    a thread of its own.
+    """
+
+    __slots__ = ("_executor", "_lock", "_pid")
+
+    def __init__(self) -> None:
+        self._executor: ThreadPoolExecutor | None = None
+        self._pid: int | None = None
+        self._lock = threading.Lock()
+
+    def get_executor(self) -> ThreadPoolExecutor:
+        """Return this process's single-thread executor, for 
``loop.run_in_executor``."""
+        if self._pid != (pid := os.getpid()):
+            with self._lock:
+                if self._pid != pid:
+                    self._executor = ThreadPoolExecutor(max_workers=1, 
thread_name_prefix="supervisor-comms")
+                    self._pid = pid
+        if TYPE_CHECKING:
+            assert self._executor is not None
+        return self._executor
+
+
 @attrs.define()
 class CommsDecoder(Generic[ReceiveMsgType, SendMsgType]):
     """Handle communication between the task in this process and the 
supervisor parent process."""
@@ -248,55 +274,50 @@ class CommsDecoder(Generic[ReceiveMsgType, SendMsgType]):
 
     err_decoder: TypeAdapter[ErrorResponse] = attrs.field(factory=lambda: 
TypeAdapter(ToTask), repr=False)
 
-    _thread_lock: threading.Lock = attrs.field(factory=threading.Lock, 
repr=False)
-    _async_lock: asyncio.Lock = attrs.field(factory=asyncio.Lock, repr=False)
-    _loop_thread_id: int | None = attrs.field(default=None, repr=False, 
init=False)
+    # Reentrant, so that a send() which interrupts its own thread's (a signal 
handler on the main
+    # thread) is let in instead of waiting for itself, and can tell from 
_is_exchanging whether that
+    # thread was in the middle of a request. The RLock records its owner when 
it is taken, so no
+    # moment is left where the thread holds the lock but is not yet known as 
its holder.
+    _thread_lock: threading.RLock = attrs.field(factory=threading.RLock, 
repr=False)
+    _worker: _RequestWorker = attrs.field(factory=_RequestWorker, repr=False, 
init=False)
+    # Whether the thread holding _thread_lock is between writing a request and 
reading its
+    # response. Only that thread can read it as True once it holds the lock 
itself.
+    _is_exchanging: bool = attrs.field(default=False, repr=False, init=False)
 
     def _make_frame(self, msg: SendMsgType) -> _RequestFrame:
         carrier: dict[str, str] = {}
         _trace_propagator.inject(carrier)
         return _RequestFrame(id=next(self.id_counter), body=msg.model_dump(), 
context_carrier=carrier or None)
 
-    @property
-    def _is_on_loop_thread(self) -> bool:
-        if threading.get_ident() == self._loop_thread_id:
-            with suppress(RuntimeError):
-                return bool(asyncio.get_running_loop())
-        return False
-
-    @property
-    def _asend_in_flight_on_this_thread(self) -> bool:
+    def send(self, msg: SendMsgType) -> ReceiveMsgType | None:
         """
-        Whether an ``asend()`` coroutine of a loop that runs on the current 
thread is in flight.
-
-        ``asend()`` holds ``_async_lock`` for its whole duration, from before 
it takes
-        ``_thread_lock`` (in an executor thread) until after it releases it, 
so the async lock
-        being held is the reliable signal that the thread lock is, or is about 
to be, held by a
-        coroutine. Such a coroutine only makes progress when its loop runs, 
and that loop runs on
-        this thread. This is thread-scoped on purpose: a loop running on 
*another* thread keeps
-        going while this one blocks, so ``send()`` from there can safely wait 
for the lock.
+        Send a request to the parent and block until the response is received.
+
+        Called on an event loop's thread while an ``asend()`` is in flight, 
this waits for that
+        request's round trip: ``asend()`` runs on a worker thread that needs 
no loop to finish, so
+        the wait ends, but it stalls every coroutine on the loop meanwhile. 
Async code should
+        prefer ``asend()`` and the async SDK calls built on it. Only a call on 
a thread that is
+        itself in the middle of a request raises 
:class:`DeadlockImminentError`, as waiting there
+        would never end.
         """
-        return threading.get_ident() == self._loop_thread_id and 
self._async_lock.locked()
-
-    def send(self, msg: SendMsgType) -> ReceiveMsgType | None:
-        """Send a request to the parent and block until the response is 
received."""
         frame_bytes = self._make_frame(msg).as_bytes()
+        with self._thread_lock:
+            # Another thread's request makes the acquire above wait for it. 
This thread's own lets
+            # it in again: in the middle of that request, the call would wait 
for its own response,
+            # so it raises; before the request is written or after its 
response is read, the
+            # channel is free and this call is exchanged whole in between.
+            if self._is_exchanging:
+                raise DeadlockImminentError(msg)
+            return self._exchange(msg, frame_bytes)
+
+    def _exchange(self, msg: SendMsgType, frame_bytes: bytes | bytearray) -> 
ReceiveMsgType | None:
+        """
+        Write one request and read its response; the caller holds 
``_thread_lock``.
 
-        # An asend() in flight on this thread's loop can only release 
_thread_lock once that loop
-        # runs again, and the loop cannot run while this thread blocks in 
send(). Raise instead of
-        # blocking. This covers the loop being paused between two 
run_until_complete() calls, where
-        # the running-loop check below does not apply: 
asyncio.get_running_loop() raises, so send()
-        # would otherwise fall through to a blocking acquire and freeze the 
process with every
-        # thread idle (seen with a sync XCom read pulling the next iterated 
sub-task's input while a
-        # sub-task's asend() was parked mid-I/O).
-        if self._asend_in_flight_on_this_thread:
-            raise DeadlockImminentError(msg)
-
-        # When called from the event loop thread while the loop is running, 
use non-blocking
-        # acquire to detect an imminent deadlock: an asend() coroutine 
currently holds
-        # _thread_lock and is waiting for the event loop to complete its I/O.
-        if not self._thread_lock.acquire(blocking=not self._is_on_loop_thread):
-            raise DeadlockImminentError(msg)
+        An exception raised between the write and the read leaves the response 
on the socket for
+        the next request: https://github.com/apache/airflow/issues/77240.
+        """
+        self._is_exchanging = True
         try:
             self.socket.sendall(frame_bytes)
             if isinstance(msg, ResendLoggingFD):
@@ -315,42 +336,43 @@ class CommsDecoder(Generic[ReceiveMsgType, SendMsgType]):
 
             return self._get_response()
         finally:
-            self._thread_lock.release()
+            self._is_exchanging = False
+
+    def _acquire_and_exchange(
+        self, msg: SendMsgType, frame_bytes: bytes | bytearray, abandoned: 
threading.Event
+    ) -> ReceiveMsgType | None:
+        """
+        Take ``_thread_lock``, exchange one request and its response, and 
release it.
+
+        A request whose caller gave up while this thread waited for the lock 
(a ``send()`` on
+        another thread held the channel) is not sent: nothing reached the 
parent yet, and its side
+        effects (an XCom push, a state update) belong to a coroutine that was 
cancelled. Once sent,
+        its response is always read, so the next request never reads it as its 
own.
+        """
+        with self._thread_lock:
+            if abandoned.is_set():
+                return None
+            return self._exchange(msg, frame_bytes)
 
     async def asend(self, msg: SendMsgType) -> ReceiveMsgType | None:
         """
         Send a request to the parent without blocking.
 
-        Uses async lock for coroutine safety and thread lock for socket safety.
+        The request runs on the decoder's own worker thread, which takes 
``_thread_lock``, writes
+        the request, reads its response and releases the lock. Requests of 
every event loop queue
+        for that one thread. Cancelling the await drops a request that was not 
sent yet; one already
+        sent has its response drained before the thread lets go of the 
channel, so the next request
+        never reads a response that was not its own.
         """
-        self._loop_thread_id = threading.get_ident()
-
         frame_bytes = self._make_frame(msg).as_bytes()
-
-        async with self._async_lock:
-            # Acquire the threading lock without blocking the event loop
-            loop = asyncio.get_running_loop()
-            await loop.run_in_executor(None, self._thread_lock.acquire)
-            try:
-                # Async write to socket
-                await loop.sock_sendall(self.socket, frame_bytes)
-
-                if isinstance(msg, ResendLoggingFD):
-                    if recv_fds is None:
-                        return None
-                    # Blocking read in a thread
-                    frame, fds = await asyncio.to_thread(self._read_frame, 
maxfds=1)
-                    resp = self._from_frame(frame)
-                    if TYPE_CHECKING:
-                        assert isinstance(resp, SentFDs)
-                    resp.fds = fds
-                    return resp  # type: ignore[return-value]
-
-                # Normal blocking read in a thread
-                frame = await asyncio.to_thread(self._read_frame)
-                return self._from_frame(frame)
-            finally:
-                self._thread_lock.release()
+        abandoned = threading.Event()
+        try:
+            return await asyncio.get_running_loop().run_in_executor(
+                self._worker.get_executor(), self._acquire_and_exchange, msg, 
frame_bytes, abandoned
+            )
+        except BaseException:
+            abandoned.set()
+            raise
 
     @overload
     def _read_frame(self, maxfds: None = None) -> _ResponseFrame: ...
diff --git a/task-sdk/tests/task_sdk/execution_time/test_comms.py 
b/task-sdk/tests/task_sdk/execution_time/test_comms.py
index 17ace970b63..0ae7712c216 100644
--- a/task-sdk/tests/task_sdk/execution_time/test_comms.py
+++ b/task-sdk/tests/task_sdk/execution_time/test_comms.py
@@ -18,8 +18,14 @@
 from __future__ import annotations
 
 import asyncio
+import gc
+import os
+import signal
 import threading
+import time
 import uuid
+import weakref
+from unittest import mock
 
 import msgspec
 import pytest
@@ -40,6 +46,45 @@ from airflow.sdk.execution_time.comms import (
 )
 
 
+def _is_taken(lock) -> bool:
+    """Whether a thread holds ``lock``, asked from a thread of its own: an 
RLock lets its owner in again."""
+    free: list[bool] = []
+
+    def probe():
+        free.append(lock.acquire(blocking=False))
+        if free[0]:
+            lock.release()
+
+    prober = threading.Thread(target=probe)
+    prober.start()
+    prober.join()
+    return not free[0]
+
+
+def _recv_exactly(sock, n: int) -> bytes:
+    """Read exactly ``n`` bytes: a stream socket may return fewer per call."""
+    buffer = bytearray()
+    while len(buffer) < n:
+        if not (chunk := sock.recv(n - len(buffer))):
+            raise EOFError("socket closed before a full frame was received")
+        buffer.extend(chunk)
+    return bytes(buffer)
+
+
+def _read_request(sock) -> _RequestFrame:
+    """Read one request frame, as the supervisor does."""
+    length = int.from_bytes(_recv_exactly(sock, 4), "big")
+    return msgspec.msgpack.decode(_recv_exactly(sock, length), 
type=_RequestFrame)
+
+
+def _respond(sock, request: _RequestFrame, value: str = "v") -> None:
+    """Answer ``request`` with a ``VariableResult`` carrying the request's own 
key."""
+    assert request.body is not None
+    resp = {"type": "VariableResult", "key": request.body["key"], "value": 
value}
+    encoded = msgspec.msgpack.encode(_ResponseFrame(request.id, resp, None))
+    sock.sendall(len(encoded).to_bytes(4, "big") + encoded)
+
+
 class TestCommsModels:
     """Test Pydantic models used in task communication for proper 
validation."""
 
@@ -198,26 +243,14 @@ class TestCommsDecoder:
         for t in threads:
             t.start()
 
-        def _recv_exactly(sock, n):
-            buffer = bytearray()
-            while len(buffer) < n:
-                chunk = sock.recv(n - len(buffer))
-                if not chunk:
-                    raise EOFError("socket closed before a full frame was 
received")
-                buffer.extend(chunk)
-            return bytes(buffer)
-
         # The order in which the concurrent ``send`` calls reach the socket is 
not
         # deterministic, so the parent must not assume requests arrive in 
thread-index
         # order. Read each request as it arrives and echo a response built 
from that
         # request's own body, so every thread reliably gets the response to 
its own
         # message regardless of thread scheduling.
         for _ in range(num_threads):
-            length = int.from_bytes(_recv_exactly(w, 4), byteorder="big")
-            request = msgspec.msgpack.decode(_recv_exactly(w, length), 
type=_RequestFrame)
-            resp = {"type": "VariableResult", "key": request.body["key"], 
"value": request.body["value"]}
-            data = msgspec.msgpack.encode(_ResponseFrame(request.id, resp, 
None))
-            w.sendall(len(data).to_bytes(4, byteorder="big") + data)
+            request = _read_request(w)
+            _respond(w, request, value=request.body["value"])
 
         for t in threads:
             t.join(timeout=5)
@@ -229,25 +262,60 @@ class TestCommsDecoder:
             assert results[idx].key == f"key{idx}", f"Out-of-order or missing 
response for thread {idx}"
             assert results[idx].value == f"value{idx}", f"Incorrect value for 
thread {idx}"
 
+    @staticmethod
+    def _answer_in_order(sock, first_read: threading.Event, answer_first: 
threading.Event) -> None:
+        """
+        Act as the supervisor for two requests: signal once the first is read, 
answer it when
+        told to, then read and answer the second. Gives up after a few seconds 
by closing the
+        socket, so a send() that would wait forever fails instead of hanging 
the test.
+        """
+        sock.settimeout(5)
+        try:
+            first = _read_request(sock)
+            first_read.set()
+            if not answer_first.wait(timeout=5):
+                raise TimeoutError
+            _respond(sock, first)
+            _respond(sock, _read_request(sock))
+        except (OSError, EOFError, TimeoutError):
+            sock.close()
+
     @pytest.mark.asyncio
-    async def 
test_send_from_event_loop_raises_deadlock_imminent_error_when_asend_in_flight(
-        self, socket_pair
-    ):
+    async def 
test_send_from_the_running_loop_waits_for_an_asend_in_flight(self, socket_pair):
         """
-        Regression: send() called from the event loop thread while asend() 
holds
-        _thread_lock in a thread-pool worker must raise DeadlockImminentError
-        (deadlock_imminent=True) before attempting to acquire the lock.
+        A sync call on the loop thread while an asend() waits for its response 
no longer
+        deadlocks: asend() holds the channel on a worker thread that needs no 
loop to finish, so
+        send() waits for that round trip and then gets its own response.
+        """
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        first_read, answer_first = threading.Event(), threading.Event()
+        supervisor = threading.Thread(
+            target=self._answer_in_order, args=(w, first_read, answer_first), 
daemon=True
+        )
+        supervisor.start()
+
+        in_flight = 
asyncio.ensure_future(decoder.asend(GetVariable(key="first")))
+        assert await asyncio.to_thread(first_read.wait, 5)
+        # The first response is held back until send() has had time to block 
on the channel.
+        threading.Timer(0.1, answer_first.set).start()
+
+        result = decoder.send(GetVariable(key="second"))
 
-        DeadlockImminentError inherits from BaseException so it escapes
-        contextlib.suppress(Exception) in mask_secret() and similar helpers.
+        assert result.key == "second"
+        assert (await asyncio.wait_for(in_flight, timeout=5)).key == "first"
+        supervisor.join(timeout=5)
+
+    @pytest.mark.asyncio
+    async def 
test_asend_cancelled_while_waiting_for_the_thread_lock_leaves_it_free(self, 
socket_pair):
+        """
+        asend() waits for _thread_lock in a worker thread. Cancelling that 
wait (the executor shutting
+        down after a failure) cancels the future, not the thread: once the 
holder lets go, the thread
+        acquires, and the lock must not stay taken with nobody to release it.
         """
         r, _ = socket_pair
         decoder = CommsDecoder(socket=r, log=structlog.get_logger())
 
-        # Simulate asend() having recorded this thread as the event-loop 
thread.
-        decoder._loop_thread_id = threading.get_ident()
-
-        # Hold _thread_lock from a background thread to simulate an in-flight 
asend().
         lock_held = threading.Event()
         lock_release = threading.Event()
 
@@ -261,54 +329,77 @@ class TestCommsDecoder:
         holder.start()
         assert lock_held.wait(timeout=2), "Background thread never acquired 
_thread_lock"
 
-        try:
-            # send() from the event loop thread while lock is held must raise 
immediately.
-            with pytest.raises(DeadlockImminentError) as exc_info:
-                decoder.send(GetVariable(key="should_fail"))
+        parked = 
asyncio.ensure_future(decoder.asend(GetVariable(key="parked")))
+        await asyncio.sleep(0.05)
+        parked.cancel()
+        with pytest.raises(asyncio.CancelledError):
+            await parked
+
+        lock_release.set()
+        holder.join(timeout=2)
+        for _ in range(200):
+            if decoder._thread_lock.acquire(blocking=False):
+                decoder._thread_lock.release()
+                break
+            await asyncio.sleep(0.01)
+        else:
+            pytest.fail("_thread_lock stayed taken after the cancelled 
asend()")
 
-            msg = str(exc_info.value)
-            assert msg.startswith("comms.send() called from the event loop 
thread")
-            assert "deadlock is imminent" in msg
-        finally:
-            lock_release.set()
-            holder.join(timeout=2)
+    @pytest.mark.asyncio
+    async def 
test_asend_cancelled_while_reading_keeps_the_channel_until_its_reply_is_drained(
+        self, socket_pair
+    ):
+        """
+        Cancelling an asend() parked on the response cancels the future, not 
the read. The channel
+        must stay taken until that response is drained; otherwise the next 
send() writes its own
+        request and may read the cancelled request's response as its own.
+        """
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+
+        cancelled = 
asyncio.ensure_future(decoder.asend(GetVariable(key="cancelled")))
+        cancelled_request = await asyncio.to_thread(_read_request, w)
+        cancelled.cancel()
+        with pytest.raises(asyncio.CancelledError):
+            await cancelled
+
+        try:
+            assert _is_taken(decoder._thread_lock), "the channel was released 
before the response was read"
+
+            results: list = []
+            sender = threading.Thread(
+                target=lambda: 
results.append(decoder.send(GetVariable(key="next"))), daemon=True
+            )
+            sender.start()
+            await asyncio.to_thread(_respond, w, cancelled_request)
+            await asyncio.to_thread(lambda: _respond(w, _read_request(w)))
+            await asyncio.to_thread(sender.join, 5)
+
+            assert [result.key for result in results] == ["next"]
+            assert not _is_taken(decoder._thread_lock)
+        except BaseException:
+            # Unblocks a read left in recv, so a failure here ends the test 
instead of hanging the
+            # loop's executor shutdown.
+            w.close()
+            raise
 
     @pytest.mark.asyncio
     async def test_send_from_event_loop_succeeds_when_lock_free(self, 
socket_pair):
         """
-        send() called from the event loop thread when no asend() is currently
-        in-flight (lock not held) must proceed safely and return a result —
-        even after _loop_thread_id has been recorded by a prior asend() call.
-
-        The non-blocking acquire succeeds (lock is free), so the sync socket
-        I/O completes without needing the event loop, avoiding a deadlock.
-        DeadlockImminentError must NOT be raised in this scenario.
+        send() called from the event loop thread after an asend() has finished 
(the lock is
+        free) proceeds and returns its result: the sync socket I/O needs no 
event loop.
         """
-        import asyncio
-
         r, w = socket_pair
         decoder = CommsDecoder(socket=r, log=structlog.get_logger())
 
-        def _serve_one():
-            length = int.from_bytes(w.recv(4), "big")
-            body = b""
-            while len(body) < length:
-                body += w.recv(length - len(body))
-            req = msgspec.msgpack.decode(body, type=_RequestFrame)
-            resp = {"type": "VariableResult", "key": req.body["key"], "value": 
"v"}
-            encoded = msgspec.msgpack.encode(_ResponseFrame(req.id, resp, 
None))
-            w.sendall(len(encoded).to_bytes(4, "big") + encoded)
-
-        # Phase 1: complete one asend() to record _loop_thread_id on the 
decoder
-        server = threading.Thread(target=_serve_one, daemon=True)
+        # Phase 1: complete one asend() from this loop
+        server = threading.Thread(target=self._serve, args=(w, 1), daemon=True)
         server.start()
         await asyncio.wait_for(decoder.asend(GetVariable(key="prime")), 
timeout=5)
         server.join(timeout=2)
 
-        # Phase 2: lock is free, _loop_thread_id is set.
-        # send() from the event loop thread must succeed (non-blocking acquire
-        # gets the free lock and the sync I/O completes without the event 
loop).
-        server2 = threading.Thread(target=_serve_one, daemon=True)
+        # Phase 2: the lock is free; send() from the event loop thread 
succeeds.
+        server2 = threading.Thread(target=self._serve, args=(w, 1), 
daemon=True)
         server2.start()
         result = decoder.send(GetVariable(key="should_succeed"))
         server2.join(timeout=2)
@@ -318,35 +409,19 @@ class TestCommsDecoder:
 
     def test_send_after_event_loop_closes_does_not_raise(self, socket_pair):
         """
-        Regression test: send() called from the same thread that previously ran
-        the event loop — but after the loop has finished — must NOT raise
-        DeadlockImminentError.
+        send() called from the thread that ran an event loop, after that loop 
has finished,
+        returns its result.
 
-        Scenario: AsyncOperator.execute() runs aexecute() via
-        loop.run_until_complete(), which calls await 
SUPERVISOR_COMMS.asend(...)
-        (recording _loop_thread_id).  After execute() returns the loop is 
closed.
-        The task_runner then calls SUPERVISOR_COMMS.send() to push XCom 
results.
-        Without this fix that call raised DeadlockImminentError spuriously.
+        Scenario: AsyncOperator.execute() runs aexecute() via 
loop.run_until_complete(), which
+        calls await SUPERVISOR_COMMS.asend(...). After execute() returns the 
loop is closed, and
+        the task_runner calls SUPERVISOR_COMMS.send() to push XCom results.
         """
-        import asyncio
-
         r, w = socket_pair
         decoder = CommsDecoder(socket=r, log=structlog.get_logger())
 
-        # Helper: serve exactly one request from the given socket pair.
-        def _serve_one(sock):
-            length = int.from_bytes(sock.recv(4), "big")
-            body = b""
-            while len(body) < length:
-                body += sock.recv(length - len(body))
-            req = msgspec.msgpack.decode(body, type=_RequestFrame)
-            resp = {"type": "VariableResult", "key": req.body["key"], "value": 
"v"}
-            encoded = msgspec.msgpack.encode(_ResponseFrame(req.id, resp, 
None))
-            sock.sendall(len(encoded).to_bytes(4, "big") + encoded)
-
         # --- Phase 1: run the async part (simulates aexecute()) ---
         async def _async_phase():
-            server = threading.Thread(target=_serve_one, args=(w,), 
daemon=True)
+            server = threading.Thread(target=self._serve, args=(w, 1), 
daemon=True)
             server.start()
             await 
asyncio.wait_for(decoder.asend(GetVariable(key="async_key")), timeout=5)
             server.join(timeout=2)
@@ -359,9 +434,7 @@ class TestCommsDecoder:
             asyncio.set_event_loop(None)
 
         # --- Phase 2: sync send() after the loop is closed (simulates 
_push_xcom_if_needed) ---
-        # _loop_thread_id is still set from phase 1, but the loop is no longer 
running.
-        # This must NOT raise DeadlockImminentError.
-        server2 = threading.Thread(target=_serve_one, args=(w,), daemon=True)
+        server2 = threading.Thread(target=self._serve, args=(w, 1), 
daemon=True)
         server2.start()
 
         result = decoder.send(GetVariable(key="sync_key"))
@@ -369,64 +442,309 @@ class TestCommsDecoder:
 
         assert result is not None
 
-    def 
test_send_from_paused_event_loop_thread_raises_when_asend_in_flight(self, 
socket_pair):
+    @staticmethod
+    def _serve(sock, count: int, delay: float = 0.0) -> None:
+        """Answer ``count`` requests with their own key, after ``delay`` 
seconds each; stop on a closed socket."""
+        try:
+            for _ in range(count):
+                request = _read_request(sock)
+                time.sleep(delay)
+                _respond(sock, request)
+        except (OSError, EOFError):
+            pass
+
+    # Waiting for its own thread would never end: the limit turns a regression 
into a failure.
+    @pytest.mark.execution_timeout(10)
+    def 
test_send_on_a_thread_already_in_a_request_raises_instead_of_waiting(self, 
socket_pair):
+        """
+        A call on a thread that holds the channel for its own request would 
wait for itself: the
+        one real deadlock left, so it raises at once, and the interrupted 
request still completes.
+        """
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        threading.Thread(target=self._serve, args=(w, 1), daemon=True).start()
+        raised: list[BaseException] = []
+        original_get_response = CommsDecoder._get_response
+
+        def interrupted(self):
+            # What a signal handler would do while this thread waits for the 
response.
+            try:
+                self.send(GetVariable(key="from the handler"))
+            except DeadlockImminentError as exc:
+                raised.append(exc)
+            return original_get_response(self)
+
+        with mock.patch.object(CommsDecoder, "_get_response", interrupted):
+            result = decoder.send(GetVariable(key="outer"))
+
+        assert result.key == "outer"
+        assert len(raised) == 1
+        assert "already in the middle of a request" in str(raised[0])
+        assert not _is_taken(decoder._thread_lock)
+
+    @pytest.mark.execution_timeout(10)
+    @pytest.mark.skipif(not hasattr(signal, "setitimer"), reason="needs 
SIGALRM timers")
+    def 
test_a_signal_handler_calling_send_during_a_send_raises_instead_of_freezing(self,
 socket_pair):
+        """
+        The case the check exists for: the runner's SIGTERM handler runs 
on_kill() on the main
+        thread, and an on_kill() making a sync SDK call while the main thread 
waits for a response
+        would wait for its own thread. A real signal lands mid-request here.
+        """
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        # The response comes after the signal has fired.
+        threading.Thread(target=self._serve, args=(w, 1, 0.3), 
daemon=True).start()
+        raised: list[BaseException] = []
+
+        def on_alarm(signum, frame):
+            try:
+                decoder.send(GetVariable(key="from on_kill"))
+            except DeadlockImminentError as exc:
+                raised.append(exc)
+
+        previous = signal.signal(signal.SIGALRM, on_alarm)
+        try:
+            signal.setitimer(signal.ITIMER_REAL, 0.05)
+            result = decoder.send(GetVariable(key="interrupted"))
+        finally:
+            signal.setitimer(signal.ITIMER_REAL, 0)
+            signal.signal(signal.SIGALRM, previous)
+
+        assert result.key == "interrupted"
+        assert len(raised) == 1
+
+    def test_a_failed_request_leaves_no_request_in_flight_behind(self, 
socket_pair):
+        """
+        A request whose response cannot be decoded releases the channel and 
clears its in-flight
+        mark, so the thread's next call gets its own response instead of being 
taken for a call
+        from inside a request.
+        """
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        threading.Thread(target=self._serve, args=(w, 2), daemon=True).start()
+
+        # The frame is read before decoding fails, so no response of the 
failed request is left on
+        # the socket for the next call to read.
+        with mock.patch.object(
+            CommsDecoder, "_from_frame", autospec=True, 
side_effect=ValueError("undecodable response")
+        ):
+            with pytest.raises(ValueError, match="undecodable response"):
+                decoder.send(GetVariable(key="lost"))
+
+        assert decoder._is_exchanging is False
+        assert not _is_taken(decoder._thread_lock)
+        assert decoder.send(GetVariable(key="next")).key == "next"
+
+    @pytest.mark.execution_timeout(10)
+    @pytest.mark.parametrize("where", ["before the request is written", "after 
the response is read"])
+    def 
test_a_send_interrupting_its_own_thread_outside_a_request_is_served(self, 
socket_pair, where):
+        """
+        A signal handler can land after the interrupted send() took the 
channel but before it wrote
+        its request, or after it read its response but before it let the 
channel go. Nothing of the
+        interrupted request is on the wire then, so the handler's call is 
exchanged whole in between
+        instead of waiting for its own thread, and both callers get their own 
response.
         """
-        Regression: send() called from the loop's own thread while the loop is 
*paused* (between
-        two run_until_complete() calls) and an asend() is parked mid-I/O must 
raise
-        DeadlockImminentError instead of blocking forever.
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        threading.Thread(target=self._serve, args=(w, 2), daemon=True).start()
+        from_the_handler: list = []
+        original_exchange = CommsDecoder._exchange
+
+        def interrupted(self, msg, frame_bytes):
+            # Only the outer request is interrupted: the handler's own send() 
exchanges unpatched.
+            if msg.key != "interrupted":
+                return original_exchange(self, msg, frame_bytes)
+            if where == "before the request is written":
+                from_the_handler.append(self.send(GetVariable(key="from the 
handler")))
+                return original_exchange(self, msg, frame_bytes)
+            result = original_exchange(self, msg, frame_bytes)
+            from_the_handler.append(self.send(GetVariable(key="from the 
handler")))
+            return result
+
+        with mock.patch.object(CommsDecoder, "_exchange", interrupted):
+            result = decoder.send(GetVariable(key="interrupted"))
+
+        assert result.key == "interrupted"
+        assert [response.key for response in from_the_handler] == ["from the 
handler"]
+        assert not _is_taken(decoder._thread_lock)
+
+    def 
test_concurrent_sync_and_async_callers_each_get_their_own_response(self, 
socket_pair):
+        """Twenty threads calling send() and twenty coroutines calling asend() 
at once never cross responses."""
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        supervisor = threading.Thread(target=self._serve, args=(w, 40), 
daemon=True)
+        supervisor.start()
+        sync_results: dict[str, str] = {}
+
+        def sync_caller(key: str) -> None:
+            sync_results[key] = decoder.send(GetVariable(key=key)).key
+
+        async def main() -> list[str]:
+            threads = [threading.Thread(target=sync_caller, 
args=(f"sync-{i}",)) for i in range(20)]
+            for thread in threads:
+                thread.start()
+            results = await 
asyncio.gather(*(decoder.asend(GetVariable(key=f"async-{i}")) for i in 
range(20)))
+            for thread in threads:
+                await asyncio.to_thread(thread.join, 10)
+            return [result.key for result in results]
+
+        async_keys = asyncio.run(asyncio.wait_for(main(), timeout=20))
+
+        assert async_keys == [f"async-{i}" for i in range(20)]
+        assert sync_results == {f"sync-{i}": f"sync-{i}" for i in range(20)}
+        supervisor.join(timeout=5)
+
+    @pytest.mark.execution_timeout(10)
+    def 
test_asend_from_two_event_loops_at_once_each_gets_its_own_response(self, 
socket_pair):
+        """
+        Sync code on a worker thread that runs an event loop of its own 
(``asyncio.run(aget_connection())``)
+        sends while another loop has an ``asend`` in flight. Each call gets 
its own response, instead
+        of one failing on a lock bound to the other loop.
+        """
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        # Slow answers, so the second loop's call arrives while the first 
one's is in flight.
+        threading.Thread(target=self._serve, args=(w, 4, 0.1), 
daemon=True).start()
+        results: dict[str, list] = {"first": [], "second": []}
+        errors: list[BaseException] = []
+
+        def run_loop(name):
+            async def two_calls():
+                return await asyncio.gather(
+                    decoder.asend(GetVariable(key=f"{name} 1")), 
decoder.asend(GetVariable(key=f"{name} 2"))
+                )
+
+            try:
+                results[name] = [response.key for response in 
asyncio.run(two_calls())]
+            except BaseException as e:
+                errors.append(e)
+
+        loops = [threading.Thread(target=run_loop, args=(name,)) for name in 
results]
+        for thread in loops:
+            thread.start()
+        for thread in loops:
+            thread.join(8)
+
+        assert errors == []
+        assert results == {"first": ["first 1", "first 2"], "second": ["second 
1", "second 2"]}
+
+    @pytest.mark.execution_timeout(10)
+    def test_asend_from_a_later_event_loop_is_served(self, socket_pair):
+        """
+        Calls that had to wait for each other on one event loop do not tie the 
channel to it: a
+        later loop in the same process (another ``asyncio.run()``) has its own 
calls served too.
+        """
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        threading.Thread(target=self._serve, args=(w, 4, 0.05), 
daemon=True).start()
 
-        The running-loop check alone does not cover this: 
asyncio.get_running_loop() raises while
-        the loop is paused, so send() fell through to a blocking acquire of 
_thread_lock. The
-        holder, an asend() coroutine, can only release it once the loop runs 
again, on this very
-        thread, which is now blocked. Seen in production as an 
IterableOperator freezing with
-        every thread idle: AsyncAwareExecutor.map pulled the next sub-task's 
input through a sync
-        XCom read between two run_until_complete() calls while a sub-task's 
asend() was in flight.
+        async def two_calls(name):
+            responses = await asyncio.gather(
+                decoder.asend(GetVariable(key=f"{name} 1")), 
decoder.asend(GetVariable(key=f"{name} 2"))
+            )
+            return [response.key for response in responses]
+
+        assert asyncio.run(two_calls("first loop")) == ["first loop 1", "first 
loop 2"]
+        assert asyncio.run(two_calls("second loop")) == ["second loop 1", 
"second loop 2"]
+
+    def test_a_closed_loop_whose_calls_waited_for_each_other_is_not_kept(self, 
socket_pair):
+        """
+        The decoder keeps no event loop: sync code running ``asyncio.run()`` 
once per call does not
+        keep every closed loop until the task ends, even when the loop's calls 
overlapped.
         """
         r, w = socket_pair
         decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        threading.Thread(target=self._serve, args=(w, 6, 0.01), 
daemon=True).start()
+        loops: list[weakref.ref] = []
 
-        def _read_request(sock) -> _RequestFrame:
-            length = int.from_bytes(sock.recv(4), "big")
-            body = b""
-            while len(body) < length:
-                body += sock.recv(length - len(body))
-            return msgspec.msgpack.decode(body, type=_RequestFrame)
+        async def two_calls():
+            loops.append(weakref.ref(asyncio.get_running_loop()))
+            await asyncio.gather(decoder.asend(GetVariable(key="a")), 
decoder.asend(GetVariable(key="b")))
 
-        def _respond(sock, req: _RequestFrame) -> None:
-            assert req.body is not None
-            resp = {"type": "VariableResult", "key": req.body["key"], "value": 
"v"}
-            encoded = msgspec.msgpack.encode(_ResponseFrame(req.id, resp, 
None))
-            sock.sendall(len(encoded).to_bytes(4, "big") + encoded)
+        for _ in range(3):
+            asyncio.run(two_calls())
+        gc.collect()
+
+        assert [loop() for loop in loops] == [None, None, None]
+
+    def 
test_asend_from_every_event_loop_runs_on_one_thread_of_the_decoder(self, 
socket_pair):
+        """
+        The decoder makes every asend() request on one thread of its own, not 
on the loops' default
+        executors, so two loops' calls never take two threads and to_thread 
work keeps its executor.
+        """
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        threading.Thread(target=self._serve, args=(w, 4, 0), 
daemon=True).start()
+        threads: set[str] = set()
+        exchange = CommsDecoder._exchange
+
+        def recording_exchange(self, msg, frame_bytes):
+            threads.add(threading.current_thread().name)
+            return exchange(self, msg, frame_bytes)
+
+        async def two_calls():
+            await asyncio.gather(decoder.asend(GetVariable(key="a")), 
decoder.asend(GetVariable(key="b")))
+
+        with mock.patch.object(CommsDecoder, "_exchange", autospec=True, 
side_effect=recording_exchange):
+            asyncio.run(two_calls())
+            asyncio.run(two_calls())
+
+        assert len(threads) == 1
+        assert threads.pop().startswith("supervisor-comms")
+
+    @pytest.mark.execution_timeout(10)
+    @pytest.mark.filterwarnings("ignore:This process .* is 
multi-threaded:DeprecationWarning")
+    def test_asend_in_a_forked_child_is_served(self, socket_pair):
+        """
+        Threads do not survive a fork. A child forked after the parent made an 
asend() starts a
+        worker thread of its own instead of queueing its request for one that 
no longer exists.
+        """
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        threading.Thread(target=self._serve, args=(w, 2, 0), 
daemon=True).start()
+        assert asyncio.run(decoder.asend(GetVariable(key="parent"))).key == 
"parent"
+
+        pid = os.fork()
+        if pid == 0:
+            # In the child: exit without running pytest's teardown, 0 only 
when the call was answered.
+            status = 1
+            try:
+                signal.alarm(5)
+                if asyncio.run(decoder.asend(GetVariable(key="child"))).key == 
"child":
+                    status = 0
+            finally:
+                os._exit(status)
+
+        assert os.waitpid(pid, 0)[1] == 0
+
+    def test_send_from_the_paused_loop_waits_for_an_asend_in_flight(self, 
socket_pair):
+        """
+        The same between two run_until_complete() calls, on the loop's own 
thread: the asend()
+        parked on its response finishes on its worker thread without the loop, 
so send() waits
+        for it instead of freezing the process.
+        """
+        r, w = socket_pair
+        decoder = CommsDecoder(socket=r, log=structlog.get_logger())
+        first_read, answer_first = threading.Event(), threading.Event()
+        supervisor = threading.Thread(
+            target=self._answer_in_order, args=(w, first_read, answer_first), 
daemon=True
+        )
+        supervisor.start()
 
         loop = asyncio.new_event_loop()
         try:
-            # Park an asend() mid-I/O: its request gets written, but no 
response is sent yet, so
-            # the coroutine sits in the thread reading the response while 
holding _thread_lock.
-            in_flight = 
loop.create_task(decoder.asend(GetVariable(key="parked")))
-            parked_request = 
loop.run_until_complete(asyncio.to_thread(_read_request, w))
-            assert parked_request.body["key"] == "parked"
-            assert not in_flight.done()
-            assert decoder._thread_lock.locked()
-
-            # The loop is now paused and this thread is its thread. Before the 
fix this call
-            # blocked forever on _thread_lock.
-            with pytest.raises(DeadlockImminentError) as exc_info:
-                decoder.send(GetVariable(key="should_fail"))
-            assert "deadlock is imminent" in str(exc_info.value)
-
-            # Let the parked asend() finish; the channel must be fully usable 
afterwards.
-            _respond(w, parked_request)
-            result = loop.run_until_complete(asyncio.wait_for(in_flight, 
timeout=5))
-            assert result.key == "parked"
-
-            server = threading.Thread(target=lambda: _respond(w, 
_read_request(w)), daemon=True)
-            server.start()
-            result = decoder.send(GetVariable(key="after"))
-            server.join(timeout=2)
-            assert result.key == "after"
+            in_flight = 
loop.create_task(decoder.asend(GetVariable(key="first")))
+            assert loop.run_until_complete(asyncio.to_thread(first_read.wait, 
5))
+            threading.Timer(0.1, answer_first.set).start()
+
+            # The loop is paused and this thread is its thread.
+            result = decoder.send(GetVariable(key="second"))
+
+            assert result.key == "second"
+            assert loop.run_until_complete(asyncio.wait_for(in_flight, 
timeout=5)).key == "first"
         finally:
             loop.close()
-            asyncio.set_event_loop(None)
+        supervisor.join(timeout=5)
 
     def test_read_frame_recovers_from_short_read_on_header(self):
         msg = VariableResult(key="k", value="v", type="VariableResult")

Reply via email to