Repository navigation
Cluster topology - #70759
Merged
Merged
Cluster topology#70759
Conversation
dwoz
added a commit
to dwoz/salt
that referenced
this pull request
Nov 9, 2026
Fixes disk-exhaustion failures on saltstack#70759 CI functional zeromq 4 shards (reproduced across Amazon Linux 2023 arm64, Photon OS 4/5 fips, Ubuntu 26.04, Debian 13, Fedora 43 — 493 errors all with ''No space left on device'' writing yaml.safe_dump(master_config) in saltfactories). Root cause: salt-factories defaults every daemon's root_dir to /tmp/stsuite/<master-id>_<N>/. This directory is session-scoped and accumulates across every test that calls make_single_master() / make_cluster() with the same cluster_id. topology-east_41 in the traceback == the 42nd topology-east master instance created in one test session; each carries a full master state tree (logs, cache, run, sock_dir, token_dir). By the ~40th master the arm64 runner's disk is exhausted and the next yaml.safe_dump errors out, taking down every subsequent test in the shard (collection + setup phase). Fix: pass an explicit root_dir under the test's tmp_path to salt_master_daemon() in both make_single_master and make_cluster. pytest's rolling tmp_path cache (keeps 3 most recent) handles cleanup automatically. pki_dir already pointed under tmp_path so this closes the one remaining session-scoped surface. Local smoke test: pytest tests/pytests/functional/topology/ -x => 120 passed, 240 skipped in 17.97s (fresh runner, no disk pressure).
Re-apply the auto-fixes that pre-commit's `pip-compile` and `Upgrade code to Py3.10+` hooks made but that were missing from cdb4e84, so the `Check ALL Files On Branch` step in the Pre-Commit workflow stops exiting 1. - requirements/static/ci/py3.10/freebsd.lock Regenerated by the `FreeBSD CI Py3.10 ZeroMQ Requirements` pip-compile hook: adds `hypothesis==6.130.13` (pulled in by requirements/pytest.txt) and its transitive `sortedcontainers`, plus the corresponding `# via` edges on `attrs` and `exceptiongroup`. - tests/pytests/functional/modules/file/test_replace_encoding.py - tests/pytests/unit/modules/file/test_file_replace.py Auto-fixed by `Upgrade code to Py3.10+` (pyupgrade): drop the redundant "utf-8" argument from `.encode("utf-8")` calls in parametrized data, since UTF-8 is `str.encode`'s default. Reproduced locally with `pre-commit run --all-files`; all hooks now pass.
Pickle's default unpickle flow calls cls.__new__(cls) with no
arguments, so _args_for_getstate / _kwargs_for_getstate that
Process.__new__ normally captures from constructor args are
empty on the unpickled instance. Process.__setstate__ rebuilds
derived state via self.__init__(*args, **kwargs) but did NOT
re-seed those two attrs.
A second-generation pickle --- when a child process re-pickles
one of its Process objects to spawn a grandchild --- then
emitted an empty args tuple. The grandchild's __setstate__
called self.__init__() with no positional args and crashed:
TypeError: EventMonitor.__init__() missing 2 required
positional arguments: 'opts' and 'ipc_publisher'
On Windows topology masters (cluster_id set, cluster_peers
empty), RequestServer spawns EventMonitor via its own
ProcessManager --- a second-generation pickle --- so the
grandchild died on spawn, before logging, 2-3 times/second in a
restart loop. RequestServer never bound its worker sockets, so
minions timed out trying to connect. Observed in nightly run
41824029434/attempt-1 as 5 CLI publish-round-trip scenarios
hitting --timeout=15min each. Linux/fork doesn't hit it (no
pickle); non-topology Windows doesn't hit it (no nested
ProcessManager).
### Fix
Two lines in __setstate__ after self.__init__ to re-seed the
two attributes with copy.copy of args/kwargs, matching the
invariant __new__ establishes.
### Regression test
tests/pytests/functional/utils/test_process.py::
test_setstate_reseeds_args_for_second_generation_pickle:
construct with required positional args, pickle/unpickle, assert
the attrs round-trip, then pickle the unpickled instance again
and assert the second-generation unpickle still constructs
cleanly. Verified RED on pre-fix process.py (via git stash)
and GREEN with the fix.
### Live verification
Applied the patch to a Windows VM and re-ran
test_scenario_cli_glob_publish_round_trip_with_peered_topology:
- pre-fix: 15-min timeout, RequestServer die-restart loop,
minion never connects.
- post-fix: passes in 4m09s.
…ckle
The ``MasterPubServerChannel`` pickle pair was dropping
``SMaster.secrets`` -- only ``opts`` and ``transport`` survived.
On Windows ``multiprocessing.spawn``, the EventPublisher subprocess
re-imports :mod:`salt.master` from scratch, so ``SMaster.secrets``
starts as the empty-dict default and ``cluster_aes`` / ``aes`` are
not reachable.
The non-topology publisher path happens to survive because its
IPC-based ``PublishServer`` never touches ``SMaster.secrets``. The
new topology code path
(:func:`salt.topology.link_manager.start` -> ``_open_inbound_listener``)
calls :meth:`ReqServerChannel.post_fork`, which initialises a
``Crypticle`` via the ``aes_key`` property. That property reads
``SMaster.secrets["cluster_aes"]["secret"].value`` directly and
raises ``KeyError('cluster_aes')`` when the class-attribute is
empty. The inbound listener is then dropped with a WARNING, the
``topology_link_port`` REP socket never binds, and every outbound
peer link handshake to this master times out with ``Message timed
out`` -- which stalls ``C@peer`` compound publishes on Windows and
was the direct cause of
``test_scenario_cli_c_at_peer_publish_round_trip_with_peered_topology``
timing out on run 41970401917.
Matches the established pattern on :class:`salt.master.SMaster` and
:class:`salt.master.MWorker` (both round-trip ``SMaster.secrets``
through their own ``__getstate__`` / ``__setstate__``). On Linux
the default fork start method keeps the class attribute inherited
across forks and these pickle hooks are only exercised by explicit
copy/deepcopy -- no behavior change on fork-mode platforms.
Verified red-then-green against a new regression test in
``tests/pytests/unit/channel/test_server.py``.
Rebase onto origin/master pulled in PR saltstack#70656 (remote CLI / ClientKey subclass). KeyCLI.__init__ now unconditionally instantiates ClientKey, which opens a salt.cache.Cache with the ``keys.cache_driver`` opt. Our master-scope unit fixture predated ClientKey and did not supply that opt, so KeyCLI construction raised KeyError on five tests. _update_opts also gained a new tier of client_* opts (list_clients, accept_client, ...) that the fixture must declare because the dispatch loop iterates over every entry. Fix: * Add ``keys.cache_driver: "localfs_key"`` (matches the default in salt/config/__init__.py). * Add ``client_auth: False`` so KeyCLI takes the non-client branch. * Add the six client_* opts with empty values. * Monkeypatch ``salt.key.ClientKey`` to a dummy so the test does not open the real client-keys cache. No production code change; only the master-scope test fixture adapts to the new KeyCLI shape introduced upstream. 32 tests in test_salt_key_master.py now pass; 1466 unit tests across cluster / channel / topology / client suites all green.
Post-rebase unification follow-up (A). After PR saltstack#70656 introduced ClientKey(Key), the Key class carried three disjoint API surfaces: minion (base), master (our additions bolted onto Key), client (ClientKey subclass). Upstream started the subclass pattern with ClientKey; this commit completes it by moving the master-scope surface into a sibling MasterKey(Key) subclass. Benefits: 1. Same public API as the base Key (``accept``, ``reject``, ``delete_key``, ``finger``, ``list_keys``, ``list_status``), so KeyCLI dispatches via the standard CLI_KEY_MAP instead of a scope-specific CLI_KEY_MASTER_MAP. 2. Shared KIND / ACC / PEND / REJ / DEN class attributes parallel to ClientKey, laying groundwork for follow-up (B) that lifts shared bucket primitives into the base. 3. MasterKey instances fire their own event bus; KeyCLI.destroy now cleans up all three subclass instances. Changes: * salt/key.py: - Remove ``_MASTER_BUCKETS``, ``_master_*`` helpers, ``list_master``/``accept_master``/``reject_master``/ ``delete_master``/``finger_master`` from ``Key``. - Add ``class MasterKey(Key)`` with the same semantics, renamed to standard base-class names and matching signatures. ``list_status(match=None)`` aliases ``list_keys`` so ``salt-key -L --master`` (routed via CLI_KEY_MAP["list"] = "list_status") returns the full bucket inventory. - ``KeyCLI.__init__`` instantiates ``self.master_key`` alongside ``self.key`` (minion) and ``self.client_key``. - ``KeyCLI._run_cmd`` dispatches master-scope to ``self.master_key`` using the standard CLI_KEY_MAP; the old scope-specific CLI_KEY_MASTER_MAP is removed. - ``KeyCLI.destroy`` iterates over all three instantiated Key subclasses to release their event buses. * tests/pytests/unit/topology/test_salt_key_master.py: - Fixture uses ``salt.key.MasterKey(opts)`` instead of ``salt.key.Key(opts)``. - Method calls use standard base-class names instead of removed ``*_master`` names. - Dispatch tests spy on ``cli.master_key.calls``. - Legacy test for CLI_KEY_MASTER_MAP dropped. Unit regression: 1465 passed across cluster / channel / topology / client. Zero functional behavior change --- same files, same Raft propose path, same event firing. Follow-ups B (lift shared bucket primitives to base) and C (unify --kind flag) remain.
Post-rebase integration follow-up (R). BUG-023 taught LocalClient to recognise the ``cluster_retry`` sentinel a clustered master returns while Raft is still forming / not a committed voter -- without that, LocalClient.pub would ``KeyError: 'jid'`` on the sentinel's load (which has ``ret: False`` and no ``jid``), and ``cmd_async`` would wrap that as the useless ``SaltClientError: 'jid'``. The new RemoteClient from PR saltstack#70656 inherits most of LocalClient but defines its own ``pub`` method with the same post-send return pattern (``payload["load"]["jid"]``), so the same KeyError-to- useless-error cascade applies to remote CLI operators. This commit adds the same cluster_retry guard to ``RemoteClient.pub`` so a remote operator hitting a not-yet-ready cluster gets the clean "cluster consensus still forming, retry" message instead of ``SaltClientError: 'jid'``. Regression test: ``tests/pytests/unit/client/test_init.py::test_remote_client_pub_raises_clean_error_on_cluster_retry`` -- builds a RemoteClient with the network-event setup stubbed, drives ``channel.send`` to return the sentinel, asserts ``SaltClientError`` matches ``cluster consensus still forming``. Red-then-green verified via git stash of the production diff. Changelog: ``changelog/70653.fixed.md``.
Post-rebase unification follow-up (B). :class:`MasterKey` (added in commit 1c08b0d) carried its own ``_bucket_path`` / ``_list_bucket`` helpers that were nearly identical to the inline path construction in the base :class:`Key` class. Lift the two helpers into the base so both filesystem-backed Key subclasses (base minion scope + :class:`MasterKey` peer-master scope) share one implementation. Changes: * salt/key.py: - Add ``Key._bucket_path(bucket)`` and ``Key._list_bucket(bucket)`` taking a bucket name (``"minions"``, ``"masters_pre"``, ...) and returning the on-disk path / sorted ``.pub`` filenames. - Rewrite ``Key._check_minions_directories`` to call ``_bucket_path`` with the class-level ``ACC`` / ``PEND`` / ``REJ`` / ``DEN`` constants instead of inline ``os.path.join`` calls. - Drop the duplicated ``_bucket_path`` / ``_list_bucket`` from :class:`MasterKey`; inherit from the base. Side-effect: MasterKey's bucket paths now derive from ``self.pki_dir`` (which :meth:`Key.__init__` already resolves to ``cluster_pki_dir`` when ``cluster_id`` is set) instead of the raw ``self.opts.get("pki_dir", "")``. This aligns with BUG-022's intent that peer-master keys on a clustered master live under the shared ``cluster_pki_dir`` so every cluster peer sees the same bucket contents. The old MasterKey code read ``pki_dir`` directly, which was a gap the subclass extraction incidentally closes. Zero functional behavior change on solo masters (both paths resolve to ``opts["pki_dir"]``). On clustered masters this is the intended BUG-022 behavior. :class:`ClientKey` is untouched because it overrides storage via cache banks and never calls the filesystem primitives. Unit regression: 1494 passed across cluster / channel / topology / client / test_key / wheel/test_key.
Post-rebase unification follow-up (C). The three Key subclasses
(MinionKey / default Key, MasterKey, ClientKey) each have their
own CLI flag style:
* Minion: default; no flag.
* Master: ``--master`` boolean modifying the standard
``-L / -a / -d / -F`` actions.
* Client: ``--list-clients`` / ``--accept-client`` / etc. family
of per-action flags.
Add ``--kind {minion|master|client}`` that gives operators a
unified mental model across all three. Legacy flags remain
supported.
Semantics:
* ``--kind minion`` (or no ``--kind``): unchanged behavior.
* ``--kind master``: equivalent to ``--master`` (sets
``master_scope=True``).
* ``--kind client``: rewrites the operator's base action opt
(``accept="alice"``) into the ``_client`` sibling
(``accept_client="alice"``), which triggers the already-shipped
ClientKey dispatch. An explicit ``--accept-client=alice``
still wins.
Changes:
* salt/utils/parsers.py:
- New ``--kind`` option on SaltKeyOptionParser's action group,
dest ``kind``, choices ``(minion, master, client)``.
- Updated the ``--master`` help text to note equivalence.
* salt/key.py:
- ``KeyCLI._update_opts`` consumes ``opts["kind"]`` at the top:
master -> set master_scope; client -> rewrite action opts.
Minion / unset is a no-op.
* tests/pytests/unit/topology/test_salt_key_master.py:
- Four new unit tests: ``--kind master`` sets master_scope,
``--kind client`` rewrites action opts to _client siblings,
minion / default no-op, explicit per-action flag wins.
Unit regression: 1498 passed across cluster / channel / topology
/ client / test_key / wheel/test_key.
Scope: legacy flags remain primary; ``--kind`` is a convenience
layer. Deprecating legacy flags is out of scope.
Commit 1c08b0d (MasterKey subclass follow-up A) renamed the unit test file ``tests/pytests/unit/topology/test_salt_key_master.py`` from the old ``*_master`` method names to the standard subclass names (``accept``, ``reject``, ``delete_key``, ``list_keys``, ``finger``). The equally-named FUNCTIONAL test file ``tests/pytests/functional/topology/test_salt_key_master.py`` was missed in that commit and nightly 42132228466's Ubuntu functional-4 chunk surfaced it with 16 ``AttributeError: 'Key' object has no attribute 'accept_master'`` / ``list_master`` / ``reject_master`` / ``delete_master`` / ``finger_master``. Apply the same renames: * Fixture ``_make_key`` constructs ``salt.key.MasterKey(opts)`` instead of ``salt.key.Key(opts)``. * Method calls use standard base-class names instead of removed ``*_master`` names. Also fix a latent test-opts gap exposed by Commit B (``_bucket_path`` lift): after the lift, MasterKey derives its bucket paths from ``self.pki_dir``, which :meth:`Key.__init__` resolves to ``opts["cluster_pki_dir"]`` whenever ``cluster_id`` is set. The ``clustered_opts`` fixture did not set ``cluster_pki_dir`` (real master configs do, via salt.config.master_config), so MasterKey writes landed under ``""/masters_pre/*.pub``. Default the test fixture's ``cluster_pki_dir`` to ``pki_dir``. Full ``tests/pytests/functional/topology/test_salt_key_master.py`` run with ``--run-slow``: 16 passed.
Same post-Commit-A miss as commit 461d20f but for the scenarios test file. ``test_salt_key_master_concurrent_accept_delete_toctou`` in tests/pytests/scenarios/topology/test_adversarial_trust.py built a ``salt.key.Key(opts)`` and called ``.accept_master("east")`` / ``.delete_master("east")``. After commit 1c08b0d those methods only exist on :class:`MasterKey`, so the test raised ``AttributeError``. Rename to the subclass: * ``salt.key.Key(opts)`` -> ``salt.key.MasterKey(opts)`` * ``key.accept_master(x)`` -> ``key.accept(x)`` * ``key.delete_master(x)`` -> ``key.delete_key(x)``
The Windows clustered branch of ``MasterPubServerChannel.factory`` used to bind its primary ``tcp.PublishServer`` on ``publish_port`` / ``cluster_pool_port`` because the Unix socket paths were nulled out (no AF_UNIX on Windows). Two port collisions followed: 1. The regular ``PubServerChannel`` spawned at ``salt/master.py:1262`` also binds ``publish_port`` -- its ZMQ ``pub_sock.bind()`` on the second publisher hung indefinitely on the collision, the child's ``started`` event never fired, and ``Master.start()`` sat in ``chan.transport.started.wait(60)`` until ``salt-factories`` killed the master as timed-out. ``tests/pytests/functional/topology/ test_harness.py::test_single_cluster_multi_peer`` could not get a single peer past that point. 2. ``cluster_pool_port`` is already owned by the ``pool_puller`` TCPPuller set up in ``_publish_daemon``; the primary's pull socket racing it is why the factory carried an ``errno.EADDRINUSE`` fallback to ``pull_port=0``. The primary ``MasterPubServerChannel.transport`` IS the master event bus -- the role ``master_event_pub.ipc`` / ``master_event_pull.ipc`` plays on Linux. Its TCP equivalent is ``tcp_master_pub_port`` / ``tcp_master_pull_port``. Bind that pair on Windows clustered instead of ``publish_port`` / ``cluster_pool_port``. No collision, the event bus works, and ``send_aes_key_event()`` / pytest_engine's ``salt/master/<id>/start`` fire immediately instead of timing out at 30s. The bind host must also be the loopback literal ``_ipc_loopback`` uses (``127.0.0.1``). ``salt.utils.event.SaltEvent.connect_pull`` and ``connect_pub`` route through ``salt.transport.ipc_publish_client`` / ``ipc_publish_server``, both of which hard-code ``_ipc_loopback(opts)`` with no consultation of ``opts["interface"]``. Binding the primary on peer 2's ``interface=127.0.0.2`` leaves every in-process ``get_master_event()`` client inside peer 2's own ``EventPublisher`` / ``MainProcess`` / engine subprocesses connecting to 127.0.0.1 and getting ``StreamClosedError`` from fire_event. ``MasterPubServerChannel.__setstate__`` also re-initialises ``self.master_key`` / ``self.peer_keys`` / ``self.cluster_peers`` / ``self._discover_token`` / ``self._discover_candidates`` so the Windows-spawned ``EventPublisher`` child inherits the same attribute surface ``__init__`` would set. Without those, the child crashes on the first inbound ``cluster/peer/discover`` payload with AttributeError. Harness side: * ``tests/support/topology/cluster.py`` ``_ensure_lo_alias`` adds Windows support via ``netsh interface ipv4 add address "Loopback Pseudo- Interface 1" 127.0.0.N 255.0.0.0``. Without the alias, 127.0.0.2+ connections fail with ``StreamClosedError`` and the Raft peers never form a cluster. * ``make_cluster`` allocates distinct ``tcp_master_pub_port`` / ``tcp_master_pull_port`` / ``tcp_master_publish_pull`` / ``tcp_master_workers`` per peer. ``_ipc_loopback`` hard-codes ``127.0.0.1`` and ignores ``opts["interface"]``, so without unique ports every peer would try to bind the same four ports on 127.0.0.1 and masters 2..N would silently lose the bind on Windows (EADDRINUSE). * ``tests/pytests/functional/topology/conftest.py`` single_cluster fixture spawns peers in parallel threads. The Raft founding CONFIG requires majority quorum, so the first peer cannot bootstrap alone -- it needs the other peers online. On Linux the sequential path happened to work by timing; on Windows the aes-key-event send blocks for 30s when Raft cannot form, long enough that the 240s per-peer start_timeout trips. Regression test: ``test_master_pub_server_channel_factory_windows_binds_event_bus_ports`` asserts the primary transport binds ``tcp_master_pub_port`` / ``tcp_master_pull_port`` on ``127.0.0.1`` (NOT ``publish_port`` / ``cluster_pool_port`` on ``opts["interface"]``) when the Windows clustered branch is taken. Verified on win-11: ``test_single_cluster_multi_peer`` passes in 106s with all three peers firing their ``salt/master/<id>/start`` events.
Strip BUG-NNN mentions from changelog entries, source comments, and test docstrings. Replace each with the technical context the ID previously stood in for (e.g. "BUG-025" -> "the commit_index persistence fix"). The internal bug IDs won't resolve to anything after the branch merges upstream, so the comments need to carry the meaning on their own.
Six sites across the topology code where cluster_id, peer_cluster_id, origin_cluster_id, or _cluster_is_ready / cluster_retry names a boundary that applies equally to solo and clustered masters. No rename --- adding master_id would clash with the existing opts\["id"\] on every master and confuse readers. Instead, each affected docstring / comment now spells out that the cluster_id suffix is the opts-key name of a master's identity, not a claim that the peer is multi-master. Follow-up (separate commit): sweep public docs and changelog entries with the same terminology clarification, and rename rfc-pub-ack-complete since we aren't taking comments.
Phase 2 of the cluster/master terminology clarification. - Rename rfc-pub-ack-complete.md -> pub-ack-complete.md; drop RFC framing since we aren't taking comments. Updates 'this RFC proposes' / 'RFC rationale' / 'RFC rejected' phrasing to 'design' equivalents; preserves the wire-format spec unchanged. - index.md gains a 'Terminology' subsection in Vocabulary spelling out that cluster_id names a master's external identity; solo and clustered peers show up identically at the topology boundary. (cluster_id was introduced in 3007.0 with the master-cluster feature, not 3008.x.) - overview.md: three string changes where 'cluster' was literally standing in for 'master' (two-master peered topology, three or more peer masters chained, destination master in troubleshooting). - changelog/70644 rewritten to describe the 'peer is itself a 3008.x master cluster' case explicitly instead of the ambiguous 'multi-master peer cluster' phrasing. Other changelog entries use 'cluster' legitimately (describing cluster-internal Raft behavior, cluster_retry sentinel, cluster_pki_dir seeding, etc.) and were left as-is.
The master-cluster feature as a user-facing shape arrived in two steps: 3007.0 introduced the cluster_id / cluster_peers / cluster_pki_dir opts and a shared-filesystem backing for the shared state; 3008.0 moved to Raft-replicated state over the wire so a shared FS is no longer required. The Terminology note and opts table both call out both milestones so readers don't collapse them onto one release.
Nine doc bugs identified by a 15-agent review and fixed by nine follow-up teams. All claims verified against current code and pinned with regression tests in a separate commit. - overview.md + index.md troubleshooting: salt-run topology.links never emits pending_accept from the subprocess path (it hardcodes connected/attached). Rewrote the handshake-stuck guidance to describe the actually-visible states (attached with null last_summary_at OR absent) and point at salt-key -L --master as the authoritative signal. - index.md opts table: auto_accept_masters row now shows default False instead of *(absent)* (opt is declared but not yet honored). - index.md key-management section: added a clustered-fallback note that keys live under cluster_pki_dir/ (not pki_dir/) when cluster_id + cluster_pki_dir are both set, matching the resolution in link_manager._masters_subdir and Key.__init__. - index.md return path: breadcrumb cache key is a bare <jid>, not <cluster_id>:<jid> as previously claimed. - pub-ack-complete.md pub-ack ordering: rewrote the overclaim "ack guaranteed to precede any return" to accurately describe the ensure_future + await asyncio.sleep(0) mechanism at link_manager.py L1450-1459. The real guarantee is that the ack *begins* its wire send before the local publish fan-out; on-wire delivery is still best-effort. Flagged as a fragile monotonic invariant pinned by test_pub_ack_scheduled_before_local_publish_await. - pub-ack-complete.md transit ack: qualified "transit peers also ack" to distinguish flood (every participant acks) from scoped routing (only destination peers ack; pure-transit peers with local_match=False skip the ack path). - pub-ack-complete.md pub-complete enforcement: softened the "enforced at originator; WARNING log + fail-open" claim. The invariant is emitter-side construction only (link_manager.py:2231); the originator does NOT re-verify and the validator is stateless. - pub-ack-complete.md cancelled semantics: clarified that Phase 1.5 hard-codes cancelled=False and cancel_reason=None at _emit_pub_complete_once (link_manager.py L2077-2078). Both documented triggers (topology/jid-cancel Tier 2 frame; parent peer master disappeared mid-job) are aspirational; no in-tree code sets cancelled=True today.
…s docstring
Two code-side fixes paired with the doc-cleanup commit:
- salt/scripts.py:salt_syndic now calls warnings.warn with
DeprecationWarning before the Syndic daemon starts. The message
names master topology (topology_enabled: True) as the migration
target. Backs the 'syndic is deprecated' claim in overview.md and
index.md with a real user-visible signal instead of leaving the
claim aspirational. Pinned by test_syndic_deprecation.py.
- salt/topology/breadcrumbs.py module docstring and put() docstring
previously claimed the cache key is <cluster_id>:<jid>. The actual
key is a bare publish <jid> (router.py:847,887 pass load.get('jid')
through to put, master.py:3488 looks up by the same bare jid). The
docstring drift was caught in the 15-agent review and is corrected
here. Pinned by test_return_path.py::test_key_is_bare_jid_not_cluster_scoped.
Adds regression coverage from the 15-agent doc-review pass. Every doc claim that was factually verified now has a test that will fail loudly if the code drifts; every claim that turned out to be wrong is replaced by a test pinning the actual behavior (see the companion doc-fix commit). New test files: - test_cluster_scope.py (14 tests) — pins every documented C@ matcher example and edge case; includes a regression guard for the salt/master.py:6538 missing-nodegroups= call site. - test_doc_examples.py (10 tests) — regex-extracts every yaml block from overview.md / index.md and round-trips each through the config loader so prose-and-example drift fails loudly. - test_key_paths.py (11 tests) — pins solo-vs-clustered pki-dir resolution across both link_manager._masters_subdir and MasterKey._bucket_path, and the symbol parity between MasterKey.ACC and the handshake code. - test_pub_ack_wire.py (8 tests) — pins the pub-ack frame shape, ensure_future + sleep(0) ordering invariant, and the scoped-vs-flood transit-peer ack behavior. - test_pub_complete.py (15 tests) — pins pub-complete frame shape, emitter-side missed-set construction, fail-open behavior on originator (no cross-frame xor check), and the Phase 1.5 cancelled=False / cancel_reason=None hard-coding. - test_return_path.py (9 tests) — pins breadcrumb entry shape with bare-jid key (not cluster-scoped), TTL honoring across grace / max_age opts, and the salt/topology/return/<origin>/<jid> event tag format. - test_route_learning.py (10 tests) — pins topology/sum wire fields, path append-only semantics, routing-table entry shape, and the verbatim flood-on-unresolved WARNING line. - test_conf_master_defaults.py (16 tests + 3 skips) — parses the Master Cluster Settings block from conf/master and cross-checks every key / type / default against DEFAULT_MASTER_OPTS and VALID_OPTS. - test_syndic_deprecation.py (2 tests) — pins the DeprecationWarning from salt-syndic. Extended existing files: - test_config_opts.py — 22 new parametrized cases pinning every documented opt row in index.md plus a guard that new operator-facing topology_* opts must appear in the doc table. - test_runner.py — added test_links_pre_handshake_key_not_pending_accept pinning the actually-emitted subprocess-path health values. Full run (venv314): 663 passed, 3 skipped, 9.73s on tests/pytests/unit/topology/ + the two new sibling dirs.
Companion to the earlier rename of rfc-pub-ack-complete.md -> pub-ack-complete.md. The architecture toctree at doc/topics/topology/index.rst already referenced the master-topology overview and index pages; the new design doc needs the same entry so Sphinx does not warn about an orphan document. Caught by nightly run 42348605789: Documentation / Build (man) failed with 'pub-ack-complete.md: WARNING: document isn'\''t included in any toctree' (treated as error via --Werror).
Nightly 42350369860 failed all 8 unit shards (Ubuntu + Windows) at collection time of test_conf_master_defaults.py with FileNotFoundError: /__w/salt/salt/artifacts/salt/lib/python3.14/site-packages/conf/master. Root cause: the test resolved REPO_ROOT from pathlib.Path(salt.config.__file__).parents[2] which points at the installed site-packages in the onedir CI environment, where conf/master is not shipped. It works locally against a dev checkout but breaks under the test-against-installed CI shape. Fix: resolve REPO_ROOT from __file__ of the test itself (parents[4]). Also degrade gracefully with a module-level skip when conf/master does not exist, so a wheel-only environment does not error at collection time.
Fixes disk-exhaustion failures on saltstack#70759 CI functional zeromq 4 shards (reproduced across Amazon Linux 2023 arm64, Photon OS 4/5 fips, Ubuntu 26.04, Debian 13, Fedora 43 — 493 errors all with ''No space left on device'' writing yaml.safe_dump(master_config) in saltfactories). Root cause: salt-factories defaults every daemon's root_dir to /tmp/stsuite/<master-id>_<N>/. This directory is session-scoped and accumulates across every test that calls make_single_master() / make_cluster() with the same cluster_id. topology-east_41 in the traceback == the 42nd topology-east master instance created in one test session; each carries a full master state tree (logs, cache, run, sock_dir, token_dir). By the ~40th master the arm64 runner's disk is exhausted and the next yaml.safe_dump errors out, taking down every subsequent test in the shard (collection + setup phase). Fix: pass an explicit root_dir under the test's tmp_path to salt_master_daemon() in both make_single_master and make_cluster. pytest's rolling tmp_path cache (keeps 3 most recent) handles cleanup automatically. pki_dir already pointed under tmp_path so this closes the one remaining session-scoped surface. Local smoke test: pytest tests/pytests/functional/topology/ -x => 120 passed, 240 skipped in 17.97s (fresh runner, no disk pressure).
Project-wide pytest-timeout default is 90s. test_single_cluster_multi_peer brings up a 3-peer master cluster and the peers have to reach Raft quorum before any one of them reports started. Local bare-metal runs land around 60-100s; slower CI runners (ARM, Fedora 43) overshoot 90s and trip the function-level timeout. Caught by saltstack#70759 CI attempt 3 after the earlier disk-exhaustion fix (commit 813166c) cleared the way for this test to actually run. All 13 functional zeromq 4 shards hit the same 90s timeout on this single test. No behavior change --- just letting the Raft quorum form. Adds @pytest.mark.timeout(300) to the single test.
…hdog Attempt 2 of run 42708140037 still had test_single_cluster_multi_peer timing out at 300s on every Linux functional-4 shard. The thread.join in conftest's multi-peer branch used no timeout, so when one peer's factory.start never returned (observed as only one topology-west in Process Statistics while the fixture was waiting for three), the join blocked forever and pytest-timeout aborted the test. Three combined changes: - Per-peer start_timeout: 240s -> 60s. Saltfactories retries up to max_start_attempts (default 3) on FactoryNotStarted, so one peer's worst-case wall-clock is start_timeout * 3 = 180s. - Per-join watchdog: thread.join now takes a 240s timeout. If any peer thread is still alive after that, raise RuntimeError naming the stuck peer indices and terminate the surviving peers. Prevents the test from eating the whole pytest-timeout budget on an internal hang. - @pytest.mark.timeout: 300s -> 420s on test_single_cluster_multi_peer to leave room for 240s watchdog + 60s teardown + ~120s headroom. Local functional topology run: 17 skipped + 0 failures in 0.14s (collection path; the slow test gates behind a runtime filter).
…8 bytes Local repro of saltstack#70759 functional-4 shard failure surfaced the real cause of test_single_cluster_multi_peer hanging past pytest-timeout: OSError: AF_UNIX path too long at tornado.netutil.bind_unix_socket(pub_path) pub_path='/tmp/pytest-of-root/pytest-0/test_single_cluster_multi_peer0/west-127.0.0.3-root/tmp/sXXXXX/master_event_pub.ipc' len=119 Chain of surprises: - Earlier disk-exhaustion fix (813166c) routed root_dir under pytest tmp_path. pytest's tmp_path prefix alone (/tmp/pytest-of-<user>/pytest-<n>/<nodeid>/) is 60-80 chars. - sock_dir derives from root_dir via salt.config.prepend_root_dir --- and prepend_root_dir treats any path starting with / as 'under def_root_dir', strips the leading / via salt.utils.path.join (lstrips os.sep from non-first parts), and prepends root_dir. An absolute /tmp/sXXX sock_dir override becomes <root_dir>/tmp/sXXX, i.e. always under root_dir. - Salt additionally has if len(sock_dir) > len(cachedir) + 10: sock_dir = <cachedir>/.salt-unix guard in apply_master_config that fights short sock_dir overrides. - Net effect: any sock_dir path gets anchored under root_dir. With long tmp_path root_dir, every unix socket overflows AF_UNIX sun_path (108 bytes on Linux). Fix: route root_dir to a SHORT tempfile.mkdtemp(prefix='r', dir='/tmp') path (~13 chars). sock_dir then resolves to <root_dir>/var/run/salt/master (~35 chars); unix sockets fit comfortably in 108 bytes. Reverts the earlier sock_dir override (unnecessary + fought the prepend logic). Local verification (was previously hanging at 300s pytest-timeout): pytest tests/pytests/functional/topology/test_harness.py::test_single_cluster_multi_peer => 1 passed in 9.22s Full functional topology suite: pytest tests/pytests/functional/topology/ --core-tests --slow-tests => 358 passed, 2 skipped in 845.08s Teardown: salt-factories tears the master down at exit-stack close; the short mkdtemp root_dir stays as an empty directory tree under /tmp until the next reboot or os.tmpfiles cleanup. Acceptable tradeoff vs. tmp_path's 3-roll since each root_dir is only a few KB and most of its content is removed by the factory shutdown.
Fixes two sides of the same bug that have been ping-ponging the functional-4 shard: - Before 813166c (default /tmp/stsuite): session-scoped accumulation of 40+ master dirs exhausted CI disk. - 813166c (tmp_path): pytest-managed cleanup, but tmp_path prefix alone (~60-80 chars) overflowed AF_UNIX's 108-byte sun_path. - f390788 (mkdtemp /tmp): short paths, but no cleanup --- master logs/cache accumulated on the 7.9 GB tmpfs that mounts /tmp inside the Docker container --> ENOSPC after ~40 masters. Right shape is short path AND explicit cleanup, on a filesystem with real-disk headroom: - new helper _make_short_root_dir() prefers $GITHUB_WORKSPACE (an overlay fs with ~99 GB free on the nightly runners) over tempfile.gettempdir(). Locally the env var is absent so it falls back to /tmp, which is a real disk on dev machines. The prefix is a single r character so mkdtemp names stay around 10-15 chars total. - make_single_master returns the root_dir as the 4th tuple element; make_cluster returns the per-peer root_dirs list. The functional conftest registers a shutil.rmtree(root_dir, ignore_errors=True) callback on _topology_exit_stack BEFORE entering each factory context, so teardown order (LIFO) terminates the factory first and rmtree runs on the now-idle tree. Local verification (venv314, zeromq, Linux): tests/pytests/functional/topology/test_harness.py::test_single_cluster_multi_peer => 1 passed in 8.22s (was hanging past 300s pytest-timeout) tests/pytests/functional/topology/ (--core-tests --slow-tests) => 358 passed, 2 skipped in 821.19s (0:13:41) => zero /tmp/r* directories remain after the suite
Fixes saltstack#70759 CI failure on the Photon OS 5 Arm64 FIPS functional-4 shard: salt.exceptions.UnsupportedAlgorithm: Algorithm OAEP-SHA1 uses SHA1 which is not allowed in FIPS mode at salt/channel/server.py:3245 send_aes_key_event at salt/crypt.py:333 _enforce_fips Pre-existing bug in 3008.x cluster defaults, not introduced by the master-topology work: salt/config/__init__.py sets publish_signing_algorithm: 'PKCS1v15-SHA1' cluster_encryption_algorithm: 'OAEP-SHA1' and both contain SHA1 which _enforce_fips rejects. Any clustered master in FIPS mode fails startup the same way regardless of the master-topology code. The master-topology functional test fixture is the first widely-exercised caller of make_cluster on FIPS runners, so the pre-existing defect surfaced here. Fix (scoped to the test harness): the make_cluster override dict now sets both algorithms to their SHA224 variants, which are valid under both FIPS and non-FIPS cryptography stacks. The underlying 3008.x default change is out of scope for this PR; this unblocks the CI shards while leaving that discussion to a follow-up. Local verification (venv314, zeromq, Linux non-FIPS): tests/pytests/functional/topology/test_harness.py::test_single_cluster_multi_peer => 1 passed in 8.14s (unchanged) tests/pytests/functional/topology/ (--core-tests --slow-tests) => 358 passed, 2 skipped in 824.37s (0:13:44) (unchanged) The FIPS check itself is a CI runner-side property; the fix will be exercised when the next CI run hits the Photon OS fips shard.
Reproduces + fixes the Photon OS 5 Arm64 FIPS functional-4 shard
failures (18 tests at the 90s pytest-timeout) by running the exact
CI image + FIPS provider locally per CONTAINERS.txt:
docker run --platform linux/arm64 -v $PWD:/salt --privileged
ghcr.io/saltstack/salt-ci-containers/testing:photon-5
tdnf install -y openssl-fips-provider
sed -i '/^#\.include \\/etc\\/ssl\\/provider_default.cnf/s/^#//g' /etc/ssl/distro.cnf
=> cryptography.hazmat.backends.openssl.backend._fips_enabled: True
Two root causes, both landing here:
1. Salt's defaults encryption_algorithm / signing_algorithm /
publish_signing_algorithm / cluster_encryption_algorithm
are all SHA1 variants. _enforce_fips at salt/crypt.py
rejects SHA1 under FIPS, so master<->minion auth silently retries
past the pytest-timeout. Added SHA224 overrides in
make_single_master (was missing), extended make_cluster's
existing overrides to cover the two additional opts, and added
matching minion-side overrides in the attach_minion conftest
fixture.
2. single_master / attach_minion / two_cluster_fixture
are factory-callables invoked inside the test body, so
timeout_func_only = true in pytest.ini does NOT keep their
start-up out of the per-test clock. Under FIPS the RSA keygen +
handshake takes well over 90s even on real arm64; under qemu the
repro here took 193s for one master+minion. Bumped
@pytest.mark.timeout to 600s on test_attach_minion and
added module-level pytest.mark.timeout(600) to
test_compound_integration.py + test_master_cluster_grain.py.
Local verification:
- FIPS arm64 container (qemu-user-static):
test_attach_minion => 1 passed in 193.88s
test_c_at_local_cluster_matches_local_minion +
test_grain_present_on_topology_minion => 2 passed in 421.24s
- Non-FIPS x86 host, full functional topology suite:
tests/pytests/functional/topology/
(--core-tests --slow-tests) => 358 passed, 2 skipped in 13:42
twangboy
approved these changes
Nov 11, 2026
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.
Summary
Introduces master topology: a new master-to-master layer that links two or more independent Salt masters so a publish on one can reach minions attached to another. Replaces the syndic federation model with per-peer authenticated links, breadcrumb-based return routing, and a compound
C@<cluster_id>matcher for cross-cluster targeting.The feature is off by default (
topology_enabled: False). When disabled, nothing insalt.topologyimports. When enabled, each master gets an authenticated REQ/REP channel ontopology_link_port(default 4521) to every peer listed intopology_peers.What is a topology
From any master's point of view, a peer is just another master — identified by its
cluster_idopt. That same opt names a 3008.x master cluster (shared cluster, multiple masters behind a load balancer) at a higher layer; master topology does not care which flavor the peer is. A topology node can therefore be a solo master or a Raft-coordinated cluster, and the two features compose cleanly: HA inside a site, topology between sites.Publish flow (two-master example)
salt '*' test.ping.jid → inbound-link = east) and publishes to its own minions.Transit hops (3+ masters chained) follow the same pattern: each hop writes a breadcrumb at publish time and uses it to send the return back out the inbound link.
Capabilities shipped
salt-key -L --master/salt-key -a <cluster_id> --master.C@<cluster_id>(salt -C 'C@west and G@os:ubuntu' test.ping). Nodegroups with embeddedC@expand correctly. Unresolved destinations flood deliberately (better a duplicate than silently dropped).topology_breadcrumb_grace+topology_breadcrumb_max_ageso stale breadcrumbs are swept.topology/sumsummary carrying each master'scluster_id, minion counts, and authenticated path. Receiving peers populate a(destination_cluster_id → (next_hop_peer_id, hop_count))table.topology/pub-ack+topology/pub-completeframes (seedoc/topics/master-topology/pub-ack-complete.md) that give the originating CLI deterministic answers towho should I wait for?andam I done?without any master-side job state — Phase 1 through Phase 3 landed,topology_pub_ack_consumerdefaults to True.Peer,Controller,Managed) with onlyPeerwired today;Controller/Managedare the planned per-peer asymmetric-trust flags.salt-run topology.{peers,links,find,graph,trust}plussalt-key --masterscope for the identity key store.last_summary_at,health(via LinkHealth enum), fault counters, andsalt/topology/pub/failed/<peer>events on per-link send failure.Config
All opts default to off / empty. Example at
doc/topics/master-topology/index.md. Minimal config:Full opts table + handshake knobs + example subscriptions at
doc/topics/master-topology/index.md.Relationship to syndic
Syndic is now marked deprecated via a
DeprecationWarningonsalt-syndicstartup (migration target:topology_enabled: True). A master may run both during the migration window. All of syndic's job-federation use cases map onto topology peering: a flat mesh, or a tree expressed asC@<cluster_id>targeting across hops.Companion cluster fixes
The 3008.x-backportable subset of the cluster-correctness work driven by this branch has been pulled out into a separate smaller PR: #70755 (stale CONFIG regression, cluster-ready latching, Raft pusher table drift, LocalClient
cluster_retryhandling, opts type widening). Independent of this PR; already on 3008.x milestone.Non-goals (deferred)
Controller/Managedrole wiring. Vocabulary present; enforcement is a follow-up.topology/jid-cancelframe (pub-complete.cancelled=Truetriggers). Hard-codedFalsein Phase 1.5; Tier 2 follow-up.all-minions-returned-exit-earlyon cross-cluster publishes. Documented limitation — origin master cannot know peer minion lists at publish time without a protocol-level minion-set exchange.Test plan
tests/pytests/unit/topology/— 32 new test files (+5 extended), ~770 teststests/pytests/functional/topology/— fixtures + per-feature behavior tests under atopology-sandbox-style harnesstests/pytests/unit/cluster/consensus/— 400+ tests exercising the cluster-correctness extensionsdwoz/master-topology-build; last green on commitc302c8bdc70; current tip0981d01dcf5after today's doc/toctree and test-path fixupsScope
salt/topology/— new package (link, link_manager, router, breadcrumbs, summary, registry, migration, config schema)salt/cluster/consensus/— extensions (commit_index persistence, stale-CONFIG guards, pusher-table keying, topology state machine)salt/channel/server.py,salt/master.py,salt/key.py,salt/client/__init__.py— integration points for the new scopedoc/topics/master-topology/— architecture, overview, pub-ack designtests/pytests/{unit,functional,scenarios}/topology/— test suitestests/support/topology/cluster.py— test harnessTotal: 211 files, ~50k insertions, ~600 deletions. 100 commits.
Follow-ups for after merge
RemoteClient.pubcluster_retryhandling ships with this PR; its 3008.x counterpart cannot backport because RemoteClient depends on Manage Salt master clusters #70656 (Potassium-only)