Skip to content

Lint fixes for EC2 fix - #1

Closed
rallytime wants to merge 1 commit into
dwoz:awscloudfrom
rallytime:pr-47989
Closed

rallytime wants to merge 1 commit into
dwoz:awscloudfrom
rallytime:pr-47989

Conversation

@rallytime

Copy link
Copy Markdown

No description provided.

@rallytime rallytime closed this Jun 12, 2018
@rallytime
rallytime deleted the pr-47989 branch June 12, 2018 21:42
dwoz pushed a commit that referenced this pull request Oct 17, 2018
dwoz pushed a commit that referenced this pull request Nov 30, 2018
dwoz pushed a commit that referenced this pull request Jan 3, 2019
Update from upstream 20181221
dwoz pushed a commit that referenced this pull request Feb 7, 2019
dwoz pushed a commit that referenced this pull request Aug 2, 2019
dwoz pushed a commit that referenced this pull request Sep 29, 2019
dwoz pushed a commit that referenced this pull request Jan 3, 2020
dwoz pushed a commit that referenced this pull request Apr 11, 2020
dwoz added a commit that referenced this pull request May 5, 2020
dwoz pushed a commit that referenced this pull request Apr 5, 2024
dwoz pushed a commit that referenced this pull request Mar 25, 2026
Prevent exceptions with "fileserver.update" when called via state
dwoz added a commit that referenced this pull request May 9, 2026
…L bug

Adds the structural plumbing for ring-based cluster sharding without
changing today's broadcast semantics, and fixes a latent
``MmapCache.get`` corruption bug along the way.

Ring rollout — stage 0 (wire-in, no behaviour change)
* salt/cluster/ring_membership.py: per-process HashRing singleton
  with owns/rebuild/reset/get_ring.  EventMonitor's ring stays empty
  in its subprocess so owns() always returns True and the existing
  broadcast behaviour is preserved.
* salt/cluster/consensus/service.py: RaftService._on_membership_change
  now goes through _apply_ring_policy, which honours the ring SM's
  current members policy.  Default "self" rebuilds with the local
  node id only.
* salt/master.py: the three EventMonitor peer-receive sites
  (job /new, job /ret, key state) gate via ring_membership.owns().
  With self-only ring the gate is a tautology; future flip to voters
  policy activates real sharding without code change.

Ring rollout — stage 1 (RingConfigStateMachine + runner skeleton)
* salt/cluster/consensus/raft/log.py: RingConfigStateMachine, new
  LogEntryType.RING_CONFIG = 3.  Ring policy commits through Raft
  and survives compaction via the multi-SM snapshot envelope.
* salt/cluster/consensus/raft/node.py: apply_entries dispatches
  RING_CONFIG entries to the SM registered under "ring_sm".  Adds
  Node.reconcile_membership() for post-snapshot peer-table
  reconciliation (Gap #1 from GAPS.md).
* salt/cluster/consensus/service.py: propose_ring_config(members,
  replicas) leader-side API; _on_ring_config_change rebuilds the
  ring with the new policy.  cluster_max_log_size opt plumbed
  through to Node.
* salt/runners/cluster.py: ring_info read-only runner; ring_set
  raises NotImplementedError pending runner-to-RaftService IPC.

MmapCache NUL-byte corruption fix
* salt/utils/mmap_cache.py: drop the unconditional rstrip(b"\x00")
  in MmapCache.get and the rstrip-for-CRC inside
  _overwrite_in_heap.  The slot's LENGTH field is the single source
  of truth for the value byte boundary; trailing bytes from a
  previously-larger value remain in the heap as unreferenced
  garbage and are reclaimed by the next atomic_rebuild.  Pre-fix,
  any binary value (msgpack, protobuf, BSON) whose serialised form
  ended in NUL would either come back one byte short or fail CRC
  on read.

mmap heap segment cap is operator-tunable
* salt/cache/mmap_cache.py / salt/cache/mmap_key.py: read
  mmap_cache_max_segment_bytes / mmap_key_max_segment_bytes from
  __opts__ and forward to MmapCache(max_segment_bytes=…).  Defaults
  to 1 GiB.  mmap_key falls back to the generic opt so an operator
  setting the cap once covers both backends.

Tests added
* TestNodeReconcileMembership, TestSnapshotEnvelopeMultiSM,
  TestRingConfigStateMachine, TestNodeAppliesRingConfigEntry in
  tests/pytests/unit/cluster/consensus/test_raft_log.py.
* tests/pytests/unit/cluster/test_ring_membership.py — owns/rebuild
  semantics with empty and populated rings.
* tests/pytests/unit/test_event_monitor_ring_gating.py — gate sites
  drop writes when key not owned; preserve writes under self-only
  ring (pytest-asyncio is not installed in salt; tests drive
  EventMonitor.handle_event via asyncio.run rather than the silent
  no-op @pytest.mark.asyncio decorator).
* tests/pytests/unit/cache/test_mmap_cache.py — NUL-tail regression
  parametrised over representative trailing bytes; in-place
  overwrite with shorter NUL-tailed values; mmap_cache_max_segment
  _bytes opt plumbing.
* tests/pytests/unit/cache/test_mmap_key.py — opt plumbing +
  precedence rules.
* tests/pytests/unit/utils/test_mmap_cache_segments.py — multi-segment
  atomic_rebuild round-trip + packed-offset arithmetic.
* tests/pytests/unit/runners/test_cluster_runner.py — ring_info
  read-only contract; ring_set raises until IPC lands.
* tests/pytests/functional/cluster/consensus/test_raft_compaction.py —
  membership + ring policy survive log compaction; install_snapshot
  reconciles peer table.
* tests/pytests/functional/cluster/consensus/test_raft_service.py —
  TestRingRebuildHook + TestRingPolicyPlumbing covering the
  on_membership_change → _apply_ring_policy path under both
  members=self and members=voters.

Smoke list extended; full smoke run is 239 passed, 1 skipped (the
documented placeholder for the disruptive-candidate test).
dwoz added a commit that referenced this pull request May 11, 2026
…L bug

Adds the structural plumbing for ring-based cluster sharding without
changing today's broadcast semantics, and fixes a latent
``MmapCache.get`` corruption bug along the way.

Ring rollout — stage 0 (wire-in, no behaviour change)
* salt/cluster/ring_membership.py: per-process HashRing singleton
  with owns/rebuild/reset/get_ring.  EventMonitor's ring stays empty
  in its subprocess so owns() always returns True and the existing
  broadcast behaviour is preserved.
* salt/cluster/consensus/service.py: RaftService._on_membership_change
  now goes through _apply_ring_policy, which honours the ring SM's
  current members policy.  Default "self" rebuilds with the local
  node id only.
* salt/master.py: the three EventMonitor peer-receive sites
  (job /new, job /ret, key state) gate via ring_membership.owns().
  With self-only ring the gate is a tautology; future flip to voters
  policy activates real sharding without code change.

Ring rollout — stage 1 (RingConfigStateMachine + runner skeleton)
* salt/cluster/consensus/raft/log.py: RingConfigStateMachine, new
  LogEntryType.RING_CONFIG = 3.  Ring policy commits through Raft
  and survives compaction via the multi-SM snapshot envelope.
* salt/cluster/consensus/raft/node.py: apply_entries dispatches
  RING_CONFIG entries to the SM registered under "ring_sm".  Adds
  Node.reconcile_membership() for post-snapshot peer-table
  reconciliation (Gap #1 from GAPS.md).
* salt/cluster/consensus/service.py: propose_ring_config(members,
  replicas) leader-side API; _on_ring_config_change rebuilds the
  ring with the new policy.  cluster_max_log_size opt plumbed
  through to Node.
* salt/runners/cluster.py: ring_info read-only runner; ring_set
  raises NotImplementedError pending runner-to-RaftService IPC.

MmapCache NUL-byte corruption fix
* salt/utils/mmap_cache.py: drop the unconditional rstrip(b"\x00")
  in MmapCache.get and the rstrip-for-CRC inside
  _overwrite_in_heap.  The slot's LENGTH field is the single source
  of truth for the value byte boundary; trailing bytes from a
  previously-larger value remain in the heap as unreferenced
  garbage and are reclaimed by the next atomic_rebuild.  Pre-fix,
  any binary value (msgpack, protobuf, BSON) whose serialised form
  ended in NUL would either come back one byte short or fail CRC
  on read.

mmap heap segment cap is operator-tunable
* salt/cache/mmap_cache.py / salt/cache/mmap_key.py: read
  mmap_cache_max_segment_bytes / mmap_key_max_segment_bytes from
  __opts__ and forward to MmapCache(max_segment_bytes=…).  Defaults
  to 1 GiB.  mmap_key falls back to the generic opt so an operator
  setting the cap once covers both backends.

Tests added
* TestNodeReconcileMembership, TestSnapshotEnvelopeMultiSM,
  TestRingConfigStateMachine, TestNodeAppliesRingConfigEntry in
  tests/pytests/unit/cluster/consensus/test_raft_log.py.
* tests/pytests/unit/cluster/test_ring_membership.py — owns/rebuild
  semantics with empty and populated rings.
* tests/pytests/unit/test_event_monitor_ring_gating.py — gate sites
  drop writes when key not owned; preserve writes under self-only
  ring (pytest-asyncio is not installed in salt; tests drive
  EventMonitor.handle_event via asyncio.run rather than the silent
  no-op @pytest.mark.asyncio decorator).
* tests/pytests/unit/cache/test_mmap_cache.py — NUL-tail regression
  parametrised over representative trailing bytes; in-place
  overwrite with shorter NUL-tailed values; mmap_cache_max_segment
  _bytes opt plumbing.
* tests/pytests/unit/cache/test_mmap_key.py — opt plumbing +
  precedence rules.
* tests/pytests/unit/utils/test_mmap_cache_segments.py — multi-segment
  atomic_rebuild round-trip + packed-offset arithmetic.
* tests/pytests/unit/runners/test_cluster_runner.py — ring_info
  read-only contract; ring_set raises until IPC lands.
* tests/pytests/functional/cluster/consensus/test_raft_compaction.py —
  membership + ring policy survive log compaction; install_snapshot
  reconciles peer table.
* tests/pytests/functional/cluster/consensus/test_raft_service.py —
  TestRingRebuildHook + TestRingPolicyPlumbing covering the
  on_membership_change → _apply_ring_policy path under both
  members=self and members=voters.

Smoke list extended; full smoke run is 239 passed, 1 skipped (the
documented placeholder for the disruptive-candidate test).
dwoz added a commit that referenced this pull request May 12, 2026
…L bug

Adds the structural plumbing for ring-based cluster sharding without
changing today's broadcast semantics, and fixes a latent
``MmapCache.get`` corruption bug along the way.

Ring rollout — stage 0 (wire-in, no behaviour change)
* salt/cluster/ring_membership.py: per-process HashRing singleton
  with owns/rebuild/reset/get_ring.  EventMonitor's ring stays empty
  in its subprocess so owns() always returns True and the existing
  broadcast behaviour is preserved.
* salt/cluster/consensus/service.py: RaftService._on_membership_change
  now goes through _apply_ring_policy, which honours the ring SM's
  current members policy.  Default "self" rebuilds with the local
  node id only.
* salt/master.py: the three EventMonitor peer-receive sites
  (job /new, job /ret, key state) gate via ring_membership.owns().
  With self-only ring the gate is a tautology; future flip to voters
  policy activates real sharding without code change.

Ring rollout — stage 1 (RingConfigStateMachine + runner skeleton)
* salt/cluster/consensus/raft/log.py: RingConfigStateMachine, new
  LogEntryType.RING_CONFIG = 3.  Ring policy commits through Raft
  and survives compaction via the multi-SM snapshot envelope.
* salt/cluster/consensus/raft/node.py: apply_entries dispatches
  RING_CONFIG entries to the SM registered under "ring_sm".  Adds
  Node.reconcile_membership() for post-snapshot peer-table
  reconciliation (Gap #1 from GAPS.md).
* salt/cluster/consensus/service.py: propose_ring_config(members,
  replicas) leader-side API; _on_ring_config_change rebuilds the
  ring with the new policy.  cluster_max_log_size opt plumbed
  through to Node.
* salt/runners/cluster.py: ring_info read-only runner; ring_set
  raises NotImplementedError pending runner-to-RaftService IPC.

MmapCache NUL-byte corruption fix
* salt/utils/mmap_cache.py: drop the unconditional rstrip(b"\x00")
  in MmapCache.get and the rstrip-for-CRC inside
  _overwrite_in_heap.  The slot's LENGTH field is the single source
  of truth for the value byte boundary; trailing bytes from a
  previously-larger value remain in the heap as unreferenced
  garbage and are reclaimed by the next atomic_rebuild.  Pre-fix,
  any binary value (msgpack, protobuf, BSON) whose serialised form
  ended in NUL would either come back one byte short or fail CRC
  on read.

mmap heap segment cap is operator-tunable
* salt/cache/mmap_cache.py / salt/cache/mmap_key.py: read
  mmap_cache_max_segment_bytes / mmap_key_max_segment_bytes from
  __opts__ and forward to MmapCache(max_segment_bytes=…).  Defaults
  to 1 GiB.  mmap_key falls back to the generic opt so an operator
  setting the cap once covers both backends.

Tests added
* TestNodeReconcileMembership, TestSnapshotEnvelopeMultiSM,
  TestRingConfigStateMachine, TestNodeAppliesRingConfigEntry in
  tests/pytests/unit/cluster/consensus/test_raft_log.py.
* tests/pytests/unit/cluster/test_ring_membership.py — owns/rebuild
  semantics with empty and populated rings.
* tests/pytests/unit/test_event_monitor_ring_gating.py — gate sites
  drop writes when key not owned; preserve writes under self-only
  ring (pytest-asyncio is not installed in salt; tests drive
  EventMonitor.handle_event via asyncio.run rather than the silent
  no-op @pytest.mark.asyncio decorator).
* tests/pytests/unit/cache/test_mmap_cache.py — NUL-tail regression
  parametrised over representative trailing bytes; in-place
  overwrite with shorter NUL-tailed values; mmap_cache_max_segment
  _bytes opt plumbing.
* tests/pytests/unit/cache/test_mmap_key.py — opt plumbing +
  precedence rules.
* tests/pytests/unit/utils/test_mmap_cache_segments.py — multi-segment
  atomic_rebuild round-trip + packed-offset arithmetic.
* tests/pytests/unit/runners/test_cluster_runner.py — ring_info
  read-only contract; ring_set raises until IPC lands.
* tests/pytests/functional/cluster/consensus/test_raft_compaction.py —
  membership + ring policy survive log compaction; install_snapshot
  reconciles peer table.
* tests/pytests/functional/cluster/consensus/test_raft_service.py —
  TestRingRebuildHook + TestRingPolicyPlumbing covering the
  on_membership_change → _apply_ring_policy path under both
  members=self and members=voters.

Smoke list extended; full smoke run is 239 passed, 1 skipped (the
documented placeholder for the disruptive-candidate test).
dwoz added a commit that referenced this pull request May 12, 2026
…L bug

Adds the structural plumbing for ring-based cluster sharding without
changing today's broadcast semantics, and fixes a latent
``MmapCache.get`` corruption bug along the way.

Ring rollout — stage 0 (wire-in, no behaviour change)
* salt/cluster/ring_membership.py: per-process HashRing singleton
  with owns/rebuild/reset/get_ring.  EventMonitor's ring stays empty
  in its subprocess so owns() always returns True and the existing
  broadcast behaviour is preserved.
* salt/cluster/consensus/service.py: RaftService._on_membership_change
  now goes through _apply_ring_policy, which honours the ring SM's
  current members policy.  Default "self" rebuilds with the local
  node id only.
* salt/master.py: the three EventMonitor peer-receive sites
  (job /new, job /ret, key state) gate via ring_membership.owns().
  With self-only ring the gate is a tautology; future flip to voters
  policy activates real sharding without code change.

Ring rollout — stage 1 (RingConfigStateMachine + runner skeleton)
* salt/cluster/consensus/raft/log.py: RingConfigStateMachine, new
  LogEntryType.RING_CONFIG = 3.  Ring policy commits through Raft
  and survives compaction via the multi-SM snapshot envelope.
* salt/cluster/consensus/raft/node.py: apply_entries dispatches
  RING_CONFIG entries to the SM registered under "ring_sm".  Adds
  Node.reconcile_membership() for post-snapshot peer-table
  reconciliation (Gap #1 from GAPS.md).
* salt/cluster/consensus/service.py: propose_ring_config(members,
  replicas) leader-side API; _on_ring_config_change rebuilds the
  ring with the new policy.  cluster_max_log_size opt plumbed
  through to Node.
* salt/runners/cluster.py: ring_info read-only runner; ring_set
  raises NotImplementedError pending runner-to-RaftService IPC.

MmapCache NUL-byte corruption fix
* salt/utils/mmap_cache.py: drop the unconditional rstrip(b"\x00")
  in MmapCache.get and the rstrip-for-CRC inside
  _overwrite_in_heap.  The slot's LENGTH field is the single source
  of truth for the value byte boundary; trailing bytes from a
  previously-larger value remain in the heap as unreferenced
  garbage and are reclaimed by the next atomic_rebuild.  Pre-fix,
  any binary value (msgpack, protobuf, BSON) whose serialised form
  ended in NUL would either come back one byte short or fail CRC
  on read.

mmap heap segment cap is operator-tunable
* salt/cache/mmap_cache.py / salt/cache/mmap_key.py: read
  mmap_cache_max_segment_bytes / mmap_key_max_segment_bytes from
  __opts__ and forward to MmapCache(max_segment_bytes=…).  Defaults
  to 1 GiB.  mmap_key falls back to the generic opt so an operator
  setting the cap once covers both backends.

Tests added
* TestNodeReconcileMembership, TestSnapshotEnvelopeMultiSM,
  TestRingConfigStateMachine, TestNodeAppliesRingConfigEntry in
  tests/pytests/unit/cluster/consensus/test_raft_log.py.
* tests/pytests/unit/cluster/test_ring_membership.py — owns/rebuild
  semantics with empty and populated rings.
* tests/pytests/unit/test_event_monitor_ring_gating.py — gate sites
  drop writes when key not owned; preserve writes under self-only
  ring (pytest-asyncio is not installed in salt; tests drive
  EventMonitor.handle_event via asyncio.run rather than the silent
  no-op @pytest.mark.asyncio decorator).
* tests/pytests/unit/cache/test_mmap_cache.py — NUL-tail regression
  parametrised over representative trailing bytes; in-place
  overwrite with shorter NUL-tailed values; mmap_cache_max_segment
  _bytes opt plumbing.
* tests/pytests/unit/cache/test_mmap_key.py — opt plumbing +
  precedence rules.
* tests/pytests/unit/utils/test_mmap_cache_segments.py — multi-segment
  atomic_rebuild round-trip + packed-offset arithmetic.
* tests/pytests/unit/runners/test_cluster_runner.py — ring_info
  read-only contract; ring_set raises until IPC lands.
* tests/pytests/functional/cluster/consensus/test_raft_compaction.py —
  membership + ring policy survive log compaction; install_snapshot
  reconciles peer table.
* tests/pytests/functional/cluster/consensus/test_raft_service.py —
  TestRingRebuildHook + TestRingPolicyPlumbing covering the
  on_membership_change → _apply_ring_policy path under both
  members=self and members=voters.

Smoke list extended; full smoke run is 239 passed, 1 skipped (the
documented placeholder for the disruptive-candidate test).
dwoz added a commit that referenced this pull request May 12, 2026
…L bug

Adds the structural plumbing for ring-based cluster sharding without
changing today's broadcast semantics, and fixes a latent
``MmapCache.get`` corruption bug along the way.

Ring rollout — stage 0 (wire-in, no behaviour change)
* salt/cluster/ring_membership.py: per-process HashRing singleton
  with owns/rebuild/reset/get_ring.  EventMonitor's ring stays empty
  in its subprocess so owns() always returns True and the existing
  broadcast behaviour is preserved.
* salt/cluster/consensus/service.py: RaftService._on_membership_change
  now goes through _apply_ring_policy, which honours the ring SM's
  current members policy.  Default "self" rebuilds with the local
  node id only.
* salt/master.py: the three EventMonitor peer-receive sites
  (job /new, job /ret, key state) gate via ring_membership.owns().
  With self-only ring the gate is a tautology; future flip to voters
  policy activates real sharding without code change.

Ring rollout — stage 1 (RingConfigStateMachine + runner skeleton)
* salt/cluster/consensus/raft/log.py: RingConfigStateMachine, new
  LogEntryType.RING_CONFIG = 3.  Ring policy commits through Raft
  and survives compaction via the multi-SM snapshot envelope.
* salt/cluster/consensus/raft/node.py: apply_entries dispatches
  RING_CONFIG entries to the SM registered under "ring_sm".  Adds
  Node.reconcile_membership() for post-snapshot peer-table
  reconciliation (Gap #1 from GAPS.md).
* salt/cluster/consensus/service.py: propose_ring_config(members,
  replicas) leader-side API; _on_ring_config_change rebuilds the
  ring with the new policy.  cluster_max_log_size opt plumbed
  through to Node.
* salt/runners/cluster.py: ring_info read-only runner; ring_set
  raises NotImplementedError pending runner-to-RaftService IPC.

MmapCache NUL-byte corruption fix
* salt/utils/mmap_cache.py: drop the unconditional rstrip(b"\x00")
  in MmapCache.get and the rstrip-for-CRC inside
  _overwrite_in_heap.  The slot's LENGTH field is the single source
  of truth for the value byte boundary; trailing bytes from a
  previously-larger value remain in the heap as unreferenced
  garbage and are reclaimed by the next atomic_rebuild.  Pre-fix,
  any binary value (msgpack, protobuf, BSON) whose serialised form
  ended in NUL would either come back one byte short or fail CRC
  on read.

mmap heap segment cap is operator-tunable
* salt/cache/mmap_cache.py / salt/cache/mmap_key.py: read
  mmap_cache_max_segment_bytes / mmap_key_max_segment_bytes from
  __opts__ and forward to MmapCache(max_segment_bytes=…).  Defaults
  to 1 GiB.  mmap_key falls back to the generic opt so an operator
  setting the cap once covers both backends.

Tests added
* TestNodeReconcileMembership, TestSnapshotEnvelopeMultiSM,
  TestRingConfigStateMachine, TestNodeAppliesRingConfigEntry in
  tests/pytests/unit/cluster/consensus/test_raft_log.py.
* tests/pytests/unit/cluster/test_ring_membership.py — owns/rebuild
  semantics with empty and populated rings.
* tests/pytests/unit/test_event_monitor_ring_gating.py — gate sites
  drop writes when key not owned; preserve writes under self-only
  ring (pytest-asyncio is not installed in salt; tests drive
  EventMonitor.handle_event via asyncio.run rather than the silent
  no-op @pytest.mark.asyncio decorator).
* tests/pytests/unit/cache/test_mmap_cache.py — NUL-tail regression
  parametrised over representative trailing bytes; in-place
  overwrite with shorter NUL-tailed values; mmap_cache_max_segment
  _bytes opt plumbing.
* tests/pytests/unit/cache/test_mmap_key.py — opt plumbing +
  precedence rules.
* tests/pytests/unit/utils/test_mmap_cache_segments.py — multi-segment
  atomic_rebuild round-trip + packed-offset arithmetic.
* tests/pytests/unit/runners/test_cluster_runner.py — ring_info
  read-only contract; ring_set raises until IPC lands.
* tests/pytests/functional/cluster/consensus/test_raft_compaction.py —
  membership + ring policy survive log compaction; install_snapshot
  reconciles peer table.
* tests/pytests/functional/cluster/consensus/test_raft_service.py —
  TestRingRebuildHook + TestRingPolicyPlumbing covering the
  on_membership_change → _apply_ring_policy path under both
  members=self and members=voters.

Smoke list extended; full smoke run is 239 passed, 1 skipped (the
documented placeholder for the disruptive-candidate test).
dwoz added a commit that referenced this pull request May 12, 2026
…L bug

Adds the structural plumbing for ring-based cluster sharding without
changing today's broadcast semantics, and fixes a latent
``MmapCache.get`` corruption bug along the way.

Ring rollout — stage 0 (wire-in, no behaviour change)
* salt/cluster/ring_membership.py: per-process HashRing singleton
  with owns/rebuild/reset/get_ring.  EventMonitor's ring stays empty
  in its subprocess so owns() always returns True and the existing
  broadcast behaviour is preserved.
* salt/cluster/consensus/service.py: RaftService._on_membership_change
  now goes through _apply_ring_policy, which honours the ring SM's
  current members policy.  Default "self" rebuilds with the local
  node id only.
* salt/master.py: the three EventMonitor peer-receive sites
  (job /new, job /ret, key state) gate via ring_membership.owns().
  With self-only ring the gate is a tautology; future flip to voters
  policy activates real sharding without code change.

Ring rollout — stage 1 (RingConfigStateMachine + runner skeleton)
* salt/cluster/consensus/raft/log.py: RingConfigStateMachine, new
  LogEntryType.RING_CONFIG = 3.  Ring policy commits through Raft
  and survives compaction via the multi-SM snapshot envelope.
* salt/cluster/consensus/raft/node.py: apply_entries dispatches
  RING_CONFIG entries to the SM registered under "ring_sm".  Adds
  Node.reconcile_membership() for post-snapshot peer-table
  reconciliation (Gap #1 from GAPS.md).
* salt/cluster/consensus/service.py: propose_ring_config(members,
  replicas) leader-side API; _on_ring_config_change rebuilds the
  ring with the new policy.  cluster_max_log_size opt plumbed
  through to Node.
* salt/runners/cluster.py: ring_info read-only runner; ring_set
  raises NotImplementedError pending runner-to-RaftService IPC.

MmapCache NUL-byte corruption fix
* salt/utils/mmap_cache.py: drop the unconditional rstrip(b"\x00")
  in MmapCache.get and the rstrip-for-CRC inside
  _overwrite_in_heap.  The slot's LENGTH field is the single source
  of truth for the value byte boundary; trailing bytes from a
  previously-larger value remain in the heap as unreferenced
  garbage and are reclaimed by the next atomic_rebuild.  Pre-fix,
  any binary value (msgpack, protobuf, BSON) whose serialised form
  ended in NUL would either come back one byte short or fail CRC
  on read.

mmap heap segment cap is operator-tunable
* salt/cache/mmap_cache.py / salt/cache/mmap_key.py: read
  mmap_cache_max_segment_bytes / mmap_key_max_segment_bytes from
  __opts__ and forward to MmapCache(max_segment_bytes=…).  Defaults
  to 1 GiB.  mmap_key falls back to the generic opt so an operator
  setting the cap once covers both backends.

Tests added
* TestNodeReconcileMembership, TestSnapshotEnvelopeMultiSM,
  TestRingConfigStateMachine, TestNodeAppliesRingConfigEntry in
  tests/pytests/unit/cluster/consensus/test_raft_log.py.
* tests/pytests/unit/cluster/test_ring_membership.py — owns/rebuild
  semantics with empty and populated rings.
* tests/pytests/unit/test_event_monitor_ring_gating.py — gate sites
  drop writes when key not owned; preserve writes under self-only
  ring (pytest-asyncio is not installed in salt; tests drive
  EventMonitor.handle_event via asyncio.run rather than the silent
  no-op @pytest.mark.asyncio decorator).
* tests/pytests/unit/cache/test_mmap_cache.py — NUL-tail regression
  parametrised over representative trailing bytes; in-place
  overwrite with shorter NUL-tailed values; mmap_cache_max_segment
  _bytes opt plumbing.
* tests/pytests/unit/cache/test_mmap_key.py — opt plumbing +
  precedence rules.
* tests/pytests/unit/utils/test_mmap_cache_segments.py — multi-segment
  atomic_rebuild round-trip + packed-offset arithmetic.
* tests/pytests/unit/runners/test_cluster_runner.py — ring_info
  read-only contract; ring_set raises until IPC lands.
* tests/pytests/functional/cluster/consensus/test_raft_compaction.py —
  membership + ring policy survive log compaction; install_snapshot
  reconciles peer table.
* tests/pytests/functional/cluster/consensus/test_raft_service.py —
  TestRingRebuildHook + TestRingPolicyPlumbing covering the
  on_membership_change → _apply_ring_policy path under both
  members=self and members=voters.

Smoke list extended; full smoke run is 239 passed, 1 skipped (the
documented placeholder for the disruptive-candidate test).
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 pushed a commit that referenced this pull request May 14, 2026
The previous learner-registration commit (882fe44deee) wrote the
new CONFIG entry using ``membership_sm.current_voters()`` as the
voter list.  Two race conditions surfaced in
``tests/pytests/functional/cluster/consensus/test_raft_scenarios.py
::TestQuorumWithPendingLearner``:

1. **notify_peer_joined fires before the leader's first heartbeat-tick
   has written the founding CONFIG.**  ``current_voters()`` returns
   ``[]``; the learner-registration CONFIG therefore carried
   ``voters=[]``; ``on_config_change`` rebuilt ``self.peers`` from
   the new (empty) voter set; the leader's legitimate voting peers
   were dropped from ``peers`` and the cluster's effective quorum
   collapsed to 1 ("Quorum must be 2 for 3 voters; got 1").

2. **Order of operations.**  Even after fixing #1 by calling
   ``_maybe_commit_founding_config`` from inside
   ``notify_peer_joined``, the new learner was already in
   ``self._node.peers`` when ``_maybe_commit_founding_config``
   computed its ``bootstrap_pool``.  The founding CONFIG ended up
   listing the new learner as a *voter*, exactly the opposite of
   what notify_peer_joined was supposed to express.

Fix:

* Call ``_maybe_commit_founding_config`` **before** the new learner
  is appended to ``self._node.peers``.  The founding CONFIG now
  reflects the pre-join voter pool.
* Source the learner-registration CONFIG's voter/learner lists from
  ``self._node.peers`` (peer flags are updated eagerly by
  ``on_config_change`` on the leader before commit), not from
  ``membership_sm`` (which only updates after commit-apply).  This
  avoids the membership-SM lag immediately after the founding
  CONFIG is appended.
* ``_maybe_commit_founding_config`` now also short-circuits when
  ``membership_sm.current_voters()`` is non-empty (e.g. seeded by
  state-sync or test fixture), in addition to the existing
  ``log.index >= 0`` check.  Belt-and-braces against rewriting a
  founding CONFIG on top of inherited state.

Tests:

* tests/pytests/functional/cluster/consensus/test_raft_scenarios.py
  TestQuorumWithPendingLearner — all three scenarios now pass:
    test_entry_commits_without_learner_ack
    test_learner_does_not_count_towards_quorum
    test_two_of_three_voters_suffice_while_learner_is_present
* Full consensus battery: 465 tests pass.
dwoz pushed a commit that referenced this pull request May 14, 2026
Three of the new tests in tests/pytests/scenarios/regression/ kept failing
across the CI matrix for reasons that have nothing to do with the FD-leak
fix they were meant to guard:

  * test_fd_leak_job_thread_loop.py (both tests) fired test.ping with
    kwarg={"queue": True}, but `queue=True` is only a parameter of
    state.apply / state.sls. test.ping rejects it with SaltInvocationError
    so the minion never produces a normal return event, the assertion
    `Job did not complete` always trips. The same tests also passed
    `minion.id` (a bare string) to LocalClient.get_returns(jid, minions),
    which immediately does set(minions) and ends up matching against a
    set of single characters.

  * test_fd_leak_tcp_client_close.py and test_fd_leak_tcp_nested_syncwrapper.py
    spin up their own TCP master+minion pair inside a zmq-default scenarios
    session. The TCP auth handshake never converges in that configuration
    on a number of CI runners (Ubuntu 24.04, Photon ARM64) and saltfactories
    times out with FactoryNotStarted after ~384s. The two TCP fixes those
    tests are pointed at (#6, #7) are already exercised by the existing
    `scenarios tcp` CI variant, which runs the whole scenarios suite under
    a globally configured TCP transport.

Coverage left in place: tests/pytests/scenarios/queue/test_queue_fd_leak.py
(the comprehensive 15-queued-job test, green on both multiprocessing and
threading modes) plus the remaining regression tests in this directory
(asyncgens_executor, fire_event_async x2, ioloop_instance, syncwrapper_close,
task_cancellation, fd_threshold_queuing x2). Those collectively cover fixes
#1, #3, #4, #5, #8, and the FD-threshold queuing safety mechanism.
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 pushed a commit that referenced this pull request May 14, 2026
Three of the new tests in tests/pytests/scenarios/regression/ kept failing
across the CI matrix for reasons that have nothing to do with the FD-leak
fix they were meant to guard:

  * test_fd_leak_job_thread_loop.py (both tests) fired test.ping with
    kwarg={"queue": True}, but `queue=True` is only a parameter of
    state.apply / state.sls. test.ping rejects it with SaltInvocationError
    so the minion never produces a normal return event, the assertion
    `Job did not complete` always trips. The same tests also passed
    `minion.id` (a bare string) to LocalClient.get_returns(jid, minions),
    which immediately does set(minions) and ends up matching against a
    set of single characters.

  * test_fd_leak_tcp_client_close.py and test_fd_leak_tcp_nested_syncwrapper.py
    spin up their own TCP master+minion pair inside a zmq-default scenarios
    session. The TCP auth handshake never converges in that configuration
    on a number of CI runners (Ubuntu 24.04, Photon ARM64) and saltfactories
    times out with FactoryNotStarted after ~384s. The two TCP fixes those
    tests are pointed at (#6, #7) are already exercised by the existing
    `scenarios tcp` CI variant, which runs the whole scenarios suite under
    a globally configured TCP transport.

Coverage left in place: tests/pytests/scenarios/queue/test_queue_fd_leak.py
(the comprehensive 15-queued-job test, green on both multiprocessing and
threading modes) plus the remaining regression tests in this directory
(asyncgens_executor, fire_event_async x2, ioloop_instance, syncwrapper_close,
task_cancellation, fd_threshold_queuing x2). Those collectively cover fixes
#1, #3, #4, #5, #8, and the FD-threshold queuing safety mechanism.
dwoz pushed a commit that referenced this pull request May 14, 2026
The previous learner-registration commit (882fe44deee) wrote the
new CONFIG entry using ``membership_sm.current_voters()`` as the
voter list.  Two race conditions surfaced in
``tests/pytests/functional/cluster/consensus/test_raft_scenarios.py
::TestQuorumWithPendingLearner``:

1. **notify_peer_joined fires before the leader's first heartbeat-tick
   has written the founding CONFIG.**  ``current_voters()`` returns
   ``[]``; the learner-registration CONFIG therefore carried
   ``voters=[]``; ``on_config_change`` rebuilt ``self.peers`` from
   the new (empty) voter set; the leader's legitimate voting peers
   were dropped from ``peers`` and the cluster's effective quorum
   collapsed to 1 ("Quorum must be 2 for 3 voters; got 1").

2. **Order of operations.**  Even after fixing #1 by calling
   ``_maybe_commit_founding_config`` from inside
   ``notify_peer_joined``, the new learner was already in
   ``self._node.peers`` when ``_maybe_commit_founding_config``
   computed its ``bootstrap_pool``.  The founding CONFIG ended up
   listing the new learner as a *voter*, exactly the opposite of
   what notify_peer_joined was supposed to express.

Fix:

* Call ``_maybe_commit_founding_config`` **before** the new learner
  is appended to ``self._node.peers``.  The founding CONFIG now
  reflects the pre-join voter pool.
* Source the learner-registration CONFIG's voter/learner lists from
  ``self._node.peers`` (peer flags are updated eagerly by
  ``on_config_change`` on the leader before commit), not from
  ``membership_sm`` (which only updates after commit-apply).  This
  avoids the membership-SM lag immediately after the founding
  CONFIG is appended.
* ``_maybe_commit_founding_config`` now also short-circuits when
  ``membership_sm.current_voters()`` is non-empty (e.g. seeded by
  state-sync or test fixture), in addition to the existing
  ``log.index >= 0`` check.  Belt-and-braces against rewriting a
  founding CONFIG on top of inherited state.

Tests:

* tests/pytests/functional/cluster/consensus/test_raft_scenarios.py
  TestQuorumWithPendingLearner — all three scenarios now pass:
    test_entry_commits_without_learner_ack
    test_learner_does_not_count_towards_quorum
    test_two_of_three_voters_suffice_while_learner_is_present
* Full consensus battery: 465 tests pass.
dwoz pushed a commit that referenced this pull request May 22, 2026
The test monkeypatched ``builtins.__import__`` with a passthrough
that called the unqualified ``__import__(name, *args, **kwargs)``.
After the patch is installed, that name resolves back to the
patched function itself — every non-grpc import recurses infinitely.

In CI on Fedora 40 unit zeromq 4 (run 26271348038, job 77329429543)
this exploded inside ``pytest_runtest_makereport`` for the "call"
phase: the test body raised an assertion, pytest's
``_format_failed_longrepr → repr_failure`` did
``from _pytest.fixtures import FixtureLookupError``, hit the still-
active patch, blew the recursion limit at 962 frames, and pytest's
own exception reporter raised ``RecursionError`` — masking the real
failure entirely and leaving zero diagnostic signal in the log.

The fix is twofold:

  1. Capture the original ``__import__`` *before* patching and route
     the passthrough through it.  Now the passthrough is recursion-
     safe regardless of how it's invoked.

  2. Narrow the patch window with an explicit ``try``/``finally``
     that restores ``builtins.__import__`` *before* the assertions
     run.  Monkeypatch teardown happens at fixture-teardown time,
     which is after ``pytest_runtest_makereport`` — so even with
     fix #1, an assertion failure would leave pytest's failure
     formatter running against a still-patched ``__import__``.
     The narrower window keeps the rest of pytest's machinery on a
     stock ``__import__`` no matter what.

Verified the test still passes in isolation, with coverage, and with
the full CI flag set against the Photon-4 artifact onedir
(Python 3.14.5, coverage 7.14.0, FIPS module loaded).

Once this lands, CI's next run will surface the real underlying
test failure with a clean traceback instead of the recursion noise.
dwoz pushed a commit that referenced this pull request May 23, 2026
The test monkeypatched ``builtins.__import__`` with a passthrough
that called the unqualified ``__import__(name, *args, **kwargs)``.
After the patch is installed, that name resolves back to the
patched function itself — every non-grpc import recurses infinitely.

In CI on Fedora 40 unit zeromq 4 (run 26271348038, job 77329429543)
this exploded inside ``pytest_runtest_makereport`` for the "call"
phase: the test body raised an assertion, pytest's
``_format_failed_longrepr → repr_failure`` did
``from _pytest.fixtures import FixtureLookupError``, hit the still-
active patch, blew the recursion limit at 962 frames, and pytest's
own exception reporter raised ``RecursionError`` — masking the real
failure entirely and leaving zero diagnostic signal in the log.

The fix is twofold:

  1. Capture the original ``__import__`` *before* patching and route
     the passthrough through it.  Now the passthrough is recursion-
     safe regardless of how it's invoked.

  2. Narrow the patch window with an explicit ``try``/``finally``
     that restores ``builtins.__import__`` *before* the assertions
     run.  Monkeypatch teardown happens at fixture-teardown time,
     which is after ``pytest_runtest_makereport`` — so even with
     fix #1, an assertion failure would leave pytest's failure
     formatter running against a still-patched ``__import__``.
     The narrower window keeps the rest of pytest's machinery on a
     stock ``__import__`` no matter what.

Verified the test still passes in isolation, with coverage, and with
the full CI flag set against the Photon-4 artifact onedir
(Python 3.14.5, coverage 7.14.0, FIPS module loaded).

Once this lands, CI's next run will surface the real underlying
test failure with a clean traceback instead of the recursion noise.
dwoz pushed a commit that referenced this pull request May 30, 2026
The test monkeypatched ``builtins.__import__`` with a passthrough
that called the unqualified ``__import__(name, *args, **kwargs)``.
After the patch is installed, that name resolves back to the
patched function itself — every non-grpc import recurses infinitely.

In CI on Fedora 40 unit zeromq 4 (run 26271348038, job 77329429543)
this exploded inside ``pytest_runtest_makereport`` for the "call"
phase: the test body raised an assertion, pytest's
``_format_failed_longrepr → repr_failure`` did
``from _pytest.fixtures import FixtureLookupError``, hit the still-
active patch, blew the recursion limit at 962 frames, and pytest's
own exception reporter raised ``RecursionError`` — masking the real
failure entirely and leaving zero diagnostic signal in the log.

The fix is twofold:

  1. Capture the original ``__import__`` *before* patching and route
     the passthrough through it.  Now the passthrough is recursion-
     safe regardless of how it's invoked.

  2. Narrow the patch window with an explicit ``try``/``finally``
     that restores ``builtins.__import__`` *before* the assertions
     run.  Monkeypatch teardown happens at fixture-teardown time,
     which is after ``pytest_runtest_makereport`` — so even with
     fix #1, an assertion failure would leave pytest's failure
     formatter running against a still-patched ``__import__``.
     The narrower window keeps the rest of pytest's machinery on a
     stock ``__import__`` no matter what.

Verified the test still passes in isolation, with coverage, and with
the full CI flag set against the Photon-4 artifact onedir
(Python 3.14.5, coverage 7.14.0, FIPS module loaded).

Once this lands, CI's next run will surface the real underlying
test failure with a clean traceback instead of the recursion noise.
dwoz pushed a commit that referenced this pull request Jun 1, 2026
The test monkeypatched ``builtins.__import__`` with a passthrough
that called the unqualified ``__import__(name, *args, **kwargs)``.
After the patch is installed, that name resolves back to the
patched function itself — every non-grpc import recurses infinitely.

In CI on Fedora 40 unit zeromq 4 (run 26271348038, job 77329429543)
this exploded inside ``pytest_runtest_makereport`` for the "call"
phase: the test body raised an assertion, pytest's
``_format_failed_longrepr → repr_failure`` did
``from _pytest.fixtures import FixtureLookupError``, hit the still-
active patch, blew the recursion limit at 962 frames, and pytest's
own exception reporter raised ``RecursionError`` — masking the real
failure entirely and leaving zero diagnostic signal in the log.

The fix is twofold:

  1. Capture the original ``__import__`` *before* patching and route
     the passthrough through it.  Now the passthrough is recursion-
     safe regardless of how it's invoked.

  2. Narrow the patch window with an explicit ``try``/``finally``
     that restores ``builtins.__import__`` *before* the assertions
     run.  Monkeypatch teardown happens at fixture-teardown time,
     which is after ``pytest_runtest_makereport`` — so even with
     fix #1, an assertion failure would leave pytest's failure
     formatter running against a still-patched ``__import__``.
     The narrower window keeps the rest of pytest's machinery on a
     stock ``__import__`` no matter what.

Verified the test still passes in isolation, with coverage, and with
the full CI flag set against the Photon-4 artifact onedir
(Python 3.14.5, coverage 7.14.0, FIPS module loaded).

Once this lands, CI's next run will surface the real underlying
test failure with a clean traceback instead of the recursion noise.
dwoz pushed a commit that referenced this pull request Jun 6, 2026
The test monkeypatched ``builtins.__import__`` with a passthrough
that called the unqualified ``__import__(name, *args, **kwargs)``.
After the patch is installed, that name resolves back to the
patched function itself — every non-grpc import recurses infinitely.

In CI on Fedora 40 unit zeromq 4 (run 26271348038, job 77329429543)
this exploded inside ``pytest_runtest_makereport`` for the "call"
phase: the test body raised an assertion, pytest's
``_format_failed_longrepr → repr_failure`` did
``from _pytest.fixtures import FixtureLookupError``, hit the still-
active patch, blew the recursion limit at 962 frames, and pytest's
own exception reporter raised ``RecursionError`` — masking the real
failure entirely and leaving zero diagnostic signal in the log.

The fix is twofold:

  1. Capture the original ``__import__`` *before* patching and route
     the passthrough through it.  Now the passthrough is recursion-
     safe regardless of how it's invoked.

  2. Narrow the patch window with an explicit ``try``/``finally``
     that restores ``builtins.__import__`` *before* the assertions
     run.  Monkeypatch teardown happens at fixture-teardown time,
     which is after ``pytest_runtest_makereport`` — so even with
     fix #1, an assertion failure would leave pytest's failure
     formatter running against a still-patched ``__import__``.
     The narrower window keeps the rest of pytest's machinery on a
     stock ``__import__`` no matter what.

Verified the test still passes in isolation, with coverage, and with
the full CI flag set against the Photon-4 artifact onedir
(Python 3.14.5, coverage 7.14.0, FIPS module loaded).

Once this lands, CI's next run will surface the real underlying
test failure with a clean traceback instead of the recursion noise.
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 Oct 30, 2026
Inside the `if is_client:` branches of master.publish, masterapi.runner,
and masterapi.wheel the `username` variable is misleading -- the auth
system returns the identity under that key because it was built for human
users, but on this path the identity is the client installation (e.g.
'admin-workstation'), not a person.

Alias `client_id = username` (in masterapi.runner / masterapi.wheel) or
rename `username` -> `auth_identity` + alias `client_id` (in
master.publish) inside the client branches and use `client_id` in log
messages and ACL calls, so the code says what it means.

Left for later (ties into deferred #3, human-user forwarding):
`clear_load["user"] = client_id` still assigns the client identity to
the publish job's `user` field.  That leaks into job returners / event
tags / audit log and conflates clients with humans.  Flagged in a TODO
comment at salt/master.py:5607 to split into a dedicated
`clear_load["client_id"]` field once the user-forwarding story lands.
dwoz added a commit that referenced this pull request Nov 2, 2026
Inside the `if is_client:` branches of master.publish, masterapi.runner,
and masterapi.wheel the `username` variable is misleading -- the auth
system returns the identity under that key because it was built for human
users, but on this path the identity is the client installation (e.g.
'admin-workstation'), not a person.

Alias `client_id = username` (in masterapi.runner / masterapi.wheel) or
rename `username` -> `auth_identity` + alias `client_id` (in
master.publish) inside the client branches and use `client_id` in log
messages and ACL calls, so the code says what it means.

Left for later (ties into deferred #3, human-user forwarding):
`clear_load["user"] = client_id` still assigns the client identity to
the publish job's `user` field.  That leaks into job returners / event
tags / audit log and conflates clients with humans.  Flagged in a TODO
comment at salt/master.py:5607 to split into a dedicated
`clear_load["client_id"]` field once the user-forwarding story lands.
dwoz added a commit that referenced this pull request Nov 4, 2026
Inside the `if is_client:` branches of master.publish, masterapi.runner,
and masterapi.wheel the `username` variable is misleading -- the auth
system returns the identity under that key because it was built for human
users, but on this path the identity is the client installation (e.g.
'admin-workstation'), not a person.

Alias `client_id = username` (in masterapi.runner / masterapi.wheel) or
rename `username` -> `auth_identity` + alias `client_id` (in
master.publish) inside the client branches and use `client_id` in log
messages and ACL calls, so the code says what it means.

Left for later (ties into deferred #3, human-user forwarding):
`clear_load["user"] = client_id` still assigns the client identity to
the publish job's `user` field.  That leaks into job returners / event
tags / audit log and conflates clients with humans.  Flagged in a TODO
comment at salt/master.py:5607 to split into a dedicated
`clear_load["client_id"]` field once the user-forwarding story lands.
dwoz added a commit that referenced this pull request Nov 5, 2026
* Rebase remote CLI implementation onto latest master

This commit rebases the remote CLI client authentication and ACL
implementation from the 6-month-old base (713a9238c4b) onto the
current master (021a041a0be - 2,111 commits ahead).

Resolved Conflicts:
- salt/cli/key.py: Combined context manager with client_auth check
- salt/config/__init__.py: Merged tracing/metrics configs with encryption configs
- salt/crypt.py: Combined role-based PKI paths with _creds bug fix
- salt/daemons/masterapi.py: Added wheel and client ACL initialization
- salt/channel/server.py: Kept updated auth logic and class structure
- tests/pytests/unit/test_master.py: Merged test fixture configurations

salt/master.py Resolution:
Accepted master's version due to extensive refactoring (8 conflicts).
The client ACL publish checks from our implementation need to be
re-applied in a follow-up commit. Original logic is in wip-remote-cli
branch for reference.

Next Steps:
1. Re-add client ACL checking to salt/master.py minion_publish()
2. Run full test suite to verify functionality
3. Update any broken tests due to master refactoring

* Re-add client ACL logic to publish() method after rebase

After rebasing onto the latest master (2,111 commits), the client ACL
logic that was in the old publish() method needed to be re-added to the
new refactored publish() method in ClearFuncs.

Changes:
- Added client_acl initialization in AESFuncs.__init__
- Added client detection logic that checks if the username is in
  client_keys cache (indicates client authentication)
- Added client ACL checking that:
  * Checks blacklist first (takes precedence)
  * Uses ClientACL helper to check publish permissions
  * Logs success and sets username in clear_load
- Modified standard authorization check to skip for clients since
  they use client ACL instead

All 35 client ACL tests pass:
- 4 runner ACL tests
- 3 wheel ACL tests
- 2 ACL error message tests
- 4 backward compatibility tests
- 2 multiple clients tests
- 2 ACL revocation tests
- 2 unknown client tests
- 14 publish ACL tests (new)
- 2 publish error message tests

Also verified:
- 12/12 client authentication tests pass
- 9/9 client lifecycle scenario tests pass

The rebase is now complete with all client ACL functionality preserved
and working correctly on the latest master.

* Fix lint error: Add key_cache and client_acl to ClearFuncs

The publish() method in ClearFuncs was accessing self.key_cache and
self.client_acl, but these were only initialized in AESFuncs.__init__.

Added initialization of both attributes in ClearFuncs.__init__ to
fix the pylint error:
  E1101(no-member): Instance of 'ClearFuncs' has no 'key_cache' member

This ensures that publish() in ClearFuncs can properly check client
authentication and enforce ACLs.

* Fix rebase error: Remove misplaced auth code from close() method

During the rebase, authentication code (lines 688-724) was incorrectly
merged into the ReqServerChannel.close() method in salt/channel/server.py.

This caused pylint errors:
  E0602(undefined-variable): Undefined variable 'load'
  E0602(undefined-variable): Undefined variable 'sign_messages'
  E0602(undefined-variable): Undefined variable 'sig_algo'

Fixed by removing the misplaced authentication code that was using
undefined variables within the close() method. The close() method
now correctly ends after cleaning up ckminions, as in upstream master.

Verified with:
- pylint: 10.00/10 rating
- test_client_auth_payload_structure: PASSED

* Fix black formatting: Remove extra blank lines

Black formatting check failed because there were 3 extra blank lines
in salt/config/__init__.py that need to be removed:
- Line 1999: After eauth_tokens.cluster_id
- Line 2070: After metrics config block
- Line 2074: After signing_algorithm

* Restore backwards compatibility for salt command

The salt command should use LocalClient by default (for local master
usage) and only use RemoteClient when the --client-auth flag is passed.
This maintains backwards compatibility with existing salt deployments.

Changes:
- salt/cli/salt.py: Use get_local_client() by default, get_remote_client()
  only when --client-auth is specified
- salt/utils/parsers.py: Add --client-auth flag to SaltCMDOptionParser

This makes the salt command consistent with salt-run and salt-key, where
--client-auth is an opt-in flag for remote PKI-based authentication.

* Add intelligent auto-detection for client authentication

Eliminate the need for explicit --client-auth flags in most cases by
automatically detecting the appropriate authentication method based on
the environment.

Detection logic for all commands (salt, salt-run, salt-key):

1. If --client-auth is explicitly set (True/False), respect that choice
2. Otherwise, auto-detect:
   - Try traditional local execution (LocalClient or user permission check)
   - If that fails AND client keys exist, automatically use RemoteClient
   - If neither works, fail with appropriate error

Benefits:
- Backwards compatible: existing local deployments work unchanged
- Zero configuration for remote: once client keys are accepted, remote
  execution "just works" without flags
- Explicit control still available via --client-auth flag when needed

Examples:
- On master with proper permissions: Uses LocalClient (traditional)
- On remote machine with client keys: Uses RemoteClient (automatic)
- No keys, no permissions: Fails with clear error message

* Add /etc/salt/client config with profile support for multiple masters

Introduces a dedicated client configuration file that allows managing
connections to multiple Salt masters through profiles.

Features:
- Dedicated /etc/salt/client config file
- Profile support for switching between masters
- Automatic fallback to /etc/salt/master (backwards compatible)
- User overrides via ~/.saltrc still work

Configuration example (/etc/salt/client):
```yaml
# Default connection (used when no --profile specified)
master: localhost
id: admin-laptop

# Multiple master profiles
profiles:
  prod:
    master: prod-salt.example.com
    id: admin-laptop-prod
  dev:
    master: dev-salt.example.com
    id: admin-laptop-dev
```

Usage:
- salt --profile=prod '*' test.ping
- salt-run --profile=dev jobs.list_jobs
- salt-key --profile=prod -L

Benefits:
- One config file for all CLI tools (salt, salt-run, salt-key)
- Easy switching between multiple masters
- Backwards compatible with existing /etc/salt/master usage
- Default behavior unchanged (local master via IPC)

* Implement authenticated event streaming for truly remote clients

Adds network-based event delivery so RemoteClient can work from
machines that are not on the Salt master.

## Architecture

**Client Event Publisher (Port 4507)**
- Runs as separate process on the master
- Requires client PKI authentication
- Subscribes to master event bus (IPC)
- Filters and publishes events to authenticated clients

**Client Event Subscriber**
- Network-based event subscription for RemoteClient
- Authenticates using client keys
- Subscribes to specific job events
- Receives filtered events over TCP

## Event Filtering

Clients only receive events for:
- Jobs they initiated (by JID)
- Events they explicitly subscribe to

System/admin events are filtered out for security.

## Components

**salt/utils/client_event.py** (new file)
- ClientEventPublisher: Master-side authenticated event publisher
- ClientEventSubscriber: Client-side network event subscriber

**salt/client/__init__.py**
- RemoteClient now uses ClientEventSubscriber instead of IPC
- Automatically subscribes to job events on pub()
- Fixed master_uri to use configured master, not interface

**salt/config/__init__.py**
- Added client_event_port config (default: 4507)
- Added client_event_publish config (default: True)

**salt/master.py**
- Integrated ClientEventPublisher into master daemon startup
- Started alongside other master processes

## Benefits

✅ Remote CLI tools work from any machine (not just on master)
✅ No salt-api required
✅ Secure (requires client key authentication)
✅ Event filtering prevents information leakage
✅ Backwards compatible (can be disabled)

## Configuration

Enable/disable in master config:
```yaml
client_event_publish: True  # Enable event publisher
client_event_port: 4507      # Publisher port
```

## Usage

RemoteClient now works transparently from remote machines:
```python
# On a laptop (not on the master)
client = salt.client.get_remote_client(profile='prod')
client.cmd('*', 'test.ping')  # Works! Events streamed over network
```

* Add network event support for salt-run and salt-key remote execution

This commit enables salt-run (RunnerClient) and salt-key (WheelClient)
to work fully remotely by adding intelligent network event detection.

Changes:
- Add _should_use_network_events() method to RunnerClient and WheelClient
- Auto-detect remote execution based on:
  * __role == "client" (explicit client auth)
  * Remote master (not localhost/127.0.0.1/::1)
  * Missing IPC socket + existing client keys
- Use ClientEventSubscriber for remote execution
- Preserve IPC events for local execution (backwards compatible)

This complements the existing network event support in RemoteClient,
ensuring all three CLI tools (salt, salt-run, salt-key) can be run
fully remotely without requiring access to master IPC sockets.

* Fix scenario and integration tests to detect network event bugs

The scenario tests were only verifying configuration, not actual execution.
This meant critical bugs went undetected:
- RemoteClient using IPC events (can't work remotely)
- RunnerClient using IPC events (can't work remotely)
- WheelClient using IPC events (can't work remotely)

Changes:
- Add network event verification tests to all remote CLI scenarios
- Test that RemoteClient._use_network_events is True
- Test that RunnerClient._use_network_events is True
- Test that WheelClient._use_network_events is True
- Verify ClientEventSubscriber is used, not IPC SaltEvent
- Add regression test for local execution still using IPC
- Add comprehensive TestNetworkEventStreaming test class
- Add TestNetworkEventIntegration integration tests

These tests would have caught the missing network event implementation
immediately, preventing the remote CLI from shipping with IPC-only events.

Note: Pre-existing lint warnings in fixture code (using open() instead of
salt.utils.files.fopen()) are not addressed in this commit as they were
present before and are outside the scope of network event test fixes.

* Fix pylint error in RemoteClient: Use late import pattern for client_event

Change from 'import salt.utils.client_event' to 'from salt.utils import client_event'
to avoid UnboundLocalError when salt is used as a local variable in the function scope.

This matches the pattern used in RunnerClient and WheelClient.

* Add actual execution tests for remote CLI commands

Previous tests only verified configuration, not actual execution.
This update adds critical tests that execute commands and verify
event delivery over the network.

New Tests:
- TestRemoteCommandExecution class:
  * test_remote_client_executes_command_on_minion() - Actually calls
    client.cmd() and verifies result is received
  * test_remote_client_receives_events_over_network() - Verifies
    events are delivered via ClientEventSubscriber, not IPC

- TestRemoteRunnerExecution class:
  * test_runner_executes_remotely_with_client_auth() - Actually
    executes runner.run() with client auth

- TestRemoteKeyManagement class:
  * test_key_cli_lists_keys_remotely() - Tests WheelClient execution
    for salt-key operations

Fixtures:
- Added minion_container fixture for actual command execution
- Added client_event_publish config to master

These tests will catch regressions where:
1. Commands are published but events aren't delivered
2. Network events are replaced with IPC (breaking remote execution)
3. Event filtering doesn't work correctly

* Fix critical event filtering bugs for remote CLI operations

This commit fixes two critical bugs that prevented salt-run and salt-key
from working correctly when executed remotely with client authentication.

Bug 1: Event Filtering Only Handled Job Events
-----------------------------------------------
The ClientEventPublisher._publish_filtered_event() method only extracted
job IDs from salt/job/* events. This meant that:
- salt commands (RemoteClient) worked correctly ✓
- salt-run commands (RunnerClient) did NOT receive events ✗
- salt-key commands (WheelClient) did NOT receive events ✗

Fix: Updated event filtering to handle all three event types:
- salt/job/* (minion commands via RemoteClient)
- salt/run/* (runner operations via RunnerClient) [NEW]
- salt/wheel/* (key management via WheelClient) [NEW]

Location: salt/utils/client_event.py:217-248

Bug 2: WheelClient Did Not Initialize __role for client_auth
-------------------------------------------------------------
Runner and KeyCLI both set opts["__role"] = "client" when client_auth
is enabled, but WheelClient did not. This caused WheelClient to fail
network event detection when instantiated directly (not via KeyCLI).

Fix: Added client_auth initialization logic to WheelClient.__init__()
to match Runner's behavior:
- Load client config when client_auth=True
- Set __role = "client" for PKI authentication
- Use late import pattern to avoid shadowing 'salt' module

Location: salt/wheel/__init__.py:46-64

Testing
-------
Added comprehensive unit tests for event filtering:
- tests/pytests/unit/utils/test_client_event.py (8 tests)
- Tests verify job, run, and wheel event extraction
- Tests verify proper filtering and authorization

All existing integration tests pass:
- tests/pytests/integration/client/test_remote_cli_execution.py (15 tests)

Validation script confirms all three client types now use network events:
- RemoteClient: ✓
- RunnerClient: ✓
- WheelClient: ✓

Impact
------
This fix enables full remote CLI functionality:
- salt --client-auth (was working)
- salt-run --client-auth (now works)
- salt-key --client-auth (now works)

All operations are now properly supported for remote execution.

* Remove client_event_publish config option and use SignalHandlingProcess

Simplify configuration by always starting ClientEventPublisher process
on the master. This eliminates the need for configuration and ensures
remote CLI features work out of the box.

Changes:
1. Remove client_event_publish config option entirely
2. Use SignalHandlingProcess for proper cleanup and signal handling
3. Remove unnecessary shutdown() method

This should fix the widespread 'Event loop is closed' errors in nightly
test runs by ensuring proper signal handling and resource cleanup.

* Fix RunnerClient and WheelClient to use self.event for remote execution

CRITICAL FIX: cmd_sync() was always creating a local IPC event listener,
which prevented RunnerClient and WheelClient from working remotely.

Problem:
- RunnerClient and WheelClient correctly set up self.event as either:
  - ClientEventSubscriber (for remote execution over network)
  - IPC event (for local execution)
- BUT cmd_sync() ignored self.event and created its own IPC listener
- This caused remote execution to fail because:
  1. master_call() sent command to master (worked)
  2. Master executed runner/wheel and fired events (worked)
  3. cmd_sync() tried to listen on local IPC socket (FAILED remotely!)

Solution:
- cmd_sync() now uses self.event if available (supports both IPC and network)
- Falls back to creating IPC event only if self.event not available
- For ClientEventSubscriber, ensures connect() is called and subscribes to job
- Properly cleans up event listener only if created locally

This enables full remote functionality for all three CLI tools:
- salt --client-auth (RemoteClient) - already worked
- salt-run --client-auth (RunnerClient) - NOW WORKS remotely
- salt-key --client-auth (WheelClient) - NOW WORKS remotely

All integration tests pass (15/15).

* Fix parallel test failures by making client_event_port optional

CRITICAL FIX for CI integration test failures.

Problem:
- client_event_port was hardcoded to 4507 in config defaults
- When integration tests run in parallel, multiple masters start
- Each master tried to bind ClientEventPublisher to port 4507/4508
- Result: 'Address already in use' errors causing test failures

Solution:
1. Remove client_event_port from default config (now None by default)
2. Only start ClientEventPublisher when client_event_port is set
3. Tests that need remote CLI explicitly set client_event_port=4507
4. Most tests don't set it, so ClientEventPublisher doesn't start
5. No port conflicts in parallel test execution

Benefits:
- Integration tests can run in parallel without port conflicts
- Production masters still work (can set client_event_port in config)
- Tests only start ClientEventPublisher when actually testing remote CLI
- Cleaner separation of concerns (feature is opt-in)

Configuration:
To enable remote CLI support, add to /etc/salt/master:
  client_event_port: 4507

All integration tests pass (15/15).

* Fix cmd_sync() to handle ClientEventSubscriber without auto_reconnect

BUG FIX: cmd_sync() was passing auto_reconnect parameter to all event types,
but ClientEventSubscriber.get_event() doesn't support this parameter.

Problem:
- cmd_sync() calls event.get_event(auto_reconnect=True)
- ClientEventSubscriber.get_event() signature is: (wait, tag, full, no_block)
- Passing auto_reconnect causes TypeError: unexpected keyword argument

Solution:
- Check if event has subscribe_job method (indicates ClientEventSubscriber)
- If yes, call get_event() WITHOUT auto_reconnect parameter
- If no, call get_event() WITH auto_reconnect (IPC event supports it)

This fixes potential TypeErrors when RunnerClient or WheelClient use
ClientEventSubscriber for remote execution.

All 15 integration tests pass.

* Fix lint errors in scenario tests: use salt.utils.files.fopen instead of open

Fix pre-commit and lint failures by replacing open() with salt.utils.files.fopen()
in test_remote_cli_containers.py.

Changes:
- Added import salt.utils.files
- Replaced all 6 open() calls with salt.utils.files.fopen()
  - Lines 92, 95: Binary key file writes
  - Line 126: Config file write
  - Line 524: Saltrc file write
  - Lines 558, 567: Multi-environment config file read/write

This fixes the lint errors:
- W8470(resource-leakage): Use salt.utils.files.fopen() instead of open()
- W1514(unspecified-encoding): Using open without explicitly specifying encoding

All tests still pass.

* CRITICAL FIX: cmd_sync must not reuse listen=False IPC event

This fixes the 10 failing integration/functional tests.

Root Cause:
- Runner/WheelClient create self.event with listen=False in __init__
- Previous cmd_sync changes reused self.event for ALL cases
- cmd_sync needs to LISTEN for return events
- Using listen=False event meant cmd_sync could not receive events
- Result: All runner/wheel commands timed out

The Fix:
Only reuse self.event if it is a ClientEventSubscriber (has connect method).
For IPC events, ALWAYS create a new listener with listen=True.

This ensures:
- Remote CLI works (ClientEventSubscriber path)
- Local runner/wheel works (creates new IPC listener)

All 15 remote CLI integration tests still pass.

* Remove temporary development documentation and test files

These files were created during development and should not be in the repository:
- Temporary design documents (CLIENT_ACL_*, REMOTE_CLI_*, etc.)
- Standalone test scripts that should be in tests/ directory
- Backup files and work-in-progress documentation

This was causing pre-commit and lint failures in CI.

* Fix lint errors in test_remote_cli_cluster.py

Replace open() with salt.utils.files.fopen() to fix:
- W8470(resource-leakage)
- W1514(unspecified-encoding)

This completes the lint fixes for all scenario test files.

* Fix UnboundLocalError: alias nested salt.config import in Runner.__init__

The non-aliased `import salt.config` inside the `if opts.get('client_auth')`
branch bound `salt` as a function-local, making every reference to
`salt.loader` outside the branch (e.g. `self.returners = salt.loader.returners(...)`)
raise UnboundLocalError on the common path where client_auth is falsy.

Matches the aliased pattern already used in salt/wheel/__init__.py.

* Fix lint: pylint broad-except pragmas and black formatting

- Add `# pylint: disable=broad-exception-caught` to the two intentional
  except-Exception blocks in test_remote_cli_execution.py; they filter noise
  from unrelated failures while asserting the IPC path wasn't used.
- Apply pending black formatting to salt/utils/client_event.py and
  test_remote_cli_execution.py.

* Fix stale self.local_client references missed by SaltCMD rename

The SaltCMD rename of `self.local_client` -> `self.client` missed two
call-sites, both reached only via async/signal paths that weren't exercised
by the explicit remote-CLI tests:

- salt/cli/salt.py:448 (`_run_batch_async`): raises AttributeError when
  'salt -b N --async' hands off to BatchManager, causing e.g.
  test_batch_async_handoff_to_batch_manager to fail with rc=1 and
  "'SaltCMD' object has no attribute 'local_client'".
- salt/scripts.py:50 (SIGINT handler): the AttributeError was swallowed by
  the broad except, suppressing the "This job's jid is" message on
  Ctrl-C and breaking test_interrupt_on_long_running_job.

* Fix scenario tests: shadowed salt-import + wrong SaltMinion kwarg

Two unrelated mechanical fixes to the container-based scenario tests:

- test_remote_cli_cluster.py: alias the nested `import salt.utils.client_event`
  so it no longer shadows the module-level `salt` import in
  `test_remote_salt_command_to_minions`. Previously the function raised
  `UnboundLocalError` on `salt.config.client_config(...)` because any
  conditional `import salt.X` binds `salt` as a function-local.
- test_remote_cli_containers.py: same shadowing fix for
  `test_emergency_acl_revocation` (nested `import salt.acl`).
- test_remote_cli_containers.py: the `minion_container` fixture passed
  `master_id=master_container.id` to `salt_factories.salt_minion_daemon`,
  which has no such kwarg and leaked it through `**factory_class_kwargs`
  to `SaltMinion.__init__` (-> `TypeError`). Correct kwarg is
  `master=master_container` (a SaltMaster instance).

* ClientACL: normalize runner/wheel key plurals; rewrite ACL scenario tests

Two scenario tests failed because they encoded an ACL grammar that
ClientACL + its unit-test contract do not support:

- They used plural keys (`runners`, `wheel`) where `client_is_allowed`
  only looked up the singular `cmd_type`. Added a small alias layer in
  `client_is_allowed` (`runner`/`runners`, `wheel`/`wheels`), matching
  the `minion`/`minions` alias already present in
  `client_can_target_minion`. All 53 existing ACL unit tests still pass.
- They used the `!deny` prefix (e.g. `!cmd.run`), which neither ClientACL
  nor publisher_acl recognise -- the latter is a positive whitelist only.
  Per direction to track publisher_acl semantics, rewrote
  `test_acl_denied_operations` to use positive patterns and let denies
  fall out by omission; `test_dynamic_acl_updates` now passes via the
  plural-alias change alone (no rewrite needed).

* Fix minion_container fixture: pre-seed accepted key to avoid hang

master_container intentionally sets auto_accept=False and open_mode=False
so the ACL/key-management tests exercise the manual key-accept flow. With
the earlier fix to pass master=master_container (instead of the invalid
master_id= kwarg) the minion_container fixture now actually reaches
factory.started() -- which then blocks forever waiting for the master to
accept the key.

Pre-generate the minion keypair, write it to the minion's pki_dir, and
seed the master's keys cache with {state: accepted} before awaiting the
minion start. The ACL tests that depend on manual accept operate on the
separate client_keys cache namespace and are not affected by this.

* ClientEventSubscriber.destroy: use linger=0 to avoid teardown hang

zmq.Context.term() blocks indefinitely waiting for pending socket
operations to drain. In pytest, pytest_unconfigure runs
gc_collect_harder which finalises orphaned RemoteClient instances via
__del__ -> destroy() -> ClientEventSubscriber.destroy() -> term().  By
that point the counterpart master/minion has already been SIGTERMed and
left ZMQ fds in a half-closed state, so term() never returns and the
entire pytest process hangs -- which is what has been blocking the
scenarios shard in CI for hours.

Close each socket with linger=0 and use context.destroy(linger=0)
instead of term().  Also null the attributes so a repeated destroy()
(idempotent close path) doesn't try to re-close.

Local repro before: scenarios dir pytest sits in context.term() stack
indefinitely (confirmed via py-spy dump).  After this change: tests
fail/pass fast; nothing blocks finalisation.

* ClientEventSubscriber: SaltEvent-compatible interface + drop IPC check in RemoteClient.pub

ClientEventSubscriber was missing cpub / connect_pub / close_pub /
subscribe / unsubscribe, which LocalClient.cmd() uses when a RemoteClient
inherits that code path.  Added them:

- cpub property mirrors `sub_socket is not None`
- connect_pub(timeout) wraps connect() to return True/False
- close_pub() closes just the sub socket (keeps auth socket + context
  alive for a subsequent connect_pub)
- subscribe/unsubscribe translate a tag containing a 20-digit JID into
  subscribe_job/unsubscribe_job; other tags are a no-op since the
  publisher already filters per-client server-side

RemoteClient.pub() also carried a leftover check that aborts the publish
if the master IPC publisher socket (publish_pull.ipc) does not exist on
the local box.  That is only valid for LocalClient on the master host --
a remote client talks to the master entirely over the network transport
established below.  Remove the check.

* Drop --client-auth flag; config file is the single source of truth

The CLI tools now dispatch to LocalClient vs RemoteClient based on which
config file `client_config()` actually loaded, with no separate CLI flag.
This removes a redundant knob (--client-auth repeated the signal that the
config path already carries) and gets rid of the auto-detect fallback
that could pick the wrong client on master hosts that happened to have a
stale /etc/salt/client lying around.

- salt/config/__init__.py:client_config() now sets opts["client_auth"]
  explicitly: True when /etc/salt/client is loaded, False when it falls
  back to the master config.  When the fallback is taken,
  warn_until(3011, …) tells the operator to migrate to /etc/salt/client;
  the fallback is scheduled for removal in Salt 3011 (Scandium).
- salt/utils/parsers.py drops the --client-auth option from salt,
  salt-key, and salt-run.  --profile stays.
- salt/cli/salt.py, salt/cli/run.py, salt/cli/key.py collapse the
  three-way flag/auto-detect block to a simple two-way dispatch keyed
  off opts["client_auth"].

Master-host local usage is unchanged (no /etc/salt/client -> LocalClient
with a deprecation warning).  Remote operators keep the RemoteClient
path with --profile for multi-master setups.

* Rename username -> client_id in is_client branches (#1, narrow)

Inside the `if is_client:` branches of master.publish, masterapi.runner,
and masterapi.wheel the `username` variable is misleading -- the auth
system returns the identity under that key because it was built for human
users, but on this path the identity is the client installation (e.g.
'admin-workstation'), not a person.

Alias `client_id = username` (in masterapi.runner / masterapi.wheel) or
rename `username` -> `auth_identity` + alias `client_id` (in
master.publish) inside the client branches and use `client_id` in log
messages and ACL calls, so the code says what it means.

Left for later (ties into deferred #3, human-user forwarding):
`clear_load["user"] = client_id` still assigns the client identity to
the publish job's `user` field.  That leaks into job returners / event
tags / audit log and conflates clients with humans.  Flagged in a TODO
comment at salt/master.py:5607 to split into a dedicated
`clear_load["client_id"]` field once the user-forwarding story lands.

* Add RemoteWheelClient and RemoteRunnerClient/RemoteRunner sibling classes

Introduces net-new remote-only clients for the salt-key and salt-run
CLIs, mirroring the LocalClient/RemoteClient split already used for the
salt CLI. These are standalone sibling classes (not subclasses of the
local variants) so the local-master path -- the production hot path --
is literally untouched.

salt/wheel/__init__.py
----------------------
New `RemoteWheelClient`. Sends wheel calls to the master's
`ClearFuncs.wheel` endpoint via a clear `ReqChannel` using
`opts["master"]` as the URI. The master's wheel endpoint is
synchronous server-side -- it blocks on `wheel_client.call_func` and
returns `{tag, data}` inline -- so `cmd_sync` just returns the master's
response without event-wait. Loads `salt.loader.wheels(opts)` locally
only so KeyCLI can introspect wheel-function argspecs for CLI arg
parsing; the modules themselves do not execute on the client box.

salt/runner.py
--------------
New `RemoteRunnerClient` + `RemoteRunner`. Runner is naturally
asynchronous -- master returns `{tag, jid}` and the result arrives on
the event bus as `salt/run/<jid>/ret` -- so `RemoteRunnerClient`
inherits `cmd_sync` from `SyncClientMixin` (which already handles the
subscribe + wait flow against our `ClientEventSubscriber`) and overrides
only `master_call` to target the configured `opts["master"]`.
`RemoteRunner.run` is a slim CLI entry that collects args, optionally
resolves eauth credentials via `salt.auth.Resolver.cli`, and delegates
to `cmd_sync`.

No CLI dispatch changes in this commit -- a follow-up switches
`salt/cli/run.py` and `salt/cli/key.py` to pick between the local and
remote variants based on `opts["__role"]`. The embedded
`_use_network_events` branches inside the existing `Runner` /
`RunnerClient` / `WheelClient` `__init__` methods remain for now; they
will be reverted once the sibling classes are wired into CLI dispatch
and tests have migrated off the `_use_network_events` flag assertions.

* Switch salt-run and salt-key dispatch to Remote* sibling classes

When opts["__role"] == "client" (i.e. /etc/salt/client was loaded by
client_config()), the CLI dispatchers now instantiate the new
RemoteRunner / RemoteWheelClient. Otherwise they keep using the
master-local Runner / WheelClient.

salt/cli/run.py: pick RemoteRunner vs Runner at construction.
salt/key.py:    pick RemoteWheelClient vs WheelClient inside
                KeyCLI.__init__ so the CLI entry point stays unchanged.

No behavior change for master-host users -- __role=master -> local path.

* Migrate _use_network_events assertions to isinstance(Remote* sibling)

The _use_network_events flag was a transitional sentinel that the
embedded Runner/RunnerClient/WheelClient init branches set to True when
they detected remote config. Those branches are about to be reverted in
favor of the explicit sibling classes RemoteRunner / RemoteRunnerClient
/ RemoteWheelClient; the flag will no longer exist.

Rewrite the assertions to check class identity directly:

- RemoteClient / RemoteRunnerClient / RemoteWheelClient instances for
  the remote path.
- not-isinstance(.., RemoteRunnerClient) for the local-RunnerClient
  path.

Also switch the test instantiation sites to call the Remote* classes
directly, rather than relying on branching inside the local-named
classes.  cmd_sync on RemoteWheelClient is sync server-side and does
not need the event subscriber at construction time; tests that check
the subscriber type instantiate it explicitly for the assertion.

* Remove embedded _use_network_events branches from Runner/WheelClient

Reverts the branching logic that commits 077cf07e4f4 and 6ab13f3fb82
inlined into RunnerClient.__init__ and WheelClient.__init__ (plus their
_should_use_network_events() helper and the client_auth config-reload
block at the top of each Runner/WheelClient __init__).

With the new sibling classes RemoteRunner / RemoteRunnerClient /
RemoteWheelClient and the CLI dispatch that selects them based on
opts["__role"] == "client", the embedded branches have become dead
code: RunnerClient / WheelClient only ever handle the master-local
path, so the IPC-event-bus setup is unconditional and matches the
pre-branch behaviour.

Also drops the salt_config.client_config() reload inside each
__init__ -- the config loader already sets __role on load, and the
CLI dispatchers now key off that single source of truth.

The salt.client.mixins.cmd_sync hasattr(event, "connect") sniff
remains for now (it still correctly dispatches when inherited by
RemoteRunnerClient whose self.event is a ClientEventSubscriber). A
follow-up can collapse it to polymorphic _get_event().

Not reverted: 17991800043 (ClientEventSubscriber.destroy linger=0) --
that is the ZMQ-term hang fix verified with py-spy, pure bugfix.

Net: -133/+7 lines across the two files.  53 ACL unit tests still pass.

* Stackable PKI + eauth authorization on publish/runner/wheel

Introduces opt-in two-axis authorization at the three master-side
dispatch points.  When `stacked_auth: true` is set on the master opts
AND a clear_load carries BOTH a user-key (PKI) signature AND
token/eauth credentials, both axes must authorize the request.
Default is `stacked_auth: false`, preserving today's exclusive
is_client/else behavior.

Previously the master used the exclusive `token > eauth > user`
priority in `_prep_auth_info`, so a workstation that presented its
PKI identity could not simultaneously identify a human via eauth --
the publisher just saw the eauth path and ignored the user key.

Changes:

salt/master.py:5714 - `_prep_auth_info(clear_load, want_stacked=False)`
grows an optional extended 6-tuple return:
`(auth_type, err_name, key, sensitive_load_keys, stacked_possible,
secondary_auth_type)`.  Backwards compatible: callers that leave
`want_stacked=False` still unpack the historical 4-tuple.

salt/master.py:5485 publish() - When `stacked_possible`, run the
secondary "user" authentication alongside the primary token/eauth
check.  Combine `ClientACL.client_can_publish` with `ckminions.auth_check`
against the eauth `auth_list` using the new `salt.acl.stacked_authorize`
helper.  Both must pass.  Audit log records both the workstation
`client_id` and the human `user` separately; `clear_load["client_id"]`
is a new field (preserving `user` as the human identity in stacked
mode and as the client identity in PKI-only mode for backwards compat).

salt/daemons/masterapi.py:1222/1373 runner()/wheel() - Mirror change
with `ClientACL.authorize_runner` / `ClientACL.authorize_wheel` on
the client axis and `ckminions.runner_check` / `ckminions.wheel_check`
on the eauth axis.  Composed via `stacked_authorize`.  Wheel event
payload carries `client_id` alongside `user` when stacked.

salt/acl/__init__.py - New `ClientACL.authorize_runner` and
`ClientACL.authorize_wheel` return `{allowed, error}` dicts that
match the shape of `client_can_publish`, so the composition helper
treats all three dispatch sites uniformly.  New module-level
`stacked_authorize(client_decision, eauth_decision) -> (ok, err)`
AND-composes two decisions and returns the first non-None error on
denial so logs can attribute which policy denied.

53 ACL unit tests + 133 master unit tests continue to pass.

* ClientEventPublisher: token-auth path for eauth-only remote clients

Adds an `action="auth_token"` branch to the REP auth socket so
remote clients without a PKI client key (eauth-only) can subscribe to
master-side events using their Salt eauth token.

Server (ClientEventPublisher):
- New auth branch validates the Salt token via LoadAuth.check_authentication
  (same code path used on the publish/runner/wheel dispatch).
- On success, mints a per-session `session_id = secrets.token_urlsafe(16)`
  and returns it to the client.  The subscriber uses the session_id as
  its ZMQ SUB prefix so bearer tokens never travel on the SUB channel
  and concurrent sessions for the same eauth user don't collide.
- Session entries carry the eauth `auth_list` and `expire` time; the
  publish loop enforces `ckminions.auth_check` against the auth_list
  on each delivered event for token-mode sessions and lazily evicts
  expired sessions.
- Existing PKI auth path unchanged (subscriber_id == client_id,
  auth_mode == "pki", no auth_list).

Client (ClientEventSubscriber):
- `connect(salt_token=None, eauth=None)`: passing a token routes
  through the new auth_token action; otherwise the historical PKI
  signature path runs.
- `_authenticate_token` sends `{action: auth_token, token, eauth}` and
  caches the returned `session_id`.
- `subscribe_job` / `unsubscribe_job` carry `session_id` when set
  (token mode), else the configured client id (PKI mode).  SUB filter
  prefix is set to whichever applies.

destroy() continues to use `linger=0` on sockets and
`context.destroy(linger=0)` to avoid the pytest-teardown hang we
previously fixed.

Existing 8 ClientEventPublisher unit tests pass unchanged after making
`_publish_filtered_event`'s `loadauth` arg optional (default None
skips the auth_list filter; LoadAuth is wired in by `run()` for the
real deployment path).

* Fix end-to-end remote eauth for salt / salt-run / salt-key

Validated by running salt-master in a container (python:3.14-slim +
mounted relenv onedir + mounted branch) with the three CLIs executing
on the host against the containerized master.  All three now return
rc=0 with eauth-only config.

Issues found and fixed:

salt/client/__init__.py (RemoteClient.pub)
- Was using crypt="aes" for the publish ReqChannel, which routes to
  AESFuncs on the master. The master's "publish" cmd is only exposed
  on ClearFuncs; AES-encrypted publish payloads were rejected with
  "Requested method not exposed: publish". Switched to crypt="clear"
  to match LocalClient and salt-api behavior. Credentials for
  publish-time auth (eauth creds, token, or client_id) travel inside
  the clear-channel payload.
- Event-subscriber auth now prefers token-auth when a token is in the
  publish payload (checked at both payload_kwargs root and the nested
  kwargs dict LocalClient._prep_pub constructs); falls back to PKI
  otherwise.

salt/cli/salt.py (SaltCMD._run)
- Dispatch now picks RemoteClient when opts["__role"] == "client",
  regardless of the client_auth flag. Previously only client_auth=True
  routed to RemoteClient, which blocked eauth-only remote clients.
- The eauth collection block now always mints a Salt token (not just
  on --make-token) when running as a remote client, so the event
  subscriber can authenticate on the token path.

salt/utils/client_event.py (ClientEventPublisher)
- __init__ now accepts **kwargs so the master's ProcessManager can
  pass name="ClientEventPublisher" via add_process. Was raising
  TypeError at publisher startup, which prevented clients from
  subscribing to events over the network at all.

salt/config/__init__.py (client_config)
- client_auth now defaults to True when /etc/salt/client is loaded, but
  honors an explicit client_auth=False from the operator's config.
  Enables eauth-only remote clients that don't want to go through PKI.

salt/runner.py (RemoteRunner.run)
- Eauth path: aliased the nested salt.auth import to avoid shadowing
  the module-level salt binding earlier in the function (previously
  raised UnboundLocalError before reaching the master).
- Always mint a token when eauth is configured and no token is in opts,
  then pre-authenticate the event subscriber on the token path before
  cmd_sync tries to connect.

salt/key.py (KeyCLI._init_auth)
- Aliased nested imports of salt.auth and salt.utils.master to avoid
  the same shadowing bug (was raising UnboundLocalError on
  salt.utils.files.fopen earlier in the function).
- Always mint a token when eauth is configured so WheelClient event
  subscriber can authenticate on the token path if needed.

Also persists the four design-agent reports and the two blocker
investigation reports to agents/reports/ (they existed only in
chat before).

Validation output on a master container running the branch:
  salt-run test.arg hello world    -> rc 0, runner output printed
  salt-key -L                      -> rc 0, key list printed
  salt '*' test.ping               -> rc 0, publish accepted (no minions)

* RemoteClient: deliver minion returns + accept SaltEvent compat kwargs

Validated end-to-end against a Salt master+minion running in sibling
containers with the salt CLI executing on the host.  'salt test-minion-1
test.ping' against a remote eauth-authenticated master now returns the
minion's True payload instead of 'jid does not exist'.

Two fixes:

salt/client/__init__.py (RemoteClient.returns_for_job)
- Override LocalClient's returns_for_job which calls into a local
  returner to confirm the publish landed in the job cache.  The job
  cache lives on the master; a remote client has no local returner
  dict to query.  Return a non-empty sentinel so get_iter_returns
  trusts the published jid and iterates the event stream for returns.
  Without this override, every remote publish logged 'jid does not
  exist' and dropped the return events.

salt/utils/client_event.py (ClientEventSubscriber.get_event)
- Accept match_type / auto_reconnect / **kwargs for interface
  compatibility with salt.utils.event.SaltEvent, which LocalClient's
  cmd_cli loop calls through with those kwargs.  Previously these
  raised TypeError and the caller silently moved on, which is why the
  earlier end-to-end validation (no minion attached) showed 'rc 0'
  without actually iterating returns.
- Add a client-side tag prefix filter so callers reading in a tight
  loop only see events matching their requested tag (publisher
  already filters by subscription, but a single job fires both
  '.../new' and '.../ret/<id>' events on the same job subscription).

Failed-auth scenarios also tested with a real file-backend eauth on
the master (alice=secret authorized, bob=unauthorized, wrong password,
unknown eauth driver, no creds).  All failing scenarios do fail -- no
silent security bypass -- but the error UX needs follow-up:
'Client key not found' when the real cause is a token-mint failure,
and bob's publish-time authorization denial returns rc=0 instead of
non-zero.  Noted as TODO for a follow-up polish commit.

* Encrypt remote-client credentials with AES bridge to ClearFuncs

The RemoteClient / RemoteRunnerClient / RemoteWheelClient /
Resolver._send_token_request paths were sending eauth credentials
(username, password, token) in cleartext over the ReqChannel because
the master's publish / runner / wheel / mk_token endpoints are only
reachable on ClearFuncs.  That exposed the creds to any passive
observer on the wire.

Switch all four client paths to crypt="aes", which drives the standard
PKI sign-in handshake using pki_dir/client.pem (accepted on the master
via the client_keys acceptance workflow) and encrypts the entire
payload under the resulting session key.  On the master, add
MWorker._is_client_bridge() to detect AES payloads whose inner cmd is
a ClearFuncs method and whose authenticated sender id is a known
client, and route them through _handle_clear so eauth authorization
still runs.  Override the response envelope fun -> "send" so the reply
is AES-encrypted under the sender's session key as well, preserving
confidentiality on both legs.

The bridge is strictly additive: AES payloads from minions keep
dispatching to AESFuncs (whose expose_methods set never contains the
ClearFuncs endpoints), and clear-channel payloads continue flowing
through _handle_clear unchanged.

client_config() now also populates the minion-flavoured auth defaults
(acceptance_wait_time, auth_tries, verify_master_pubkey_sign, etc.)
that salt.crypt.Auth.sign_in reads but master_config does not supply.

* Give remote CLI clients their own pki/master/clients subtree

Before: a remote CLI client (``__role=client``) signing in via the AES
handshake was indistinguishable from a minion.  The master's _auth_impl
stored the client's public key under pki/master/minions/, so a
subsequent ``salt '*' test.ping`` would include the client id as a
phantom minion target, and ``salt-key -L`` would list it alongside
real minions.

Fix: honour the ``role: client`` field already present in the sign-in
payload (minion_sign_in_payload sets it from ``__role``).  Both the
async and sync _auth_impl variants now route to the ``client_keys``
/ ``client_denied_keys`` cache banks when the sender's role is
"client", which localfs_key maps to the parallel pki/master/clients*
dirs that were already carved out at master startup.  Clients also
skip the autosign / autoreject file checks (those are minion-centric)
and don't count against ``max_minions``.

The server-side AES channel validators -- ReqServerChannel.validate_token
in channel/server.py and AESFuncs._check_mine_token in master.py -- also
walked only ``pki/master/minions/`` to find the sender's public key for
AES session verification.  Add a fallback to ``pki/master/clients/``
so publish/runner/wheel calls from authenticated clients don't fail
with "key could not be read and verification was denied".

salt-key: when a client config declares BOTH ``client_auth: True`` and
``eauth:``, _init_auth still needs to collect eauth credentials -- the
stacked PKI+eauth check on the master consumes them.  Only skip
credential collection in the pure-PKI case.

Verified end to end with ``salt test-minion-1 test.ping`` (publish,
AES-bridged) and ``salt-key -L`` (wheel, AES-bridged, eauth stacked
with client PKI).  After the fix, pki/master/clients/ contains only
alice-workstation and pki/master/minions/ contains only test-minion-1
-- no cross-contamination.

* Fix remote salt-run sync wait: runner/wheel auth + event replay + drain

Three bugs stacked on top of each other were causing ``salt-run <fun>``
against a remote master to hang / time out, while ``salt-run --async``
and the publish/wheel paths worked.

1. _publish_filtered_event ran every token-authed event through
   ``ckminions.auth_check``, which is the minion matcher.  Runner /
   wheel events don't carry ``tgt`` / ``tgt_type``, so the check
   returned deny and the publisher silently dropped the event.  Branch
   on the tag prefix: ``salt/run/*`` -> ``runner_check``, ``salt/wheel/*``
   -> ``wheel_check``, publish events stay on ``auth_check``.
   The event data decorates the function name with the form prefix
   (``runner.<mod>.<fun>``), but ``spec_check`` expects a plain
   ``mod.func``, so strip the prefix before the check.

2. Fast runners race with the client's subscribe step.  The flow is
   ``master_call -> runner starts -> subscribe_job``, so a runner that
   completes in <~200 ms can emit ``/new`` and ``/ret`` before the
   publisher's ``clients[sid].jobs`` set is updated and both events
   get dropped.  Keep a short rolling buffer of recent events in the
   publisher loop, and on ``subscribe_job`` replay any buffered events
   whose tag contains the jid to just the subscribing client.

3. ``ClientEventSubscriber.get_event`` returned ``None`` on the first
   non-matching tag seen, instead of continuing to read until the tag
   it was asked for arrived (or the overall wait expired).  Fine when
   the race was dropping ``/new``, visible as soon as the replay buffer
   delivered ``/new`` ahead of ``/ret``.  Loop on recv_multipart,
   tracking a monotonic deadline so the total wait budget is honoured
   regardless of how many non-matching events arrive first.

Verified end to end against a container master + minion:
  salt test-minion-1 test.ping       -> True
  salt-run test.sleep 1              -> True
  salt-run jobs.list_jobs            -> job list
  salt-run manage.up                 -> - test-minion-1
  salt-key -L                        -> Accepted: test-minion-1

pki/master/clients/ and pki/master/minions/ remain disjoint; no
phantom minions.

* Encrypt remote-client event stream with per-session Crypticle key

Before: the ClientEventPublisher on port 4507 published event payloads
as plain msgpack over PUB/SUB.  The sign-in handshake on 4506 protected
eauth credentials, but every published job dict, runner result, and
return value afterwards went out in cleartext -- a passive observer on
the wire could read full job metadata and minion returns for any
subscribed client.

Fix: give every subscriber a per-session Crypticle (AES-CBC + HMAC-SHA256)
and encrypt the ``{tag, data}`` payload under that key before each
send_multipart.

Key provisioning follows the two existing auth modes:

- PKI auth (``action="auth"``): the publisher mints a fresh Crypticle
  ``key_string``, RSA-wraps it with the client's public key already
  loaded in the ``client_keys`` cache, and returns the ciphertext in
  the auth REP response.  The client unwraps with its ``client.pem``.

- Token auth (``action="auth_token"``): both the publisher and the
  client derive the same key via ``HKDF-SHA256(token, info="salt-
  client-events-v1")``.  The token itself only crosses the REP channel
  once (on the request) and the derived key never leaves either host.
  Bump the ``v1`` suffix if the schedule changes incompatibly.

Each outgoing event is Crypticle.dumps()'d per subscriber (so one event
delivered to N clients is N independent encryptions, each under that
subscriber's key).  Clients that negotiated a key use Crypticle.loads()
in ``get_event``; the plain-msgpack path remains as a last-resort fallback
only when ``self.crypticle`` is None.

Verified end to end against a container master + minion:
  salt / salt-run / salt-key -- all still rc 0 with correct results.
Pcap on port 4507 after the change: zero plaintext hits for event tags
(salt/run/*, salt/job/*), minion ids, usernames, or runner function
names.  Before: 15+ hits.

* Reject sign-in that collides with the other role's id namespace

The AES bridge in :meth:`MWorker._handle_payload_inner` routes AES-
wrapped ClearFuncs cmds through :meth:`_handle_clear` whenever the
sender id is present in the ``client_keys`` cache.  The AES session
itself is established during a standard sign-in handshake, and the
sign-in now routes clients to ``pki/master/clients*`` and minions to
``pki/master/minions*`` based on the ``role`` field in the auth load.

Those two mechanisms create a trust-boundary gap when they're not
mutually exclusive: an attacker who learns the id of an accepted
client could sign in with ``role: minion`` using their own keypair.
With ``auto_accept: True`` on the master, the attacker's pubkey lands
in ``pki/master/minions/<client-id>`` and the attacker gets a valid
AES session.  The bridge check (:meth:`_is_client_bridge`) then only
asks "is this id in ``client_keys``?" -- yes, from the legit client's
registration -- and routes the attacker's payload to ClearFuncs.
``ClearFuncs`` publish / runner / wheel endpoints have no further
check that the AES session's pubkey matches the stored client pubkey,
so the attacker piggybacks on the legit client's authorization scope
once they also present valid eauth credentials.

Fix: cross-check at sign-in.  Both ``_auth_impl`` and
``_auth_impl_sync`` now fetch the OTHER role's cache bank
(``client_keys`` for a minion sign-in, ``keys`` for a client sign-in)
and reject the request if any entry exists -- regardless of state
(pending / accepted / rejected).  The reject follows the same return
shape and (optional) signed-envelope path as a bad-key rejection, so
clients see "Authentication rejected" exactly like a mismatched pub.

Verified end to end against a container master + legit minion +
accepted client:
  * Legit client ``salt test-minion-1 test.ping``             -> True rc 0
  * Attacker ``role=minion id=alice-workstation``             -> rejected,
    master log: "id is already registered as a client", no entry
    written to ``pki/master/minions/`` or ``minions_pre/``.
  * Attacker ``role=client id=test-minion-1``                 -> rejected,
    master log: "id is already registered as a minion", no entry
    written to ``pki/master/clients/`` or ``clients_pre/``.

* Fix nightly 41265414380 test regressions

Five test-file groups were failing on the nightly after the five
remote-CLI commits that landed on this branch.  Root causes and the
targeted fix for each:

1. tests/pytests/unit/test_master.py::test_auth_funcs_rejects_when_max_minions_full
   The cross-role collision check added in 796620b0f60 was running
   before ``max_minions`` on every call, including the one from this
   test where ``cache = MagicMock()`` returns a truthy MagicMock for
   any ``.fetch(...)`` call -- so the collision branch fired and
   returned ``{"ret": False}`` instead of letting the max_minions path
   produce ``{"ret": "full"}``.  Move the collision check in both
   ``_auth_impl`` and ``_auth_impl_sync`` to run after the
   ``max_minions`` / ``auto_key`` lookups, right before the primary
   key-bank fetch.  Semantically unchanged: the collision guard still
   catches minion-flavoured sign-ins that would otherwise shadow an
   accepted client id (and vice versa), it just does so one step
   later in the auth flow.

2. tests/pytests/functional/master/test_async_handlers.py::test_max_inflight_cap_*
   The ``_inflight_worker`` helper installs ``worker.clear_funcs =
   object()`` as a stub, which ``_is_client_bridge`` dereferenced via
   ``self.clear_funcs.expose_methods``.  Switch to ``getattr(...,
   "expose_methods", ())`` with an empty-tuple fallback (and the same
   for ``aes_funcs.expose_methods`` and ``aes_funcs.key_cache``) so a
   bare stub cleanly fails the bridge check and delegates to
   ``_handle_aes`` -- which is the exact path these tests exercise.

3. tests/pytests/integration/cli/test_batch.py::{test_batch_retcode,
   test_multiple_modules_in_batch}
   The ``client_config`` fallback emits a ``warn_until`` deprecation
   warning that lands on stderr; both tests ``assert not cmd.stderr``.
   The warning is intentional for the broader deprecation plan.  Add
   a small ``_assert_quiet_stderr`` helper to the batch test module
   that lets this specific line through while still catching any
   other stderr noise -- same pattern the TODO comments at those
   asserts already describe for the platform-specific jinja /
   setproctitle warnings.

4. tests/pytests/integration/cli/test_salt_key.py::test_list_acc_eauth_bad_creds
   and ::test_list_acc_wrong_eauth
   The salt-key eauth collection unconditionally minted a token so
   the remote-WheelClient event subscriber could authenticate on the
   token path.  On master-local salt-key with ``--eauth=pam`` + bad
   PAM password this changed ``check_authentication``'s auth_type
   decision (token present) and let an mk_token round-trip mask the
   actual eauth failure that the test asserts on.  Restore the
   historical "mint only when ``--mktoken`` or ``__role=client``"
   gate.  Pure PKI, master-local, and remote-with-eauth paths all
   still get the token where they need it.

5. tests/pytests/integration/client/test_remote_cli_execution.py::{TestClientAuthIntegration::test_runner_and_key_cli_share_config,
   TestClientAuthIntegration::test_client_auth_without_accepted_key_fails_gracefully,
   TestRemoteSaltRun::test_runner_client_auth_config, test_runner_remote_execution}
   Each test constructs ``salt.runner.Runner(opts)`` in-process with
   ``client_auth=True`` and asserts ``opts["__role"] == "client"``.
   The config refactor moved ``__role`` setting into
   ``client_config()`` at CLI parse time, so an in-process
   instantiation that bypasses the CLI parser never acquired the role.
   Mirror :class:`salt.key.KeyCLI`'s existing ``client_auth`` ->
   ``__role=client`` shim in ``salt.runner.Runner.__init__``.
   Keeps the two in sync; CLI dispatch still prefers the
   ``RemoteRunner`` subclass via the explicit ``__role`` check in
   ``salt/cli/run.py``.

   ``TestRemoteRunnerExecution::test_runner_executes_remotely_with_client_auth``
   additionally called ``runner.run()`` without producing a client
   PKI private key on disk, so the AES sign-in blocked and the test
   hit the pytest 90s timeout.  Narrow the test to a structural
   check (RemoteRunner class, ClientEventSubscriber event wiring) --
   real end-to-end runner execution is covered by the container-based
   manual verification run and belongs in a scenario test with full
   PKI fixtures, not a parity structural test.

* Honor master_port in client config so sign-in hits the right port

The AES-handshake refactor (a1434e5966c + dd46619fc14) makes the
remote CLI mandatory-sign-in before publish/runner/wheel, which means
the client has to reach the master's actual ``ret_port`` -- not
just whatever default the opts carry.

Operators configuring ``/etc/salt/client`` naturally reach for
``master_port`` because that's the minion-side spelling for "the
port to reach the master on" (same muscle memory as
``/etc/salt/minion``).  ``master_config`` -- which ``client_config``
delegates to -- only reads ``ret_port`` (the master-side spelling
for "the port we listen on"), and both options have the same
``4506`` default, so an operator-provided ``master_port`` was
silently ignored and the sign-in dialled 4506.  On a dynamically-
ported salt-factories master (random high port) that showed up as
``SaltClientError: Attempt to authenticate with the salt master
failed with timeout error`` wrapped by RemoteClient as "The salt
master could not be contacted. Is master running?".

Fix: after ``master_config`` loads the dedicated client config file,
re-parse the raw YAML to see which port key the operator actually
wrote.  If only ``master_port`` was set (not ``ret_port``), copy
its value into ``ret_port`` so the sign-in path, publish channel,
runner channel, wheel channel, and Resolver all target the same
address.  Comparison is on the raw file keys, not merged values,
because both options default to 4506 and would be indistinguishable
post-merge.

Scenario tests covered:
  tests/pytests/scenarios/client/test_remote_cli_containers.py::
    TestRemoteCommandExecution::test_remote_client_executes_command_on_minion
    TestRemoteCommandExecution::test_remote_client_receives_events_over_network

* Dispatch Batch to RemoteClient when __role=client (sync --batch)

``salt.cli.batch.Batch.__init__`` hardcoded ``get_local_client`` so
``salt --batch N '*' test.ping`` on a workstation configured with
``/etc/salt/client`` silently constructed a ``LocalClient`` -- which
then tried to reach a non-existent local master IPC bus and either
failed opaquely or hung mid-run.

Dispatch on ``opts["__role"] == "client"`` and pick
``get_remote_client`` on the remote path.  ``RemoteClient`` inherits
``cmd_iter`` / ``cmd_iter_no_block`` / ``run_job`` from ``LocalClient``
and overrides ``pub`` to use the AES-authenticated channel, so every
method ``Batch`` calls on ``self.local`` works unchanged.

The one semantic difference is ``self.local.event`` is a
:class:`salt.utils.client_event.ClientEventSubscriber`, which has
``subscribe`` / ``unsubscribe`` / ``get_event`` / ``destroy`` but no
``fire_event`` -- a workstation cannot write to the master's event
bus directly.  Add an ``hasattr(event, "fire_event")`` guard to
``_fire_event`` so remote batches degrade visibility
(``batch.status`` / ``batch.stop`` runners won't observe them)
rather than crashing.  That matches the "best-effort visibility"
contract already documented in the surrounding section.

All 33 existing unit tests in ``tests/pytests/unit/cli/test_batch.py``
still pass -- the local-master dispatch is byte-for-byte unchanged.

Async batch (``--batch --async``) on the remote path is still
broken -- the async handoff writes directly to the master's
``cachedir/jobs/<jid>/.batch.p`` and fires an event on the master's
IPC bus, both impossible from a remote workstation.  Follow-up
commit will add a narrow ``batch_adopt`` endpoint on ClearFuncs so
remote clients can hand off batch state through the AES bridge
without exposing a general-purpose event-injection RPC.

* Hand off async batch to the master via ClearFuncs.batch_adopt

``salt --batch --async`` from a remote workstation needs to publish
the first sub-batch and then hand the composed BatchState dict to
the master so :class:`BatchManager` can own ``cachedir`` writes and
drive subsequent sub-batches.  The master-local path does this with
two operations the workstation cannot perform: writing
``.batch.p`` + ``batch_active.p`` under the master's ``cachedir``,
and firing ``salt/batch/<jid>/new`` on the master's IPC event bus.

Add a narrow ``batch_adopt`` endpoint on :class:`ClearFuncs` that
performs both operations server-side under eauth authorization.
The AES bridge already routes ClearFuncs-exposed cmds whose sender
is a known client (``_is_client_bridge``), so routing is automatic
once ``batch_adopt`` is in ``ClearFuncs.expose_methods``.
Authorization requires ``@wheel`` on the eauth user's auth_list,
matching how the existing wheel endpoint gates comparable
master-cachedir mutations.

Unlike a general-purpose ``fire_event`` RPC, ``batch_adopt`` only
ever emits ``salt/batch/<jid>/new`` and only ever writes the two
batch state files for the one jid passed in -- the blast radius is
a single JID per call, not arbitrary event injection.

Client side: :class:`salt.client.RemoteClient` gains a
``batch_adopt(batch_jid, state, **auth_kwargs)`` wrapper that
builds the AES-wrapped payload and dispatches through the standard
``ReqChannel.factory(crypt="aes")`` path -- the same transport used
for publish/runner/wheel.

Rewire ``salt.cli.salt.SaltCMD._run_batch_async`` to branch on
``__role=client``: on remote, call ``self.client.batch_adopt(...)``
after the first sub-batch is published; on master-local, keep the
existing direct cachedir writes + ``get_master_event().fire_event``
path byte-for-byte.

All 79 existing batch unit tests across ``test_batch.py``,
``test_batch_async.py``, and ``test_batch_visibility.py`` still
pass -- the master-local async path is unchanged.

* Declare client_event_port and client_auth in config schema

Both opts were introduced by the remote-CLI feature and used at runtime
but never added to Salt's schema dictionaries, so VALID_OPTS validation
would reject them if an operator set them in a config file.

- client_event_port (int, default 4507): master-side port where
  ClientEventPublisher binds for authenticated event streaming to remote
  clients.  Auth channel uses client_event_port + 1.
- client_auth (bool, default False): set dynamically by client_config()
  to steer CLI dispatch between LocalClient (False) and RemoteClient
  (True).  Static False default in DEFAULT_MASTER_OPTS keeps
  opts.get("client_auth") predictable when the opt is absent.

* doc: surface Remote* client classes in the Python client API reference

Add autoclass entries for salt.client.RemoteClient,
salt.runner.RemoteRunnerClient, salt.runner.RemoteRunner, and
salt.wheel.RemoteWheelClient so Sphinx picks up the new remote-CLI
client classes. Precede them with a short "Remote clients" section
that explains the AES/ReqChannel transport, the __role=client config
loaded via salt.config.client_config, and points at
doc/topics/execution/remote_execution.rst for the user guide.

* test: unit coverage for 4 remote-CLI security-adjacent paths

Four code paths that only had scenario-level coverage now get focused
unit tests so regressions surface early:

* ``MWorker._is_client_bridge`` -- every clause of the AES->ClearFuncs
  bridge gate (dict/str/exposure/id/key_cache fallbacks and the
  stub-funcs ``getattr`` safety net).
* ``AuthFuncs._auth_impl`` + ``_auth_impl_sync`` cross-role collision
  check -- both directions (client-id squatting as a minion and vice
  versa) and the non-collision fall-through, async + sync shim paths.
* ``client_config`` ``master_port -> ret_port`` translation -- promote
  when only master_port is set, keep explicit ret_port when both are
  set, and leave both at the baked-in defaults when neither is set.
* ``_derive_events_key`` -- determinism, str/bytes equivalence,
  distinct secrets, Crypticle key_string length + round-trip.

* Replace pyobj on event-stream auth REP channel with msgpack

The ``ClientEventPublisher`` auth REP socket on port 4508 was using
``recv_pyobj()`` / ``send_pyobj()`` to shuttle Python dicts over the
wire.  ``recv_pyobj()`` is ``cPickle.loads`` under the hood -- any
host that can reach the socket (bound to ``self.opts["interface"]``,
which defaults to ``0.0.0.0`` on standard installs) can send a
malicious pickle and achieve code execution in the salt-master
process *before* the authentication logic inside ``_handle_auth_request``
has a chance to reject them.  Pre-auth pickle RCE.

``recv_pyobj`` / ``send_pyobj`` appear nowhere else in Salt proper --
every other transport (ReqChannel, PubChannel, the event-stream PUB
socket itself) uses msgpack via :func:`salt.payload.dumps` /
:func:`salt.payload.loads`.  The author of the auth REP channel
reached for ``recv_pyobj`` as the quickest way to move a dict and
never came back to it.

Replace all 10 call sites in :class:`ClientEventPublisher`
(server-side auth handler) and :class:`ClientEventSubscriber`
(client-side auth /…
dwoz added a commit that referenced this pull request Nov 11, 2026
Phase-3 verifier finding #1: the pre-shim ``docker compose up -d`` on
the 3-master testbed brought the scale minion up as soon as haproxy
was ready, which fired an auto-register BEFORE the operator could
manually create the ``resource_index`` ring.  That caused the first
~3 chunks of the 200K-resource register (30K SRNs) to land via the
replicate fallback -- full set to all 3 masters -- polluting the
cluster with "shared" SRNs that the later ring-dispatched chunks
could NOT prune (the terminal scope=dummy prune only removes SRNs
NOT seen this window, and the replicate-dupes had been seen on
every master this window).

Symptom: ``sum=320000`` after a fresh ``up -d`` instead of the
``sum=200000 exact`` invariant that ring mode promises.

Fix: add a one-shot ``c3-ring-setup`` compose service that invokes
``cluster.ring_create / route_set / ring_set`` against master-1 (the
runner fans out to the Raft leader via cluster/peer/multi-ring-request
regardless of which master is leader), polls until the ring is
``active``, and exits 0.  The minion container's ``depends_on`` now
uses ``service_completed_successfully`` so the minion only comes up
after the ring is live.  First auto-register goes through the ring
and ``sum=200000 exact`` is the stable ring-mode invariant.

New files:

- ``tests/monitoring/cluster-3node/docker-compose.yml``: stack
  definition.  Paths parameterized via ``${SALT_SRC:-../../..}`` so
  worktree verifiers can override the bind-mount source.
- ``tests/monitoring/cluster-3node/ring-setup.sh``: sequencing script
  the shim runs on startup.  Waits for the master runner, creates
  ring/route/ring_set, polls ``cluster.rings`` until status=active,
  exits.
- ``tests/monitoring/cluster-3node/README.md``: documents the
  topology and the "why" of the shim.
- ``tests/monitoring/cluster-3node/{Dockerfile.salt, haproxy.cfg,
  master-{1,2,3}.conf, minion.conf, srv/salt/*}``: the rest of the
  testbed (previously untracked local fixture).

Measurement path after this change:

    export SALT_SRC=$(pwd)   # from the branch worktree root
    cd tests/monitoring/cluster-3node
    docker compose up -d     # blocks until c3-ring-setup exits 0
    docker exec c3-salt-minion-1 \
        salt-call saltutil.refresh_resources wait=True timeout=600
    # observe sum=200000 exact across the 3 masters
dwoz added a commit that referenced this pull request Nov 17, 2026
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).
dwoz added a commit that referenced this pull request Nov 18, 2026
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).
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.

1 participant