Skip to content

Close arm64 cluster cache-replication race class - #70831

Merged
dwoz merged 14 commits into
saltstack:3008.xfrom
dwoz:fix/arm64-race-closure
Nov 18, 2026
Merged

dwoz merged 14 commits into
saltstack:3008.xfrom
dwoz:fix/arm64-race-closure

Conversation

@dwoz

@dwoz dwoz commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Note: no changelog entry — the races this PR closes were introduced by #70773 which is milestoned for the same unreleased Argon v3008.7. #70773's changelog entry already covers user-visible release-notes text; this PR is a pre-release race-fix pass before that feature ships.

Summary

Close 5 arm64 cluster cache-replication races surfacing as nightly test failures on saltstack/salt-nightlies 3008.x after #70773 merged (runs 43780520102 + follow-ups). The 5 commits are the Phase-3 implementation of the Phase-1 race-matrix review (agents/reports/followup-race-matrix-reviewer.md) and the Phase-2 reviewer-corrected design (agents/reports/design-arm64-race-closure-reviewer.md).

  • NEW-10 (collect-from-peers): gate fan-out + per-peer peers_eofed set on the completion sentinel so a straddler peer cannot false-complete a run. Closes test_jobs_migration_round_trip collect-sentinel timeouts.
  • NEW-6 / NEW-7a (sync_roots + multi-ring runner fan-outs): apply the same handshake gate with pending_event=None so un-joined peers skip with a WARN. Closes documented correctness defects.
  • NEW-9 (steady-state pending-flush): periodic 2 s sweep + per-peer asyncio.Lock flush-latch that serialises sweep drains against live publishes. live wins over stale preserved under last-writer-wins. Closes stranded-queue hazard where a peer joined after enqueue but no further handshake event fired. Closes test_grains_replicate_across_cluster_peers + test_resource_registry_replicates.
  • D-1b (fingerprint stamp): PendingEvent carries a cluster_aes_fp stamp at encrypt time. Flush path drops mismatches (and any <unavailable> sentinel on either side) with a loud WARN so a rotation racing the encrypt+enqueue window no longer causes silent Failed to decrypt on peers.
  • NEW-4 (_cache_bank_barriers lock): plain threading.Lock makes the check-then-act in _handle_delegate_cache_write atomic against concurrent _release_cache_bank_barrier / _drain_cache_bank_barrier on the event-loop thread. Snapshot-under-lock-then-release keeps the lock non-reentrant.

Each fix is a separate commit for bisect friendliness, in reviewer-approved order (lowest-risk-highest-leverage first, highest-risk last).

Nightly tests this closes

From saltstack/salt-nightlies 3008.x run 43780520102 (after #70773's squash-merge landed at eae114eaeaa):

Failing test Slice Fix
test_cache_replication.py::test_grains_replicate_across_cluster_peers AL2023 Arm64 int zmq 3 NEW-9 (stranded-queue steady-state flush — gate-skipped grain writes were stranded when no later handshake event re-fired)
test_cache_replication.py::test_resource_registry_replicates Ubuntu 22.04 Arm64 tcp 3 NEW-9 (same mechanism for the resources bank)
test_jobs_migration.py::test_jobs_migration_round_trip Ubuntu 22.04 Arm64 tcp 3 NEW-10 (collect-from-peers was sizing expected_peers from unfiltered pushers; a mid-handshake peer kept the completion sentinel below complete=True until the 180s timeout)

Out of scope (filed as separate 3008.x follow-ups):

  • test_isolated_cluster.py::test_isolated_sync_roots_runner_file_only — source carries a # CI flake in run 42790718166 annotation; pre-existing arm64 timing flake independent of this PR
  • test_ring_lifecycle.py::test_ring_create_route_destroy_round_trip — Raft log-tail propagation, independent of cache-replication; filed separately

Also surfaced during Phase-1/Phase-2 review but not firing in named nightly tests yet (defense-in-depth coverage this PR adds):

  • _run_root_sync_to_peers + _fanout_multi_ring_request bypassed filter_joined_pushers (NEW-6 / NEW-7a)

  • _cache_bank_barriers check-then-act was unprotected against the executor/event-loop concurrency boundary (NEW-4)

  • cluster_aes rotation could race the encrypt+enqueue window and leave stale bytes in the pending queue after drop_all_pending (D-1b)## Test plan

  • Unit: tests/pytests/unit/cache/test_cluster_replicator.py + tests/pytests/unit/channel/test_{cache_bank_barrier_lock,collect_from_peers_gate,sync_roots_multi_ring_gates,pending_flush_sweep,cluster_state_sync_cache_banks}.py — 1014 passed, 1 skipped locally

  • 1M-SR stress test on 3-master arm64-timed sandbox: zero Failed to decrypt across all masters under full load, memory parity vs. pre-5-commits baseline, no fd leak

  • Nightly saltstack/salt-nightlies 3008.x arm64 integration-3 slices green (AL2023 arm64, Rocky 8 arm64, Ubuntu 22.04 arm64 tcp, Photon 4 arm64)

@dwoz
dwoz requested a review from a team as a code owner November 16, 2026 23:34
@dwoz dwoz added the test:full Run the full test suite label Nov 16, 2026
@dwoz dwoz added this to the Argon v3008.7 milestone Nov 16, 2026
@dwoz
dwoz force-pushed the fix/arm64-race-closure branch from a550a15 to 6acb165 Compare November 17, 2026 08:00
dwoz added a commit to dwoz/salt that referenced this pull request Nov 18, 2026
The unified cluster-key state machine commits via ``mark_committed``
only in the receiver install path.  A founding master never receives
its own locally-generated ``cluster_aes`` / ``cluster.pem`` via
``cluster/peer/join-reply`` -- it generated them itself at startup
via ``MasterKeys._setup_keys`` / ``find_or_create_keys``.  So the
founder's state machine stayed in BOOTSTRAP forever and the
sentinel file was never written.

Observable impact (PR saltstack#70831 run 44184265603 Debian 12 Arm64 int
zmq 3, confirmed from CI log artifact):

  * Each master restart within a test (test-harness retries, fixture
    teardowns) finds a missing sentinel -> ``verify_committed_state_
    on_startup`` returns ``BOOTSTRAP``, and if the on-disk key was
    also removed between restarts (e.g. function-scoped ``tmp_path``)
    ``find_or_create_keys`` regenerates a fresh random key.
  * Peers that already COMMITTED the previous value refuse the new
    one with the ``differs from committed; refusing install`` WARN
    (expected state-machine behaviour), and the cluster never
    converges.  Minion<->master auth then fails because the minion's
    cached master.pub does not match the master's post-restart
    master_key.key.

Fix at the founder-election site in
``_start_raft_as_founding_voter``: right after the join sentinel is
written, read the on-disk ``cluster_aes`` + ``cluster.pem`` bytes
and call ``sm.mark_committed(...)`` for each.  That writes the
state-machine sentinel + sets the in-memory shadow, so subsequent
restarts hit ``verify_committed_state_on_startup`` -> ``COMMITTED``
and stay authoritative.

Three new unit tests exercise:
  * commit transitions both keys to ``STATE_COMMITTED`` with correct
    fingerprints
  * sentinels land on disk and match ``fingerprint_bytes``
  * missing on-disk keys at election time -> both keys stay in
    ``STATE_BOOTSTRAP`` (receiver path remains available)

Local run: ``tests/pytests/unit/channel/`` + ``tests/pytests/unit/
cache/`` green; pre-commit clean on the two touched files.
dwoz added 14 commits November 17, 2026 17:24
NEW-10 (arm64 race closure, phase 1 of 5).

* ``_run_collect_from_peers`` consults ``filter_joined_pushers`` before
  sizing ``expected_peers`` so the sentinel's completion threshold is
  set from the kept set, not the raw ``self.pushers`` list.  Un-joined
  peers are enumerated in ``skipped_peers`` on the sentinel JSON for
  operator forensics.  ``pending_event=None`` keeps the "skip + WARN,
  no replay" contract -- a PULL cannot be meaningfully re-played
  because the sentinel's ``expected_peers`` is scoped to one run.
  Empty-kept aborts BEFORE emitting any collect-request and writes a
  deterministic sentinel.

* Reviewer correction #2 (per-peer EOF tracking): ``_record_collect_chunk``
  now takes an optional ``source_peer`` kwarg and the sentinel's
  per-channel state carries a ``peers_eofed`` sorted list.  The
  completion check is ``peers_eofed >= set(expected_peers)`` per
  channel, not a monotonic ``eofs_seen`` counter.  Without per-peer
  identity, a SKIPPED peer whose cluster_aes install races the
  fan-out and emits an eof could flip ``complete=True`` with
  ``eofs_seen == len(kept)`` before every kept peer actually eofed.
  Peer attribution is carried on the wire via a new ``source_peer``
  field in the ``sync-roots-begin`` payload emitted by
  ``_handle_collect_request``; ``_begin_root_sync_session`` stashes it
  on the session so ``_apply_state_sync_chunk`` can forward to
  ``_record_collect_chunk``.  The ``eofs_seen`` counter is kept for
  back-compat with external operator tooling that reads the sentinel.

* Reviewer correction Q4 (runner.py in scope): ``cluster.collect_from_peers``
  returns a backwards-compatible dict with two new informational keys
  (``sentinel_path``, ``skipped_peers_note``).  Scripts that key on
  ``.get("status") == "fan-out initiated"`` keep working.

Primary design doc: §Fix 2 (NEW-10).
Reviewer audit: correction #2 (per-peer sentinel), Q4 (runner scope).
NEW-6 + NEW-7a (arm64 race closure, phase 2 of 5).

* ``_run_root_sync_to_peers``: wrap ``self.pushers`` through
  ``filter_joined_pushers`` with ``pending_event=None`` before the
  per-peer send loop.  Un-joined peers are enumerated in a WARN and
  catch up via the join-time state-sync (sync_roots is a multi-event
  session; pending-queue replay would duplicate chunks against the
  join-time catch-up).

* ``_fanout_multi_ring_request``: same gate, same ``pending_event=None``.
  The Raft log replication layer carries the committed entry to a
  skipped peer independently of the fan-out; replaying a multi-ring
  request would duplicate propose attempts (idempotent at Raft but
  noisy).

* Reviewer correction Q4: runner return payloads carry a
  ``skipped_peers_note`` key pointing operators at the master-log
  signal (``cluster.sync_roots: skipping un-joined peers`` /
  ``multi-ring fan-out: skipping un-joined peers``).  Shape is
  backwards-compatible: existing ``status: "fan-out initiated"``
  scripts continue to work; ``skipped_peers_note`` is purely
  informational.

Primary design doc: §Fix 4 (NEW-6) + §Fix 5 (NEW-7a).
Reviewer audit: Q4 (runner scope).
NEW-9 (arm64 race closure, phase 3 of 5).

Introduces a per-peer ``asyncio.Lock`` (flush-latch) that serialises
``flush_pending_for_peer`` (handshake-driven drain, scheduled from
``_schedule_pending_flush``) against live ``publish_cache_write`` /
``publish_resource_register_write`` on the SAME peer.

Without the latch, a live publish that arrives mid-drain can land on
the peer socket BEFORE the drain finishes publishing its stale
entries.  For ``(bank, key)`` last-writer-wins buckets this reorders
as "stale wins", corrupting peer state.  Holding the latch across
both paths forces the drain's stale entries to land first, then the
live entry -- under last-writer-wins the peer converges to the live
value ("live wins over stale").

Implementation details:

* ``_PENDING_PEER_LATCHES`` dict + ``_PENDING_PEER_LATCHES_SYNC``
  threading.Lock guard the per-peer lock registry.
* ``_get_peer_latch(peer_host)`` returns the per-peer asyncio.Lock,
  creating it on first touch.  Bounded by N_peers; no eviction.
* ``publish_with_latch(peer_host, pusher, event)`` wraps a live
  ``pusher.publish`` in ``async with latch`` so it waits for an in-
  flight drain.
* ``flush_pending_for_peer`` acquires the SAME per-peer latch across
  its entire drain+publish sequence.
* Both live-publish sites (``publish_cache_write`` and
  ``publish_resource_register_write``) route through
  ``publish_with_latch`` for each kept peer.

``asyncio.Lock`` is appropriate because both drain and live publish
run as asyncio tasks on the publish daemon's event loop; a sync
``threading.Lock`` would deadlock on the loop thread when the
holding coroutine awaits.

Reviewer audit: correction #3 (per-peer latch) kept as the useful
output of the NEW-9 investigation.  The originally-paired periodic
pending-queue sweep is dropped: CI evidence from run 43983101731
showed arm64 integration-3 failures are a cluster_aes divergence
upstream of the pending queue, not a pending-flush starvation, so
the sweep closes nothing (see Agent saltstack#148's followup-new9-not-
closing-primary.md diagnosis).  The founder-only cluster_aes gate
addresses the real cause in a separate commit.
D-1b (arm64 race closure, phase 4 of 5).

Closes the ``read T0 cluster_aes → rotation T1 → encrypt T2 → enqueue
post-drop`` race window.  Entries that were encrypted under a stale
``cluster_aes`` would otherwise be published to a peer after rotation
and fail to decrypt silently; the fingerprint comparison promotes
that failure to a loud sender-side drop.

* ``PendingEvent`` carries a new ``cluster_aes_fp`` field (default
  ``"<unavailable>"``).  Both publish sites (``publish_cache_write``
  and ``publish_resource_register_write``) stamp it from the
  ``cluster_aes`` value they encrypted under via ``secret_fingerprint``.

* ``flush_pending_for_peer`` compares each entry's stamped fp against
  ``_current_cluster_aes_fp()`` and drops mismatches with a per-entry
  WARN + a summary WARN at the end of the flush.

* Reviewer correction Q3: drop on ANY ``<unavailable>`` sentinel
  (either side), not "publish on symmetric sentinel" as the primary
  chose.  Symmetric ``<unavailable>`` means we cannot verify
  stability; the safer failure mode is false-drop (operator re-runs
  the write) over false-publish (silent corruption on the peer).

Test-suite plumbing:

* Existing ``test_cluster_replicator.py`` tests autouse-patch
  ``_current_cluster_aes_fp`` to the test's default stamped value so
  the flush path accepts their entries.  Four new tests exercise the
  mismatch, unavailable-on-either-side, and mixed-matching-stale paths.

* ``test_multi_ring_fanout.py`` (pre-existing, NEW-7a gated it in
  commit 2) opts the gate off via
  ``cluster_cache_replicate_require_joined=False`` so the fan-out
  reaches un-joined fake pushers.  Cleaner than threading
  _discover_replies state into every test case.

Primary design doc: §Fix 6 (D-1b).
Reviewer audit: correction Q3 (drop on either <unavailable>).
NEW-4 (arm64 race closure, phase 5 of 5).

Final commit in the race-closure series.  Highest-risk change goes
last so any regression is bisect-pinnable to this commit alone.

* Adds per-channel ``_cache_bank_barrier_lock`` (lazy-init via
  ``_ensure_cache_bank_barrier_lock``) protecting the five sites
  that mutate ``_cache_bank_barriers``:
  1. ``_handle_delegate_cache_write`` (executor-thread check+enqueue)
  2. ``_cache_bank_barrier_active`` (now a locked wrapper over
     ``_cache_bank_barrier_active_locked``)
  3. ``_queue_cache_bank_delta`` (same split)
  4. ``_release_cache_bank_barrier`` (event-loop-thread: snapshot
     queue + session-bank set under lock; replay OUTSIDE the lock
     so free-function disk / mmap work doesn't serialise executor
     threads)
  5. ``_drain_cache_bank_barrier`` (snapshot bank list under lock,
     release the lock, then call ``_release_cache_bank_barrier``
     per bank -- each re-acquires)
  6. ``_begin_state_sync_session`` barrier dict assignment

* Reviewer correction #4: plain ``threading.Lock``, NOT ``RLock``.
  The only re-entrant call site (``_drain`` -> ``_release``) is
  refactored to snapshot-under-lock-then-release so no re-entry
  happens.  Plain Lock is strictly faster than RLock and easier to
  audit for deadlock.

* Lock-ordering (unchanged from design cross-cutting section):
  ``SMaster.secrets["cluster_aes"]["lock"]`` →
  ``_cache_bank_barrier_lock`` → ``_PENDING_LOCK`` →
  ``_SKIP_LOG_LOCK``.  No path acquires out of order.

* Reviewer-mandated actual-concurrency unit test:
  ``test_check_and_enqueue_atomic_under_concurrent_release`` uses
  ``threading.Barrier(2)`` to force two threads into the check-
  then-act window simultaneously and asserts the delta is applied
  exactly once in either ordering (NEVER silently dropped).  The
  primary's "sleep inside the lock" approach is rejected because
  it only serialises -- it does not prove check-and-act atomicity.

* Companion test-harness update in
  ``test_cluster_state_sync_cache_banks.py``: expose the new
  ``_ensure_cache_bank_barrier_lock`` + ``_locked`` variants on the
  ``_BarrierHarness`` so existing barrier tests continue to drive
  the same lock-acquisition paths as production.

Changelog entry (``changelog/70780.fixed.md``) consolidates all five
fixes in the PR as reviewer specified.

Primary design doc: §Fix 1 (NEW-4).
Reviewer audit: correction #1 (plain Lock vs. RLock) +
corrected test methodology (threading.Barrier(2), not sleep).
Addresses the actual root cause of the arm64 integration-3 cluster-
replication failures: a non-founder master in the three-master
bootstrap window can install a locally-generated bootstrap
``cluster_aes`` and then reply to a third master's
``cluster/peer/discover`` with that bootstrap value in the
``cluster/peer/join-reply`` inner payload, racing the founder's
join-reply on the receiver.  When the non-founder's reply lands
last, the receiver overwrites the founder's authoritative
``cluster_aes`` and the cluster diverges.

CI timeline (Agent saltstack#148's diagnosis, run 43983101731,
``followup-new9-not-closing-primary.md``):

  05:47:33.403  m2 installs cluster_aes from m1 (founder)
  05:47:45.826  m2 installs cluster_aes from m3 (overwrites m1's)
  05:47:47.136  m3 installs cluster_aes from m1
  05:47:47.724  m3 installs cluster_aes from m2 (= m3's bootstrap)

Final state: ``m1 != m2 == m3``.  Delegate-cache-write events from
m1 (encrypted under m1's cluster_aes) then fail to decrypt on m2/m3
every time, producing the ``cluster-decrypt-failed: tag=cluster/
peer/delegate-cache-write ... handshake incomplete or cluster_aes
mismatch`` errors seen in the CI log.

Two-layer defence:

* **Sender gate** (``cluster/peer/join`` handler,
  ``salt/channel/server.py`` ~line 5090): the responder now
  consults ``is_designated_cluster_founder(self.opts)`` before
  attaching ``inner_payload["cluster_aes"]``.  Non-founders omit the
  field and log an INFO explaining why.  They still ship
  ``cluster_pem`` / ``cluster_pub`` (static per-cluster material)
  and the ``aes`` secret for the master-to-minion AES key -- only
  the cluster-wide session key is founder-gated.

* **Receiver filter** (``cluster/peer/join-reply`` handler,
  ``salt/channel/server.py`` ~line 4728): the install path now
  routes the inner payload through
  ``filter_non_founder_cluster_aes_from_join_reply`` which drops
  ``cluster_aes`` when ``inner["peer_id"]`` is not the designated
  founder of OUR configured cluster.  Logs a WARN so operators see
  divergence attempts in the master log.

Founder predicate (``_cluster_bootstrap_founder_id``) matches the
bootstrap decision at ``_publish_daemon`` line ~4222: the lowest
id in ``sorted({node_id, *cluster_peers})`` is the founder.  This
is deterministic from static config, so every master in the
cluster agrees on founder identity without network round-trips.

New unit tests in
``tests/pytests/unit/channel/test_cluster_aes_founder_only.py``
cover:
  - founder predicate (lowest-id, mid-id, highest-id, single-master,
    multi-id cross-check against the bootstrap decision),
  - receiver filter accepts cluster_aes from founder,
  - receiver filter drops cluster_aes from non-founder,
  - receiver filter does not mutate the caller's dict,
  - receiver filter passes through when no cluster_aes present,
  - receiver filter drops when sender id is missing (defence-in-
    depth against malformed payloads),
  - founder's own identity path is preserved,
  - non-dict input does not crash the filter.

Expected integration regression:
``tests/pytests/integration/cluster/test_cache_replication.py::
test_isolated_cluster_aes_converges`` -- previously treated as a
flaky canary -- becomes deterministic PASS with this fix in place.
It is the signal the suite has been showing all along; see the
"Isolated cluster_aes divergence" entry in Agent saltstack#148's report for
why NEW-9's instrumentation plan would not have reached this cause.
Commit 6 (``6acb1653613``) introduced two identity-based defences
against the three-master bootstrap race on ``cluster_aes``:

1. Sender-side founder gate in the ``cluster/peer/join-reply`` builder:
   only the designated founder attaches ``cluster_aes`` to the inner
   payload.
2. Receiver-side identity filter in
   ``filter_non_founder_cluster_aes_from_join_reply``: drops the field
   when the sender isn't the designated founder.

The pair closes the pure-bootstrap race but **permanently breaks
late-joiner propagation** (reviewer §6 of
``followup-minion-auth-reviewer.md``): once the founder dies, a
surviving non-founder cannot deliver ``cluster_aes`` to a brand-new
master joining through it -- the sender omits the key by identity and
the receiver filter would drop it even if it were included.

This commit reverses commit 6's identity gates in preparation for the
unified cluster-key propagation primitive (next commit).  Behaviour
change: ``cluster_aes`` is now unconditionally attached to every
join-reply, and the receiver filter is a no-op shim that logs a
one-shot deprecation WARN per process.  **The three-master bootstrap
race is reopened for one commit**; the next commit closes it via the
new state-machine primitive in
``salt/channel/_cluster_key_state.py`` (receiver-side
bootstrap-vs-committed state + founder-wait window).

The helpers ``_cluster_bootstrap_founder_id`` and
``is_designated_cluster_founder`` remain in use by the upcoming
receiver-side founder-wait logic and keep their behaviour.
``filter_non_founder_cluster_aes_from_join_reply`` is kept as a shim
(not removed) so cross-fork integrators who cherry-picked commit 6 as
a backport candidate continue to build -- T-6 (reviewer tweak):
additive, no history rewrite, downstream backports pinning SHA
6acb165 continue to work.

Tests updated:

* ``test_cluster_aes_founder_only.py`` -- founder-predicate tests
  unchanged; filter tests re-authored to pin the shim contract
  (no-op + one-shot deprecation WARN).
Introduces ``salt/channel/_cluster_key_state.py``: the receiver-side
state machine that gates ``cluster_aes`` / ``cluster.pem`` installs
on ``cluster/peer/join-reply``.  Per the reviewer-approved Candidate D
design (with tweaks T-1, T-2, T-6) in
``agents/reports/design-unified-cluster-key-propagation-reviewer.md``.

Model
-----

Each key is tracked per-process in one of two states:

* **BOOTSTRAP** -- the local bytes are mutable; the next install
  commits.  Non-founder arrivals during this state defer for up to
  ``cluster_bootstrap_founder_wait_s`` seconds (T-1: default 2.0s) so
  the designated founder's reply lands first.  If the window expires
  without a founder reply, the next arriving install commits and a
  WARN is logged -- this is the late-joiner-through-non-founder path
  the old commit-6 identity gate broke.
* **COMMITTED** -- the on-disk value is cluster-authoritative.  Equal
  arrivals are DEBUG no-ops; divergent arrivals WARN and are skipped.

Transitions are persisted via one sentinel per key under
``cluster_pki_dir``: ``.cluster_aes.committed`` and
``.cluster_pem.committed``.  Each sentinel's content is
``sha256:<64-hex>`` of the committed bytes (T-2: fingerprint-in-sentinel,
not emptiness) so a restart whose on-disk key no longer matches the
sentinel reverts to BOOTSTRAP instead of silently refusing a legitimate
re-sync.  Sentinels are written atomically via tempfile + ``os.replace``.

New config opt ``cluster_bootstrap_founder_wait_s`` (default 2.0s)
exposes the founder-wait window.  Defined in ``salt/config/__init__.py``
alongside the other cluster-mode knobs.

Shape of the API
----------------

* ``cluster_key_sentinel_path(cluster_pki_dir, key_name)`` -- path
  resolver with key-name validation.
* ``fingerprint_bytes(key_bytes)`` -- deterministic ``sha256:<hex>``.
* ``read_sentinel_fingerprint(path) -> str | None`` -- defensive
  parser that treats torn / malformed sentinels as absent.
* ``write_sentinel_fingerprint(path, fingerprint)`` -- atomic write.
* ``verify_committed_state_on_startup(cluster_pki_dir, key_name,
  on_disk_bytes)`` -- the T-2 startup check: returns
  ``("committed", fp)`` only when sentinel matches disk, else
  ``("bootstrap", None)`` (and deletes the stale sentinel on
  mismatch).
* ``ClusterKeyStateMachine`` -- the per-process receiver state
  machine.  ``decide(key_name, arriving_bytes, sender_peer_id,
  is_founder)`` returns one of ``install``/``noop``/``reject``/``defer``.
  Caller invokes the install side effects, then calls
  ``mark_committed(key_name, committed_bytes)``.
* ``install_cluster_key(sm, key_name, arriving_bytes, ...,
  install_fn)`` -- high-level helper that composes
  ``decide`` + the caller-supplied install closure + commit.

No production call sites wired yet -- the next commit wires both
``cluster_aes`` and ``cluster.pem`` install sites to this primitive
in ``salt/channel/server.py``.

Tests
-----

``tests/pytests/unit/channel/test_cluster_key_state.py`` exercises:

* Fingerprint helpers (format, determinism, bytes/str parity,
  non-bytes rejection).
* Sentinel atomicity (double-write leaves no tmp files;
  roundtrip; malformed-content handling).
* Startup reconciliation: BOOTSTRAP when absent; COMMITTED when
  fingerprint matches; BOOTSTRAP + sentinel-deleted when the
  fingerprint mismatches (T-2); BOOTSTRAP when sentinel present but
  disk bytes missing.
* Decision table: founder install, non-founder defer within window,
  non-founder accept after window (monkey-patched clock), committed
  noop, committed mismatch reject + WARN, ``None`` bytes reject,
  unsupported key_name raises.
* ``mark_committed`` persists sentinel, flips state, reports
  BOOTSTRAP->COMMITTED transition; idempotent recommit returns
  ``transition=False``.
* ``bootstrap_reset`` re-opens the commit window and deletes the
  sentinel.
* ``load_from_disk`` reflects verify_committed_state_on_startup.
* ``install_cluster_key`` closure runs on install, skips on
  noop/reject/defer, and handles install-failed (install_fn returns
  ``None``) by staying in BOOTSTRAP.
* End-to-end 3-master bootstrap determinism simulation: founder
  bytes win in every arrival order within the window.
…hine

Wires both ``cluster/peer/join-reply`` install sites to the
unified cluster-key propagation state machine from the previous
commit (``salt/channel/_cluster_key_state.py``).

Receiver-side changes (``salt/channel/server.py``)
--------------------------------------------------

* Import ``salt.channel._cluster_key_state`` at module scope.
* ``MasterPubServerChannel.__init__`` seeds a new private
  ``_cluster_key_sm`` slot.
* New lazy accessor ``_cluster_key_state_machine()`` instantiates
  the per-process ``ClusterKeyStateMachine`` on first use and
  reconciles it against the on-disk sentinels + current key bytes
  (``cluster_pki_dir/.aes`` and ``cluster_pki_dir/cluster.pem``).
  Uses ``getattr(self, "_cluster_key_sm", None)`` so instances
  built via ``__new__`` in tests (which skip ``__init__``) remain
  usable.
* ``handle_pool_publish`` for ``cluster/peer/join-reply``:
  - Consults the state machine before installing ``cluster_aes``.
    BOOTSTRAP + founder: install, mark_committed.  BOOTSTRAP +
    non-founder: defer within the founder-wait window (T-1).
    COMMITTED + equal: noop (no secret flip, no fsync).
    COMMITTED + mismatch: WARN + skip.  ``drop_all_pending`` now
    fires on the BOOTSTRAP->COMMITTED transition OR when the raw
    bytes change (same guarantee the prior ``prev != new`` gate
    provided).
  - Same primitive applied to the ``cluster.pem`` install block.
    **This is the NEW-11 closure**: COMMITTED + divergent arrival
    no longer unlinks ``cluster.pem``, no longer rewrites
    ``cluster.pub``, and no longer reassigns
    ``master_key.cluster_key`` / ``master_key.key`` -- the on-disk
    bytes and in-memory PrivateKey stay bound to the committed
    value.  BOOTSTRAP + founder: unlink + rewrite + cache.store +
    rebind, then mark_committed.
* Sender-side already made the attach unconditional in commit A;
  no further change here.
* Keeps the deprecated no-op shim call
  (``filter_non_founder_cluster_aes_from_join_reply``) at its
  historical site so T-6's additive history is preserved.

Tests
-----

New ``tests/pytests/unit/channel/test_cluster_key_state_wiring.py``
drives ``handle_pool_publish`` end-to-end against a stripped-down
channel (same pattern as the existing NEW-11 fix test):

* ``test_cluster_pem_committed_mismatch_skips_install`` -- the
  NEW-11 closure: committed master receives divergent pem from
  non-founder; disk, pub, and master_key.key all unchanged; WARN
  observed.
* ``test_cluster_pem_committed_equal_is_noop`` -- no cache.store,
  no master_key.key rebind on an equal arrival.
* ``test_cluster_pem_bootstrap_founder_arrival_commits`` -- full
  install path, sentinel written, master_key.key rebound.
* ``test_cluster_pem_bootstrap_non_founder_deferred`` -- within
  founder-wait window the non-founder arrival is deferred; disk
  unchanged; state stays BOOTSTRAP.
* ``test_cluster_aes_bootstrap_founder_commits_and_drops_pending``
  -- ``.aes`` written, SMaster.secrets flipped,
  ``drop_all_pending`` fires on the BOOTSTRAP->COMMITTED
  transition, sentinel persisted.
* ``test_cluster_aes_committed_equal_is_noop`` -- equal arrival
  does NOT call drop_all_pending and does NOT re-enter the
  SMaster.secrets lock.

Full unit suite ``tests/pytests/unit/channel/`` runs 166 tests;
all green at this HEAD.
Regression test for the commit-6 (``6acb1653613``) founder-only
``cluster_aes`` sender gate's **late-joiner flaw**: once the
designated founder dies, a surviving non-founder could not deliver
``cluster_aes`` to a brand-new master joining through it because the
sender omitted the key by identity and the receiver filter (now a
no-op shim, deprecated in commit A of this stack) would have dropped
it even if included.

The unified cluster-key propagation state machine (commits B + C)
restores late-joiner reachability: the sender ships unconditionally
and the receiver's BOOTSTRAP state honours the install from any peer
once the founder-wait window elapses or a committed non-founder peer
responds with the authoritative bytes.

Test
----

``test_late_joiner_through_non_founder_receives_committed_cluster_keys``
in ``tests/pytests/integration/cluster/test_failure_modes.py``:

1. Boots masters A/B/C (fixtures ``cluster_master_{1,2,3}_isolated``)
   and polls their on-disk ``.aes`` + ``cluster.pem`` to a 3-way
   convergence precondition.
2. Kills founder A via ``terminate()``.
3. Brings up master D (``cluster_master_4_isolated`` fixture with
   ``cluster_peers = [A, B, C]``).  A is unreachable; D's discover
   lands on B or C.
4. Asserts D's ``.aes`` equals B's committed ``.aes`` and D's
   ``cluster.pem`` equals B's committed ``cluster.pem``, each within
   60s of D's startup.  Also sanity-checks C's bytes to catch an
   A-dies / B-C-diverge regression.

Pre-fix (commit 6 alone) the assertion fails because D stays on its
locally-generated bootstrap AES.  Post-fix the assertion holds in
every observed arrival order.

Changelog
---------

``changelog/70831.fixed.md`` summarises the unified primitive for the
release notes (bootstrap race fix, state-machine primitive, sentinel
fingerprints, ``cluster_bootstrap_founder_wait_s`` opt, operator
reset path).
The unified cluster-key state machine commits via ``mark_committed``
only in the receiver install path.  A founding master never receives
its own locally-generated ``cluster_aes`` / ``cluster.pem`` via
``cluster/peer/join-reply`` -- it generated them itself at startup
via ``MasterKeys._setup_keys`` / ``find_or_create_keys``.  So the
founder's state machine stayed in BOOTSTRAP forever and the
sentinel file was never written.

Observable impact (PR saltstack#70831 run 44184265603 Debian 12 Arm64 int
zmq 3, confirmed from CI log artifact):

  * Each master restart within a test (test-harness retries, fixture
    teardowns) finds a missing sentinel -> ``verify_committed_state_
    on_startup`` returns ``BOOTSTRAP``, and if the on-disk key was
    also removed between restarts (e.g. function-scoped ``tmp_path``)
    ``find_or_create_keys`` regenerates a fresh random key.
  * Peers that already COMMITTED the previous value refuse the new
    one with the ``differs from committed; refusing install`` WARN
    (expected state-machine behaviour), and the cluster never
    converges.  Minion<->master auth then fails because the minion's
    cached master.pub does not match the master's post-restart
    master_key.key.

Fix at the founder-election site in
``_start_raft_as_founding_voter``: right after the join sentinel is
written, read the on-disk ``cluster_aes`` + ``cluster.pem`` bytes
and call ``sm.mark_committed(...)`` for each.  That writes the
state-machine sentinel + sets the in-memory shadow, so subsequent
restarts hit ``verify_committed_state_on_startup`` -> ``COMMITTED``
and stay authoritative.

Three new unit tests exercise:
  * commit transitions both keys to ``STATE_COMMITTED`` with correct
    fingerprints
  * sentinels land on disk and match ``fingerprint_bytes``
  * missing on-disk keys at election time -> both keys stay in
    ``STATE_BOOTSTRAP`` (receiver path remains available)

Local run: ``tests/pytests/unit/channel/`` + ``tests/pytests/unit/
cache/`` green; pre-commit clean on the two touched files.
Previous 750-1500ms election window (15-30x heartbeat) proved too tight
on constrained arm64 CI runners (2 vCPU / 8 GB).  Under load the 50ms
heartbeat tick is delayed by hundreds of ms by process scheduling;
elections fire before the "late" heartbeat arrives, term bumps,
cascading churn.

Observed on PR 70831's arm64 reproduction of
``test_isolated_multi_minion_targetable_from_every_master``:

* 105 ``BECOMING CANDIDATE`` events on one Debian 12 Arm64 int-3 job
* term reached 16 in 2 seconds on a 2-core arm64 instance
* join-reply from founder to late-joiner stalled 7 minutes waiting for
  Raft to converge
* minion-N auth timeout (393s via 3x 130s factory retries) fired long
  before the cluster was stable

Triple the window to 2250-4500ms (45-90x heartbeat).  x86 fast boxes
rarely hit the election timer at all so the bump is benign there.
Legitimate failover of a dead leader now takes a few extra seconds,
which is an acceptable trade for CI-stable bootstrap.
MWorker processes forked by RequestServer before the join-reply install
path (channel/server.py) rewrote cluster.pem in place hold the
bootstrap PrivateKey in self.key.  get_pub_str() reads cluster.pub
from disk (now the founder's bytes) and serves it to the minion, but
self.master_key.decrypt() uses the forked-in-memory bootstrap priv --
so every minion-auth token fails to decrypt with
ValueError('Decryption failed') and the minion loops on 'The Salt
Master server's public key did not authenticate!'.

Observed on the arm64 reproduction of
test_isolated_multi_minion_targetable_from_every_master after commit F
(cluster/consensus: raise default election window) let Raft stabilize
in time for the key install to succeed -- state machine committed and
disk converged across all three masters, but minion decrypts kept
failing for 7 minutes until pytest-salt-factories gave up.

Fix: on every MasterKeys.decrypt call under cluster_id, check the
on-disk cluster.pem's SHA256 against the cached fingerprint; reload
the PrivateKey if changed.  Small per-auth disk read, no cross-process
signaling required.
Defense in depth for the MWorker split-brain fixed in
2e46b1a ('MWorker reload cluster_key from disk before auth
decrypt').  In the master auth response the sequence is:

  1. MasterKeys.decrypt(load['token'], enc_algo)  -- fixed in 2e46b1a
  2. pub.encrypt(aes, enc_algo)                   -- minion pub, unaffected
  3. MasterKeys.encrypt(digest)                   -- master signs AES digest

Step 3 uses the master's PrivateKey ('encrypt' is RSA signing in this
code path).  After step 1 the reload has already run, so step 3 is
covered in practice.  But any standalone caller of MasterKeys.sign or
MasterKeys.encrypt from a forked MWorker that skipped decrypt (e.g.,
sync-flow _clear_signed) would still be exposed.  Adding the
fingerprint-guarded reload to all three proxies closes the hole with
one disk read per call -- SHA256 compare against the cached
fingerprint skips the PEM parse on the hot path.

This branch was previously deployed

1 inactive deployment
ci — 9544d00c Deployed Nov 18, 2026 by dwoz via Build Onedir Packages / RPM (arm64) #29216
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test:full Run the full test suite

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants