Repository navigation
Cluster-master stability bundle for 3008.x (8 fixes + regression tests) - #70756
Merged
Merged
Conversation
AsyncPubChannel.connect() picks between the operator's minion-side
publish_port and the master-reported value with:
if int(self.opts.get("publish_port", 4506)) != 4506:
publish_port = self.opts.get("publish_port")
else:
publish_port = self.auth.creds["publish_port"]
The fallback default 4506 is the ret port; the publish port default is
4505. The intent (per the inline comment on the else branch) is: if the
operator explicitly overrode publish_port, trust them; otherwise use the
master-reported value. With the wrong default, a minion with the common-
case publish_port: 4505 satisfies `int(4505) != 4506` and always looks
like an explicit override, so the master-reported publish_port is
ignored.
Use 4505 as the sentinel so the default-vs-override detection matches
the real default. Discovered while investigating saltstack#66846 (status.master
using the wrong port in the same code family); the status.master fix is
delivered in a separate PR.
Refs: saltstack#70724, saltstack#66846
…66846) The scheduled __master_alive_<master> job on the minion calls status.master(), which decides "still connected?" by scanning the OS TCP table for the minion's own opts["publish_port"] (default 4505). The pub channel actually connects to the master-reported publish_port from self.auth.creds["publish_port"] (salt/channel/client.py). When the master uses a non-default publish_port and the operator does not mirror it on the minion, remote_port_tcp(4505) returns an empty set, status.master fires __master_disconnected, and Minion.handle_event tears down a healthy pub channel. The scheduler re-arms the job on reconnect, producing a ~1 Hz flap. In a 5-master cluster test this manifested as 2347 spurious disconnects per minion in 40 min and ~400 cross-master publishes/sec of amplified event traffic. Mirroring publish_port into minion config is a known workaround; this fix removes the trap. Mechanism of the fix: * AsyncPubChannel.connect() now writes the authenticated publish port back into opts as _auth_publish_port (underscore prefix signals runtime-written). The scheduler child process inherits opts via pickle so it sees the correct value. * salt/modules/status.master() and salt/modules/win_status.master() now prefer opts["_auth_publish_port"] over config "publish_port", falling back to 4505 only if neither is populated. Note: an older attempt at this fix moved the lookup into salt/utils/minion.connected_masters() in 2016 (saltstack#37832) and was reverted in 2017 (c0d8048) because scheduler child processes have no __salt__/__opts__ injection in salt.utils.*. Threading the value through pickled opts avoids that trap.
Three log statements fired during normal cluster bringup were over-leveled and misled operators / alerting pipelines that watch for CRITICAL/WARNING lines: * ``'master_type' set to 'failover' but 'retry_dns' is not 0`` (``salt/minion.py``) was CRITICAL even though the next line simply sets ``retry_dns = 0`` -- a helpful auto-correction, not a failure. Dropped to INFO. * ``Master ip address changed from X to Y`` (``salt/minion.py``) is the intended behavior of ``master_alive_interval`` DNS refresh; dropped from WARNING to INFO. * ``Peer key missing <path>`` (``salt/channel/server.py``) is the expected transient state before cluster key exchange has completed; the next line schedules the fetch. Dropped from WARNING to INFO. Deprecation warnings (``master_shuffle``) and genuine cluster-join integrity failures (``Cluster join signature invalid.``, peer public key mismatch, token mismatch) stay at their current levels. Refs: saltstack#70728
…tack#70727) When a clustered master defers a minion's initial pillar fetch with the ``cluster_retry`` sentinel while its Raft node catches up, the minion retries and eventually succeeds — but each retry currently emits three hard ``[ERROR]`` lines plus a traceback, which looks like a failure to operators reviewing bringup logs: [ERROR] Master did not return a session key for pillar request (cluster not ready) [ERROR] Error while bringing up minion for multi-master. ... Exception getting pillar. [ERROR] This Minion was scheduled to stop. Not running Minion.tune_in() Changes: * ``salt.channel.client`` exposes ``CLUSTER_NOT_READY_SUFFIX`` and a ``_is_cluster_not_ready_message`` detector so upstream callers can recognize the sentinel without parsing a raw error string. * ``salt.pillar.{Async,}RemotePillar.compile_pillar`` logs the cluster-not-ready sentinel at ``DEBUG`` (not ``ERROR``) and re-raises the wrapping ``SaltClientError`` with ``from exc`` so the retry loop can see the original cause. * ``MinionManager._connect_minion`` detects the sentinel on the ``SaltClientError``'s ``__cause__`` and logs a single ``INFO`` retry notice instead of ``log.error(..., exc_info=True)``. Non-cluster ``SaltClientError``s keep the existing ERROR + traceback path. * ``MinionManager._connect_minion`` also resets ``minion._running`` to ``None`` after ``destroy()`` so the successful retry's ``tune_in(start=False)`` no longer falls into the "scheduled to stop" branch in ``_pre_tune`` and actually binds this master — fixing a latent correctness gap where the first-master retry task was left unbound (hidden in practice because sibling master tasks succeed). Adds four unit tests in ``tests/pytests/unit/test_minion.py`` covering the sentinel detector contract, the quiet-retry log level, the ``_running`` reset, and that non-cluster errors still log at ERROR. Fixes saltstack#70727.
Three distinct races surface on salt-master / salt-minion SIGTERM:
1. PubServer.close() and ZeroMQSocketMonitor.stop() cancel their
background tasks but, being sync calls, cannot drive the event loop
long enough for the cancellation to be delivered. The tasks stay in
the "cancelling" state and asyncio prints
Task was destroyed but it is pending!
task: <... coro=<PubServer._drain_loop() ...>>
task: <... coro=<ZeroMQSocketMonitor.consume() ...>>
on loop teardown. PubServer.close() now routes cancelled drain
tasks through _drain_cancelled_tasks (which already suppresses the
GC warning when it cannot drive the loop synchronously).
ZeroMQSocketMonitor.stop() sets task._log_destroy_pending = False
directly.
2. During docker compose down, the Raft leader dumps dozens of lines
per second:
[ERROR] SaltPeer: failed to send cluster/raft/append-entries to ...
because SaltPeer._send logs ConnectionError / StreamClosedError via
log.exception at ERROR level with a full traceback -- even though
peer-unreachable is the expected shutdown signature. Demote expected
unreachable-peer exceptions (ConnectionError, OSError, StreamClosedError)
to DEBUG; unexpected exceptions still log at ERROR.
3. _publish cached a _TCPPubServerPublisher on the pusher and kept
reusing it after the first send failure, so every heartbeat tick
fired against the same dead stream. On exception, close and drop
the cached client so the next tick reconnects.
Issue: saltstack#70730
Regression tests:
tests/pytests/unit/cluster/consensus/test_peer.py
- test_peer_unreachable_logs_debug_not_error
- test_unexpected_send_error_still_logs_exception
- test_publish_invalidates_cached_client_on_failure
tests/pytests/unit/transport/test_tcp_pubserver_close_cycle.py
- test_close_does_not_leave_pending_drain_tasks
tests/pytests/unit/transport/test_zeromq_monitor_shutdown.py
- test_stop_suppresses_pending_consume_task_warning
Follow-up to saltstack#70727 / saltstack#70732. Alpha's fix demoted the pillar-path ``cluster_retry`` ERROR to DEBUG/INFO using a new ``_is_cluster_not_ready_message`` helper keyed on the ``CLUSTER_NOT_READY_SUFFIX`` sentinel. Two gaps remained: 1. ``AsyncReqChannel._crypted_transfer`` (the generic non-pillar transfer path) raises ``AuthenticationError("master cluster is not ready")`` when its retry-until-deadline loop expires. This message does not carry the suffix, so Alpha's helper did not recognize it and non-pillar callers still logged at ERROR. 2. ``SyndicManager._connect_syndic`` catches ``SaltClientError`` from ``connect_master`` and logs an unconditional ``log.error("Error while bringing up syndic for multi-syndic. Is the master at %s responding?")``. The syndic connect path drives the same pillar fetch Alpha quieted, so the ``__cause__`` chain already carries the cluster-not-ready sentinel — only the demotion was missing. Changes: * ``salt.channel.client`` adds ``CLUSTER_NOT_READY_DEADLINE_MESSAGE`` and extends ``_is_cluster_not_ready_message`` to match it as well as the suffix form; the deadline raise now uses the named constant so the message string stays stable. * ``SyndicManager._connect_syndic`` applies the same sentinel-aware demotion as ``MinionManager._connect_minion``: cluster-not-ready gets a single INFO retry notice; non-cluster ``SaltClientError`` keeps the existing ERROR path. Adds three unit tests in ``tests/pytests/unit/syndic/test_syndic.py`` covering the extended detector contract, the quiet-retry log level, and that non-cluster ``SaltClientError`` still logs at ERROR. Fixes saltstack#70735.
Follow-up audit to saltstack#70733: the same "expected unreachable peer / closed stream / cancelled future" pattern Gamma fixed in SaltPeer._send + _publish + PubServer.close + ZeroMQSocketMonitor.stop surfaces in six more places during cluster SIGTERM / `docker compose down`. Each site below was observed firing ERROR tracebacks on expected shutdown paths, obscuring real errors. The fix is a targeted level demotion with the unexpected-exception branch left at ERROR so real bugs remain visible. 1. `salt/cluster/consensus/peer.py::RaftDispatcher._reply` -- same pattern as SaltPeer._send: inbound RPCs arriving after a peer's stream has been torn down trigger `_publish` via the dying pusher. Catch _PEER_UNREACHABLE_EXCEPTIONS (ConnectionError / OSError / StreamClosedError) -> DEBUG; keep broad-except -> log.exception. 2. `salt/transport/tcp.py::RequestServer.close` -- EBADF (errno 9) from `req_server.close()` means the fd was already closed under us (fork-safety teardown, SIGTERM racing close, inherited fd closed in a child). Demote log.exception -> log.debug for errno==9 specifically; non-EBADF OSError continues to raise. 3. `salt/transport/zeromq.py::RequestServer.close` -- `task.cancel()` raises RuntimeError when the IOLoop is already closed. Expected during a clean shutdown sequence where loop teardown ran before this close() path. Demote log.error -> log.debug. 4. `salt/transport/zeromq.py::ZeroMQSocketMonitor.consume` -- ZMQError with errno in (ENOTSOCK, ETERM, EINTR) is the socket/context-torn- down-under-us signature. Demote to DEBUG; other errnos (EFAULT, EMTHREAD, ...) stay at ERROR so genuine transport bugs are visible. 5. `salt/transport/zeromq.py` receive-poll CancelledError -- the sibling log.trace already covers this path; the redundant log.error("Master is unavailable (Connection Cancelled).") fired on every reconnect at shutdown. Drop the redundant ERROR; keep the TRACE for diagnostic purposes. 6. `salt/transport/tcp.py::MessageClient._stream_return` (two call sites) -- "Exception parsing response" fires at ERROR even when `self._closing` or `self._closed` is already set. Add the shutdown-aware predicate: DEBUG while tearing down, ERROR in steady state. The reconnect/disconnect-callback logic following the log site is unchanged. 7 new regression tests + 5 scope tests; 42/42 pass via venv314 under --core-tests. Pre-commit clean. Fixes saltstack#70736.
Four pytest-integration tests covering cross-module cluster regressions: - test_minion_alive_check.py: status.master() detects the connection even when the minion's publish_port opt is unset or differs from the master's non-default publish_port. - test_bootstrap_retry_backoff.py: minion contacting a not-yet-committed clustered master logs an INFO-level 'still catching up' line and retries, rather than ERRORing and firing __master_disconnected. - test_pub_channel_port_discovery.py: minion with no explicit publish_port uses the master-reported port from auth.creds, not the minion-side fallback default. - test_voter_identity_at_scale.py: 5-master cluster founding voter list contains exactly five entries, no hostname-plus-IP duplicates that would inflate quorum requirements. Uses the existing salt-factories + loopback-alias fixture pattern from tests/pytests/integration/cluster/conftest.py. Each test verified to FAIL against the pre-fix baseline and PASS against the current tree.
Follow-up to saltstack#70733 (SIGTERM-time async cleanup). The release-notes review for the 3008.x cluster-master stability fixes observed 8 residual ``Task was destroyed but it is pending!`` occurrences across 2 of 5 minions over a 666 s steady-state window with saltstack#70733 applied -- i.e. at non-SIGTERM times. The 1:1 correlation between per-minion bootstrap "Master ip address changed" events (5 and 3) and the destroyed-task warnings (5 and 3) points at the ``_connect_minion`` retry loop and its siblings. Root cause is the one ``Minion._spawn_background`` already documents at ``salt/minion.py:4462``: ``self.io_loop.create_task(coro)`` without a caller-held strong reference leaves the Task tracked only by asyncio's module-level ``WeakSet``. Python 3.10+ CPython's garbage collector can then destroy the still-pending Task mid-``await``, emitting the warning and silently dropping whatever work the coroutine was doing. Fix: route every long-lived / fire-and-forget scheduling site in ``salt.minion`` through a ``_spawn_background`` helper that keeps a strong reference in a per-instance set until the task completes. Adds the helper to ``MinionManager`` and ``SyndicManager`` (``Minion`` already had it) and migrates the remaining call sites: MinionManager.__init__ -> process_manager.run MinionManager._bind -> event_publisher.publisher MinionManager._spawn_minions -> _connect_minion (the 5:5 / 3:3 case) Minion.__init__ -> process_manager.run Minion.process_process_queue -> _process_process_queue_async Minion._process_handler -> _handle_decoded_payload (re-queue) Minion.handle_payload -> _handle_decoded_payload Minion.process_state_queue -> _process_state_queue_async Minion (ping master loop) -> _fire_master_main SyndicManager._spawn_syndics -> connect(...) Also drain the ``_background_tasks`` set from ``MinionManager.destroy``, ``Minion.destroy`` and ``Syndic.destroy`` so a strong-referenced Task whose loop never ran (e.g., a short-lived unit test that constructs + destroys without driving the loop) does not re-emit the very warning this change prevents elsewhere. Not a log suppression: no ``task._log_destroy_pending = False`` added anywhere. Keeping a strong reference causes the coroutine to actually run to completion rather than silencing a GC-collected leak. Issue: saltstack#70748 Regression tests (``tests/pytests/unit/test_minion.py``): - test_minion_manager_spawn_minions_keeps_task_reference - test_minion_manager_bind_keeps_publisher_task_reference - test_minion_process_process_queue_keeps_task_reference All three fail against pre-fix code and pass against the patched code; each asserts no ``Task was destroyed but it is pending!`` lands on the ``asyncio`` logger during the test window.
Seven new scenario tests under ``tests/pytests/scenarios/cluster/`` that each FAIL on origin/3008.x and PASS on the fully-integrated fix branch (``zeta/integration-all-fixes``). Together they encode the 10-check matrix from the 5-master cluster investigation (see ``agents/reports/integration-zeta/REPORT.md`` -- external to the upstream PR) into pytest form so the regressions do not silently return. Tests (and the fix PR(s) each regression-covers): * ``test_steady_state_quietness.py`` -- 60 s idle observation; zero ``Connection to master ... lost`` flaps. Covers saltstack#70725 + saltstack#70726 (``status.master`` port-scan + sibling pub-channel default). * ``test_bootstrap_race.py`` -- a ``master_type: failover`` minion with ``retry_dns > 0`` must not emit ``[CRITICAL]`` for the auto-correction. Covers saltstack#70729 (``retry_dns`` CRITICAL -> INFO). * ``test_non_default_cluster_port.py`` -- cluster on a non-default publish port, minion with no ``publish_port`` override; asserts ``test.ping`` delivery + no flap. Covers saltstack#70725 + saltstack#70726 (double publish-port mismatch regression). * ``test_shutdown_graceful.py`` -- SIGTERM on the Raft leader must not flood its followers' logs with ``SaltPeer: failed to send`` ``[ERROR]`` tracebacks. Covers saltstack#70733 (unreachable-peer ERROR -> DEBUG + cached-stream invalidation). * ``test_peer_departure_quiet.py`` -- stop one follower; the leader's ``SaltPeer: failed to send ... append-entries`` ERROR count stays low. Covers saltstack#70733 (same fix, opposite side). * ``test_minion_failover_no_task_leak.py`` -- failing over a minion between masters must not emit ``[WARNING]`` for the ``Master ip address changed`` line, and must not leave ``Task was destroyed`` traces. Covers saltstack#70729 + saltstack#70750 (log-level demotion + ``_spawn_background`` strong-ref fix). * ``test_restart_loop_convergence.py`` -- two consecutive restart cycles (minion, then peer master) each converge to a clean ``test.ping`` and leave zero ``[CRITICAL]`` lines in the minion log across cycles. Covers saltstack#70729 (across repeated startups) + saltstack#70732 latent ``_running = None`` reset. The conftest also adds a ``cluster_minion_fast_tick`` fixture which mirrors ``cluster_minion_1`` but shortens ``master_alive_interval`` to 3 s so a 60 s observation window records many scheduler ticks instead of one. The saltstack#66846 flap is per-tick; without the short interval the test tautologically passes on both pre-fix and post-fix. Each test is designed so the pre-fix / post-fix delta is deterministic on the asserted signature -- the reviewer gate (same test runs against ``origin/3008.x`` and must FAIL there) is recorded in the per-test docstring. This PR is tests-only. It depends on PRs saltstack#70725, saltstack#70726, saltstack#70729, saltstack#70732, saltstack#70733, saltstack#70737, saltstack#70738, and saltstack#70750 -- CI on this PR is expected to be red until those land.
3 tasks done
In test harnesses that patch 'salt.crypt.AsyncAuth.authenticated' and 'gen_token' but not 'creds', self.auth.creds is None at the point AsyncPubChannel.connect() enters. The mirror line added in the status.master fix was unconditionally subscripting creds['publish_port'] and raising TypeError: 'NoneType' object is not subscriptable, which bubbled up as SaltClientError and short-circuited the connect call -- tests/pytests/unit/transport/test_tcp.py:: test_async_tcp_pub_channel_connect_publish_port then failed because channel.transport.connect was never invoked. Use getattr(self.auth, 'creds', None) + a type/key guard before writing the mirror, and fall through the publish_port selection to creds['publish_port'] only when creds is a populated dict. When creds is unpopulated AND the operator-override branch did not fire, preserve the original raise shape so callers that relied on SaltClientError continue to see it. In production, auth.creds is populated on authenticate() success (which the preceding if not self.auth.authenticated ensures), so this is a defensive guard, not a behavioral change.
pylint E1102 'channel.connect_callback is not callable' is a false positive -- pylint cannot resolve the return type of AsyncPubChannel.factory() (a classmethod with no return annotation) and treats the returned channel as an opaque object. The callable in question is an async def method on the concrete subclass. Only surfaces under the test:full label, which runs Lint on the full test suite. Add a scoped # pylint: disable=not-callable with a one-paragraph comment so a future reader knows why it's there.
twangboy
approved these changes
Nov 10, 2026
This was referenced Nov 10, 2026
Closed
2 tasks done
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.
Bundle of cluster-master stability fixes for 3008.x plus two tiers of pytest regression coverage, assembled from observational work on a 5-master + 5-minion docker cluster under load.
Summary
Eight behavioral fixes, surfaced in order by instrumentation on a real cluster:
AsyncPubChannel.connect()fallback default was4506(ret port) instead of4505(publish port). With the common-casepublish_port: 4505on the minion the operator-override sentinel misfired and the master-reported publish port was ignored.status.master()publish-port fix. Minion health check port-scanned the OS TCP table using the minion's ownpublish_portconfig instead of the master-reported value. On clusters with a non-defaultpublish_portevery tick saw an empty result, fired__master_disconnected, and killed a healthy pub channel. Caused a self-reinforcing ~1 Hz flap and a ~400 publishes/sec cross-master event storm at idle.[CRITICAL] 'master_type' set to 'failover' but 'retry_dns' is not 0(helpful auto-correction) → INFO.[WARNING] Master ip address changedduring normal failover → INFO.[WARNING] Peer key missingduring startup race → INFO. Preserved all genuine CRITICAL/WARNING signals (master_shuffledeprecation, cluster-join integrity failures, etc.).[INFO] Master <ip> is still catching up (cluster not ready); retrying in 10sinstead of three[ERROR]lines. Also resetsminion._runningafterdestroy()so the successful retry'stune_in(start=False)actually binds (silent correctness bug, not just log noise)._cluster_retrypaths. Pillar path handled thecluster_retrysentinel; non-pillar RPC paths (_crypted_transferdeadline branch +SyndicManager._connect_syndic) did not. Added aCLUSTER_NOT_READY_DEADLINE_MESSAGEconstant and extended_is_cluster_not_ready_message()to match both sentinel forms.PubServer.close()andZeroMQSocketMonitor.stop()cancelled background coroutines without awaiting them, producingTask was destroyed but it is pendingon every minion SIGTERM. Fix routes cancelled drain tasks through the existing_drain_cancelled_taskshelper.SaltPeer: failed to send cluster/raft/append-entriesERROR lines per second — two compounding causes:_sendcalledlog.exceptionon expectedConnectionError/StreamClosedError, and_publishcached a dead_TCPPubServerPublisherand reused it indefinitely instead of reconnecting. Demoted expected unreachable-peer exceptions to DEBUG; close+drop the cached client on send failure.Task was destroyed. Residual leak outside the SIGTERM path: the prior fix only covered graceful stop; this fix migrates 10io_loop.create_tasksites insalt/minion.pyto a_spawn_backgroundhelper that holds strong references and drains properly. Reviewer confirmed no_log_destroy_pendingsuppression — the leaks are actually drained, not silenced.log.error/log.exceptionsites acrosssalt/transport/+salt/cluster/consensus/demoted to DEBUG for expected unreachable-peer / closed-stream / cancelled-future contexts. Each kept anunexpected-exceptionbranch at ERROR so real bugs still surface.Regression test coverage
Two tiers of pytest regression tests cover the observable behaviors above:
tests/pytests/scenarios/cluster/, 7 tests):test_steady_state_quietness,test_bootstrap_race,test_non_default_cluster_port,test_shutdown_graceful,test_peer_departure_quiet,test_minion_failover_no_task_leak,test_restart_loop_convergence. Each asserts against a tight threshold (0 to ≤3) and a realistic observation window (60s for flap, 15s for peer departure).tests/pytests/integration/cluster/, 4 tests):test_minion_alive_check,test_bootstrap_retry_backoff,test_pub_channel_port_discovery,test_voter_identity_at_scale. Narrower in-process tests using salt-factories + loopback-alias masters.Each test verified to FAIL against the pre-bundle baseline and PASS against this branch. Pre-fix regression signatures captured: ~2347 minion disconnects per minion in 40 min, ~400 publishes/sec cross-master storm during the flap, ~475
SaltPeer: failed to send ... append-entriesERRORs in a 15-second shutdown window, 2-3 bootstrap ERRORs per minion per bringup, 1 misleading[CRITICAL]per minion per bringup.Validation on a live cluster
Validated end-to-end on a 5-master + 5-minion docker cluster under
tests/monitoring/cluster-5node/. Steady-state after the bundle is applied: 0 minion flap over 380 s, 0.03 publishes/sec cross-master (down from ~400/s), 0 steady-state master-side ERROR/CRITICAL, 1 LEADER + 4 FOLLOWER + 1 total CANDIDATE transition,salt '*' test.ping3/3 from both leader and follower.Changelog + hygiene
Numeric changelog entries for each fix per convention. No
Co-Authored-Bytrailers. Pre-commit clean.