Skip to content

Async MWorker: convert AESFuncs/ClearFuncs handlers to async dispatch - #70129

Merged
dwoz merged 25 commits into
saltstack:3008.xfrom
dwoz:dwoz/feature/async-mworker-rebase-20260823
Aug 26, 2026
Merged

dwoz merged 25 commits into
saltstack:3008.xfrom
dwoz:dwoz/feature/async-mworker-rebase-20260823

Conversation

@dwoz

@dwoz dwoz commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Convert the master's per-request handlers in AESFuncs and ClearFuncs to async def, offloading synchronous work to a context-propagating ThreadPoolExecutor, and add the worker_pools config to partition MWorkers by command type. Under the TCP transport where the request pump already dispatches via asyncio.create_task per message (see SaltMessageServer.handle_stream), each MWorker can now process multiple requests concurrently within its own io_loop.

The async path is opt-in on 3008.x via the master_async_mworker flag (default False — sync REP behavior preserved). Enable it explicitly to get the new dispatch.

Scope of change

  • Handler-by-handler async migration under AESFuncs and ClearFuncs (opt-in via a per-method allow-list at the top of each class), so risky methods stay sync and the diff is reviewable in slices
  • worker_pools config: partitions workers into named pools (default {auth: 1, default: 4}) so a slow ext_pillar can't starve minion auth
  • _ContextThreadPoolExecutor in salt/master.py — snapshots contextvars across run_in_executor so request_ctxvar and OTel spans propagate through offloaded sync work
  • Cache module made thread-safe for the async path (salt/cache/__init__.py)
  • Fair pool distribution + per-worker IPC socket bind in salt.transport.tcp.RequestServer.pre_fork — the pool router opens worker_count clients round-robin, eliminating the accept-race that pinned one MWorker while peers stayed idle

Config

Backward compatible on 3008.x — default behavior is unchanged:

  • master_async_mworker (bool, default False) — opt-in gate. When False, sync REP handlers run via per-instance _sync_* shims extracted verbatim from origin/3008.x:salt/master.py. When True, the new async dispatch + all transport-layer async paths activate.
  • master_mworker_max_inflight (int, default 0 = unlimited) — bounds concurrent request handlers per MWorker when master_async_mworker=True. Each worker uses its own asyncio.BoundedSemaphore so effective total across the pool is cap × worker_threads. Backpressure is natural (coroutines block on the semaphore, TCP task queue fills, ZMQ HWM applies) — no error returns, no drops.
  • worker_pools — partitions workers into named pools (default {auth: 1, default: 4} = 5 workers total, matches historical worker_threads: 5)
  • worker_threads: N still works — synthesized as a single catchall pool
  • worker_pools_enabled: false restores single-pool behavior

Performance signal

On the async-mworker author's stress rig (TCP transport, 50 minions, 10 parallel test.ping --async shell loops, single-master):

  • ~200 returns/min before this work (auth was broken under bursty parallel invocations)
  • ~22,000 returns/min sustained 5 min after this work

On ZMQ transport under a 15-min BURST=3 × 5s state.highstate synthetic (from a local perdaemon-metrics stack):

  • 100.0% return success (13,500 / 13,500) with all fixes applied
  • Note: ZMQ MWorker's request pump (salt/transport/zeromq.py RequestServer.request_handler) still awaits each request serially before the next recv, so async dispatch alone doesn't yield per-worker concurrency on ZMQ — that requires a separate REP→DEALER refactor which is not in this PR

Test coverage

  • tests/pytests/functional/master/test_async_handlers.py — end-to-end AESFuncs/ClearFuncs async handler coverage; extended with in-flight-cap functional tests
  • tests/pytests/unit/test_master_async_error_paths.py — cancellation, executor-thread errors, contextvar-propagation
  • tests/pytests/unit/test_master_async_optin.py — asserts default off, sync-shim path preserved when flag off, async path only when flag on
  • tests/pytests/unit/test_shared_state_races.py — concurrent cache access races
  • tests/pytests/unit/test_master.py — significantly extended for the per-method async surface + in-flight-cap unit coverage
  • tests/pytests/unit/conftest.py — asyncio blocking-detection fixture
  • tests/pytests/unit/transport/test_tcp.py — added test_publish_closes_stale_publisher_on_stream_closed
  • tests/pytests/unit/channel/test_server.py — added test_pool_routing_channel_caches_auto_key_on_init

Follow-ups on top of the opt-in shim

  • Cache stale publisher cleanup on StreamClosedError (was leaking Python object graph across reconnect; FD release was already handled by tornado)
  • Cache AutoKey on PoolRoutingChannel.__init__ instead of re-instantiating per auth (restores pre-PR per-worker mtime-cache behavior for autosign_file / autoreject_file; fixes O(N) disk reads under auth storms on LTS-default path)
  • Bounded per-worker in-flight-request cap via master_mworker_max_inflight (opt-in, default 0)

Test plan

  • CI green (pending — this is a draft; will mark ready when CI settles)
  • Manual: run a TCP-transport master with master_async_mworker: True, ≥3 workers, and drive concurrent state runs
  • Manual: run a ZMQ-transport master with the same load — verify no regression vs today (flag off = LTS default)
  • Manual: verify default (flag off) matches pre-PR 3008.x behavior byte-for-byte
  • Manual: verify master_mworker_max_inflight: 10 caps concurrency under a burst
  • Review the per-method async allow-lists (AESFuncs.async_methods, ClearFuncs.async_methods) — are we missing any hot path?

@dwoz dwoz added the test:full Run the full test suite label Aug 24, 2026
@dwoz dwoz added this to the Argon v3008.3 milestone Aug 24, 2026
dwoz added a commit to dwoz/salt that referenced this pull request Aug 25, 2026
…LTS)

PR saltstack#70129 converted every AESFuncs / ClearFuncs / AuthFuncs handler on
3008.x to async def, refactored PoolRoutingChannel to bind one IPC
socket per MWorker with round-robin dispatch, added a per-loop
_TCPPubServerPublisher cache to PublishServer.publish, and rewired
fire_event_async to bypass SyncWrapper.  On the LTS branch (3008.x)
those behaviour changes must be strictly opt-in.

Add master_async_mworker (default False on 3008.x).  When the flag is
off (the LTS default) restore pre-PR behaviour byte-for-byte:

- AESFuncs.__init__ empties instance async_methods and shadows every
  async def handler (fileserver family aliases + _pillar / _return /
  _syndic_return / _register_resources / _file_recv / verify_minion /
  _master_tops / _master_opts / _mine* / pub_ret / minion_pub /
  minion_publish / minion_runner / revoke_auth) with sync callables
  whose bodies are copied verbatim from origin/3008.x.
- ClearFuncs.__init__ restores async_methods to the pre-PR tuple
  ("publish",) and shadows runner / wheel / mk_token / get_token /
  ping with sync callables.
- AuthFuncs._auth stays async def (callers already await) but
  dispatches to a verbatim _auth_impl_sync + _clear_signed_sync in
  the sync path.
- salt.channel.server.PoolRoutingChannel gates pool_worker_count and
  per-worker RequestClient fan-out on the flag; sync mode uses one
  shared workers-{pool}.ipc socket and one RequestClient (pre-PR).
- salt.transport.tcp.PublishServer.publish gates the async-context
  bypass on the flag; sync mode calls self.pub_sock.send(payload)
  directly as before.
- salt.utils.event.fire_event and fire_event_async gate the
  drop-and-warn / SyncWrapper-bypass on the flag.
- salt.channel.server.PubServerChannel.presence_callback tolerates
  verify_minion returning either a sync bool or a coroutine.

Adds tests/pytests/unit/test_master_async_optin.py exercising the OFF
path (default 3008.x behaviour).  Existing tests written against the
async handler signatures opt in via the master_opts fixture and via
_git_pillar_base_config / encrypted_requests / _base_opts.

Refs saltstack#70129
@dwoz
dwoz marked this pull request as ready for review August 25, 2026 21:13
@dwoz
dwoz requested a review from a team as a code owner August 25, 2026 21:13
…ime cache

PoolRoutingChannel.__init__ was setting auto_key=None, forcing the
_auth fallback to reconstruct AutoKey on every auth and reset the
autosign/autoreject file mtime cache. Fixes O(N) disk reads under
auth storms on masters with autosign_file or autoreject_file
configured. Restores pre-PR per-worker caching behavior on the LTS
default path.
Bounds the number of concurrent request handlers per MWorker process
when master_async_mworker=True. Default 0 = unlimited (existing
behavior). Set to a positive integer to cap; each MWorker uses its
own asyncio.BoundedSemaphore so effective total across the pool is
cap * worker_threads.

Backpressure is natural: coroutines block on the semaphore, TCP
task queue fills, kernel buffers apply, ZMQ HWM applies. No error
returns, no drops.

Observability: exposes per-worker _MW_INFLIGHT counters (waiters,
wait_ms_total) that tests introspect directly; the parent process
cannot observe worker-local semaphore state across the fork.

No effect when master_async_mworker=False (LTS default) or when
master_mworker_max_inflight=0 (default).
CI on run 32905758852 showed two new deterministic failure clusters
after the round-1 fix (fe86a8c):

- ``test_asynchronous.py`` (3 tests): ``test_helpers``,
  ``test_double``, ``test_double_sameloop`` error at teardown with
  ``asyncio slow-callback threshold of 0.050s exceeded`` (14 unit-
  zeromq-4 jobs, every distro/arch). The tests wrap ``HelperA``/
  ``HelperB`` whose ``sleep()`` yields ``tornado.gen.sleep(0.1)`` —
  the coroutine's resume Handle legitimately holds the loop for
  ~100 ms because that is exactly the SyncWrapper contract these
  tests assert. The unit-conftest ``_asyncio_blocking_detection``
  autouse fixture (added for the async-MWorker path) cannot
  distinguish legitimate sync-in-async wrapping from a handler
  bug; apply ``@pytest.mark.no_blocking`` per test with the
  rationale documented inline.

- ``test_mworker_stress.py::test_requester_disconnect_midflight``:
  ZMQError ``Address already in use`` on ``get_monitor_socket()``
  after re-binding the fresh DEALER (3 jobs — 2 zeromq, 1 tcp).
  Same-context reuse races two ways under CI load: the closed
  DEALER's ``inproc://monitor.s-<FD>`` endpoint can still be held
  by the just-closed monitor, and the DEALER's TCP port can linger
  in TIME_WAIT despite ``LINGER=0``. Create a fresh ``zmq.Context``
  for the new DEALER — no shared FD table, no shared inproc
  namespace — and add the same bind-with-deadline retry the
  handle's initial ``start()`` uses. ``handle.stop()`` still tears
  the swapped-in context down.

``test_topfile_order`` also flaked once (FileNotFoundError on
``RUNTIME_VARS.TMP``) but passed on retry and is unrelated to the
async-mworker code — leave for a separate investigation of the
shared /tmp/salt-tests-tmpdir-0 lifecycle.
dwoz added 2 commits August 25, 2026 23:05
test_pillar.test_topfile_order (and similar callers) use
tempfile.mkdtemp(dir=RUNTIME_VARS.TMP) which fails with FileNotFoundError
when /tmp/salt-tests-tmpdir-<uid> hasn't been created. Integration
runs rely on saltfactories fixtures for this, but a bare unit run has
no such guarantee and CI parallelism can clean the parent between
tests.

Add a session-scoped autouse fixture in tests/pytests/unit/conftest.py
that runs os.makedirs(RUNTIME_VARS.TMP, exist_ok=True) once at session
start. Fixes the topfile_order failure surfaced on the Photon fips jobs.
test_rsa_verify_concurrent and test_rsa_sign_concurrent call
PrivateKey.sign()/PublicKey.verify() with their default algorithm,
PKCS1v15-SHA1. Salt's BaseKey._enforce_fips rejects any SHA1-based
algorithm when OpenSSL FIPS mode is enabled, so both tests fail on
the Photon fips CI distros with UnsupportedAlgorithm.

The concurrency invariant these tests exercise (shared-state safety
on the RSA sign/verify path used from executor threads) is orthogonal
to the hash choice: both SHA1 and SHA224 paths go through the same
self.key.sign/verify call. Pass PKCS1v15-SHA224 explicitly (already
one of Salt's VALID_SIGNING_ALGORITHMS) so the tests exercise the
same shared-state paths under both FIPS and non-FIPS runs.

This branch was previously deployed

1 inactive deployment
ci — e5776b1f Deployed Aug 26, 2026 by dwoz via Build Onedir Packages / Windows (amd64) #26718
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.

2 participants