Repository navigation
Conversation
2 tasks
dwoz
added a commit
that referenced
this pull request
Aug 12, 2026
When ``TCPPublishServer.publish`` was invoked from a running asyncio loop (e.g. via ``MWorker._return -> store_job -> fire_event``), the outer ``SaltEvent.pusher`` SyncWrapper's worker thread ran this coroutine, then ``self.pub_sock.send`` invoked SyncWrapper *again* -- it detected the inner thread's running io_loop, spawned yet another thread, and both deadlocked on ``threading.Thread.join()``. Detect the async context via ``asyncio.get_running_loop()`` and bypass the outer SyncWrapper. Since 3006.x's ``publish`` is sync (no ``async def``), dispatch to ``loop.create_task(...)`` as a fire-and-forget (matches the ``fire_event`` / ``spawn_callback`` precedent in ``salt/utils/event.py``). Cache a raw ``IPCMessageClient`` per running loop via ``WeakKeyDictionary`` so a fresh SyncWrapper asyncio_loop can't inherit a dead client via id() recycling. Invalidate proactively (pre-flight ``stream.closed()``) and reactively (retry once on ``salt.ext.tornado.iostream.StreamClosedError``). 3006.x-specific counterpart to 3008.x PR #69992. Fixes #69986
dwoz
force-pushed
the
dwoz/fix/bug1-syncwrapper-3008.x
branch
from
August 16, 2026 21:11
dcf3248 to
e7557f5
Compare
…followup) Prior commit removed publish / send / connect / _connect from the class-level async_methods on PublishServer and _TCPPubServerPublisher so SyncWrapper.__getattr__ exposed them as raw coroutines. The inner _TCPPubServerPublisher change was wrong: pub_sock was constructed by PublishServer.connect() as SyncWrapper(_TCPPubServerPublisher, loop_kwarg='io_loop'), so its self.stream lives on pub_sock's dedicated io_loop. Awaiting pub_sock.send(...) from a caller on a different loop hung -- the stream.write future's completion callback fires on pub_sock.io_loop, never on the caller's loop. The Rocky Linux 9 integration zeromq 1 job on PR 69992 caught this: test_ext_modules.py::LoaderOverridesTest.test_overridden_internal hit pytest-timeout(120) because sys.list_functions's return event never propagated -- MWorker's fire_event scheduled a task on the request-handler loop, the task awaited pub_sock.send, and the write future's callback fired on the wrong loop. Fix: * Revert _TCPPubServerPublisher.async_methods to ['send', 'connect', '_connect']. The inner SyncWrapper needs the sync _wrap form so sync-context callers keep working. * Keep PublishServer.async_methods = [] -- caller (SaltEvent.fire_event) still gets a raw coroutine to schedule. * On the async path in PublishServer.publish, do NOT use self.pub_sock. Construct a raw _TCPPubServerPublisher bound to the caller's own running loop (cached per-loop in self._async_pubs, a WeakKeyDictionary). Rebuild once on StreamClosedError. * Preserve the sync path (no running loop) using the legacy self.pub_sock -- external sync callers keep blocking send. * PublishServer.close releases the per-loop cache. Verified locally: * Deadlock repros all pass: test_deadlock_repro.py, test_deadlock_direct_repro.py, test_deadlock_delivery_check.py. * The exact CI failure reproduces PASSING with this fix: tests/integration/loader/test_ext_modules.py:: LoaderOverridesTest::test_overridden_internal. * CLI integration tests pass: tests/pytests/integration/cli/test_salt.py (8/8). * Full regression sweep: SyncWrapper, event, transport, http -- 131 passed, 19 skipped, 0 failed.
twangboy
previously approved these changes
Aug 18, 2026
The previous commit (44f9ddd) introduced a race condition when multiple concurrent publish() calls occurred on the same asyncio loop. Both calls would see _async_pubs.get(loop) == None and create duplicate _TCPPubServerPublisher instances that attempted to connect to the same Unix socket simultaneously, causing "fd added twice" and cascading "Already reading" errors. The CI logs showed: Publisher connecting to .../minion_event_xxx_pull.ipc Publisher connecting to .../minion_event_xxx_pull.ipc [duplicate] Exception: fd 43 added twice Exception: Already reading Fix: - Add per-loop asyncio.Lock in _async_pubs_locks WeakKeyDictionary - Protect publisher creation/connection with async lock - Also protect StreamClosedError recovery path - Clean up locks in close() method This ensures only one publisher is created per loop under concurrent publish() calls.
The previous fix used threading.Lock which blocks the event loop in async context. Multiple coroutines could also create separate asyncio.Lock objects, defeating synchronization. Fix: Use dict.setdefault() which is atomic in CPython due to the GIL. This ensures all coroutines on the same event loop use the same Lock instance without blocking the event loop. Note: The integration test failure test_state_queue_basic with TCP transport is a pre-existing bug that exists in commits before these changes (tested at e7557f5 and 44f9ddd). The test passes with ZeroMQ transport. The root cause is self.auto_key being None during master authentication, unrelated to the publisher race condition fixes.
The prior "Explicitly close the underlying socket before closing the stream" pattern in ``_TCPPubServerPublisher.close()`` was counterproductive: closing the socket first invalidates ``self.stream.fileno()``, so tornado's ``io_loop.remove_handler(self.fileno())`` inside ``IOStream.close()`` silently no-ops and the fd stays registered in the selector. Any subsequent accept()'d socket assigned that fd number then fails to register with ``fd X added twice``, and the affected server-side handle_stream loop's ``read_bytes`` raises ``Already reading`` on every retry -- flooding runtests-install.log at wire speed (millions of lines per test), pinning a CPU core, and killing the pytest process with SIGKILL under log-file backpressure. This exactly explains PR saltstack#69992's 187 Test Package failures: the CI runtests-install.log artifact from Amazon Linux 2023 install grew to 1.3 GB with 5.9 million ``Already reading`` lines, and pytest exited with -9 (SIGKILL) mid-run before it could print the failure summary. Fixes: 1. ``_TCPPubServerPublisher.close``: let ``IOStream.close()`` handle both fd deregistration and socket close; drop the explicit ``self.stream.socket.close()`` that preceded it. 2. ``TCPPuller.handle_stream``: split the read loop into ``_handle_stream_loop`` and wrap the caller in ``try/finally`` so the stream is explicitly closed on the way out (belt-and-braces against GC-delayed fd deregistration). 3. ``TCPPuller._handle_stream_loop``: break out of the loop on any non-``StreamClosedError`` exception (``StreamAlreadyReadingError``, non-zero-errno ``OSError``) instead of tight-looping. The prior log-and-continue was fine for transient errors but catastrophic when the stream reached a permanent bad state.
This branch had an error being deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
PublishServer.publishwhen in async context_TCPPubServerPublisherper running loop viaWeakKeyDictionaryStreamClosedErrorboth proactively and reactivelyFixes #69986
Test plan
salt.transport.tcpunit tests passfire_eventload without wedging (validated in local 10-min stress bench)Related PRs
dwoz/fix/bug1-syncwrapper-3006.x(pending, needs review before opening due to substantial adaptation)