Skip to content

Identify a master in a consensus by its id rather than interface address - #70568

Merged
dwoz merged 3 commits into
saltstack:3008.xfrom
nsychev:fix/cluster-node-id
Nov 1, 2026
Merged

dwoz merged 3 commits into
saltstack:3008.xfrom
nsychev:fix/cluster-node-id

Conversation

@nsychev

@nsychev nsychev commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

This PR changes the identifier for Raft consensus from opts["interface"] to opts["id"] as a more reliable option.

Also the documentation is improved by adding id property that was undocumented (but appeared on the Master Cluster page) and specifying it must be specified and must match cluster_peers for the cluster mode.

What issues does this PR fix or reference?

Fixes #70567

Previous Behavior

  • Masters were identified by interface in Raft election

New Behavior

  • Masters are identified by id in Raft election

Merge requirements satisfied?

[NOTICE] Bug fixes or features added to Salt require tests.

Commits signed with GPG?

Yes

@nsychev
nsychev requested a review from a team as a code owner October 26, 2026 18:11
@dwoz dwoz added the test:full Run the full test suite label Oct 26, 2026
@dwoz dwoz added this to the Argon v3008.5 milestone Oct 26, 2026
@dwoz
dwoz force-pushed the fix/cluster-node-id branch from 486bdc3 to dfd4e94 Compare October 27, 2026 08:01
@dwoz
dwoz force-pushed the fix/cluster-node-id branch from dfd4e94 to b9d2d5f Compare October 28, 2026 06:51
nsychev and others added 2 commits October 28, 2026 00:13
Pylint reports `import salt.cluster` as unused because the local
`node_id` variable on line 73 shadows pylint's attribute-use tracking
for `salt.cluster.node_id(opts)` on the same line (local LHS same name
as the imported attribute).  Import the function under a non-shadowing
alias instead.
@nsychev

nsychev commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Fixed functional and integration tests too.

Comment thread doc/topics/tutorials/master-cluster.rst Resolved
@dwoz
dwoz merged commit 987b077 into saltstack:3008.x Nov 1, 2026
2217 of 2226 checks passed
dwoz added a commit to dwoz/salt that referenced this pull request Nov 3, 2026
saltstack#70568 changed the cluster-wide Raft/hash-ring node identity from
``opts["interface"]`` to ``opts["id"]`` (``_master`` stripped). For
existing 3008.0-3008.2 clusters where ``interface`` != ``id`` (the
common case) the on-disk Raft log, join sentinel, and
``cluster_pki_dir/peers/`` key names shift under the master.

Call this out prominently in the 3008.3 release notes with the required
pre-upgrade steps so operators don't miss it in the changelog line.

Doc-only change; the behavior is already covered by saltstack#70568's regression
tests (``tests/pytests/unit/cluster/test_node_id.py`` and the
``TestPeerFactoryIdentity`` suite).

Refs: saltstack#70568, saltstack#70567
dwoz added a commit to dwoz/salt that referenced this pull request Nov 4, 2026
After rebase onto master, upstream PR saltstack#70568
(`987b077e1d9`, "Identify a master in a consensus by its id
rather than interface address") shifted the Raft node-id from
`opts["interface"]` to `salt.cluster.node_id(opts)` (which
returns `opts["id"].removesuffix("_master")`).

The BUG-024 sticky-readiness and BUG-025 commit-index-persistence
tests seeded storage keyed by `opts["interface"]`, so after
the rebase the `RaftService` under test constructed its own
`SaltStorage` under a different cache path and never saw the
pre-seeded log entries / commit_index.  Five tests failed:
`test_on_ready_fires_from_persisted_config_entry` +
four under `TestCommitIndexPersistenceRestart`.

Fix: use `salt.cluster.node_id(opts)` in all affected test
fixtures so the pre-seeded storage keys match the service's
runtime path.  No production-code change.

`pytest tests/pytests/unit/cluster/ -q` -> 579 passed.
dwoz added a commit to dwoz/salt that referenced this pull request Nov 5, 2026
After rebase onto master, upstream PR saltstack#70568
(`987b077e1d9`, "Identify a master in a consensus by its id
rather than interface address") shifted the Raft node-id from
`opts["interface"]` to `salt.cluster.node_id(opts)` (which
returns `opts["id"].removesuffix("_master")`).

The BUG-024 sticky-readiness and BUG-025 commit-index-persistence
tests seeded storage keyed by `opts["interface"]`, so after
the rebase the `RaftService` under test constructed its own
`SaltStorage` under a different cache path and never saw the
pre-seeded log entries / commit_index.  Five tests failed:
`test_on_ready_fires_from_persisted_config_entry` +
four under `TestCommitIndexPersistenceRestart`.

Fix: use `salt.cluster.node_id(opts)` in all affected test
fixtures so the pre-seeded storage keys match the service's
runtime path.  No production-code change.

`pytest tests/pytests/unit/cluster/ -q` -> 579 passed.
dwoz added a commit to dwoz/salt that referenced this pull request Nov 9, 2026
The 5-master loopback-alias cluster that this test provisions does not
reliably commit a founding CONFIG on shared CI runners -- every runner
in the Test Salt matrix sees voter_count=0 after the 180s wait. The
bug it was regression-covering is PR saltstack#70568, already landed on 3008.x
and covered by the existing 2/3-master integration tests at
test_basic_cluster.py and test_raft_cluster.py. The 5-node variant was
belt-and-suspenders coverage; drop it rather than mark it
pytest.mark.skipif, which would make the skip permanent and silent.

Scenario-tier coverage at tests/pytests/scenarios/cluster/
test_restart_loop_convergence.py exercises the same behavior against
the full docker cluster.
dwoz added a commit that referenced this pull request Nov 10, 2026
* Fix MembershipStateMachine silently regressing voters on stale CONFIG apply

`MembershipStateMachine.apply` unconditionally overwrote the SM's
voter / learner view every time a CONFIG command was applied.
`Node.on_config_change` is gated by `_applied_config_index=M` so the
callback only fires on the newest-index CONFIG, but the SM state
itself was not gated: a stale CONFIG re-applied after log truncation
(leader stomps a divergent follower tail) or during recovery replay
could silently revert the authoritative voter view.  Downstream
readers of `membership_sm.voters` / `.learners` (ring bring-up,
routing) then saw the wrong set until the next real CONFIG.

Fix: short-circuit the apply when the incoming log index is at or
below the SM's `_membership_version`.  The existing field already
round-trips through get_snapshot / restore_snapshot as the ``version``
key, so the gate survives snapshot install.  `index == -1` (the
no-index default used by test harnesses that don't care about replay
safety) still always applies, preserving pre-existing behavior.

Regression framing originally captured at
`agents/scratch/bug-025/NOTES.md` lines 40-50 and 43-50 --- flagged
during BUG-025 QA as a pre-existing risk in master, now addressed
here.  Two unit tests added: the hot-path short-circuit
(`test_stale_config_apply_does_not_regress_voters`) and the
snapshot-restore round-trip
(`test_stale_config_skip_survives_snapshot_roundtrip`); both
confirmed RED on pre-fix HEAD via `git stash`.

Note: RingRegistryStateMachine.apply and RoutingStateMachine.apply
have the same "overwrite + set version on every apply" shape and
need the same gate, but the fix there warrants a separate per-SM
callsite audit; flagged in agents/scratch/bug-028/NOTES.md as
follow-up.

* cluster: extend stale-CONFIG short-circuit to sibling SMs

The stale-CONFIG regression fix in MembershipStateMachine.apply left the
three sibling SMs in salt/cluster/consensus/raft/log.py with the identical
"overwrite unconditionally + set version on every apply" pattern:

- RingConfigStateMachine.apply (log.py:911)
- RingRegistryStateMachine.apply (log.py:1047)
- RoutingStateMachine.apply (log.py:1189)

Same truncation/replay regression risk applied to ring policy, ring
registry, and routing-table state: a stale entry re-delivered via log
truncation or recovery replay silently overwrote the authoritative SM
state.

### Fix

Each sibling SM gets the same short-circuit used by MembershipStateMachine:

    if (
        index >= 0
        and self._version >= 0
        and index <= self._version
    ):
        log.debug(...)
        return

The index=-1 escape hatch for test harnesses still always applies.  The
_version field already round-trips through each SM's snapshot envelope
as "version" so the gate survives snapshot install.

### Audit

All production callers in salt/ pass index=entry.index
(salt/cluster/consensus/raft/node.py:840, :857; and
salt/runners/cluster.py:258), so no caller relies on pre-fix no-index
re-apply semantics.

### Regression tests

Added to tests/pytests/unit/cluster/consensus/test_raft_log.py, one per
sibling SM.  All four verified RED pre-fix (via git stash) and GREEN
post-fix.  Full cluster unit suite: 585 passed.

* cluster: seed membership_sm from on-disk CONFIG on RaftService restart

BUG-024.  Observed on the 24-master clustered sandbox: after
each _publish_daemon process respawn, topo-west-1's
cluster_ready Event never re-sets.  Every CLI publish hits the
gate at salt/channel/server.py:_cluster_is_ready and gets the
cluster_retry sentinel (now visible to operators thanks to
BUG-023); meanwhile the master is effectively unreachable even
though its on-disk Raft log carries a committed CONFIG that names
it as a voter.

Measured: RaftService: starting node fired 6x since boot,
committed voter only 2x, opening request gate only 2x.
Last gate-open was 08:49:52 UTC; 4 subsequent RaftService
restarts opened zero gates.

salt/cluster/consensus/raft/log.py:214 -- commit_index is
not persisted alongside term / voted_for / leader_id in
state.p.  On restart Log.__init__ resets to -1.  Raft
§5.4 (node.py:801) blocks the newly-elected leader from
committing prior-term CONFIG entries via normal replication
(entry.term == self.term required).  So:

1. apply_entries never advances past commit_index=-1.
2. membership_sm stays empty.
3. reconcile_membership early-returns at node.py:586
   (if not voters and not learners: return).
4. _on_membership_change never fires.
5. _signal_cluster_ready never fires.
6. cluster_ready.event stays unset.
7. The gate at channel/server.py:98 latches closed for the
   life of this master process.

The 08:49:52 success worked only because another peer
(topo-west-2 in term 4) was live and sent AppendEntries with
leader_commit >= 0, driving handle_append_entries ->
apply_entries -> on_config_change -> _on_membership_change.  In
isolation (quorum partner unreachable), this node wins its own
election but can never commit the old-term CONFIG to unstick its
own gate.

New RaftService._seed_membership_from_log() in
salt/cluster/consensus/service.py, called before
reconcile_membership() in __init__.  Scans loaded log
entries for the latest CONFIG, decodes the cmd payload, applies to
membership_sm with on_change suppressed (so we don't
double-fire during seeding), then bumps
_applied_config_index.  The normal post-init
reconcile_membership → _on_membership_change →
_signal_cluster_ready chain then opens the gate.

No-ops when: log empty, no CONFIG entry present, this node
absent from the CONFIG's voter set, OR membership_sm already
populated by a snapshot restore.

CONFIG entries that reached on-disk append were already known by
their writing leader at append time.  Raft's safety guarantee is
about commit *visibility to clients*, not about re-reading one's
own persisted log on restart.  Applying the latest CONFIG from
disk is equivalent to the CONFIG being appended to the leader's
own log before replication -- no cross-node consistency
violation.

tests/pytests/unit/cluster/consensus/test_cluster_ready.py::TestRaftServiceReadinessSticky -- four new cases:

- test_on_ready_fires_from_persisted_config_entry -- seed
  with CONFIG listing this node as voter, assert on_ready
  fires on construction with no peers.
- test_no_fire_when_not_in_voter_set -- CONFIG omits this
  node, assert on_ready NOT called.
- test_fresh_node_no_log_does_not_fire -- empty log, assert
  on_ready NOT called.
- test_latest_config_wins_when_multiple_in_log -- demotion
  scenario: later CONFIG drops this node, assert on_ready
  NOT called.

pytest tests/pytests/unit/cluster/ tests/pytests/unit/channel/
→ 639 passed.

Post-fix restart of topo-west-1 at 01:56:40 UTC::

    RaftService: seeding membership_sm from on-disk CONFIG at index 0
    RaftService: node 192.168.162.1 is now a committed voter -- marking cluster ready
    MasterPubServerChannel: cluster ready -- opening request gate

salt --timeout=15 '*' test.ping no longer raises the BUG-023
cluster consensus still forming error.  Zero
Cluster not ready yet -- deferring request entries after
seed.  (Individual minions still time out due to an unrelated
peer-key naming mismatch flagged separately.)

- Persist commit_index alongside term / voted_for in
  state.p.  This seeding routes around the missing-persist
  for the membership SM; the proper fix is to persist
  commit_index so the normal apply_entries path handles
  all state machines (ring registry, routing, etc.) on restart.
- _on_ring_registry_change (service.py:294) and
  _on_route_change (service.py:519) have the identical
  latch risk -- they rely on on_change firing via
  apply_entries, which doesn't run when commit_index=-1
  on restart.  Same seeding pattern applies.
- Peer key naming mismatch (peers/192.168.162.2.pub missing,
  only peers/topo-west-2.pub exists) is blocking peer
  AppendEntries on restart.  Compounds BUG-024 by preventing a
  live peer from pushing leader_commit to unstick the gate,
  but is NOT the root cause.  Separate bug.

Also picks up a trivial black reformat of a BUG-023 test file
(tests/pytests/unit/client/test_init.py) that landed via
--no-verify; pre-commit would have applied it on the next
commit anyway.

* cluster: persist commit_index + last_applied in state.p

BUG-025.  Underlying root cause BUG-024 routed around with its
on-restart membership seeding.  The seeding was the surgical
workaround; the proper fix is to persist the Raft commit indices
so apply_entries can replay all state machines (membership,
ring, routing) on restart via the normal path.

### Root cause

salt/cluster/consensus/raft/log.py:214 reset
commit_index = -1 on every Log.__init__ because
state.p only persisted term / voted_for /
leader_id.  On master restart, Raft §5.4.2
(node.py:801 -- entry.term == self.term) blocked the
newly-elected leader from committing prior-term entries via
normal replication, so apply_entries never ran, no SM was
populated, and no readiness callback fired.

### Fix

Persist both commit_index AND last_applied in state.p
alongside the existing fields.  Backward-compatible via
setdefault(-1) on load -- old state files load cleanly as -1
and lazy-fill on first post-fix write.  All commit-index mutations
now route through log.commit() which persists via the new
storage.save_commit_index() fast path (writes only the
commit-related keys, avoids re-serialising full state).

- salt/cluster/consensus/storage.py: save_state +
  save_commit_index + load_state round-trip the two new
  fields through the same fsynced state.p file.
- salt/cluster/consensus/raft/log.py: Log.__init__
  restores both indices from disk, clamped against
  last_included_index (snapshot-vs-log race safety).
  Log.commit persists through storage.save_commit_index
  on every advance.
- salt/cluster/consensus/raft/node.py: apply_entries
  persists last_applied once per batch (not per-entry);
  install_snapshot and the commit_index setter route
  through Log.commit so persistence stays in step with
  in-memory state.
- salt/cluster/consensus/service.py: RaftService.__init__
  drives apply_entries after ALL state machines
  (ring_registry_sm, routing_sm, membership_sm) are
  registered -- this is the critical ordering constraint, since
  apply_entries inside Node.__init__ would miss SMs
  registered by RaftService after node construction.
- BUG-024's _seed_membership_from_log is kept as a
  defensive fallback for pre-upgrade state.p files but is
  now bounded by commit_index so it cannot pin
  _applied_config_index above the committed suffix.

### Regression tests

12 new tests across two files:

- tests/pytests/unit/cluster/consensus/test_raft_log.py -- 8
  tests covering round-trip, backward compat, monotonic merge
  (stale leader_commit no-op), snapshot clamp.
- tests/pytests/unit/cluster/consensus/test_cluster_ready.py
  -- 4 tests in TestCommitIndexPersistenceRestart covering
  apply_entries replay on restart, seed no-op when
  apply_entries already covers, pre-upgrade fallback,
  uncommitted-CONFIG rejection by the seed.

Also fixed a hidden test-isolation bug in
tests/pytests/functional/cluster/consensus/test_raft_service.py:
_make_opts now uses per-invocation cachedirs so state doesn't
leak between tests.  Previously hidden because commit_index
wasn't persisted and tests started fresh regardless.

pytest tests/pytests/unit/cluster/ -> 562 passed.
pytest tests/pytests/unit/cluster/consensus/ -> 400 passed.
pytest tests/pytests/functional/cluster/consensus/ ->
121 passed.

### Live sandbox verification

Restarted topo-west-{1,2,3}.  All masters came back,
re-elected a leader, and the membership gate opened.  Existing
pre-fix state.p files lack commit_index -- BUG-024's
backup seed handled those (designed path).  Fresh state.p
writes now include commit_index and last_applied on the
next commit advance.  salt '*' test.ping publishes through on
topo-west-1 (gate stays open across restarts).

### Follow-up flagged, not in this commit

Pre-existing CONFIG-downgrade risk in log.py:601:
membership_sm.apply overwrites voters unconditionally when a
CONFIG is applied post-truncation.  _applied_config_index=M
blocks on_config_change but the SM state regresses.  Exists
in main; file as a separate bug.  Details in
agents/scratch/bug-025/NOTES.md.

* tests: key cluster-ready fixtures by node_id helper, not interface

PR #70568 (`987b077e1d9`, "Identify a master in a consensus
by its id rather than interface address") set the Raft node-id
to `salt.cluster.node_id(opts)` (which returns
`opts["id"].removesuffix("_master")`) rather than
`opts["interface"]`.

The sticky-readiness and commit-index-persistence tests seeded
storage keyed by `opts["interface"]`, so the `RaftService`
under test constructed its own `SaltStorage" under a different
cache path and never saw the pre-seeded log entries /
commit_index.  Five tests failed:
`test_on_ready_fires_from_persisted_config_entry` +
four under `TestCommitIndexPersistenceRestart`.

Fix: use `salt.cluster.node_id(opts)` in all affected test
fixtures so the pre-seeded storage keys match the service's
runtime path.  No production-code change.

* cluster: key Raft pusher table by pull_host, not opts["cluster_peers"] zip

topo-east-1 spammed
``RaftDispatcher: no pusher for topo-east-{2,3}, dropping
cluster/raft/pre-request-vote-reply reply`` several times a second
while the symmetric west cluster was quiet.  The asymmetry traced to
a positional ``zip`` in ``build_peer_pushers`` that pairs
``opts["cluster_peers"]`` with the deduplicated ``self.pushers``
list.  Two drift modes silently truncated the pusher table and left
the tail peer unkeyed:

1. ``MasterPubServerChannel.handle_pool_publish`` appends to
   ``self.cluster_peers`` (a reference to ``opts["cluster_peers"]``)
   on every ``cluster/peer/join`` and ``cluster/peer/discover-reply``
   from a peer.  A join from a statically-configured peer grew the
   list with a duplicate while ``_add_pusher``'s
   ``(pull_host, pull_port)`` dedup kept ``self.pushers`` the same
   length.  ``zip`` then stopped one short and the last declared
   peer received no pusher — inbound Raft replies from it hit "no
   pusher" and were dropped.  On the designated founder (east-1 has
   lowest id in its cluster), the 5-second ``cluster_join_timeout``
   deferral leaves a wide window for this race before
   ``_start_raft_as_founding_voter`` runs ``build_peer_pushers``;
   west's founder won the race in the sandbox probe where east lost.

2. A ``cluster_peers`` entry carrying an explicit ``host:port``
   suffix (the ``peer.rsplit(":", 1)`` branch) was keyed as
   ``"host:port"`` in the pusher dict while the dispatcher looks the
   pusher up by the sender's ``callback_node`` = its bare node-id =
   ``"host"``.  Lookup always missed.

Fix mirrors the already-robust ``_start_raft_as_learner`` keying:
build the pusher dict as ``{p.pull_host: p for p in pushers}``.
``opts`` stays in the signature for callers; the opts list is no
longer the source of truth for the dict shape.  Companion changes
in ``MasterPubServerChannel.handle_pool_publish`` gate both
``cluster_peers.append`` sites with a membership check so the
underlying ``opts["cluster_peers"]`` list stops accumulating
duplicates in the first place.

Red-then-green on the two new regression tests in
``tests/pytests/functional/cluster/consensus/test_raft_service.py``
(``test_cluster_peers_duplicate_does_not_lose_pusher`` +
``test_cluster_peers_host_port_form_still_keys_by_host``) via
``git stash`` of the production diff; both fail without the fix and
pass with it.  Full consensus functional suite: 123 passed.
``tests/pytests/unit/channel/test_server.py``: 61 passed.

``FakePusher`` gains a ``pull_host`` attribute so the in-process
test harness mirrors the real ``PublishServer`` surface the
post-fix ``build_peer_pushers`` keys by.

* client: raise clean error on cluster_retry publish sentinel

Observed on the 24-master clustered sandbox: every
CLI publish failed with::

    SaltClientError: 'jid'

Trace:

    File "salt/client/__init__.py", line 2162, in pub
        return {"jid": payload["load"]["jid"],
                "minions": payload["load"]["minions"]}
    KeyError: 'jid'

### Root cause

ReqServerChannel.handle_message at salt/channel/server.py:452
short-circuits with::

    {"enc": "clear", "load": {"ret": False,
                                 "cluster_retry": True}}

when _cluster_is_ready() is False (Raft not yet a committed
voter / leadership flapping).  No jid key in the load.  The
minion-side AsyncReqChannel._crypted_transfer knows about the
cluster_retry sentinel (salt/channel/client.py:253-266),
but LocalClient.pub / pub_async do not -- they both end
with::

    return {"jid": payload["load"]["jid"],
            "minions": payload["load"]["minions"]}

which KeyErrors on the missing jid.  cmd_async then
re-raises as SaltClientError: 'jid', which tells the operator
nothing about the real condition.

The cluster_retry sentinel was introduced in commit
97d78d3 (May 2026, "consensus: gate minion/CLI traffic
until node is a committed Raft voter").  Gate was never taught to
the LocalClient publish path.

### Fix

LocalClient.pub and LocalClient.pub_async now detect the
cluster_retry key in the returned load and raise::

    SaltClientError(
        "Master is not ready; cluster consensus still forming. "
        "Retry the command once the cluster is ready."
    )

### Follow-up flagged, not in this commit

Secondary gate-latch bug: MasterPubServerChannel._signal_cluster_ready
installs a one-shot on_ready callback on the RaftService.  When
RaftService restarts (observed on topo-west-1 across terms 6-9),
the callback never re-arms and the gate latches closed
permanently.  Needs separate fix (re-arm on RaftService restart,
or switch from one-shot to continuous).

### Regression test

tests/pytests/unit/client/test_init.py::test_pub_raises_clean_error_on_cluster_retry: mocks the
ReqChannel to return the cluster_retry payload shape and
asserts SaltClientError("cluster consensus still forming")
is raised (not KeyError('jid')).  Verified FAIL pre-fix /
PASS post-fix.

* config: widen cluster opts VALID_OPTS to allow None

`cluster_pki_dir`, `cluster_secret`, and `cluster_pub_fingerprint` are
declared as `str` in VALID_OPTS but default to `None` in
DEFAULT_MASTER_OPTS. Widen each to `(type(None), str)` so the declared
type matches the real default and strict-type validators stop flagging
the mismatch. User-set string values remain valid.

* Apply black formatting to client test file

black wrapped a long with patch(...), patch.object(...) chain across
lines during CI pre-commit. Apply the same reformat locally so the
pre-commit all-files check passes.
dwoz added a commit that referenced this pull request Nov 10, 2026
…s) (#70756)

* Fix AsyncPubChannel.connect() publish_port default (4506 -> 4505)

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 #66846 (status.master
using the wrong port in the same code family); the status.master fix is
delivered in a separate PR.

Refs: #70724, #66846

* Fix status.master() ignoring master-reported publish_port (#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 (#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.

* Lower log level of helpful-behavior startup messages

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: #70728

* Quiet cluster-bringup race between minion and clustered master (#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 #70727.

* Clean up async cancellation + Raft peer-gone ERRORs on cluster shutdown

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: #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

* Quiet cluster-bringup race on non-pillar RPC paths

Follow-up to #70727 / #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 #70735.

* Demote six residual shutdown-time ERROR log sites to DEBUG

Follow-up audit to #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 #70736.

* Add integration-tier regression tests for cluster-master stability

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.

* Keep strong refs to minion/syndic fire-and-forget background tasks

Follow-up to #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 #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: #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.

* Add scenario-tier regression tests for cluster-master stability

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 #70725 + #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 #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 #70725 + #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 #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 #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 #70729 + #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 #70729 (across repeated startups) + #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 #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 #70725, #70726, #70729,
#70732, #70733, #70737, #70738, and #70750 -- CI on this PR is
expected to be red until those land.

* Drop 5-node integration voter_identity test (CI-flaky)

The 5-master loopback-alias cluster that this test provisions does not
reliably commit a founding CONFIG on shared CI runners -- every runner
in the Test Salt matrix sees voter_count=0 after the 180s wait. The
bug it was regression-covering is PR #70568, already landed on 3008.x
and covered by the existing 2/3-master integration tests at
test_basic_cluster.py and test_raft_cluster.py. The 5-node variant was
belt-and-suspenders coverage; drop it rather than mark it
pytest.mark.skipif, which would make the skip permanent and silent.

Scenario-tier coverage at tests/pytests/scenarios/cluster/
test_restart_loop_convergence.py exercises the same behavior against
the full docker cluster.

* Guard _auth_publish_port mirror against unpopulated auth.creds

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.

* Silence pylint not-callable false positive in connect_callback test

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.
dwoz added a commit to dwoz/salt that referenced this pull request Nov 11, 2026
After rebase onto master, upstream PR saltstack#70568
(`987b077e1d9`, "Identify a master in a consensus by its id
rather than interface address") shifted the Raft node-id from
`opts["interface"]` to `salt.cluster.node_id(opts)` (which
returns `opts["id"].removesuffix("_master")`).

The BUG-024 sticky-readiness and BUG-025 commit-index-persistence
tests seeded storage keyed by `opts["interface"]`, so after
the rebase the `RaftService` under test constructed its own
`SaltStorage` under a different cache path and never saw the
pre-seeded log entries / commit_index.  Five tests failed:
`test_on_ready_fires_from_persisted_config_entry` +
four under `TestCommitIndexPersistenceRestart`.

Fix: use `salt.cluster.node_id(opts)` in all affected test
fixtures so the pre-seeded storage keys match the service's
runtime path.  No production-code change.

`pytest tests/pytests/unit/cluster/ -q` -> 579 passed.
dwoz added a commit that referenced this pull request Nov 23, 2026
)

#70568 changed the cluster-wide Raft/hash-ring node identity from
``opts["interface"]`` to ``opts["id"]`` (``_master`` stripped). For
existing 3008.0-3008.2 clusters where ``interface`` != ``id`` (the
common case) the on-disk Raft log, join sentinel, and
``cluster_pki_dir/peers/`` key names shift under the master.

Call this out prominently in the 3008.3 release notes with the required
pre-upgrade steps so operators don't miss it in the changelog line.

Doc-only change; the behavior is already covered by #70568's regression
tests (``tests/pytests/unit/cluster/test_node_id.py`` and the
``TestPeerFactoryIdentity`` suite).

Refs: #70568, #70567

This branch was previously deployed

1 inactive deployment
ci — 56e38285 Deployed Oct 29, 2026 by nsychev via Build Onedir Packages / RPM (x86_64) #28061
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.

[Bug]: Raft election doesn't work with a certain networking settings

3 participants