Skip to content

Simplify file contents in roots fileserver test - #2

Merged
dwoz merged 2 commits into
dwoz:state_echo_fixfrom
terminalmage:state_echo_fix
Jul 27, 2018
Merged

dwoz merged 2 commits into
dwoz:state_echo_fixfrom
terminalmage:state_echo_fix

Conversation

@terminalmage

Copy link
Copy Markdown

This removes the need to hard code contents in the test. The roots fileserver just reads from the file in binary mode, so we should be able to do the same in the test to confirm the correct behavior of the roots backend.

This removes the need to hard code contents in the test. The roots
fileserver just reads from the file in binary mode, so we should be able
to do the same in the test to confirm the correct behavior of the roots
backend.
@dwoz
dwoz merged commit d5e6009 into dwoz:state_echo_fix Jul 27, 2018
dwoz pushed a commit that referenced this pull request Aug 1, 2018
dwoz pushed a commit that referenced this pull request Jul 10, 2019
Use venv_bin from pillar or opts first
s0undt3ch pushed a commit that referenced this pull request Nov 30, 2019
…ter-2

[PyTest #2] Function name must not start with `test_` or pytest picks it up
dwoz added a commit that referenced this pull request Dec 2, 2019
dwoz pushed a commit that referenced this pull request Apr 11, 2020
Creating config file for external site links
dwoz pushed a commit that referenced this pull request May 5, 2020
dwoz pushed a commit that referenced this pull request May 5, 2020
@terminalmage
terminalmage deleted the state_echo_fix branch February 13, 2024 00:13
dwoz added a commit that referenced this pull request May 4, 2026
Closes three gaps identified in the Raft correctness audit.

Dynamic join — joiner starts as learner (priority #2 & #6)
-----------------------------------------------------------
A master that joins via discover_peers starts _publish_daemon before the
join handshake completes, so cluster_peers is empty and RaftService is not
started.  Once join-reply arrives the MasterPubServerChannel now calls
_start_raft_as_learner(), which:
  - builds pushers to every peer received in join-reply (fixes gap #6:
    dispatcher had no pushers to reply to the leader)
  - starts RaftService with voting=False (fixes gap #2: joiner was starting
    as a voter, risking split-brain before the leader promoted it)

salt/channel/server.py
- _start_raft_as_learner(known_peers): new helper started from the
  join-reply handler; builds peer pushers and calls
  RaftService(voting=False).
- join-reply handler: calls _start_raft_as_learner after event.set().

salt/cluster/consensus/service.py
- RaftService(voting=True): new optional parameter passed to Node so the
  node starts in learner mode when the master joined dynamically.

Founding CONFIG entry (priority #5)
-------------------------------------
The first elected leader of a fresh cluster now writes a CONFIG entry
recording the founding voter set before any application entries.  This
makes cluster membership durably verifiable from the log alone.

salt/cluster/consensus/service.py
- _maybe_commit_founding_config(): proposes {voters, learners} CONFIG entry
  when the leader's log is empty; no-ops if the log already has content.
- _heartbeat_tick: calls _maybe_commit_founding_config() on every tick
  while leader (the guard makes it idempotent).

Tests
-----
tests/pytests/functional/cluster/consensus/test_raft_service.py
- TestFoundingConfig: leader writes CONFIG entry on empty log; no-ops if
  log is non-empty.
- TestDynamicJoinerAsLearner: RaftService(voting=False) produces a
  non-voting node; learner-mode service does not start elections.
dwoz added a commit that referenced this pull request May 5, 2026
Closes three gaps identified in the Raft correctness audit.

Dynamic join — joiner starts as learner (priority #2 & #6)
-----------------------------------------------------------
A master that joins via discover_peers starts _publish_daemon before the
join handshake completes, so cluster_peers is empty and RaftService is not
started.  Once join-reply arrives the MasterPubServerChannel now calls
_start_raft_as_learner(), which:
  - builds pushers to every peer received in join-reply (fixes gap #6:
    dispatcher had no pushers to reply to the leader)
  - starts RaftService with voting=False (fixes gap #2: joiner was starting
    as a voter, risking split-brain before the leader promoted it)

salt/channel/server.py
- _start_raft_as_learner(known_peers): new helper started from the
  join-reply handler; builds peer pushers and calls
  RaftService(voting=False).
- join-reply handler: calls _start_raft_as_learner after event.set().

salt/cluster/consensus/service.py
- RaftService(voting=True): new optional parameter passed to Node so the
  node starts in learner mode when the master joined dynamically.

Founding CONFIG entry (priority #5)
-------------------------------------
The first elected leader of a fresh cluster now writes a CONFIG entry
recording the founding voter set before any application entries.  This
makes cluster membership durably verifiable from the log alone.

salt/cluster/consensus/service.py
- _maybe_commit_founding_config(): proposes {voters, learners} CONFIG entry
  when the leader's log is empty; no-ops if the log already has content.
- _heartbeat_tick: calls _maybe_commit_founding_config() on every tick
  while leader (the guard makes it idempotent).

Tests
-----
tests/pytests/functional/cluster/consensus/test_raft_service.py
- TestFoundingConfig: leader writes CONFIG entry on empty log; no-ops if
  log is non-empty.
- TestDynamicJoinerAsLearner: RaftService(voting=False) produces a
  non-voting node; learner-mode service does not start elections.
dwoz added a commit that referenced this pull request May 5, 2026
Closes three gaps identified in the Raft correctness audit.

Dynamic join — joiner starts as learner (priority #2 & #6)
-----------------------------------------------------------
A master that joins via discover_peers starts _publish_daemon before the
join handshake completes, so cluster_peers is empty and RaftService is not
started.  Once join-reply arrives the MasterPubServerChannel now calls
_start_raft_as_learner(), which:
  - builds pushers to every peer received in join-reply (fixes gap #6:
    dispatcher had no pushers to reply to the leader)
  - starts RaftService with voting=False (fixes gap #2: joiner was starting
    as a voter, risking split-brain before the leader promoted it)

salt/channel/server.py
- _start_raft_as_learner(known_peers): new helper started from the
  join-reply handler; builds peer pushers and calls
  RaftService(voting=False).
- join-reply handler: calls _start_raft_as_learner after event.set().

salt/cluster/consensus/service.py
- RaftService(voting=True): new optional parameter passed to Node so the
  node starts in learner mode when the master joined dynamically.

Founding CONFIG entry (priority #5)
-------------------------------------
The first elected leader of a fresh cluster now writes a CONFIG entry
recording the founding voter set before any application entries.  This
makes cluster membership durably verifiable from the log alone.

salt/cluster/consensus/service.py
- _maybe_commit_founding_config(): proposes {voters, learners} CONFIG entry
  when the leader's log is empty; no-ops if the log already has content.
- _heartbeat_tick: calls _maybe_commit_founding_config() on every tick
  while leader (the guard makes it idempotent).

Tests
-----
tests/pytests/functional/cluster/consensus/test_raft_service.py
- TestFoundingConfig: leader writes CONFIG entry on empty log; no-ops if
  log is non-empty.
- TestDynamicJoinerAsLearner: RaftService(voting=False) produces a
  non-voting node; learner-mode service does not start elections.
dwoz added a commit that referenced this pull request May 7, 2026
Closes three gaps identified in the Raft correctness audit.

Dynamic join — joiner starts as learner (priority #2 & #6)
-----------------------------------------------------------
A master that joins via discover_peers starts _publish_daemon before the
join handshake completes, so cluster_peers is empty and RaftService is not
started.  Once join-reply arrives the MasterPubServerChannel now calls
_start_raft_as_learner(), which:
  - builds pushers to every peer received in join-reply (fixes gap #6:
    dispatcher had no pushers to reply to the leader)
  - starts RaftService with voting=False (fixes gap #2: joiner was starting
    as a voter, risking split-brain before the leader promoted it)

salt/channel/server.py
- _start_raft_as_learner(known_peers): new helper started from the
  join-reply handler; builds peer pushers and calls
  RaftService(voting=False).
- join-reply handler: calls _start_raft_as_learner after event.set().

salt/cluster/consensus/service.py
- RaftService(voting=True): new optional parameter passed to Node so the
  node starts in learner mode when the master joined dynamically.

Founding CONFIG entry (priority #5)
-------------------------------------
The first elected leader of a fresh cluster now writes a CONFIG entry
recording the founding voter set before any application entries.  This
makes cluster membership durably verifiable from the log alone.

salt/cluster/consensus/service.py
- _maybe_commit_founding_config(): proposes {voters, learners} CONFIG entry
  when the leader's log is empty; no-ops if the log already has content.
- _heartbeat_tick: calls _maybe_commit_founding_config() on every tick
  while leader (the guard makes it idempotent).

Tests
-----
tests/pytests/functional/cluster/consensus/test_raft_service.py
- TestFoundingConfig: leader writes CONFIG entry on empty log; no-ops if
  log is non-empty.
- TestDynamicJoinerAsLearner: RaftService(voting=False) produces a
  non-voting node; learner-mode service does not start elections.
dwoz added a commit that referenced this pull request May 14, 2026
This commit fixes catastrophic FD exhaustion in Salt minions running
queued state jobs. The issue manifested as "Too many open files" errors
after ~15 queued jobs.

Root causes and fixes:

1. Unawaited coroutine (salt/utils/event.py:785)
   - Changed self.pusher.publish(msg) to await self.pusher.publish(msg)

2. Unclosed event loops in job threads (salt/minion.py)
   - Added loop.close() in finally blocks of _thread_return() and _thread_multi_return()

3. SyncWrapper __getattr__ preventing cleanup (salt/utils/event.py)
   - Explicitly call SyncWrapper.close() instead of relying on __getattr__

4. Missing task cancellation (salt/utils/asynchronous.py)
   - Cancel pending tasks before closing event loop
   - Shutdown async generators with shutdown_asyncgens()
   - Shutdown executor with shutdown_default_executor()

5. IOLoop auto-creation (salt/utils/asynchronous.py)
   - Changed IOLoop.current() to IOLoop.current(instance=False)

6. Nested SyncWrapper in TCP transport (salt/transport/tcp.py)
   - Explicitly close pub_sock SyncWrapper in PublishServer.close()

7. Unclosed TCP client (salt/transport/tcp.py)
   - Added _tcp_client.close() in PublishClient.close()

8. Async generator/executor shutdown (salt/utils/asynchronous.py)
   - Call shutdown_asyncgens() and shutdown_default_executor() before loop close

Impact:
- Before: 237 FDs leaked per 15 queued jobs → OSError after ~40 jobs
- After: 0 FDs leaked (multiprocessing), minimal leaks (threading)

Tests added:
- tests/pytests/scenarios/queue/test_queue_fd_leak.py
  Comprehensive regression test for the reported bug

- tests/pytests/scenarios/regression/test_fd_leak_fire_event_async.py
  Regression test for fix #1 (unawaited coroutine)

- tests/pytests/scenarios/regression/test_fd_leak_job_thread_loop.py
  Regression test for fix #2 (job thread event loop close)

- tests/pytests/scenarios/regression/test_fd_leak_syncwrapper_close.py
  Regression test for fix #3 (SyncWrapper explicit close)

- tests/pytests/scenarios/regression/test_fd_leak_task_cancellation.py
  Regression test for fix #4 (task cancellation and cleanup)

- tests/pytests/scenarios/regression/test_fd_leak_ioloop_instance.py
  Regression test for fix #5 (IOLoop.current(instance=False))

- tests/pytests/scenarios/regression/test_fd_leak_tcp_nested_syncwrapper.py
  Regression test for fix #6 (nested SyncWrapper in TCP)

- tests/pytests/scenarios/regression/test_fd_leak_tcp_client_close.py
  Regression test for fix #7 (TCP client close)

- tests/pytests/scenarios/regression/test_fd_leak_asyncgens_executor.py
  Regression test for fix #8 (async generator and executor shutdown)

All regression tests:
- Use real Salt master/minion infrastructure (not mocks)
- Measure actual FD counts with psutil
- Exercise specific code paths that were leaking
- Assert FD leaks are minimal (≤ threshold)
dwoz added a commit that referenced this pull request May 14, 2026
This commit fixes catastrophic FD exhaustion in Salt minions running
queued state jobs. The issue manifested as "Too many open files" errors
after ~15 queued jobs.

Root causes and fixes:

1. Unawaited coroutine (salt/utils/event.py:785)
   - Changed self.pusher.publish(msg) to await self.pusher.publish(msg)

2. Unclosed event loops in job threads (salt/minion.py)
   - Added loop.close() in finally blocks of _thread_return() and _thread_multi_return()

3. SyncWrapper __getattr__ preventing cleanup (salt/utils/event.py)
   - Explicitly call SyncWrapper.close() instead of relying on __getattr__

4. Missing task cancellation (salt/utils/asynchronous.py)
   - Cancel pending tasks before closing event loop
   - Shutdown async generators with shutdown_asyncgens()
   - Shutdown executor with shutdown_default_executor()

5. IOLoop auto-creation (salt/utils/asynchronous.py)
   - Changed IOLoop.current() to IOLoop.current(instance=False)

6. Nested SyncWrapper in TCP transport (salt/transport/tcp.py)
   - Explicitly close pub_sock SyncWrapper in PublishServer.close()

7. Unclosed TCP client (salt/transport/tcp.py)
   - Added _tcp_client.close() in PublishClient.close()

8. Async generator/executor shutdown (salt/utils/asynchronous.py)
   - Call shutdown_asyncgens() and shutdown_default_executor() before loop close

Impact:
- Before: 237 FDs leaked per 15 queued jobs → OSError after ~40 jobs
- After: 0 FDs leaked (multiprocessing), minimal leaks (threading)

Tests added:
- tests/pytests/scenarios/queue/test_queue_fd_leak.py
  Comprehensive regression test for the reported bug

- tests/pytests/scenarios/regression/test_fd_leak_fire_event_async.py
  Regression test for fix #1 (unawaited coroutine)

- tests/pytests/scenarios/regression/test_fd_leak_job_thread_loop.py
  Regression test for fix #2 (job thread event loop close)

- tests/pytests/scenarios/regression/test_fd_leak_syncwrapper_close.py
  Regression test for fix #3 (SyncWrapper explicit close)

- tests/pytests/scenarios/regression/test_fd_leak_task_cancellation.py
  Regression test for fix #4 (task cancellation and cleanup)

- tests/pytests/scenarios/regression/test_fd_leak_ioloop_instance.py
  Regression test for fix #5 (IOLoop.current(instance=False))

- tests/pytests/scenarios/regression/test_fd_leak_tcp_nested_syncwrapper.py
  Regression test for fix #6 (nested SyncWrapper in TCP)

- tests/pytests/scenarios/regression/test_fd_leak_tcp_client_close.py
  Regression test for fix #7 (TCP client close)

- tests/pytests/scenarios/regression/test_fd_leak_asyncgens_executor.py
  Regression test for fix #8 (async generator and executor shutdown)

All regression tests:
- Use real Salt master/minion infrastructure (not mocks)
- Measure actual FD counts with psutil
- Exercise specific code paths that were leaking
- Assert FD leaks are minimal (≤ threshold)
dwoz added a commit that referenced this pull request Sep 24, 2026
The finalizer tracer at
``scratch/vcops-90587-ctx-trace/zmq_finalizer_trace_v5.py`` (deployed
to nsx on Ani Baghoumian's ``ab002212-63-maas-easy-deploy`` env)
captured the exact wedge signature in production and pinned the
creation site of the leaking ``zmq.asyncio.Context`` to::

    handle_event -> _fire_master_main -> _send_req_async_main
      -> self.req_channel.send(...)
      -> transport.send -> await self.connect()
      -> _init_socket()

The trace showed a ``FINALIZE_ENTRY`` with ``closed=False`` invoked
from ``tornado/ioloop.py:945 val = self.callback()`` -- i.e. the
``weakref.finalize`` registered on a ``RequestClient`` fired from an
ioloop callback and blocked in ``zmq_ctx_term()``.

Reading the deployed source revealed the state-machine bug behind it.

``RequestClient.close_async`` does the right thing::

    self._closing = True
    self.socket = None
    self.context = None
    ...
    context.destroy(linger=1000)   # closed=True on the Context

But ``RequestClient.connect`` then silently resurrects the transport::

    async def connect(self):
        async with self._connect_lock:
            if self.socket is None:
                self._connect_called = True
                self._closing = False        # <-- clears the "closed" bit
                self._init_socket()          # <-- allocates a fresh Context
                                             #     AND registers a second
                                             #     weakref.finalize on
                                             #     this RequestClient

The wedge race is:

  1. Reconnect calls ``await old_channel.close_async()``.  The OLD
     ``RequestClient``'s Context #1 is destroyed cleanly and
     ``self.context`` is set to None.
  2. Reconnect assigns ``self.req_channel = <new>``.
  3. An in-flight coroutine (``_fire_master_main`` ->
     ``_send_req_async_main``) that captured the OLD channel across
     an ``await`` yield point now calls ``.send()`` on it.
  4. Old ``.send()`` -> old ``transport.send()`` -> ``await
     self.connect()``.  Before this change ``connect()``
     unconditionally reset ``_closing`` to False and ran
     ``_init_socket``, which allocated Context #2 and registered a
     second ``weakref.finalize`` against the same (dead)
     ``RequestClient``.
  5. Nothing calls ``close_async`` on the OLD channel again -- the
     reconnect already dropped its reference.  When the OLD channel
     is finally GC'd the second finalizer fires from an ioloop
     callback and blocks in ``zmq_ctx_term()``.  Loop wedges.

Refuse the reconnect.  A closed ``RequestClient`` cannot be reused;
any caller holding a stale reference gets a clean
``SaltClientError`` (which the surrounding ``AsyncReqChannel`` retry
logic already handles), and no second Context is allocated or
finalized.  With this in place the trace-log invariant holds: every
``FINALIZE_ENTRY`` on a ``RequestClient`` has ``closed=True`` and
the finalizer's ``context.destroy`` short-circuits.

Regression test in
``tests/pytests/functional/transport/zeromq/test_close_async_audit.py::test_closed_request_client_refuses_reconnect``
constructs a ``RequestClient``, drives ``connect -> close_async ->
connect``, and asserts (a) the second ``connect`` raises
``SaltClientError`` and (b) ``self.context`` remains ``None`` (no
resurrection).  Verified fail-without-fix (``DID NOT RAISE``) and
pass-with-fix (``1 passed``) on the debian-12 CI container.
dwoz added a commit that referenced this pull request Sep 25, 2026
The finalizer tracer at
``scratch/vcops-90587-ctx-trace/zmq_finalizer_trace_v5.py`` (deployed
to nsx on Ani Baghoumian's ``ab002212-63-maas-easy-deploy`` env)
captured the exact wedge signature in production and pinned the
creation site of the leaking ``zmq.asyncio.Context`` to::

    handle_event -> _fire_master_main -> _send_req_async_main
      -> self.req_channel.send(...)
      -> transport.send -> await self.connect()
      -> _init_socket()

The trace showed a ``FINALIZE_ENTRY`` with ``closed=False`` invoked
from ``tornado/ioloop.py:945 val = self.callback()`` -- i.e. the
``weakref.finalize`` registered on a ``RequestClient`` fired from an
ioloop callback and blocked in ``zmq_ctx_term()``.

Reading the deployed source revealed the state-machine bug behind it.

``RequestClient.close_async`` does the right thing::

    self._closing = True
    self.socket = None
    self.context = None
    ...
    context.destroy(linger=1000)   # closed=True on the Context

But ``RequestClient.connect`` then silently resurrects the transport::

    async def connect(self):
        async with self._connect_lock:
            if self.socket is None:
                self._connect_called = True
                self._closing = False        # <-- clears the "closed" bit
                self._init_socket()          # <-- allocates a fresh Context
                                             #     AND registers a second
                                             #     weakref.finalize on
                                             #     this RequestClient

The wedge race is:

  1. Reconnect calls ``await old_channel.close_async()``.  The OLD
     ``RequestClient``'s Context #1 is destroyed cleanly and
     ``self.context`` is set to None.
  2. Reconnect assigns ``self.req_channel = <new>``.
  3. An in-flight coroutine (``_fire_master_main`` ->
     ``_send_req_async_main``) that captured the OLD channel across
     an ``await`` yield point now calls ``.send()`` on it.
  4. Old ``.send()`` -> old ``transport.send()`` -> ``await
     self.connect()``.  Before this change ``connect()``
     unconditionally reset ``_closing`` to False and ran
     ``_init_socket``, which allocated Context #2 and registered a
     second ``weakref.finalize`` against the same (dead)
     ``RequestClient``.
  5. Nothing calls ``close_async`` on the OLD channel again -- the
     reconnect already dropped its reference.  When the OLD channel
     is finally GC'd the second finalizer fires from an ioloop
     callback and blocks in ``zmq_ctx_term()``.  Loop wedges.

Refuse the reconnect.  A closed ``RequestClient`` cannot be reused;
any caller holding a stale reference gets a clean
``SaltClientError`` (which the surrounding ``AsyncReqChannel`` retry
logic already handles), and no second Context is allocated or
finalized.  With this in place the trace-log invariant holds: every
``FINALIZE_ENTRY`` on a ``RequestClient`` has ``closed=True`` and
the finalizer's ``context.destroy`` short-circuits.

Regression test in
``tests/pytests/functional/transport/zeromq/test_close_async_audit.py::test_closed_request_client_refuses_reconnect``
constructs a ``RequestClient``, drives ``connect -> close_async ->
connect``, and asserts (a) the second ``connect`` raises
``SaltClientError`` and (b) ``self.context`` remains ``None`` (no
resurrection).  Verified fail-without-fix (``DID NOT RAISE``) and
pass-with-fix (``1 passed``) on the debian-12 CI container.
dwoz added a commit that referenced this pull request Nov 11, 2026
Phase-3 reviewer finding #2: two files still called deleted pillar-
driven APIs.  Both were left over from the no-pillar refactor and
were producing silent false-negatives (resource_match) or runtime
AttributeError (ssh resource module) when exercised.

salt/matchers/resource_match.py:
  Replaced the ``opts["resources"]`` read (never populated post-refactor)
  with:
  * ``salt.utils.resources.enabled_resource_types(opts)`` for the
    enabled-type gate, and
  * ``salt.loader.resource(opts)`` + per-type ``<type>.discover(opts)``
    generator consumption for ID membership checks.
  Short-circuits on the first ID match so a 200K-resource ``discover``
  generator doesn't materialize on the minion.

salt/resources/ssh/__init__.py:
  Replaced the two ``salt.utils.resources.pillar_resources_tree(opts)``
  callsites (deleted in the no-pillar refactor) with
  ``opts.get("ssh", {})`` reads, matching the opts-key pattern the
  dummy module already uses.  ``discover()`` is now a generator so the
  register loop can stream host IDs without buffering the full dict.
  Docstring updated to drop the "resource_pillar_key" reference; the
  existing ``__virtual__`` already gates on the ``ssh`` binary being
  on PATH.  Dropped the now-unused ``salt.utils.resources`` import.

Tests:
  tests/pytests/unit/matchers/test_resource_matchers.py: rewrote the
  fixtures to use ``opts["resource_types"]`` + a patched
  ``salt.loader.resource`` instead of the deleted ``opts["resources"]``.
  Added ``test_resource_match_srn_short_circuits_on_first_hit`` to
  pin the generator-short-circuit behavior the memory-ceiling rule
  requires.

Verified:
  - grep for ``opts["resources"]`` returns only comments/docstrings.
  - grep for ``pillar_resources_tree`` in salt/ returns zero hits.
dwoz added a commit that referenced this pull request Nov 11, 2026
Phase-3 verifier finding #2: ``_save_state`` + ``_load_state`` each
emit a ``log.warning`` with ``pprint.pformat(state_dict)`` per
resource.  At 200K resources that's 200K WARNING lines per full
enumeration, which:

- Drives docker container log circular-buffer rotation during scale
  tests.
- Contributes to 62-68K "dummy-0" strings in the pid-10 anon-memory
  scan (Python's logging / format interning).
- Makes real WARNING-level issues hard to spot in the firehose.

Demote both call sites to DEBUG.  Fixture noise, not production bug,
but makes the scan-and-verify loop measurably quieter and shrinks
the memory-scan false-positive footprint.

The ``log.warning`` at line 52 (``dummy_resource_count must be an
int``) stays at WARNING -- that's a one-shot config-error log and
is correctly loud.
dwoz added a commit that referenced this pull request Nov 11, 2026
Phase-3 verifier finding #2: ``_save_state`` + ``_load_state`` each
emit a ``log.warning`` with ``pprint.pformat(state_dict)`` per
resource.  At 200K resources that's 200K WARNING lines per full
enumeration, which:

- Drives docker container log circular-buffer rotation during scale
  tests.
- Contributes to 62-68K "dummy-0" strings in the pid-10 anon-memory
  scan (Python's logging / format interning).
- Makes real WARNING-level issues hard to spot in the firehose.

Demote both call sites to DEBUG.  Fixture noise, not production bug,
but makes the scan-and-verify loop measurably quieter and shrinks
the memory-scan false-positive footprint.

The ``log.warning`` at line 52 (``dummy_resource_count must be an
int``) stays at WARNING -- that's a one-shot config-error log and
is correctly loud.
dwoz added a commit that referenced this pull request Nov 11, 2026
Phase-3 verifier finding #2: ``_save_state`` + ``_load_state`` each
emit a ``log.warning`` with ``pprint.pformat(state_dict)`` per
resource.  At 200K resources that's 200K WARNING lines per full
enumeration, which:

- Drives docker container log circular-buffer rotation during scale
  tests.
- Contributes to 62-68K "dummy-0" strings in the pid-10 anon-memory
  scan (Python's logging / format interning).
- Makes real WARNING-level issues hard to spot in the firehose.

Demote both call sites to DEBUG.  Fixture noise, not production bug,
but makes the scan-and-verify loop measurably quieter and shrinks
the memory-scan false-positive footprint.

The ``log.warning`` at line 52 (``dummy_resource_count must be an
int``) stays at WARNING -- that's a one-shot config-error log and
is correctly loud.
dwoz added a commit that referenced this pull request Nov 11, 2026
Phase-3 verifier finding #2: ``_save_state`` + ``_load_state`` each
emit a ``log.warning`` with ``pprint.pformat(state_dict)`` per
resource.  At 200K resources that's 200K WARNING lines per full
enumeration, which:

- Drives docker container log circular-buffer rotation during scale
  tests.
- Contributes to 62-68K "dummy-0" strings in the pid-10 anon-memory
  scan (Python's logging / format interning).
- Makes real WARNING-level issues hard to spot in the firehose.

Demote both call sites to DEBUG.  Fixture noise, not production bug,
but makes the scan-and-verify loop measurably quieter and shrinks
the memory-scan false-positive footprint.

The ``log.warning`` at line 52 (``dummy_resource_count must be an
int``) stays at WARNING -- that's a one-shot config-error log and
is correctly loud.
dwoz added a commit that referenced this pull request Nov 13, 2026
Phase-3 verifier finding #2: ``_save_state`` + ``_load_state`` each
emit a ``log.warning`` with ``pprint.pformat(state_dict)`` per
resource.  At 200K resources that's 200K WARNING lines per full
enumeration, which:

- Drives docker container log circular-buffer rotation during scale
  tests.
- Contributes to 62-68K "dummy-0" strings in the pid-10 anon-memory
  scan (Python's logging / format interning).
- Makes real WARNING-level issues hard to spot in the firehose.

Demote both call sites to DEBUG.  Fixture noise, not production bug,
but makes the scan-and-verify loop measurably quieter and shrinks
the memory-scan false-positive footprint.

The ``log.warning`` at line 52 (``dummy_resource_count must be an
int``) stays at WARNING -- that's a one-shot config-error log and
is correctly loud.
dwoz added a commit that referenced this pull request Nov 15, 2026
* WIP: cache facade fan-out + per-bank routing

* channel: guard cluster/peer/discover-reply against missing cluster_pub

The discover-reply handler at server.py:4058 called
salt.crypt.PublicKeyString(payload["cluster_pub"]) without guarding
against None, so a joiner master that answered another joiner's
discover before its own join-reply from the founder had landed would
crash the recipient's publish daemon with
AttributeError: 'NoneType' object has no attribute 'encode'.

Fix both sides of the handshake:

* Receiver: early-return when the discover-reply payload lacks
  cluster_pub.  A debug log carries the peer_id so the retry can be
  observed.  Previously the recipient's publish daemon died outright
  via an unhandled AttributeError, after which the joiner never
  started its Raft learner and the cluster never stabilised.

* Sender: skip the discover-reply when cluster_public_key() returns
  None (the joiner has not installed cluster.pub yet).  Prevents the
  peer from having to reject or defer; the next discover round picks
  up the key once join-reply has landed.

The bug is pre-existing but was latent on resources-2 because the
publish-daemon event-loop ordering happened to always process
join-reply before any peer-discover trade.  The cache-replication
work on this branch shifts that ordering (new publish branch at
server.py:3547 and the apply_master_config default flip for
cluster_cache_replication) and surfaces the crash deterministically.
See agents/reports/cache-replicate-alpha-diagnosis.md.

* cluster: retry cluster/peer/discover until peer replies or timeout

discover_peers() in salt.master.Master.start is fire-and-forget: it sends
one cluster/peer/discover event per peer over the local IPC bus.  The
publish daemon forwards that event to each peer's pool-puller.  If the
peer's pool-puller TCP listener is not yet bound on cluster_pool_port
when the event is forwarded (a tight startup race narrowed by the extra
event-loop work the cache-replication machinery puts on the publish
daemon), the push raises StreamClosedError and the discover is lost
silently.  No discover-reply, no cluster.pub install, no Raft election,
no cluster_aes rotation, no session keys -- the joiner waits forever on
_discover_event and the whole bootstrap stalls.

Add a periodic retry owned by MasterPubServerChannel.  When a non-
founder enters _publish_daemon, _schedule_discover_retry installs a
tornado PeriodicCallback that re-sends discover to each peer whose
cluster/peer/discover-reply has not yet landed.  The retry stops as
soon as every configured peer has replied, or after
cluster_join_discover_retry_timeout seconds have elapsed; the interval
is tunable via cluster_join_discover_retry_interval (default 2 s,
timeout default 60 s).

The cancel signal is a dedicated self._discover_replies set populated
in the discover-reply branch of handle_pool_publish after the peer
signature and cluster-pub fingerprint are verified.  Earlier drafts
cancelled on peer_keys growth, but peer_keys is populated by the AES-
key broadcast (send_aes_key_event) independently of the discover
protocol: in a 3-master bring-up every joiner sees the founder's AES
key arrive well before any discover-reply, so a peer_keys-keyed cancel
fires on the very first tick and the discover stays lost.

The cache-replication work on wip/cache-cluster-replicate surfaced
this race by shifting the publish-daemon event-loop ordering during
startup, but the one-shot discover is a pre-existing bug in the
cluster bootstrap path: any added startup latency (slow disk, loaded
CI runner, extra pre-fork work) can push the handshake over the cliff
on the base branch too.

Covered by tests/pytests/unit/channel/test_cluster_discover_retry.py,
including a dedicated regression test that AES-key arrival alone does
not cancel the retry.

* cache-replicate: reuse MasterEvent handle across stores

Every ``cache.store`` on a clustered master opens a fresh
``MasterEvent`` (connect + fire + close) before emitting the
``cluster/runner/delegate_cache_write`` event.  Measured against
200K-resource register loads on a 3-master isolated-FS cluster,
the per-write connect cost adds roughly 70 seconds per master
to the replication tail (hot banks are ``grains``, ``minions``,
``resource_registry`` -- every one hits the facade).

Cache the handle in a module-local dict keyed by
``(sock_dir, opts["id"], os.getpid())``.  First call in each
process creates the handle lazily; subsequent calls reuse it.
Fork-safety comes from pid-keying: a worker that inherits a
parent's dict entry doesn't reuse the parent's stale fds, it
constructs its own on first fire.  Teardown is best-effort via
``atexit`` -- replication events are not critical on shutdown.

On a fire failure the cached handle is invalidated so the next
call re-opens the socket (e.g. after a master restart yanks the
underlying unix socket).

* state-sync: add replicate-mode cache-bank catch-up primitives

Adds the sender/receiver building blocks for join-time replicate-mode
cache-bank catch-up so a newly joining master receives every
replicate-mode bank's current contents before it starts applying live
delegate-cache-write deltas:

* BANK_SYNC_CHANNEL_PREFIX (bank_sync:<bank>) wire channel
  distinct from the operator-collect bank: prefix so the receiver
  can apply with _already_replicated=True.
* BANK_SYNC_SKIP_PREFIXES guards ring-routed / consensus-owned
  banks from the catch-up list.
* enumerate_replicate_banks walks the cachedir and returns the
  top-level banks whose per-bank routing resolves to replicate.
* iter_cache_bank_chunks chunks a bank by cumulative byte budget.
* install_bank_sync_chunk applies a chunk with the already-
  replicated flag set so the receiver doesn't re-broadcast.

* resource-registry: cross-master replication via dedicated event

The salt.utils.resource_registry.ResourceRegistry.register_minion
write path bypasses salt.cache.Cache (hash-indexed mmap with the
SRN key shape and uint32 roster) so the facade-level fan-out added in
earlier commits does not cover it.  On a 3-master cluster with haproxy
TCP round-robin, each master was writing its own slice of the
resource_index.by_id.mmap, producing three different mmap files.

Close the gap with the same architectural shape as cache replication
but a dedicated event tag so the chunk metadata path can diverge:

* Fire cluster/runner/delegate_resource_register_write from
  AESFuncs.__register_resources_sync right after the local
  update_resource_index call lands.
* Receiver side (MasterPubServerChannel) decrypts the
  cluster_aes-encrypted cluster/peer/delegate-resource-register-write
  event and applies via update_resource_index locally.  Loop-guard
  on originating_master == self.opts['id'] prevents bus echo from
  re-applying.
* Gated on the same preconditions as cache fan-out: cluster_id
  set, cluster_isolated_filesystem True,
  cluster_cache_replication not forced False.

The resource_grains cache writes at
AESFuncs.__register_resources_sync line 2942 already go through
cache.store and are covered by the existing facade-level fan-out
-- no additional hook needed there.

* resources: remove pillar-based inventory from client + config

* resources: remove pillar as resource-inventory source on the minion

Switch the minion resource subsystem off pillar and onto a per-type
opts-key model.  Resource types are declared via the ``resource_types``
minion opt; per-type modules read their own opts (e.g. the dummy module
reads ``dummy_resource_count``) rather than ``opts["pillar"]["resources"][type]``.

Key invariants enforced by this change:

* The minion never materializes ``opts["resources"]``.  Every call site
  (gen_modules loader/init loop, _post_master_init, pillar_refresh,
  resource_refresh event, target resolution, grain collection) now
  iterates ``salt.utils.resources.enabled_resource_types(opts)`` + the
  per-type ``discover(opts)`` generator.

* ``discover(opts)`` is now a streaming contract -- implementations
  MAY return a generator.  The dummy module yields
  ``f"dummy-{i:07d}"`` for i in ``range(1, dummy_resource_count + 1)``
  so a 200K-resource minion never holds the full ID list in memory.

* ``_register_resources_with_master`` is rewritten as a chunked loop
  that drains the per-type generator into fixed-size chunks
  (``resource_register_chunk_size``, default 10000), ships each chunk
  with a ``chunk_rtype`` / ``chunk_index`` / ``chunk_final`` header,
  renders grains per-chunk, and drops the chunk reference before
  streaming the next one.  Per-type peak is bounded by
  ``chunk_size * per-SRN-cost`` rather than ``total * per-SRN-cost``.

* ``salt.utils.resources.pillar_resources_tree`` and
  ``resource_pillar_key`` are deleted -- with pillar out of the picture
  the remap is meaningless.  A new helper
  ``enabled_resource_types(opts)`` returns the opt-driven type list.
  ``bare_resource_id_in_minion_data_cache`` keeps the grains-cache
  branch (unchanged behavior for offline-minion targeting) and loses
  its pillar-cache branch.

Companion to the no-pillar-resources design
(``agents/reports/no-pillar-design.md``).  ``salt/resources/ssh/``
still reads pillar and is handled in a follow-up.

* resource-registry: TTL-evict abandoned chunked-register windows

Closes Phase 3 reviewer concern #3: ResourceRegistry._pending_registers
has no GC/TTL, so a minion that ships chunks 0..k and crashes before
chunk_final=True leaves a stuck entry forever.  For 200K-register
workloads with crash-looping minions, these windows accumulate
unboundedly.

Fix shape:

* Each per-scope window state (_pending_registers[minion_id][scope])
  carries a created_ts + last_activity_ts.  Both are stamped from the
  same time.monotonic() reading that the sweep uses, so a just-created
  entry cannot be evicted on its own creation call.

* last_activity_ts refreshes on every chunk arrival for that scope, so
  active-but-slow registers never evict their own window.  A stalled
  minion is caught; a slow one is not.

* On every chunk arrival, before touching the incoming window state,
  the write path runs a sweep over _pending_registers and drops any
  scope whose last_activity_ts is older than the TTL.  Each eviction
  logs at WARNING level naming (minion_id, scope, age_seconds,
  srn_count) so operators can identify the crash-loop source.

* No background task required: every register_minion_chunk call runs
  the sweep under the existing _pending_registers_lock.  Sweep cost
  is O(live pending scopes) which is bounded by N_minions * N_types.

Config:

* New master opt cluster_resource_register_pending_ttl (float
  seconds, default 300).  Added to VALID_OPTS + DEFAULT_MASTER_OPTS
  so schema docs and the config validator both know about it.  The
  default comfortably exceeds the 200K-register window observed on
  the 3-node cluster.

Tests:

* test_register_minion_chunk_pending_ttl_evicts_abandoned_window:
  seeds a crash-loop minion's pending window, rewinds its
  last_activity_ts past the TTL, fires a chunk for a second minion,
  asserts the abandoned window is evicted + the WARNING is emitted.
* test_register_minion_chunk_pending_ttl_does_not_evict_active_window:
  negative counterpart -- a window with activity inside the TTL
  must not be evicted even when the TTL is small.

Timestamp manipulation (rewinding last_activity_ts directly) keeps
the tests deterministic with no sleep + no mock-time machinery.

* resources/dummy: demote per-resource save/load log spam to DEBUG

Phase-3 verifier finding #2: ``_save_state`` + ``_load_state`` each
emit a ``log.warning`` with ``pprint.pformat(state_dict)`` per
resource.  At 200K resources that's 200K WARNING lines per full
enumeration, which:

- Drives docker container log circular-buffer rotation during scale
  tests.
- Contributes to 62-68K "dummy-0" strings in the pid-10 anon-memory
  scan (Python's logging / format interning).
- Makes real WARNING-level issues hard to spot in the firehose.

Demote both call sites to DEBUG.  Fixture noise, not production bug,
but makes the scan-and-verify loop measurably quieter and shrinks
the memory-scan false-positive footprint.

The ``log.warning`` at line 52 (``dummy_resource_count must be an
int``) stays at WARNING -- that's a one-shot config-error log and
is correctly loud.

* channel/server: fix handle_pool_publish UnboundLocalError on salt

A plain import salt.cache._cluster_replicator inside
handle_pool_publish silently rebound salt as a function-local
name for the entire body.  Every earlier reference in the same function
(salt.utils.event.SaltEvent.unpack,
salt.cluster.consensus.rpc.is_raft_tag, etc.) then raised
UnboundLocalError: local variable 'salt' referenced before assignment
on each incoming cluster/peer event, which dropped every join-reply /
pre-vote-reply.  Masters 2+3 never discovered master-1 and the Raft
log never committed any membership entry -- blocking cluster formation
from a fresh docker compose up -d.

Switch to importlib.import_module so the submodule is loaded into
sys.modules without introducing a local binding for salt.

* channel/server: demote per-event per-peer publish log to debug

* master: batch resource_grains stores via store_many

Previously the master-side register handler called cache.store() in a
per-SR loop for the RESOURCE_GRAINS_BANK, producing one
cluster/peer/delegate-cache-write event per SR. For a 10K-SR chunk that
is 10,000 individual events fanning out to all peer masters via the
replicate routing default -- a 10,000x event amplifier vs the
registry path (which uses one event per chunk).

Switch to cache.store_many(bank, items) so one chunk fires a single
batched event (further sub-batched inside store_many by
cluster_cache_replicate_batch_size, default 1024). Semantics unchanged
-- same SR+grain pairs land in the same bank; the delegate-cache-write
dispatch batches transparently.

Affects both async (__register_resources_sync) and MWorker-sync
(_sync_register_resources) paths.

* channel/server: route write_kind=ring cache writes via resource_index ring

Replaces the TODO-fallback in _run_delegate_cache_write for the "ring"
write_kind with actual 1-of-N targeted delivery. Resolves the owning
master for each (bank, key) via the resource_index HashRing and pushes
the delegate-write event only to that peer. Self-owned writes are
dropped (originator already applied the local write); unresolved
owners fall back to broadcast so no update is lost.

Batched payloads partition by owner: each remote owner receives a
batch containing only its own [key, data] pairs. publish_cache_write
grows a target_master kwarg so a single peer can be addressed without
fanning out to the whole pool, mirroring publish_resource_register_write.

Enables cluster_cache_routing: {resource_grains: ring} to actually
cut grain fan-out from N-of-N to 1-of-N during register at scale.

* master: enforce resource_id == bank-key id at register time

Normalise gdict["resource_id"] to the id portion of the SRN before
cache.store_many in both __register_resources_sync and
_sync_register_resources. The bank key <type>:<id> is authoritative;
any resource module whose grains() emitted a divergent or missing
resource_id is now corrected on write.

Makes the grain-target "resource_id:<glob>" fast path structurally
safe: a bank-key glob match is now proof of the resource_id grain
value, independent of the resource module's grains() implementation.

* utils/minions: resource_id glob fast-path in grain-target resolver

_augment_grain_match_with_resource_grains used to pickle-load every
grain dict in the bank and run subdict_match -- O(bank-size) pickle
IO per query regardless of match count. At 500K-800K grain files per
master, that is ~13-46 s per grain-target query.

For predicates of the form "resource_id:<pattern>", the bank key
<type>:<id> carries the match answer. The new _resource_id_candidates
helper narrows the candidate set by fnmatch / regex against the id
portion of each bank key, and the main loop skips the per-match
pickle fetch entirely -- the master-side enforcement of
gdict["resource_id"] == <id> (see salt/master.py register handlers)
makes the shortcut provably correct.

Observed on a 3-master cluster at 1M SRs: grain-target queries drop
from ~46 s cold to ~0.5 s regardless of match count (100 or 300K).
Non-resource_id predicates (nested keys, other grain fields) still
go through the full fetch loop.

* docs: add _cluster_replicator to cache index and 3009.0 release stub

Pre-commit check-docs flagged salt.cache._cluster_replicator as missing
from doc/ref/cache/all/index.rst. Add it to the autosummary.

Prepare Release man-page build fails under sphinx -W because
doc/topics/releases/3009.0.md (generated during release prep) is orphan.
Add the release stub, the matching template, and 3009.* to the releases
toctree glob so the man build is clean.

* cache: driver-native store_many + mmap bridge to MmapCache.put_many

Cache.store_many previously looped self.store() per key regardless
of driver; the batched event path from _maybe_replicate_write_many
was in place but the local write still took the per-key lock on
mmap_cache. At scale (5 minions x 1024-key batches) this serialised
every MWorker on the per-bank .mmap_cache.idx.lock and reduced
mmap-backed register throughput to a trickle.

Two changes:
  - Cache.store_many now dispatches to a driver-native "store_many"
    function if the loaded driver exposes one, falling back to the
    per-item loop otherwise (preserves localfs / redis / consul
    compat).
  - salt/cache/mmap_cache.py gains a store_many that routes the
    batch through MmapCache.put_many so the whole set takes a
    single flock + batched fsync/msync set.

Ports the driver-level pieces from saltstack#70752 (closed) so the mmap
bank can keep up with the cross-master batched replicate path
this branch already ships.

* utils/minions: exact-key hash probe for literal resource_id predicates

``_augment_grain_match_with_resource_grains`` previously resolved every
``resource_id:<pattern>`` target by listing the entire
``resource_grains`` bank and iterating -- O(bank-size) per call (~400 ms
on a 400K-key bank).

Literal predicates (``resource_id:a-dummy-0000100`` with no wildcards)
are now routed to an O(T) hash probe across the configured resource
types via ``self.cache.contains(bank, "<rtype>:<rid>")`` where T is
``opts['resource_types']`` (small, typically 1-20). The master already
enforces ``bank-key == "<rtype>:<rid>"`` at register time so a probe
hit is the authoritative answer -- no bank list / per-key fetch.

Glob predicates (``resource_id:a-*``), nested predicates
(``resource_id:a:b``), regex form, non-``resource_id`` keys, and the
empty-pattern form all fall through to the existing behaviour.

Scope: literal-exact probe only. Sorted-key / reverse-value indices
and consistency metadata are out of scope for this change.

* utils/minions: sorted-key cache for resource_id prefix predicates

Adds an in-process sorted-key index of the ``resource_grains`` cache
bank so ``resource_id:<prefix>*`` style grain-target predicates can
binary-search the prefix range instead of linearly scanning + fnmatching
every entry. On a 400K-key bank a prefix query that matches ~100 keys
drops from ~500 ms to target <10 ms.

New module ``salt.utils.grain_target_cache`` holds
``{(cachedir, bank): (generation, sorted_keys)}`` guarded by a
module-level ``RLock``. Invalidation is driven by a cheap O(1)
per-bank generation signal -- the mmap_cache ``occupied_count`` header
field when available, otherwise the bank directory's ``st_mtime_ns``
(advances on any ``.p`` file add/remove/rename in the localfs driver).
Banks without a derivable signal rebuild on every query so correctness
is preserved.

Dispatch in ``_augment_grain_match_with_resource_grains`` is tiered:

1. Mission 1 literal probe for ``resource_id:<exact-id>`` (unchanged).
2. (new) Prefix fast path for ``resource_id:<glob>`` with a non-empty
   fixed prefix. Walks the sorted-key range per enabled rtype; for each
   candidate key confirms the full fnmatch pattern (handles the tail
   wildcards). Falls through if ``enabled_resource_types`` is empty so
   the linear scan still runs.
3. Existing linear ``cache.list()`` + fnmatch fallback.

Edge cases:
* ``resource_id:*foo*`` or ``resource_id:[abc]-*`` -- prefix is empty,
  dispatch falls through to the linear scan. Char-class enumeration
  was explicitly skipped (noted in the design spec); the existing
  fallback path handles it.
* PCRE (``regex_match=True``) -- prefix-of-regex analysis isn't worth
  the complexity; always falls through.
* Bank keys are ``<rtype>:<rid>`` composites; the fast path intersects
  per rtype so a single binary-search bound only covers one type's
  stride, giving O(K * log N + matches).

* utils/minions: reverse-value index for operator-declared grain keys

Adds an in-process reverse-value index keyed by
(cachedir, bank, frozenset(declared_keys)) that maps
(grain_key, value) -> [sr_key, ...] for the resource_grains bank.
The new opts list ``index_grain_keys`` names which grain keys to
index; a flat <grain_key>:<value> predicate on any declared key is
dispatched to the reverse-index lookup before falling into the
slow-path per-key cache.fetch + subdict_match loop.

Literal values are an O(matches) list read; glob and regex patterns
walk the indexed value set applying fnmatch / re.search and union
the matching sr_key lists. Lists / tuples are indexed per element
so predicates like 'tags:prod' match grains such as
tags = ['prod', 'us-east']. Nested dict values are skipped.

The index rebuilds lazily on the first lookup after a bank-generation
bump (mmap occupied-count header or bank-dir mtime, same signal as
Mission 2) and swallows build errors into an empty map so the slow
path still serves queries. Changing index_grain_keys forces a rebuild
(the declared-key frozenset is part of the cache key).

Empty / missing index_grain_keys keeps the legacy behaviour untouched.

* utils/mmap_trie_index: persistent trie-index primitive with streaming build

Add a persistent mmap-backed scalar-leaf index over the resource_grains
bank so grain-target predicates of arbitrary shape (nested
dns:nameservers:1.1.1.1, operator-undeclared keys, PCRE / glob values)
can be answered without walking the bank or holding a full reverse-map
in process RAM.

The index is a MmapCache keyed by b"<path-joined-by-\\x1e>\\x1f<value>"
holding msgpack-packed lists of sr_keys. High-cardinality buckets are
replaced with a msgpack-dict cap sentinel at
grain_trie_max_list_size (default 100000), which the dispatcher
detects and treats as "fall back to slow path" so operator-visible
results stay correct.

Rebuilds stream the primary bank one SR at a time, accumulate into a
bounded in-memory dict (default 1024 pending sr_keys), and flush via
MmapCache.put_many with merge-on-flush semantics so periodic flushes
inside a single rebuild do not overwrite earlier batches for the same
(path, value) key. Build output is atomic: files are written with a
.new suffix and os.replace()d into live names (heap, roster, index,
meta) so queries racing the rebuild see either the pre- or
post-rebuild state, never a torn mix.

Opt-in via enable_grain_trie_index; grain_trie_max_list_size and
grain_trie_build_batch_size tune the cardinality cap and flush
cadence.

* mmap_trie_index: switch leaf-list format from msgpack to length-prefixed binary

Mission 4 live measurement showed wide-match query latency on a 600K-element
sr_key list was ~78 s end-to-end, dominated by msgpack.unpackb; Mission 3's
in-process Python list was ~500 ms for similar counts. Replace the
msgpack.packb([sr_key, ...]) leaf encoding with a compact length-prefixed
binary format:

    byte 0        : 0xC1   (msgpack-reserved "never used" magic)
    byte 1..4     : uint32 LE  count of sr_keys
    byte 5..      : repeated:
                      uint16 LE  key length
                      <utf-8 key bytes>

Decode is a tight struct.unpack_from loop with no per-element Python object
overhead. _unpack_entry dispatches on the first byte: 0xC1 -> binary list;
otherwise -> msgpack (cap sentinel, and legacy msgpack-list entries from any
pre-upgrade build still decode). The cap sentinel keeps its msgpack dict
encoding; its leading bytes (0x80-0x8F or 0xDE/0xDF) never collide with 0xC1.

Also rejects sr_keys whose UTF-8 encoding exceeds the uint16 length field
with a friendly ValueError (programming error, not a data concern -- SR keys
are tens of bytes in practice).

Public API unchanged. Existing Mission 1-4 tests pass unchanged.

* tests/utils: coverage for binary leaf-list format

Mission 5 switches trie leaf-value sr_key lists from msgpack to a
length-prefixed binary format (magic byte 0xC1 + uint32 LE count +
repeated uint16 LE key length + UTF-8 key bytes). Cap sentinel stays
msgpack-encoded so the decode dispatcher branches on raw[0:1].

Adds seven tests:

* round-trip correctness across empty / 1 / 10 / 1000 / unicode cases
* magic-byte distinguishes from the cap sentinel (0xC1 is a reserved
  msgpack lead byte, chosen for exactly this purpose)
* short-buffer rejection (struct.error / ValueError / IndexError)
* 10K wide-list decode must be >=2x faster than msgpack (slow_test;
  the whole point of the Mission 5 switch)
* 10-element narrow-list decode must not regress >2x (overhead floor)
* end-to-end rebuild+lookup smoke on 10K SRs sharing a bucket
* mixed-magic-byte dispatch: list bucket + cap sentinel coexist and
  each routes through the correct decoder

Uses an import shim (_pack_list / _unpack_list) that probes a handful
of plausible helper names so the tests remain resilient to naming
drift and skip cleanly when the helpers are not yet landed.

* Revert "mmap_trie_index: switch leaf-list format from msgpack to length-prefixed binary"

This reverts commit 201fb0a.

* mmap_trie_index: chunk wide buckets instead of capping to sentinel

Mission 6 of the trie-index work. Previously a bucket whose total
sr_key count exceeded ``grain_trie_max_list_size`` was replaced with
a cap sentinel (``{"_capped": True, "count": N}``), discarding the
sr_keys and forcing queries to fall through to the legacy O(N)
``cache.fetch`` loop. A live-cluster ``dummy_grain_1:one`` match of
600K SRs took ~32 s that way.

Replace the "give up at cap" layout with chunked storage:

* The natural trie key stores a chunk marker:
  ``{"_chunks": N, "_total": T}`` (msgpack map; still distinguishable
  from a regular msgpack-array leaf).
* Chunk ``i`` lives under a derived key
  ``<natural_key> + b"\x1d" + f"{i:08X}".encode("ascii")``. The
  8-char uppercase-hex chunk index avoids NUL bytes -- MmapCache
  truncates keys at the first NUL, which would silently collapse
  chunk-0 (little-endian uint32 0 == four NULs) and all chunks after
  it onto the same slot. The ``\x1d`` separator is distinct from the
  Mission-4 path separators ``\x1e`` / ``\x1f``.
* Each chunk's value is a plain msgpack list, same shape as a small
  non-chunked bucket.

Flush path:

* No prior entry / legacy cap sentinel: write chunks directly if the
  new bucket exceeds ``max_list_size``, else a plain list.
* Prior list that overflows after merge: promote to chunks (rewrite
  everything -- rare, only on the growth transition).
* Prior chunks: touch only the LAST chunk until full, then roll over
  and start a new chunk. Earlier chunks are immutable within a
  rebuild, giving O(M) cumulative merge cost for a bucket growing to
  size M instead of the old O(M**2 / batch_size).

Query path:

* ``lookup_literal`` fans out to every chunk entry on a chunk-marker
  hit, concatenates the sr_key lists, and returns them to
  ``dispatch_predicate`` as if it were a single wide list.
* ``values_for_path`` skips chunk sub-keys (they carry no new value
  information; the natural key's marker still sits in ``list_keys``).
* An orphaned chunk marker or a missing chunk logs a WARNING and
  returns ``None`` so the caller falls back to the slow path until
  the next rebuild.

Back-compat: legacy ``_capped`` sentinels on disk from older builds
are recognised by the decoder and treated as "data was lost, trigger
slow path once". The next successful rebuild writes the bucket in
chunked form.

Benchmark (``FakeCache`` with 600_000 SRs matching one grain value,
cap 100_000):

* Build: ~3.4 s (unchanged within noise).
* Warm lookup: 29.7 ms, returns the full 600_000 sr_key list.

Down from 32 s via the legacy slow path -- a ~1000x speedup on the
live-cluster workload.

Memory discipline preserved: the only extra allocation during a flush
is the chunk-key bytes (~17 B each), bounded by the number of chunks
touched by that flush, not by total fleet size.

* tests/cli: migrate test_caller_resources fixture to opts-driven inventory

The branch's earlier commits (64657af, 2e01cc7, c380f5c)
replaced ``opts["pillar"]["resources"]`` with an opts-driven inventory
API (``resource_types`` + each type's ``discover(opts)``), but this test
file still seeded inventory via the deleted pillar path.  Result:
``_resolve_resource_targets`` returned ``[]`` and 7 of 8 tests failed
on CI.

* Fixture now sets ``resource_types = ["dummy"]`` +
  ``dummy_resource_count = 3`` so ``salt.resources.dummy.discover()``
  streams the three synthetic IDs the tests exercise.
* ID assertions updated from ``dummy-01..03`` to ``dummy-0000001..03``
  to match the module's fixed ``dummy-NNNNNNN`` (7-digit zero-padded)
  output -- the pre-refactor assertions hard-coded the shorter form
  that pillar seeding supplied.
* ``salt/cli/caller.py`` comment at the ``_resolve_resource_targets``
  call site refreshed to describe the opts-driven inventory API
  instead of the removed pillar-reading path.

* tests/unit: include resource_id in register-resources assertions

Mission 1's commit ``master: enforce resource_id == bank-key id at register
time`` normalizes ``resource_id`` into every grain dict stored by
``__register_resources_sync`` -- the id portion of the bank key
(``<type>:<id>``) is authoritative so grain targeting's
``resource_id:<glob>`` fast path can skip a per-match fetch.

Four ``test_master.py`` assertions compared the stored grain dict to the
raw ``resource_grains`` payload the test sent, which no longer matches
once the register path adds the normalized ``resource_id`` field.
Update each asserted dict to include it.

* minion: guard _register_resources_with_master against unset tok

Make the resource-register entry point defensive about ``self.tok``:
if auth has not populated the token yet, bail (debug-log) and let the
next trigger (pillar_refresh / tune_in) retry.  The attribute is
assigned on a successful ``connect_master`` handshake; a
``pillar_refresh`` that fires before the first handshake, a proxy
minion that has not yet attached its pub channel, or a bare ``Minion``
built for a unit test can all reach ``_send_register_chunk`` without
``tok`` set, which previously crashed with ``AttributeError: 'Minion'
object has no attribute 'tok'``.

This fixes the 7 metaproxy functional tests + 1 unit test
(``test_minion_keeps_schedule_on_master_reconnect``) that regressed
when ``_register_resources_with_master`` was wired into
``pillar_refresh``.

Also adapt the ``_threaded_minion_61830`` fixture in
``tests/pytests/unit/test_minion.py`` to the opts-driven resource
inventory API (see commit ``resources: remove pillar as
resource-inventory source on the minion``).  The pre-refactor fixture
set resources via pillar; after the refactor
``enabled_resource_types()`` reads ``opts["resource_types"]`` instead,
so the dummy type was never discovered and the sibling-job trigger
never fired -- ``AssertionError: sibling job never ran in the
window``.  Derive ``resource_types`` from the pillar dict and stub
``_iter_resource_ids`` to yield each type's declared IDs, same shim
pattern used in ``test_minion_resources.py``.  Fixes all 6
``test_thread_return_*_resource_job_owns_job_generation_61830``
parametrizations.

* tests/integration: migrate resources fixtures to opts-driven inventory

The ``resources/`` integration suite still seeded dummy-resource
inventory via ``opts["pillar"]["resources"]``, which earlier branch
commits (64657af, 2e01cc7, c380f5c) removed in favour of
the ``resource_types`` + per-type opts API consumed by
``salt.utils.resources.enabled_resource_types``.  Mirror the
pattern landed in 07c6b0b for the unit suite.

* Replace the pillar-seeded ``DUMMY_RESOURCES`` fixture with opts
  overrides on the minion fixtures: ``resource_types: ["dummy"]`` +
  ``dummy_resource_count: 3`` for the primary minion, and the same
  pair plus ``dummy_resource_id_prefix: "m2-"`` on the second minion
  so the two IDs sets stay disjoint.

* Update the shared ``DUMMY_RESOURCES`` constants to the dummy
  module's fixed ``dummy-NNNNNNN`` (7-digit zero-padded) output --
  ``dummy-0000001..3`` for minion 1, ``m2-dummy-0000001..2`` for
  minion 2 -- and refresh every hard-coded ID assertion across
  ``test_dummy_resource.py``, ``test_multi_minion_grain_targeting.py``,
  and ``test_resource_loader_strict.py``.  The grain-PCRE test's
  ``^dummy-0[12]$`` pattern becomes ``^dummy-000000[12]$``.

* Add ``resource_types: ["dummy", "dynamic_test"]`` to the salt_master
  fixture so the master-side literal
  ``resource_id:<id>`` fast-path in
  ``salt.utils.minions._augment_grain_match_with_resource_grains``
  can probe the bank keys per enabled rtype -- without it, the master
  never resolves single-id grain targets and the CLI exits with
  ``ERROR: No return received``.

* Rewrite ``test_pillar_addition_at_runtime_registers_new_resource``
  (pillar-only mechanism now gone) as
  ``test_all_configured_resources_registered_with_master`` -- same
  intent (every configured dummy ID reaches the master's
  ``resource_grains`` bank) without the dead pillar-mutation path.

* Rewrite ``test_minion_has_resources_configured`` to probe
  ``config.get resource_types`` + ``config.get dummy_resource_count``
  instead of the removed ``config.get resources`` path.

* ``test_cli_offline_expands_resource_targets.py``: declare
  inventory through opts (prefix ``off-cli-`` + count 3) and write
  the ``salt_resources`` subtree directly into the master's grains
  cache -- the in-tree ``salt/grains/resources.py`` still reads
  ``__opts__.get("resources")`` and under opts-driven inventory that
  is empty, so the master's primed grains cache does not carry the
  bank naturally.  Fixing that grain module is a separate change
  outside this suite's scope.

* The dynamic_test fixture keeps its pillar-reading contract (the
  whole point of the synthetic type is "discover() is authoritative";
  it legitimately reads a non-``resources`` pillar key) but now also
  sets ``resource_types: ["dynamic_test"]`` so the opts-driven
  loader enables the type.

* utils/minions: remove reverse-value grain index (superseded by trie)

The reverse-value index (``index_grain_keys``,
``grain_reverse_index``) covered operator-declared top-level grain
keys via an in-process ``{(grain_key, value) -> [sr_key, ...]}`` map.
The trie index (``enable_grain_trie_index``) subsumes every query
shape it handled -- plus nested paths, undeclared keys, and globs --
and keeps the data on mmap so process RAM stays flat with inventory.

Remove the opt-in config knob, the util module, the dispatch block
in ``CkMinions._augment_grain_match_with_resource_grains``, the
``_reverse_index_lookup`` method, the ``_indexed_grain_predicate``
helper, and the dedicated test suite. ``_augment_grain_match_with_
resource_grains`` now routes directly from the ``resource_id``
fast-path to the trie to the legacy per-key fetch loop; operators
who want fast arbitrary-grain lookups flip
``enable_grain_trie_index: True`` instead of enumerating keys.

* utils/minions: route grains-bank targeting through the trie

``_check_cache_minions`` on the per-minion ``grains`` bank was the
only grain-target entry point still doing an O(N) pickle-fetch loop
after Missions 1-4. Wire ``mmap_trie_index.dispatch_predicate`` in
front of the legacy loop so arbitrary ``<path>:<value>`` and nested
grain predicates hit the same persistent mmap trie that the
``resource_grains`` bank already uses.

The trie is bank-agnostic; no change to the primitive. Dispatch is
gated on ``opts["enable_grain_trie_index"]`` (same knob as the
resource-grains path). When the trie returns ``None`` (cap sentinel,
missing build, shape mismatch) we fall through to the legacy loop so
correctness is preserved even if the index subsystem is broken.
Trie-returned minions are intersected with the starting PKI /
cached-list set so an accepted-key filter is never bypassed by a
stale cached grain dict.

* docs: drop 3009.0 release stub from branch

The 3009.0 release notes file and the ``3009.*`` glob in the releases
index were pre-staged for the next release cycle, but they do not
belong on 3008.x -- Sphinx stops warning on the orphan page once the
release stub actually lands on the right branch.  Drop both so the
branch only carries 3008.x-shaped doc artifacts.

* docs: drop 3009.0 release template too

Follow-up to 1aea73e.  The template was introduced alongside the
3009.0 release stub; both belong on the next release cycle, not on
3008.x.

* mmap_trie_index: honor grain_trie_mmap_size opt + tests shrink mmap

Teaches for_bank to read the previously-documented-but-unwired
grain_trie_mmap_size knob and forward it to :class:.
Each bank's sparse trie.idx file is mmap_size * slot_size
bytes; the production default of 2_000_000 slots x 160-byte slots
yields a 320 MiB sparse file per bank. On CI runners with a
tmpfs-backed /tmp, a fleet of ~40 test_mmap_trie_index tests
plus the integration-test setup copying hundreds of MiB of fixtures
exhausts the tmpfs before the trie suite finishes, after which
MmapCache key-store writes silently drop and mm.get(key)
returns None for every lookup. That surfaced as
test_chunk_key_derivation_uses_1d_separator,
test_small_bucket_still_regular_list, and the other wide-bucket
assertions reporting the trie as empty on CI while all tests passed
locally.

The test adapter now passes grain_trie_mmap_size=200_000 (32 MiB
per bank) through the opts dict, and
test_rebuild_swaps_every_rolled_heap_segment which bypasses the
adapter for its grain_trie_mmap_max_segment_bytes override now
also passes grain_trie_mmap_size=50_000. Full file footprint
drops from ~12 GiB to ~1.3 GiB per run.

* tests/unit: drain PubServer subscribers before closing the test io_loop

test_minion_manager_destroy_after_closed_io_loop_does_not_raise closed
its ``manager.io_loop`` without first draining the manager's event
publisher and cancelling background tasks.  The PubServer's per-
subscriber ``_stream_read`` tasks are not part of
``manager._background_tasks``, so they survived loop teardown and
later asyncio emitted ``Task was destroyed but it is pending!`` from
a subsequent test's caplog, breaking saltstack#70748's regression check purely
as a test-cleanup artifact.  On CPython 3.14 the GC timing changed by
the resource-discovery streaming refactor makes the ghost task reach
the later test's capture window deterministically.

Close the event publisher first so each subscriber's ``_stream_read``
exits via ``StreamClosedError``, then cancel + gather the manager's
tracked background tasks, then close the loop.  Mirrors the pattern
already in ``spawn_minions_keeps_task_reference`` and
``bind_keeps_publisher_task_reference``.

* cluster-cache-replication: gate fan-out on peer handshake

Arm64 CI exercised a bootstrap race where master_1 fired a
cluster_aes-encrypted delegate-cache-write before master_2 finished
installing cluster_aes from the founder's join-reply.  master_2
could not decrypt the event, the receiver's handler ran
log.exception("Failed to decrypt..."), and the write was dropped.
Downstream tests expecting the write to have propagated timed out
at 60s.

Two complementary changes:

1. Sender-side handshake gate in salt.cache._cluster_replicator
   (filter_joined_pushers).  publish_cache_write /
   publish_resource_register_write now consult the publish daemon's
   _discover_replies + peer_keys sets before fanning out; peers that
   have not completed the discover/join handshake are skipped (and
   their catch-up is picked up by the join-time state_sync_cache_banks
   stream + subsequent write churn).  Default-on; operators can
   disable via cluster_cache_replicate_require_joined: False.

2. Correlatable, rate-limited receive-side log on decrypt failure
   (log_decrypt_failure).  Keeps the stack trace via log.exception
   but adds cluster_id, an 8-char sha256 fingerprint of cluster_aes
   (never the raw key), the event tag, and any caller-supplied
   extra context.  Repeated failures on the same (tag, source_peer)
   tuple within 5s are coalesced into a suppressed-count flushed
   on the next log.

Changelog: 70773.

* cluster/replication: fix per-key coalescer leak at skip-fan-out call sites

filter_joined_pushers() rate-limits WARN via (peer_host, context) in
_cluster_replicator._emit_skip_warn, but the two call sites in
channel/server.py passed context strings that embedded per-write keys:

    f"delegate-cache-write({bank}/{label})"
    f"delegate-resource-register-write({minion_id})"

Each unique write produced a new context tuple, bypassing the 5s
coalescer and growing _SKIP_LOG_LAST without bound for a busy master
with many skipped peers.  Caught by review of 6d6c9de; the unit
test used a static context so it did not exercise this path.

Strip the per-write suffix so coalescing collapses by stable event
tag.  Loses the per-key label in the WARN; operators keep bank/key
detail via the receiver-side log_decrypt_failure call which already
correlates on cluster_id + source peer.

* channel/server: suppress RUF006 on fire-and-forget dispatch create_task

Two ``asyncio.create_task`` calls added to the cluster event dispatcher
on this branch (``delegate_cache_write``, ``delegate_resource_register_write``)
trip ruff-incremental's RUF006 "store reference to task" rule.  The
sibling dispatches at lines 5091-5121 (sync_roots, collect_from_peers,
shed_unowned_all, delegate_write) are structurally identical and pre-
date the incremental base ref -- ruff treats them as "existing and not
enforced".  Match the existing fire-and-forget style with an inline
noqa so the incremental check passes without churning the surrounding
handler.

* cache/localfs: stage writes in sibling .localfs_tmp to avoid list race

Cluster cache replication (cluster_isolated_filesystem=True) can race
an in-process ``cache.list(bank)`` against a daemon-side
``cache.store(bank, ...)`` fan-out from a peer master.  The current
``localfs.store`` writes the tempfile with ``tempfile.mkstemp(dir=base)``
-- directly inside the bank directory -- so ``localfs.list`` enumerates
the stray ``tmpXXXXXXXX`` while the atomic rename is still in flight.

Repro: ``tests/pytests/integration/cluster/test_jobs_migration.py::
test_jobs_migration_round_trip`` on Debian 13 integration zeromq 3
(PR saltstack#70773 run 43380664466): master_1's PubServer applied a
``cluster/peer/delegate-cache-write`` broadcast from master_2 the
instant the test iterated ``jobs/loads``, so ``{jid-NNNN, tmpXXXXXXXX}``
appeared instead of just the 40 ``jid-NNNN`` entries.  Reproduced on
the first attempt inside the ``ghcr.io/saltstack/salt-ci-containers/
testing:debian-13`` image with downloaded test artifacts; also
observed on the saltstack/salt-nightlies 3008.x pipeline (same SHA
succeeded once and failed twice on consecutive runs).

Stage every write in ``<cachedir>/.localfs_tmp/`` first, then
``atomic_rename`` into the bank.  ``atomic_rename`` stays atomic
because both paths are under ``cachedir`` and therefore on the same
filesystem.  Structural fix -- any ``list_()`` scan at any point in
time now sees only ``.p`` cache files and completed sub-banks, never
in-flight mkstemp residue.

* cluster-cache-replication: queue-and-replay writes for un-joined peers

The sender-side handshake gate (14ddd5e) correctly refuses to fan
out cluster_aes-encrypted replication events to peers that have not
completed the cluster discover/join handshake, deferring to the
join-time state-sync stream to catch them up.  There is a narrow race,
visible on Arm64 CI under load: a write landing AFTER the state-sync
snapshot but BEFORE the peer enters this master's ``_discover_replies``
(or ``peer_keys``) is dropped by the gate and never caught up.  The
state-sync enumeration is taken synchronously when the join-reply is
emitted; any live write before the peer's ``discover-reply`` arrives
falls into a hole.

Fix: on every skipped fan-out, enqueue the pre-encrypted event in a
per-peer FIFO pending queue in the publish daemon.  On handshake
completion (either ``cluster/peer/discover-reply`` or the
``cluster/peer/<master_id>`` AES-key broadcast), drain the queue
through the peer's live pusher.  FIFO preserves write ordering; the
event remains decryptable because the peer installs the same
``cluster_aes`` during join-reply.

Memory bound: per-peer cap ``cluster_cache_replicate_pending_max_events``
(default 10_000) and age cap ``cluster_cache_replicate_pending_ttl``
(default 300s).  Overflow drops the oldest entry with a coalesced WARN.

Resolves the two Arm64 flakes on PR saltstack#70773 by eliminating the "write
missed state-sync + gate skip" hole:
  - test_grain_targeting_works_from_any_backend
  - test_resource_registry_replicates

Scope:
- salt/cache/_cluster_replicator.py: PendingEvent dataclass; enqueue /
  drain / flush helpers; filter_joined_pushers accepts an optional
  pending_event and enqueues to every skipped peer.
- salt/channel/server.py: publish_cache_write +
  publish_resource_register_write build the PendingEvent once and
  pass it to the filter; new _schedule_pending_flush method called
  from the two handshake-complete sites in handle_pool_publish.
- salt/config/__init__.py: two new opts.
- tests/pytests/unit/cache/test_cluster_replicator.py: 18 new tests
  (queue round-trip, cap, TTL, drain, flush, FIFO, requeue-on-error,
  staggered-join regression).
- tests/pytests/integration/cluster/test_cache_replication.py:
  test_live_write_during_join_window_reaches_late_joiner — new
  regression test for the live-write-after-join path.
- changelog/70773.fixed.md: append.

Design doc: agents/reports/design-bootstrap-race-fix.md

Local commit only; no push per task constraint.

* cluster-cache-replication: tighten pending-queue doc comment

Reviewer flagged "the gate never silently drops data on the floor" as
an overclaim: the pending queue is bounded by
cluster_cache_replicate_pending_max_events (default 10_000/peer) and
cluster_cache_replicate_pending_ttl (default 300s), and both cap-
eviction and TTL-expiry do drop events.  Cap-eviction coalesces a WARN
per peer, TTL-expiry is silent.  Describe the actual bound explicitly
so operators and future readers know the real contract.

* cluster-cache-replication: drop pending queues on cluster_aes change

Reviewer I-1 (followup-bootstrap-race-reviewer.md) flagged that the
sender-side pending-replication queue retains pre-encrypted events
after a cluster_aes change.  A peer that later installs the new key
cannot decrypt the queued bytes -- the exact ``Failed to decrypt``
silent-loss the gate was meant to prevent.

The hole surfaced as a real CI failure on PR saltstack#70773 run 43583387142
attempt 5 (AL2023 Arm64 + Photon OS 4 Arm64, integration zeromq):

  test_cache_replication.py::test_rejoining_master_catches_up FAILED
  AssertionError: pre-join seed did not replicate to running peer
    '127.0.0.2'; got {}

The mechanism is broader than operator-triggered rotation.  Any
cluster_aes CHANGE invalidates queued pre-encrypted events:

* rotation (SMaster.rotate_cluster_secret) -- previously known; and
* initial sync via ``cluster/peer/join-reply`` on a (re)joining
  master -- previously unflagged.

A (re)joining master boots with a randomly-generated local ``.aes``
file and fires writes before the cluster's authoritative key lands
via join-reply.  Those writes are enqueued pre-encrypted with the
master's fresh key; after join-reply replaces the key, peers see
``Failed to decrypt`` and the writes are silently dropped.

Fix (Option A in the task): add public ``drop_all_pending()`` in
``salt.cache._cluster_replicator`` and wire both change sites to call
it.  Queued entries cannot be re-encrypted (plaintext is not
retained); dropping is the only correctness-preserving option.  The
state-sync stream initiated by join-reply still ships the pre-join
snapshot, so no genuinely-replicated write is lost -- only the
pre-change queue of pre-encrypted bytes is cleared.

Call sites:

* ``SMaster.rotate_cluster_secret`` (salt/master.py:298) -- drop
  after the key swap and before the rotation event fires.
* ``cluster/peer/join-reply`` handler in salt/channel/server.py --
  drop after the new key is installed into shared memory and
  persisted to disk, guarded on ``prev != new`` so an idempotent
  install (same key already locally held) is a no-op.

The ``rotate_cluster_aes_key`` handler at master.py:1510 also goes
through ``SMaster.rotate_cluster_secret`` so no explicit wiring is
needed on that path.

New API: ``drop_all_pending(reason)`` clears every per-peer queue
under ``_PENDING_LOCK``, resets per-peer coalesced-log timers, emits
a single WARN that names the reason + aggregate drop count, and
returns the total.  Empty-state is a silent no-op.

Tests: 6 new unit tests in tests/pytests/unit/cache/
test_cluster_replicator.py cover empty-state no-op, aggregate clear
across multiple peer queues, the rotation-mid-flight reviewer
scenario, the join-reply initial-install scenario, concurrent
enqueue + drop under thread contention (no partial-queue state),
and the coalesce-log-timer reset.

Test results (local, x86):

* tests/pytests/unit/cache/test_cluster_replicator.py -- 47 passed
  (was 41; +6 new tests).
* tests/pytests/unit/cache/ + tests/pytests/unit/channel/ -- 387
  passed, 1 skipped.  Zero regressions.
* tests/pytests/unit/test_master.py -- 135 passed, 25 skipped.
* tests/pytests/integration/cluster/test_cache_replication.py::
  test_rejoining_master_catches_up -- PASSED (expected; the race
  needs Arm64 timing pressure to repro).
* The 3 secondary AL2023 Arm64 failures
  (test_isolated_cluster_pem_propagates,
  test_isolated_sync_roots_runner_file_only,
  test_shed_unowned_dry_run_preserves_state) all pass locally on
  x86; classified as same-root-cause suspects for CI to confirm.

Pre-commit: all hooks clean.

Scope discipline: no changes to salt/crypt, salt/transport, or
salt/cluster/consensus/.  No push.
dwoz added a commit that referenced this pull request Nov 17, 2026
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).
dwoz added a commit that referenced this pull request Nov 18, 2026
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).
dwoz added a commit that referenced this pull request Nov 18, 2026
* collect-from-peers: gate fan-out + per-peer sentinel eofs

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).

* sync_roots + multi-ring: gate fan-out on peer handshake

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).

* pending-flush: per-peer latch for handshake-driven flush ordering

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.

* cache-replication: cluster_aes fingerprint stamp + drop-on-mismatch

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>).

* state-sync barrier: threading.Lock for executor/loop concurrency

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).

* channel/server: founder-only cluster_aes attach on join-reply

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.

* channel/server: deprecate commit-6 cluster_aes gates to no-op shims

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).

* channel: add unified cluster-key propagation state machine

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.

* channel/server: gate cluster_aes + cluster.pem installs via state machine

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.

* tests/cluster: late-joiner-through-non-founder key convergence (I-2)

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).

* channel/server: founder commits own cluster keys to state machine

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.

* cluster/consensus: raise default election window for slow arm64 runners

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.

* crypt: MWorker reload cluster_key from disk before auth decrypt

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.

* crypt: reload cluster_key before sign/encrypt too

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants