Repository navigation
Async MWorker: convert AESFuncs/ClearFuncs handlers to async dispatch - #70129
Merged
dwoz merged 25 commits intoAug 26, 2026
Merged
Conversation
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
marked this pull request as ready for review
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.
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.
1 of 2 tasks
This branch was previously 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
Convert the master's per-request handlers in
AESFuncsandClearFuncstoasync def, offloading synchronous work to a context-propagatingThreadPoolExecutor, and add theworker_poolsconfig to partition MWorkers by command type. Under the TCP transport where the request pump already dispatches viaasyncio.create_taskper message (seeSaltMessageServer.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_mworkerflag (defaultFalse— sync REP behavior preserved). Enable it explicitly to get the new dispatch.Scope of change
AESFuncsandClearFuncs(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 slicesworker_poolsconfig: partitions workers into named pools (default{auth: 1, default: 4}) so a slow ext_pillar can't starve minion auth_ContextThreadPoolExecutorinsalt/master.py— snapshotscontextvarsacrossrun_in_executorsorequest_ctxvarand OTel spans propagate through offloaded sync worksalt/cache/__init__.py)salt.transport.tcp.RequestServer.pre_fork— the pool router opensworker_countclients round-robin, eliminating the accept-race that pinned one MWorker while peers stayed idleConfig
Backward compatible on 3008.x — default behavior is unchanged:
master_async_mworker(bool, defaultFalse) — opt-in gate. WhenFalse, sync REP handlers run via per-instance_sync_*shims extracted verbatim fromorigin/3008.x:salt/master.py. WhenTrue, the new async dispatch + all transport-layer async paths activate.master_mworker_max_inflight(int, default0= unlimited) — bounds concurrent request handlers per MWorker whenmaster_async_mworker=True. Each worker uses its ownasyncio.BoundedSemaphoreso effective total across the pool iscap × 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 historicalworker_threads: 5)worker_threads: Nstill works — synthesized as a single catchall poolworker_pools_enabled: falserestores single-pool behaviorPerformance signal
On the async-mworker author's stress rig (TCP transport, 50 minions, 10 parallel
test.ping --asyncshell loops, single-master):On ZMQ transport under a 15-min BURST=3 × 5s
state.highstatesynthetic (from a local perdaemon-metrics stack):salt/transport/zeromq.pyRequestServer.request_handler) still awaits each request serially before the nextrecv, so async dispatch alone doesn't yield per-worker concurrency on ZMQ — that requires a separate REP→DEALER refactor which is not in this PRTest coverage
tests/pytests/functional/master/test_async_handlers.py— end-to-end AESFuncs/ClearFuncs async handler coverage; extended with in-flight-cap functional teststests/pytests/unit/test_master_async_error_paths.py— cancellation, executor-thread errors, contextvar-propagationtests/pytests/unit/test_master_async_optin.py— asserts default off, sync-shim path preserved when flag off, async path only when flag ontests/pytests/unit/test_shared_state_races.py— concurrent cache access racestests/pytests/unit/test_master.py— significantly extended for the per-method async surface + in-flight-cap unit coveragetests/pytests/unit/conftest.py— asyncio blocking-detection fixturetests/pytests/unit/transport/test_tcp.py— addedtest_publish_closes_stale_publisher_on_stream_closedtests/pytests/unit/channel/test_server.py— addedtest_pool_routing_channel_caches_auto_key_on_initFollow-ups on top of the opt-in shim
StreamClosedError(was leaking Python object graph across reconnect; FD release was already handled by tornado)AutoKeyonPoolRoutingChannel.__init__instead of re-instantiating per auth (restores pre-PR per-worker mtime-cache behavior forautosign_file/autoreject_file; fixes O(N) disk reads under auth storms on LTS-default path)master_mworker_max_inflight(opt-in, default 0)Test plan
master_async_mworker: True, ≥3 workers, and drive concurrent state runsmaster_mworker_max_inflight: 10caps concurrency under a burstAESFuncs.async_methods,ClearFuncs.async_methods) — are we missing any hot path?