Skip to content

[3008.x] Fix nested SyncWrapper deadlock in tcp.PublishServer.publish (#69986) - #69992

Open
dwoz wants to merge 7 commits into
saltstack:3008.xfrom
dwoz:dwoz/fix/bug1-syncwrapper-3008.x
Open

dwoz wants to merge 7 commits into
saltstack:3008.xfrom
dwoz:dwoz/fix/bug1-syncwrapper-3008.x

Conversation

@dwoz

@dwoz dwoz commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Bypass nested SyncWrapper in PublishServer.publish when in async context
  • Cache raw _TCPPubServerPublisher per running loop via WeakKeyDictionary
  • Invalidate on StreamClosedError both proactively and reactively

Fixes #69986

Test plan

  • salt.transport.tcp unit tests pass
  • Master survives sustained fire_event load without wedging (validated in local 10-min stress bench)

Related PRs

  • 3006.x back-port: dwoz/fix/bug1-syncwrapper-3006.x (pending, needs review before opening due to substantial adaptation)

@dwoz
dwoz requested a review from a team as a code owner August 9, 2026 22:23
@dwoz dwoz added the test:full Run the full test suite label Aug 9, 2026
@dwoz dwoz added this to the Argon v3008.3 milestone Aug 9, 2026
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
…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
twangboy previously approved these changes Aug 18, 2026
dwoz added 3 commits August 18, 2026 14:12
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

1 failed deployment
ci — e2f7a19f Deployed Aug 23, 2026 by dwoz via Build Onedir Packages / RPM (x86_64) #26616
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test:full Run the full test suite

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MWorker deadlock via nested SyncWrapper in tcp.PublishServer.publish under async fire_event

3 participants