Repository navigation
Conversation
dwoz
added a commit
that referenced
this pull request
Dec 2, 2019
…ged-4 [PyTest #4] Stop cross-importing from test modules
dwoz
added a commit
that referenced
this pull request
Jan 2, 2026
SECURITY FIX: Previously, token validation for discover-reply was disabled with comment "XXX First token created in different process", allowing replay attacks on the discovery phase. This commit enables proper token validation by storing discover tokens in _discover_candidates and validating the return_token. Changes: discover_peers() (lines 1108-1121): - Generate unique token for each peer we're discovering from - Store token in _discover_candidates[peer_id] for later validation - Each peer gets its own token to prevent cross-peer replay attacks discover-reply handler (lines 1730-1749): - Validate peer_id exists in _discover_candidates (prevents unexpected replies) - Extract expected_token from stored candidates - Validate return_token matches the token we sent to that peer - Log warning and reject if tokens don't match Architecture: The original comment about "different process" is no longer relevant because we store tokens in _discover_candidates which is instance state shared across the event handling path. Both discover_peers() and handle_pool_publish() operate on the same instance. _discover_candidates serves dual purpose: - Joining master: Tracks peers we sent DISCOVER to (stores tokens) - Bootstrap peer: Tracks peers discovering us (stores pub + token) No collision occurs because an instance is either joining OR bootstrap, never both simultaneously. Security Impact: - Prevents replay attacks on discover-reply messages - Ensures discover-reply matches a discover we actually sent - Validates response came from the peer we queried - Protects against man-in-the-middle on discovery phase Attack Prevented: Previously, attacker could replay old discover-reply messages to: - Make joining master accept stale cluster information - Bypass freshness checks on discovery - Potentially inject malicious bootstrap peer Now, each discover-reply must contain the exact token we sent to that specific peer in that specific discover request. Resolves security issue #4 from CLUSTER_JOIN_SECURITY_ANALYSIS.md
dwoz
added a commit
that referenced
this pull request
Apr 2, 2026
SECURITY FIX: Previously, token validation for discover-reply was disabled with comment "XXX First token created in different process", allowing replay attacks on the discovery phase. This commit enables proper token validation by storing discover tokens in _discover_candidates and validating the return_token. Changes: discover_peers() (lines 1108-1121): - Generate unique token for each peer we're discovering from - Store token in _discover_candidates[peer_id] for later validation - Each peer gets its own token to prevent cross-peer replay attacks discover-reply handler (lines 1730-1749): - Validate peer_id exists in _discover_candidates (prevents unexpected replies) - Extract expected_token from stored candidates - Validate return_token matches the token we sent to that peer - Log warning and reject if tokens don't match Architecture: The original comment about "different process" is no longer relevant because we store tokens in _discover_candidates which is instance state shared across the event handling path. Both discover_peers() and handle_pool_publish() operate on the same instance. _discover_candidates serves dual purpose: - Joining master: Tracks peers we sent DISCOVER to (stores tokens) - Bootstrap peer: Tracks peers discovering us (stores pub + token) No collision occurs because an instance is either joining OR bootstrap, never both simultaneously. Security Impact: - Prevents replay attacks on discover-reply messages - Ensures discover-reply matches a discover we actually sent - Validates response came from the peer we queried - Protects against man-in-the-middle on discovery phase Attack Prevented: Previously, attacker could replay old discover-reply messages to: - Make joining master accept stale cluster information - Bypass freshness checks on discovery - Potentially inject malicious bootstrap peer Now, each discover-reply must contain the exact token we sent to that specific peer in that specific discover request. Resolves security issue #4 from CLUSTER_JOIN_SECURITY_ANALYSIS.md
dwoz
added a commit
that referenced
this pull request
Apr 7, 2026
SECURITY FIX: Previously, token validation for discover-reply was disabled with comment "XXX First token created in different process", allowing replay attacks on the discovery phase. This commit enables proper token validation by storing discover tokens in _discover_candidates and validating the return_token. Changes: discover_peers() (lines 1108-1121): - Generate unique token for each peer we're discovering from - Store token in _discover_candidates[peer_id] for later validation - Each peer gets its own token to prevent cross-peer replay attacks discover-reply handler (lines 1730-1749): - Validate peer_id exists in _discover_candidates (prevents unexpected replies) - Extract expected_token from stored candidates - Validate return_token matches the token we sent to that peer - Log warning and reject if tokens don't match Architecture: The original comment about "different process" is no longer relevant because we store tokens in _discover_candidates which is instance state shared across the event handling path. Both discover_peers() and handle_pool_publish() operate on the same instance. _discover_candidates serves dual purpose: - Joining master: Tracks peers we sent DISCOVER to (stores tokens) - Bootstrap peer: Tracks peers discovering us (stores pub + token) No collision occurs because an instance is either joining OR bootstrap, never both simultaneously. Security Impact: - Prevents replay attacks on discover-reply messages - Ensures discover-reply matches a discover we actually sent - Validates response came from the peer we queried - Protects against man-in-the-middle on discovery phase Attack Prevented: Previously, attacker could replay old discover-reply messages to: - Make joining master accept stale cluster information - Bypass freshness checks on discovery - Potentially inject malicious bootstrap peer Now, each discover-reply must contain the exact token we sent to that specific peer in that specific discover request. Resolves security issue #4 from CLUSTER_JOIN_SECURITY_ANALYSIS.md
dwoz
added a commit
that referenced
this pull request
Apr 8, 2026
SECURITY FIX: Previously, token validation for discover-reply was disabled with comment "XXX First token created in different process", allowing replay attacks on the discovery phase. This commit enables proper token validation by storing discover tokens in _discover_candidates and validating the return_token. Changes: discover_peers() (lines 1108-1121): - Generate unique token for each peer we're discovering from - Store token in _discover_candidates[peer_id] for later validation - Each peer gets its own token to prevent cross-peer replay attacks discover-reply handler (lines 1730-1749): - Validate peer_id exists in _discover_candidates (prevents unexpected replies) - Extract expected_token from stored candidates - Validate return_token matches the token we sent to that peer - Log warning and reject if tokens don't match Architecture: The original comment about "different process" is no longer relevant because we store tokens in _discover_candidates which is instance state shared across the event handling path. Both discover_peers() and handle_pool_publish() operate on the same instance. _discover_candidates serves dual purpose: - Joining master: Tracks peers we sent DISCOVER to (stores tokens) - Bootstrap peer: Tracks peers discovering us (stores pub + token) No collision occurs because an instance is either joining OR bootstrap, never both simultaneously. Security Impact: - Prevents replay attacks on discover-reply messages - Ensures discover-reply matches a discover we actually sent - Validates response came from the peer we queried - Protects against man-in-the-middle on discovery phase Attack Prevented: Previously, attacker could replay old discover-reply messages to: - Make joining master accept stale cluster information - Bypass freshness checks on discovery - Potentially inject malicious bootstrap peer Now, each discover-reply must contain the exact token we sent to that specific peer in that specific discover request. Resolves security issue #4 from CLUSTER_JOIN_SECURITY_ANALYSIS.md
dwoz
added a commit
that referenced
this pull request
Apr 12, 2026
SECURITY FIX: Previously, token validation for discover-reply was disabled with comment "XXX First token created in different process", allowing replay attacks on the discovery phase. This commit enables proper token validation by storing discover tokens in _discover_candidates and validating the return_token. Changes: discover_peers() (lines 1108-1121): - Generate unique token for each peer we're discovering from - Store token in _discover_candidates[peer_id] for later validation - Each peer gets its own token to prevent cross-peer replay attacks discover-reply handler (lines 1730-1749): - Validate peer_id exists in _discover_candidates (prevents unexpected replies) - Extract expected_token from stored candidates - Validate return_token matches the token we sent to that peer - Log warning and reject if tokens don't match Architecture: The original comment about "different process" is no longer relevant because we store tokens in _discover_candidates which is instance state shared across the event handling path. Both discover_peers() and handle_pool_publish() operate on the same instance. _discover_candidates serves dual purpose: - Joining master: Tracks peers we sent DISCOVER to (stores tokens) - Bootstrap peer: Tracks peers discovering us (stores pub + token) No collision occurs because an instance is either joining OR bootstrap, never both simultaneously. Security Impact: - Prevents replay attacks on discover-reply messages - Ensures discover-reply matches a discover we actually sent - Validates response came from the peer we queried - Protects against man-in-the-middle on discovery phase Attack Prevented: Previously, attacker could replay old discover-reply messages to: - Make joining master accept stale cluster information - Bypass freshness checks on discovery - Potentially inject malicious bootstrap peer Now, each discover-reply must contain the exact token we sent to that specific peer in that specific discover request. Resolves security issue #4 from CLUSTER_JOIN_SECURITY_ANALYSIS.md
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
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
added a commit
that referenced
this pull request
Nov 3, 2026
The 'environmental test harness pollution' turned out to be three
real production bugs that the harness exposed. Fixing them is
not optional — operators would hit the same races.
PRODUCTION BUG 1: MasterPubServerChannel.pre_fork ordering race
salt/channel/server.py:
process_manager.add_process calls process.start() synchronously,
so the EventPublisher forked BEFORE link_manager.pre_fork ran.
Child's open_writer() raced the parent's _init_index_file,
yielding partially-written mmap files (observed sizes 7.7MB /
24MB / 27MB vs expected 96MB). Fix: swap the two blocks so
pre_fork materialises all four MmapCache files BEFORE any fork.
PRODUCTION BUG 2: Minion-side cluster_id gating broken
salt/crypt.py:AsyncAuth.handle_signin_response:
Gated the auth-response cluster_id lift on
self.opts.get('topology_enabled') and
self.opts.get('topology_push_cluster_grain'), but both are
master-side opts with no minion schema entries — always falsy
on a minion. Grain never arrived on any minion. Fix: drop the
minion-side gate; master-side _topology_cluster_id_for_auth
holds the policy of whether to emit the field. Tests updated
to assert the corrected invariant.
PRODUCTION BUG 3: TopologyRouter.route_publish ignored nodegroups
salt/topology/router.py:
Called extract_cluster_scope(tgt) with no nodegroups kwarg,
so N@east_web (where east_web = 'C@east and web-*') extracted
no scope and flooded instead of routing to east. FU-A added
the kwarg but the router didn't pass it. Fix: pass
self.opts.get('nodegroups').
ITEM 2 — Signal-safety documentation (RFC follow-up #8):
Added 'Signal-safety invariant' sections to module docstrings
of salt/topology/registry.py, salt/topology/breadcrumbs.py,
and a new module docstring on salt/utils/mmap_cache.py. Each
spells out 'no subprocess spawn while flock held' with
fork-inheritance rationale.
ITEM 3 — MWorker->publish-daemon durability (RFC follow-up #4):
Added tests/pytests/stress/master_subprocess/eventpublisher/
test_topology_return_handoff.py — drives 10,000
salt/topology/return/east/<jid> payloads at the real
EventPublisher subprocess puller->subscriber wire path.
Measured: 29,083 returns/sec sustained, 0 drops, 0 duplicates,
0 reordering. Drop rate <0.0001% at 29x the target 1000/sec.
No persistent-queue needed; test parked under explicit stress
gate as a regression tripwire.
ITEM 4 — RFC follow-ups section updated:
Struck-through resolved items (expand nodegroups, MWorker
durability, signal-safety docs). Added 'Also resolved during
the final-cleanup pass' subsection documenting the three
production bugs. Remaining open items (6): strip_cluster_scope
fuzzing, LinkHealth.QUIESCING drain window, next_hop on
followers, PeerState NamedTuple schema version, atomic_rebuild
grace period, returner cluster_path schemas.
Final topology-suite result on this commit:
- test_two_master_handshake_e2e: PASSING (was failing)
- test_grain_present_on_topology_minion: PASSING (was failing)
- test_grain_survives_grains_items: PASSING (was failing)
- test_grain_matcher_targets_master_cluster_id: PASSING (was failing)
- test_scenario_cli_c_at_local_publish_round_trip: PASSING (was flaky)
948/948 topology tests pass + 1 strict-xfail (CLI e2e C@west, now
the only known-open xfail across all topology tests).
Pre-commit clean on all 10 touched files.
dwoz
added a commit
that referenced
this pull request
Nov 3, 2026
The 'environmental test harness pollution' turned out to be three
real production bugs that the harness exposed. Fixing them is
not optional — operators would hit the same races.
PRODUCTION BUG 1: MasterPubServerChannel.pre_fork ordering race
salt/channel/server.py:
process_manager.add_process calls process.start() synchronously,
so the EventPublisher forked BEFORE link_manager.pre_fork ran.
Child's open_writer() raced the parent's _init_index_file,
yielding partially-written mmap files (observed sizes 7.7MB /
24MB / 27MB vs expected 96MB). Fix: swap the two blocks so
pre_fork materialises all four MmapCache files BEFORE any fork.
PRODUCTION BUG 2: Minion-side cluster_id gating broken
salt/crypt.py:AsyncAuth.handle_signin_response:
Gated the auth-response cluster_id lift on
self.opts.get('topology_enabled') and
self.opts.get('topology_push_cluster_grain'), but both are
master-side opts with no minion schema entries — always falsy
on a minion. Grain never arrived on any minion. Fix: drop the
minion-side gate; master-side _topology_cluster_id_for_auth
holds the policy of whether to emit the field. Tests updated
to assert the corrected invariant.
PRODUCTION BUG 3: TopologyRouter.route_publish ignored nodegroups
salt/topology/router.py:
Called extract_cluster_scope(tgt) with no nodegroups kwarg,
so N@east_web (where east_web = 'C@east and web-*') extracted
no scope and flooded instead of routing to east. FU-A added
the kwarg but the router didn't pass it. Fix: pass
self.opts.get('nodegroups').
ITEM 2 — Signal-safety documentation (RFC follow-up #8):
Added 'Signal-safety invariant' sections to module docstrings
of salt/topology/registry.py, salt/topology/breadcrumbs.py,
and a new module docstring on salt/utils/mmap_cache.py. Each
spells out 'no subprocess spawn while flock held' with
fork-inheritance rationale.
ITEM 3 — MWorker->publish-daemon durability (RFC follow-up #4):
Added tests/pytests/stress/master_subprocess/eventpublisher/
test_topology_return_handoff.py — drives 10,000
salt/topology/return/east/<jid> payloads at the real
EventPublisher subprocess puller->subscriber wire path.
Measured: 29,083 returns/sec sustained, 0 drops, 0 duplicates,
0 reordering. Drop rate <0.0001% at 29x the target 1000/sec.
No persistent-queue needed; test parked under explicit stress
gate as a regression tripwire.
ITEM 4 — RFC follow-ups section updated:
Struck-through resolved items (expand nodegroups, MWorker
durability, signal-safety docs). Added 'Also resolved during
the final-cleanup pass' subsection documenting the three
production bugs. Remaining open items (6): strip_cluster_scope
fuzzing, LinkHealth.QUIESCING drain window, next_hop on
followers, PeerState NamedTuple schema version, atomic_rebuild
grace period, returner cluster_path schemas.
Final topology-suite result on this commit:
- test_two_master_handshake_e2e: PASSING (was failing)
- test_grain_present_on_topology_minion: PASSING (was failing)
- test_grain_survives_grains_items: PASSING (was failing)
- test_grain_matcher_targets_master_cluster_id: PASSING (was failing)
- test_scenario_cli_c_at_local_publish_round_trip: PASSING (was flaky)
948/948 topology tests pass + 1 strict-xfail (CLI e2e C@west, now
the only known-open xfail across all topology tests).
Pre-commit clean on all 10 touched files.
dwoz
added a commit
that referenced
this pull request
Nov 3, 2026
The 'environmental test harness pollution' turned out to be three
real production bugs that the harness exposed. Fixing them is
not optional — operators would hit the same races.
PRODUCTION BUG 1: MasterPubServerChannel.pre_fork ordering race
salt/channel/server.py:
process_manager.add_process calls process.start() synchronously,
so the EventPublisher forked BEFORE link_manager.pre_fork ran.
Child's open_writer() raced the parent's _init_index_file,
yielding partially-written mmap files (observed sizes 7.7MB /
24MB / 27MB vs expected 96MB). Fix: swap the two blocks so
pre_fork materialises all four MmapCache files BEFORE any fork.
PRODUCTION BUG 2: Minion-side cluster_id gating broken
salt/crypt.py:AsyncAuth.handle_signin_response:
Gated the auth-response cluster_id lift on
self.opts.get('topology_enabled') and
self.opts.get('topology_push_cluster_grain'), but both are
master-side opts with no minion schema entries — always falsy
on a minion. Grain never arrived on any minion. Fix: drop the
minion-side gate; master-side _topology_cluster_id_for_auth
holds the policy of whether to emit the field. Tests updated
to assert the corrected invariant.
PRODUCTION BUG 3: TopologyRouter.route_publish ignored nodegroups
salt/topology/router.py:
Called extract_cluster_scope(tgt) with no nodegroups kwarg,
so N@east_web (where east_web = 'C@east and web-*') extracted
no scope and flooded instead of routing to east. FU-A added
the kwarg but the router didn't pass it. Fix: pass
self.opts.get('nodegroups').
ITEM 2 — Signal-safety documentation (RFC follow-up #8):
Added 'Signal-safety invariant' sections to module docstrings
of salt/topology/registry.py, salt/topology/breadcrumbs.py,
and a new module docstring on salt/utils/mmap_cache.py. Each
spells out 'no subprocess spawn while flock held' with
fork-inheritance rationale.
ITEM 3 — MWorker->publish-daemon durability (RFC follow-up #4):
Added tests/pytests/stress/master_subprocess/eventpublisher/
test_topology_return_handoff.py — drives 10,000
salt/topology/return/east/<jid> payloads at the real
EventPublisher subprocess puller->subscriber wire path.
Measured: 29,083 returns/sec sustained, 0 drops, 0 duplicates,
0 reordering. Drop rate <0.0001% at 29x the target 1000/sec.
No persistent-queue needed; test parked under explicit stress
gate as a regression tripwire.
ITEM 4 — RFC follow-ups section updated:
Struck-through resolved items (expand nodegroups, MWorker
durability, signal-safety docs). Added 'Also resolved during
the final-cleanup pass' subsection documenting the three
production bugs. Remaining open items (6): strip_cluster_scope
fuzzing, LinkHealth.QUIESCING drain window, next_hop on
followers, PeerState NamedTuple schema version, atomic_rebuild
grace period, returner cluster_path schemas.
Final topology-suite result on this commit:
- test_two_master_handshake_e2e: PASSING (was failing)
- test_grain_present_on_topology_minion: PASSING (was failing)
- test_grain_survives_grains_items: PASSING (was failing)
- test_grain_matcher_targets_master_cluster_id: PASSING (was failing)
- test_scenario_cli_c_at_local_publish_round_trip: PASSING (was flaky)
948/948 topology tests pass + 1 strict-xfail (CLI e2e C@west, now
the only known-open xfail across all topology tests).
Pre-commit clean on all 10 touched files.
dwoz
added a commit
that referenced
this pull request
Nov 3, 2026
The 'environmental test harness pollution' turned out to be three
real production bugs that the harness exposed. Fixing them is
not optional — operators would hit the same races.
PRODUCTION BUG 1: MasterPubServerChannel.pre_fork ordering race
salt/channel/server.py:
process_manager.add_process calls process.start() synchronously,
so the EventPublisher forked BEFORE link_manager.pre_fork ran.
Child's open_writer() raced the parent's _init_index_file,
yielding partially-written mmap files (observed sizes 7.7MB /
24MB / 27MB vs expected 96MB). Fix: swap the two blocks so
pre_fork materialises all four MmapCache files BEFORE any fork.
PRODUCTION BUG 2: Minion-side cluster_id gating broken
salt/crypt.py:AsyncAuth.handle_signin_response:
Gated the auth-response cluster_id lift on
self.opts.get('topology_enabled') and
self.opts.get('topology_push_cluster_grain'), but both are
master-side opts with no minion schema entries — always falsy
on a minion. Grain never arrived on any minion. Fix: drop the
minion-side gate; master-side _topology_cluster_id_for_auth
holds the policy of whether to emit the field. Tests updated
to assert the corrected invariant.
PRODUCTION BUG 3: TopologyRouter.route_publish ignored nodegroups
salt/topology/router.py:
Called extract_cluster_scope(tgt) with no nodegroups kwarg,
so N@east_web (where east_web = 'C@east and web-*') extracted
no scope and flooded instead of routing to east. FU-A added
the kwarg but the router didn't pass it. Fix: pass
self.opts.get('nodegroups').
ITEM 2 — Signal-safety documentation (RFC follow-up #8):
Added 'Signal-safety invariant' sections to module docstrings
of salt/topology/registry.py, salt/topology/breadcrumbs.py,
and a new module docstring on salt/utils/mmap_cache.py. Each
spells out 'no subprocess spawn while flock held' with
fork-inheritance rationale.
ITEM 3 — MWorker->publish-daemon durability (RFC follow-up #4):
Added tests/pytests/stress/master_subprocess/eventpublisher/
test_topology_return_handoff.py — drives 10,000
salt/topology/return/east/<jid> payloads at the real
EventPublisher subprocess puller->subscriber wire path.
Measured: 29,083 returns/sec sustained, 0 drops, 0 duplicates,
0 reordering. Drop rate <0.0001% at 29x the target 1000/sec.
No persistent-queue needed; test parked under explicit stress
gate as a regression tripwire.
ITEM 4 — RFC follow-ups section updated:
Struck-through resolved items (expand nodegroups, MWorker
durability, signal-safety docs). Added 'Also resolved during
the final-cleanup pass' subsection documenting the three
production bugs. Remaining open items (6): strip_cluster_scope
fuzzing, LinkHealth.QUIESCING drain window, next_hop on
followers, PeerState NamedTuple schema version, atomic_rebuild
grace period, returner cluster_path schemas.
Final topology-suite result on this commit:
- test_two_master_handshake_e2e: PASSING (was failing)
- test_grain_present_on_topology_minion: PASSING (was failing)
- test_grain_survives_grains_items: PASSING (was failing)
- test_grain_matcher_targets_master_cluster_id: PASSING (was failing)
- test_scenario_cli_c_at_local_publish_round_trip: PASSING (was flaky)
948/948 topology tests pass + 1 strict-xfail (CLI e2e C@west, now
the only known-open xfail across all topology tests).
Pre-commit clean on all 10 touched files.
dwoz
added a commit
that referenced
this pull request
Nov 4, 2026
The 'environmental test harness pollution' turned out to be three
real production bugs that the harness exposed. Fixing them is
not optional — operators would hit the same races.
PRODUCTION BUG 1: MasterPubServerChannel.pre_fork ordering race
salt/channel/server.py:
process_manager.add_process calls process.start() synchronously,
so the EventPublisher forked BEFORE link_manager.pre_fork ran.
Child's open_writer() raced the parent's _init_index_file,
yielding partially-written mmap files (observed sizes 7.7MB /
24MB / 27MB vs expected 96MB). Fix: swap the two blocks so
pre_fork materialises all four MmapCache files BEFORE any fork.
PRODUCTION BUG 2: Minion-side cluster_id gating broken
salt/crypt.py:AsyncAuth.handle_signin_response:
Gated the auth-response cluster_id lift on
self.opts.get('topology_enabled') and
self.opts.get('topology_push_cluster_grain'), but both are
master-side opts with no minion schema entries — always falsy
on a minion. Grain never arrived on any minion. Fix: drop the
minion-side gate; master-side _topology_cluster_id_for_auth
holds the policy of whether to emit the field. Tests updated
to assert the corrected invariant.
PRODUCTION BUG 3: TopologyRouter.route_publish ignored nodegroups
salt/topology/router.py:
Called extract_cluster_scope(tgt) with no nodegroups kwarg,
so N@east_web (where east_web = 'C@east and web-*') extracted
no scope and flooded instead of routing to east. FU-A added
the kwarg but the router didn't pass it. Fix: pass
self.opts.get('nodegroups').
ITEM 2 — Signal-safety documentation (RFC follow-up #8):
Added 'Signal-safety invariant' sections to module docstrings
of salt/topology/registry.py, salt/topology/breadcrumbs.py,
and a new module docstring on salt/utils/mmap_cache.py. Each
spells out 'no subprocess spawn while flock held' with
fork-inheritance rationale.
ITEM 3 — MWorker->publish-daemon durability (RFC follow-up #4):
Added tests/pytests/stress/master_subprocess/eventpublisher/
test_topology_return_handoff.py — drives 10,000
salt/topology/return/east/<jid> payloads at the real
EventPublisher subprocess puller->subscriber wire path.
Measured: 29,083 returns/sec sustained, 0 drops, 0 duplicates,
0 reordering. Drop rate <0.0001% at 29x the target 1000/sec.
No persistent-queue needed; test parked under explicit stress
gate as a regression tripwire.
ITEM 4 — RFC follow-ups section updated:
Struck-through resolved items (expand nodegroups, MWorker
durability, signal-safety docs). Added 'Also resolved during
the final-cleanup pass' subsection documenting the three
production bugs. Remaining open items (6): strip_cluster_scope
fuzzing, LinkHealth.QUIESCING drain window, next_hop on
followers, PeerState NamedTuple schema version, atomic_rebuild
grace period, returner cluster_path schemas.
Final topology-suite result on this commit:
- test_two_master_handshake_e2e: PASSING (was failing)
- test_grain_present_on_topology_minion: PASSING (was failing)
- test_grain_survives_grains_items: PASSING (was failing)
- test_grain_matcher_targets_master_cluster_id: PASSING (was failing)
- test_scenario_cli_c_at_local_publish_round_trip: PASSING (was flaky)
948/948 topology tests pass + 1 strict-xfail (CLI e2e C@west, now
the only known-open xfail across all topology tests).
Pre-commit clean on all 10 touched files.
dwoz
added a commit
that referenced
this pull request
Nov 5, 2026
The 'environmental test harness pollution' turned out to be three
real production bugs that the harness exposed. Fixing them is
not optional — operators would hit the same races.
PRODUCTION BUG 1: MasterPubServerChannel.pre_fork ordering race
salt/channel/server.py:
process_manager.add_process calls process.start() synchronously,
so the EventPublisher forked BEFORE link_manager.pre_fork ran.
Child's open_writer() raced the parent's _init_index_file,
yielding partially-written mmap files (observed sizes 7.7MB /
24MB / 27MB vs expected 96MB). Fix: swap the two blocks so
pre_fork materialises all four MmapCache files BEFORE any fork.
PRODUCTION BUG 2: Minion-side cluster_id gating broken
salt/crypt.py:AsyncAuth.handle_signin_response:
Gated the auth-response cluster_id lift on
self.opts.get('topology_enabled') and
self.opts.get('topology_push_cluster_grain'), but both are
master-side opts with no minion schema entries — always falsy
on a minion. Grain never arrived on any minion. Fix: drop the
minion-side gate; master-side _topology_cluster_id_for_auth
holds the policy of whether to emit the field. Tests updated
to assert the corrected invariant.
PRODUCTION BUG 3: TopologyRouter.route_publish ignored nodegroups
salt/topology/router.py:
Called extract_cluster_scope(tgt) with no nodegroups kwarg,
so N@east_web (where east_web = 'C@east and web-*') extracted
no scope and flooded instead of routing to east. FU-A added
the kwarg but the router didn't pass it. Fix: pass
self.opts.get('nodegroups').
ITEM 2 — Signal-safety documentation (RFC follow-up #8):
Added 'Signal-safety invariant' sections to module docstrings
of salt/topology/registry.py, salt/topology/breadcrumbs.py,
and a new module docstring on salt/utils/mmap_cache.py. Each
spells out 'no subprocess spawn while flock held' with
fork-inheritance rationale.
ITEM 3 — MWorker->publish-daemon durability (RFC follow-up #4):
Added tests/pytests/stress/master_subprocess/eventpublisher/
test_topology_return_handoff.py — drives 10,000
salt/topology/return/east/<jid> payloads at the real
EventPublisher subprocess puller->subscriber wire path.
Measured: 29,083 returns/sec sustained, 0 drops, 0 duplicates,
0 reordering. Drop rate <0.0001% at 29x the target 1000/sec.
No persistent-queue needed; test parked under explicit stress
gate as a regression tripwire.
ITEM 4 — RFC follow-ups section updated:
Struck-through resolved items (expand nodegroups, MWorker
durability, signal-safety docs). Added 'Also resolved during
the final-cleanup pass' subsection documenting the three
production bugs. Remaining open items (6): strip_cluster_scope
fuzzing, LinkHealth.QUIESCING drain window, next_hop on
followers, PeerState NamedTuple schema version, atomic_rebuild
grace period, returner cluster_path schemas.
Final topology-suite result on this commit:
- test_two_master_handshake_e2e: PASSING (was failing)
- test_grain_present_on_topology_minion: PASSING (was failing)
- test_grain_survives_grains_items: PASSING (was failing)
- test_grain_matcher_targets_master_cluster_id: PASSING (was failing)
- test_scenario_cli_c_at_local_publish_round_trip: PASSING (was flaky)
948/948 topology tests pass + 1 strict-xfail (CLI e2e C@west, now
the only known-open xfail across all topology tests).
Pre-commit clean on all 10 touched files.
dwoz
added a commit
that referenced
this pull request
Nov 11, 2026
The 'environmental test harness pollution' turned out to be three
real production bugs that the harness exposed. Fixing them is
not optional — operators would hit the same races.
PRODUCTION BUG 1: MasterPubServerChannel.pre_fork ordering race
salt/channel/server.py:
process_manager.add_process calls process.start() synchronously,
so the EventPublisher forked BEFORE link_manager.pre_fork ran.
Child's open_writer() raced the parent's _init_index_file,
yielding partially-written mmap files (observed sizes 7.7MB /
24MB / 27MB vs expected 96MB). Fix: swap the two blocks so
pre_fork materialises all four MmapCache files BEFORE any fork.
PRODUCTION BUG 2: Minion-side cluster_id gating broken
salt/crypt.py:AsyncAuth.handle_signin_response:
Gated the auth-response cluster_id lift on
self.opts.get('topology_enabled') and
self.opts.get('topology_push_cluster_grain'), but both are
master-side opts with no minion schema entries — always falsy
on a minion. Grain never arrived on any minion. Fix: drop the
minion-side gate; master-side _topology_cluster_id_for_auth
holds the policy of whether to emit the field. Tests updated
to assert the corrected invariant.
PRODUCTION BUG 3: TopologyRouter.route_publish ignored nodegroups
salt/topology/router.py:
Called extract_cluster_scope(tgt) with no nodegroups kwarg,
so N@east_web (where east_web = 'C@east and web-*') extracted
no scope and flooded instead of routing to east. FU-A added
the kwarg but the router didn't pass it. Fix: pass
self.opts.get('nodegroups').
ITEM 2 — Signal-safety documentation (RFC follow-up #8):
Added 'Signal-safety invariant' sections to module docstrings
of salt/topology/registry.py, salt/topology/breadcrumbs.py,
and a new module docstring on salt/utils/mmap_cache.py. Each
spells out 'no subprocess spawn while flock held' with
fork-inheritance rationale.
ITEM 3 — MWorker->publish-daemon durability (RFC follow-up #4):
Added tests/pytests/stress/master_subprocess/eventpublisher/
test_topology_return_handoff.py — drives 10,000
salt/topology/return/east/<jid> payloads at the real
EventPublisher subprocess puller->subscriber wire path.
Measured: 29,083 returns/sec sustained, 0 drops, 0 duplicates,
0 reordering. Drop rate <0.0001% at 29x the target 1000/sec.
No persistent-queue needed; test parked under explicit stress
gate as a regression tripwire.
ITEM 4 — RFC follow-ups section updated:
Struck-through resolved items (expand nodegroups, MWorker
durability, signal-safety docs). Added 'Also resolved during
the final-cleanup pass' subsection documenting the three
production bugs. Remaining open items (6): strip_cluster_scope
fuzzing, LinkHealth.QUIESCING drain window, next_hop on
followers, PeerState NamedTuple schema version, atomic_rebuild
grace period, returner cluster_path schemas.
Final topology-suite result on this commit:
- test_two_master_handshake_e2e: PASSING (was failing)
- test_grain_present_on_topology_minion: PASSING (was failing)
- test_grain_survives_grains_items: PASSING (was failing)
- test_grain_matcher_targets_master_cluster_id: PASSING (was failing)
- test_scenario_cli_c_at_local_publish_round_trip: PASSING (was flaky)
948/948 topology tests pass + 1 strict-xfail (CLI e2e C@west, now
the only known-open xfail across all topology tests).
Pre-commit clean on all 10 touched files.
dwoz
added a commit
that referenced
this pull request
Nov 13, 2026
* master topology: initial design + stubs
* master topology: shared multi-cluster test harness (Phase 0)
Lands the pytest fixture + helper harness that all per-file
implementation teams will use for functional testing of the
master-topology feature.
New under tests/pytests/functional/topology/:
conftest.py - fixtures (single_master, single_cluster,
two_cluster_fixture, three_cluster_fixture,
attach_minion)
test_harness.py - 17 harness-correctness tests
New under tests/support/topology/:
cluster.py - TopologyCluster helper object
(accept_peer, revoke_peer, config_peer,
inspect_registry, inspect_breadcrumbs,
is_running, terminate)
Harness tests exercise: master startup with topology opts,
topology.conf on-disk layout, port isolation, topology_enabled
opt-out, multi-peer cluster path, two/three-cluster distinct-id +
distinct-port invariants, accept/revoke/config_peer semantics,
registry/breadcrumb shape, minion attach, teardown port release.
Known limitations captured in conftest docstrings: no MmapCache
parsing in inspect_* (returns on-disk key list / empty breadcrumbs
until registry/breadcrumbs modules land in Phase 1); accept_peer
copies placeholder pub keys (real crypto lands in Phase 1); no
in-test SIGHUP for config_peer (restart escape hatch).
17/17 tests passing.
* master topology: Phase 1 implementations (foundation files)
Lands 5 independent-dependency topology modules with full test
coverage. Each team: test-writer wrote functional tests first,
implementer made them pass, unit tests added after.
Modules implemented:
- salt/config/topology.py PeerRef, TopologyConfig, validate,
load_topology_config
- salt/matchers/cluster_match.py C@ matcher plugin
- salt/topology/summary.py ClusterSummary + collect/serialize
/deserialize/with_path_extended/
is_cycle_for/merge_into (monotonic
origin_seq)
- salt/topology/breadcrumbs.py MmapCache-backed jid->link map;
pre_create/open_writer/open_reader/
put/lookup/delete/cleanup; owner-PID
guard
- salt/topology/registry.py MmapCache-backed identity+peer
registry; reserved-key safety;
owner-PID guard
Tests:
- tests/pytests/functional/topology/test_{config,cluster_match,
summary,breadcrumbs,registry}.py (121 passing)
- tests/pytests/unit/topology/test_{config,cluster_match,summary,
breadcrumbs,registry}.py (146 passing)
Pre-commit clean on all files. Harness tests (Phase 0) still
17/17 green.
Phase 2 next: TopologyStateMachine and PeerMasterLink.
* master topology: Phase 2 implementations (state machine + link)
Lands the Raft-side write path and the peer-master link
primitives.
Modules implemented:
- salt/cluster/consensus/raft/topology.py TopologyStateMachine
(apply/get_snapshot/restore_snapshot per BaseStateMachine
interface); PeerState NamedTuple; dispatch for
MASTER_IDENTITY_KEY / MASTER_PEER_ATTACH / MASTER_PEER_DETACH
with hostile-peer validation + conflict resolution; identity
rotation path with version counter
- salt/cluster/consensus/raft/log.py new LogEntryType
values MASTER_IDENTITY_KEY=6, MASTER_PEER_ATTACH=7,
MASTER_PEER_DETACH=8
- salt/topology/link.py PeerMasterLink +
LinkHealth + LinkUnavailable; wraps AsyncReqChannel +
AsyncPubChannel directly (no new channel classes); envelope
builder honors receiver-authenticates-path rule; session AES
rotation; QUIESCING drain window; __eq__/__hash__ for the
link_manager registry dict
Tests:
- tests/pytests/functional/topology/test_state_machine.py 25 passing
- tests/pytests/functional/topology/test_link.py 18 passing
- tests/pytests/unit/topology/test_state_machine.py 19 passing
- tests/pytests/unit/topology/test_link.py 26 passing
Known gaps picked up in later phases:
- link.py functional tests mock the inbound side (receiver) because
_master_auth handler lands in Phase 3 (link_manager); true
end-to-end round-trip tests arrive with Phase 3.
- Scenario tests across multiple modules land after all
implementer phases complete.
Pre-commit clean on all touched files. Phase 0/1 tests still
green. Phase 3 next: router, migration, link_manager.
* master topology: Phase 3 implementations (router + migration + link_manager)
Lands the publish-daemon-side runtime: outbound publish routing,
return-path breadcrumb lifecycle, migration from solo to clustered,
and the inbound listener + outbound-link lifecycle.
Modules implemented:
- salt/topology/router.py TopologyRouter + extract_cluster_scope,
strip_cluster_scope (with not/paren
skip-strip), get_router, on_publish;
path-authenticated forward_publish;
destinations-shrinking; summary ingest
with cycle rejection
- salt/topology/migration.py needs_migration (peer-set diff + raft
bootstrap sentinel); promote_solo_to_
clustered (idempotent crash-resume)
- salt/topology/link_manager.py pre_fork; start (strict ordering:
mmaps -> router -> SM callbacks
-> migration -> listener -> peers);
stop; add_link via call_soon_threadsafe;
_handle_master_auth; _handle_inbound
dispatch; owner-PID guard
Companion edits (needed by migration crash-resume):
- salt/topology/registry.py added RESERVED_RAFT_
BOOTSTRAPPED_KEY and
RESERVED_RAFT_APPLIED_PEERS_KEY
- salt/cluster/consensus/raft/topology.py SM apply handlers stamp the
two Raft-side sentinels so
migration can distinguish
'raft bootstrapped' from
'registry has identity'
Reconciled during merge:
- Router's module-level singleton renamed _router -> _ROUTER to match
link_manager's convention (and other module globals like _LINKS,
_INBOUND, _LISTENER). Router test file updated accordingly.
- Dropped link_manager's 9-line router.py patch (router team shipped
the real get_router implementation).
Tests:
- functional: 34 (router) + 8 (migration) + 19 (link_manager) + 24
(new) added; 225 total topology functional passing
- unit: 15 (router) + 11 (migration) + 12 (link_manager) added;
229 total topology unit passing
- harness tests (Phase 0): 17/17 still green
- Phase 1/2 regressions: zero
Known open issues from Phase 3 agents:
- link_manager monkey-patches TopologyStateMachine's private handlers
to install callbacks (no formal register-callback API on the SM
yet). Phase 4+ can grow a proper hook if needed.
- _handle_master_auth signs the session AES with a placeholder; wiring
to real master_identity crypto lands when crypt.py MasterIdentityKey
is implemented in Phase 5.
Pre-commit clean on all touched files. Phase 4 next: runners/topology.py.
* master topology: Phase 4 implementation (runner commands)
Lands salt-run topology.* operator interface.
Modules implemented:
- salt/runners/topology.py __virtual__ (gated on topology_enabled);
status (tree summary); links (per-link
health); peers (configured + accept state);
trust (accept/reject/delete/fingerprint
wrapping salt-key --master semantics);
find (best-effort fan-out lookup); graph
(text/dot/json rendering)
Tests: 20 functional + 15 unit, all passing. Pre-commit clean.
Known limitations captured in docstrings:
- find() falls back to local-only results until links expose a
has_minion probe (Phase 5+)
- Runner degrades gracefully when link_manager.start() has not run
(reads directly from pki_dir/masters*/ and topology.conf)
- trust() operates on pki_dir/masters* directly rather than through
salt.key.Key (which is minion-focused); matches salt-key --master
design
Full topology test suite: 245 functional + 244 unit = 489 topology
tests passing on commit tip. Phase 0/1/2/3 unchanged.
Phase 5 next: modifications to existing files (compound_match,
_check_compound_minions, MasterPubServerChannel, AESFuncs._return,
store_job, crypt, salt-key --master scope, grain, VALID_OPTS).
* master topology: Phase 5 integration with existing files (partial)
Lands modifications to existing files that make the topology
modules operational against the salt-master runtime.
Modifications:
- salt/matchers/compound_match.py added C to ref dict dispatch
- salt/utils/minions.py added C to TARGET_REX engine class,
added C handling to
_check_compound_minions ref dict
- salt/channel/server.py 4 hooks on MasterPubServerChannel:
pre_fork -> link_manager.pre_fork
_publish_daemon -> link_manager.start
close -> link_manager.stop
publish_payload -> router.on_publish
All lazy-imported, gated on
topology_enabled, no-op when disabled.
- salt/master.py AESFuncs._maybe_fire_topology_return
on both async _return and sync
_sync_return paths; envelope-based
detection (NOT jid parsing);
_topology_cluster_id_for_auth helper
+ injection into _auth_impl /
_auth_impl_sync to push cluster_id
grain to minions.
- salt/utils/job.py store_job gains cluster_path kwarg;
backward-compat on all 5 existing
call sites.
- salt/crypt.py MasterIdentityKey class
(pub/priv RSA, 0400/0444 perms,
generate/load/write/fingerprint,
rotation path); handle_signin_response
lifts cluster_id from master's
auth payload to minion opts.
- salt/config/__init__.py 14 topology_* opts +
auto_accept_masters +
master_cluster_id in VALID_OPTS
and DEFAULT_*_OPTS.
- salt/grains/core.py new master_cluster_id grain
(gated on opts population).
- salt/minion.py _store_master_cluster_id helper +
SMinion refresh so the grain
reflects auth response.
Tests added across Phase 5 (per-team functional + unit):
- test_compound_integration.py (C@ end-to-end at check_minions)
- test_pub_daemon_hooks.py (MasterPubServerChannel wiring)
- test_store_job.py (cluster_path kwarg + duplicate id)
- test_identity_key.py (MasterIdentityKey + auth hook)
- test_config_opts.py (14+ opts VALID + DEFAULT)
- test_master_cluster_grain.py (minion-side grain population)
Full topology test suite: 381 unit + 321 functional = 702 passing
on this commit; one functional test flagged as follow-up (see below).
Pre-commit clean on all touched files.
Known issues / follow-ups:
- Phase 5E (salt-key --master scope) hit API Overloaded; only the
functional test file was produced. Needs retry; impl work on
salt/key.py + salt/utils/parsers.py pending.
- test_pub_daemon_hooks::test_single_master_topology_mmap_files_exist
fails: salt-factories master startup does not appear to invoke
the MasterPubServerChannel.pre_fork hook in a way the test can
observe; the hook IS wired correctly (verified by inspection), but
the test infrastructure or ordering needs follow-up. All other
Phase 5 tests pass.
- Phase 5G added _topology_cluster_id_for_auth to master.py; merged
manually atop Phase 5B's AESFuncs changes.
Next: Phase 5E retry, then scenario-test phase (per user instruction:
teams will write cross-module scenario tests after all implementation
phases complete).
* master topology: Phase 5E salt-key --master scope (retry)
Lands the salt-key --master scope that landed late because the
original Phase 5E team hit an API Error: Overloaded mid-task.
Modifications:
- salt/key.py new Key methods: list_master, accept_master,
reject_master, delete_master, finger_master;
supporting MASTERS_ACC/PEND/REJ/DEN constants;
KeyCLI.CLI_KEY_MASTER_MAP dispatch table;
--master scope branch in _run_cmd.
Propose-first ordering: on clustered masters
the Raft propose fires BEFORE any PKI file
touch; apply handler on every peer does the
rename. Guarantees cluster-peer consistency
across crashes between salt-key and Raft
commit. On solo masters, salt-key renames
directly (no Raft to propose to).
- salt/utils/parsers.py --master flag on SaltKeyOptionParser
(dest=master_scope); -L/-a/-d/-F/-A/-D
dispatch to the _master-suffixed Key methods.
Tests: 16 functional + 32 unit = 48 passing. Full topology suite
now at 798 passing (381 unit + 417 functional after this commit).
Crash-safety invariants verified by test:
- accept_master_clustered_proposes_before_touching_file
- accept_master_clustered_crash_before_apply_leaves_no_partial_state
- accept_master_clustered_apply_replay_is_idempotent
- Same assertions for delete_master.
Pre-commit clean on all touched files. No regressions in
tests/pytests/unit/cli/test_key.py.
All implementer phases now complete (Phase 0-5). Next:
scenario-test teams per user instruction (teams write cross-module
scenario tests exercising the full stack together: publish fan-out,
return rollup, breadcrumb lifecycle on failover, path authentication,
transit routing, directional-trust interactions, syndic coexistence).
* master topology: scenario tests (end-to-end multi-module)
Lands cross-cutting scenario tests exercising multiple topology
modules together through realistic operator workflows. Written
after all implementer phases (0-5) landed, per the user's
instruction that scenario tests chain modules while per-file tests
cover one module at a time.
New under tests/pytests/scenarios/topology/:
- __init__.py (package marker)
- conftest.py (re-exports harness fixtures)
- test_core_scenarios.py (4 scenarios: C@ scoped publish,
3-cluster flood with transit,
directional trust failure event,
duplicate minion_id cluster_path
disambiguation)
- test_failure_scenarios.py (4 scenarios: publish daemon
restart preserves breadcrumbs,
peer detach quiesce drains
returns, solo-to-clustered
migration preserves peers,
startup registers callbacks
before replaying attaches)
Harness extension (tests/support/topology/cluster.py):
- master_opts property, start_publish_daemon / stop_publish_daemon
(for restart-cycle tests), breadcrumb_mmap_paths helper,
real MmapCache parsing in inspect_breadcrumbs.
Each scenario exercises >=4 topology modules per test (router +
link + registry + breadcrumbs + link_manager + config.topology +
migration + raft.topology state machine, in various
combinations) via real masters, real channels (with the
test-infrastructure channel fakes used elsewhere), real
MmapCaches, real salt.utils.job.store_job.
8/8 scenarios passing. Pre-commit clean.
Full topology suite now at 798 + 8 scenarios = 806 passing tests
across unit, functional, and scenario tiers.
This completes the implementation workstream. Remaining
follow-ups from the audit (fuzz tests for strip_cluster_scope,
nodegroup-containing-C@ handling, QUIESCING drain window
specifics, MWorker->publish-daemon handoff durability under
load, next_hop leader-only enforcement, PeerState serialization
schema version, atomic_rebuild grace period, signal-safety docs,
returner schema cluster_path acceptance) are logged in
rfcs/master-topology.md under 'Implementation follow-ups' and
can be picked up by whichever team touches the relevant file.
* master topology: scenario-test gap coverage (CLI, syndic, upgrade gate, path auth)
Lands four scenario workstreams covering the gaps identified after
the first scenario pass:
- test_cli_e2e_scenarios.py Real salt CLI drives a
topology publish end-to-end
through authenticated channels
(1 passing). Harness extended:
TopologyCluster.ensure_identity_key()
generates a real RSA keypair via
salt.crypt.MasterIdentityKey.generate
and TopologyCluster.accept_peer()
copies the peer's real pub into
pki_dir/masters/.
- test_syndic_coexist_scenarios.py Syndic subtree under a topology
peer stays reachable; same master
running both syndic + topology
emits dual-mode INFO log on
startup and keeps return paths
separate (2 passing). Harness
extended: make_single_syndic.
- test_upgrade_scenarios.py Mixed-version rolling-upgrade
protocol-version gate (2
xfail(strict=True) — the gate is
not yet implemented in
RaftService; test file documents
the exact gap). Scenarios will
flip to passing in the same
commit that implements the gate.
- test_path_auth_scenarios.py Tampered publish path dropped on
receive; tampered summary dropped
on ingest; self-cycle summary
dropped; legitimate traffic
control (5 passing, 4 scenarios
with Scenario 2 split).
Also merged:
- salt/master.py _pre_flight dual-mode INFO log when
both syndic_master and topology_enabled
are set, per RFC deprecation plan.
- test_core_scenarios.py hardcoded cache-size mismatch fix
(test was broken on tip; both pS-D and
pS-C independently flagged it).
Open issues surfaced by pS-C (CLI e2e):
- ClearFuncs.publish short-circuits C@west when local check_minions
returns empty; fan-out to west happens AFTER but the publish is
already dropped. Impacts cross-cluster scoped targeting via CLI
with no local matches.
- link_manager._dispatch_pub returns forward_publish's local_match
but doesn't thread it into the inbound master's publish pipeline.
- _check_cluster_minions in utils/minions.py reads
opts['cluster_id'] which conflicts with the 3008.x cluster
primitive (which requires cluster_peers when cluster_id is set);
the topology cluster_id in topology.conf is not consulted by the
master-side compound matcher.
These three gaps are now documented in test_cli_e2e_scenarios.py's
module docstring + logged as implementation follow-ups. The CLI
scenario drives the full real path including real crypto + real
channels; the C@-scoped variant is deferred until the gaps close.
Scenario suite now: 16 passing + 2 xfail (both strict). Full
topology test suite: 798 + 16 scenarios = 814 passing tests.
Pre-commit clean on all touched files.
* master topology: multi-peer-cluster scenarios + publish-daemon failover
Lands 5 new scenario tests covering the gaps between solo-master
topology (previously well-covered) and multi-peer-cluster topology
(previously barely covered).
tests/pytests/scenarios/topology/test_multicluster_scenarios.py:
- Two 3-peer clusters peer via topology; Raft replicates
MASTER_IDENTITY_KEY + MASTER_PEER_ATTACH to all peers in each
cluster. Publish originated from a NON-primary peer (peer_index=1)
fans out through peer_index=0's link to the remote cluster;
returns route back to any receiving peer.
- Mixed topology: solo "hub" + 3-peer "edge" cluster bidirectionally
peered. Hub writes directly to its registry; edge writes via Raft;
reader shape matches on both sides; publish works both directions
from any edge peer.
- Clustered master receives topology inbound on a non-primary peer:
pre-committed MASTER_PEER_ATTACH visible on all peers; publish-
daemon start/stop cycle on peer_index=0 cleans module state and
re-wires correctly on restart.
tests/pytests/scenarios/topology/test_pd_failover_scenarios.py:
- Ownership moves peer1 -> peer2 mid-flight: PINS CURRENT BEHAVIOR
as (mC) --- breadcrumb-less transit failover with syndic parity.
Empirically confirmed:
* peer2's breadcrumb mmap has no entry for the jid peer1 recorded
* breadcrumb files are per-peer on-disk (distinct pki_dirs)
* no Raft replication of breadcrumbs
* no file_sync of breadcrumb mmap
* returns at peer2 can't route back to origin via breadcrumb
* peer1's mmap files survive on disk; RFC's (mC) operator-recovery
escape hatch via salt-run jobs.lookup_jid remains viable
This test documents the current (mC) behavior; the RFC's open
decision between (mA)/(mB)/(mC) is now empirically pinned on
(mC). Any future implementation of (mA) or (mB) must flip this
test.
- Same-peer restart recovers breadcrumbs via on-disk MmapCache
(same mmap file across process restarts; sticky ownership).
Harness extensions (tests/support/topology/cluster.py):
- master_opts(peer_index=0) per-peer opts
- start_publish_daemon(peer_index=0) start on specific peer
- stop_publish_daemon(peer_index=0) stop (module-global; kwarg
for documentation symmetry)
- inspect_breadcrumbs(peer_index=0) peer-specific inspection
- breadcrumb_mmap_paths(peer_index=0) peer-specific paths
- make_cluster() now picks unique
cluster_pool_port per cluster so two 3-peer clusters can run
concurrently without colliding on default 4520
Full scenario suite: 38 passing + 2 strict-xfail (protocol gate,
unchanged). Harness tests: 17/17 green. No regressions.
New follow-ups surfaced:
- Scenario pS-H empirically pinned (mC); the RFC's "Unresolved
questions > Transit-cluster breadcrumb failover (DECISION NEEDED)"
can now be resolved as "accept mC" or an implementation workstream
for (mA)/(mB) can be scoped against the failing test.
* master topology: adversarial test battery (6 real bugs documented)
Four adversarial teams probed the implementation looking for bugs.
Each team's mandate was 'try to break it; a failing test is a WIN.'
104 tests total: 98 verifying defenses hold, 6 strict-xfail
documenting real bugs (fix must flip them to passing).
Files added under tests/pytests/scenarios/topology/:
test_adversarial_trust.py 45 tests (44 pass + 1 xfail)
test_adversarial_concurrency.py 23 tests (20 pass + 3 xfail)
test_adversarial_statemachine.py 17 tests (15 pass + 2 xfail)
test_adversarial_scale.py 19 tests (19 pass + 0 xfail)
Bugs documented via xfail(strict=True) with precise reproducers:
TRUST (1):
- CLUSTER_ID_RE admits trailing newline. 'east\n' passes the
regex because Python's '$' matches before terminal newline by
default. A hostile authenticated peer attaches as 'east\n'
landing a corruptable cluster_id into the registry MmapCache
and 'masters/east\n.pub' filename.
Fix: use \A...\Z anchors (which do NOT accept \n) OR add
explicit newline reject in salt.config.topology.CLUSTER_ID_RE +
salt.cluster.consensus.raft.topology regex compilation +
salt.key._master_cluster_id_valid.
CONCURRENCY (3):
- link_manager.pre_fork is NOT idempotent. Second call unconditionally
re-runs _reserve_listener_socket; the first socket fd is leaked.
Fix: early-return in pre_fork when _LISTENER_SOCKET is live.
- link_manager._install_sm_callbacks does not replay pre-existing
peers on clustered restart. Only decorates future
_handle_peer_attach calls; Raft apply() does not re-fire
already-applied entries, so peers already in the registry
MmapCache never get add_link called. Clustered master comes up
with zero outbound links.
Fix: iterate registry.list_peer_ids() at end of _install_sm_callbacks
and call add_link() for each.
- MmapCache.get loses bytes type for utf-8-valid binary payloads.
'struct.pack("<Q", 0)' decodes cleanly as 8 NUL chars; the
'bytes in -> bytes out' contract is violated. Impacts any
binary msgpack blob or raw crypto bytes.
Fix: track stored type via a 1-byte heap tag OR always return
bytes when caller passed bytes.
STATE MACHINE (2):
- TopologyStateMachine.restore_snapshot is NOT atomic across
concurrent readers. Sequential delete_peer + set_peer loops;
each MmapCache op takes/releases its own flock span.
A reader polling via open_reader observes strict subsets
mid-restore. RFC claim of 'one write-locked transaction' does
not hold.
Fix: single flock span wrapping the full wipe+restore sequence,
or in-place diff apply.
- _handle_peer_attach idempotent short-circuit skips
_finalise_accepted_key_file. When replay commits the same entry,
the public_key match short-circuits before the PKI rename runs.
A crash between Raft commit and PKI rename leaves the key stuck
in masters_pre/ forever.
Fix: still call _finalise_accepted_key_file on the idempotent
branch (the file op is idempotent on a no-op rename).
SCALE (0): all 19 adversarial scale probes held. Measured
behavior pinned:
- breadcrumbs.put sustained >4 kHz
- breadcrumbs.lookup sustained >45 kHz with staleness_check_interval=0
- on_publish fan-out IS parallel (5 links, 1x2s + 4x0.5s = 2.0s
wall time, confirming RFC 'single sign, N sends' claim)
- cleanup on 10k expired entries: 2.1s with atomic_rebuild
- 20-peer summary storm: 3800 forwards (no feedback loop)
- Payload fan-out shares load['arg'] by reference across stubs
(RFC 'serialized once' claim upheld)
Full topology test suite now at 814 passing + 2 scenario-xfail
(upgrade gate) + 98 adversarial passing + 6 adversarial xfail =
920 tests + 8 strict-xfails on dwoz/master-topology.
The 6 adversarial bugs are precisely scoped and have known fixes;
each is a localized module-level change (not a design redo). All
can be addressed as follow-up PRs that flip the xfails to passing.
Pre-commit clean on all four adversarial test files.
* master topology: fix 6 adversarial bugs (flip xfails to passing)
Addresses all 6 bugs the adversarial test battery documented in
commit 67703c80f5a. Each fix flips its strict-xfail reproducer
to a passing test.
TRUST (1 bug fixed):
salt/config/topology.py:
- CLUSTER_ID_RE: ^...$ -> \A...\Z anchors. Python's $ matches
before a terminal newline by default; \Z does not. Propagates
to all three call sites (raft/topology, key.py) via the shared
import. Reproducer test_sm_peer_attach_rejects_trailing_newline
_cluster_id now passes.
CONCURRENCY (2 bugs fixed):
salt/topology/link_manager.py:
- pre_fork() is now idempotent: early-return if _LISTENER_SOCKET
is already bound to the configured interface/port. Prevents
double-bind + fd leak.
- _install_sm_callbacks() now iterates registry.list_peer_ids()
after wrapping the SM handlers and calls add_link() for each
pre-existing peer. Mirrors the solo-path _replay_registry so
clustered-master restart recreates outbound links from
previously-committed MASTER_PEER_ATTACH entries.
salt/utils/mmap_cache.py:
- MmapCache: v1 -> v2 schema bump. _HEADER_MAGIC 0xAB -> 0xAC.
Each heap record now carries a 1-byte type tag (0x00=bytes,
0x01=str) so bytes-in -> bytes-out round-trips preserve type
even when the payload is utf-8-valid binary (e.g.
struct.pack('<Q', 0) decodes as 8 NUL chars). Legacy v1 files
auto-wipe on upgrade (caches are regenerable). Zero regressions
across 299 sibling-caller tests (salt/cache/mmap_cache,
mmap_key, salt/utils/resource_registry).
- _roster_remove fast-path: switched from O_APPEND write fd
(which forces every write to EOF on Linux regardless of pwrite
seek offset) to a short-lived O_WRONLY fd with os.pwrite.
Fixes duplicate roster entries after remove. Surfaced while
fixing restore_snapshot atomicity in FIX-E.
STATE MACHINE (2 bugs fixed):
salt/cluster/consensus/raft/topology.py:
- restore_snapshot: switched from sequential delete-loop +
set-loop (readers observed strict subsets mid-restore) to
MmapCache.atomic_rebuild (file-level atomic swap via
os.replace). Readers detect the swap via _cache_id on the
next list_keys()/get() call; invariant holds that readers see
either full old-state or full new-state, never a mixed subset.
- _handle_peer_attach idempotent branch now calls
_finalise_accepted_key_file before returning. Fixes the
crash-between-Raft-commit-and-PKI-rename case where the
committed-entry replay previously skipped the rename, leaving
the peer key stuck in masters_pre/. The file-op is itself
idempotent (no-op rename if the file is already in masters/).
- _finalise_accepted_key_file: now a no-op when on-disk bytes
already match (preserves mtime, satisfies no-filesystem-churn
invariant on idempotent replay).
Full suite after fixes:
- tests/pytests/scenarios/topology/: 103 passing + 2 xfailed
(upgrade-gate, unrelated to the 6-bug battery)
- tests/pytests/unit/topology/: 435 passing
- tests/pytests/functional/topology/: 334 passing + 4 pre-existing
failures confirmed on baseline (not regressions):
test_two_master_handshake_e2e + 3 x test_master_cluster_grain
are environmental harness issues from parallel-agent process
pollution; verified via git-stash on 67703c80f5a.
Net change: 6 adversarial xfails -> passing. Only remaining
xfails are the 2 scenario-upgrade-gate ones (not in the
adversarial battery; the gate itself is a future implementation
task tracked in rfcs/master-topology.md Unresolved questions).
Pre-commit clean on all touched files.
* master topology: FU-C rolling-upgrade protocol-version gate
Flips both xfails in test_upgrade_scenarios.py to passing.
Implementation across 5 fix sites:
- salt/cluster/consensus/raft/log.py: MembershipStateMachine
_protocol_versions dict, PROTOCOL_VERSION_PRE_TOPOLOGY=0,
get/min_protocol_version(), laggard_voters(); CONFIG apply
reads cmd[protocol_versions]; snapshot/restore round-trips
- salt/cluster/consensus/service.py: TOPOLOGY_PROTOCOL_VERSION=1,
MixedVersionClusterError, RaftService.protocol_version
(opts override via cluster_protocol_version),
_min_cluster_protocol_version, _laggard_voters,
_enforce_topology_protocol_gate, propose_peer_attach/detach;
founding + join CONFIG carry protocol_versions
- salt/cluster/consensus/raft/topology.py: unknown entry types
now log WARNING with rolling-upgrade note (not silent DEBUG)
- salt/topology/link_manager.py: _maybe_propose_attach pre-check
on min_protocol_version; WARNING names laggards; late race
caught via MixedVersionClusterError
- salt/key.py: accept/delete_master catch
MixedVersionClusterError, print clear stderr error, exit 1;
no partial PKI state
Pre-topology peers never populate protocol_versions, so they
advertise 0 by default. Topology-aware peers advertise 1 and
cannot commit MASTER_* until every voter is upgraded.
923 passing + 0 xfailed on unit+scenarios suite; 4 pre-existing
functional failures unrelated to this change.
Pre-commit clean on all 7 touched files.
* master topology: FU-A/B/D/E follow-ups (compound + CLI + lifecycle + cache + returners)
Four parallel follow-up teams land four distinct improvements on
top of the FU-C protocol gate (committed as 2e5693f0120).
FU-A (compound matcher robustness):
- salt/topology/router.py: extract_cluster_scope now accepts a
nodegroups kwarg; N@ tokens are pre-expanded via
nodegroup_comp before C@ scanning so a nodegroup definition
containing C@ is visible to the router instead of defaulting
to flood. strip_cluster_scope gains a fixpoint-loop paren
cleanup so ((C@east)) collapses correctly.
- hypothesis-based fuzz tests at
tests/pytests/unit/topology/test_strip_cluster_scope_fuzz.py
- Functional tests at
tests/pytests/functional/topology/test_nodegroup_c_at.py
FU-B (CLI e2e gaps):
- salt/master.py: ClearFuncs.publish no longer short-circuits on
empty local-match when the target has C@ scopes not including
the local cluster; publish is allowed through for topology
forwarding.
- salt/topology/link_manager.py: _dispatch_pub became async;
calls router.forward_publish and, on local_match=True, strips
C@ scopes and dispatches to local minions via a transient
PubServerChannel.
- salt/utils/minions.py: _check_cluster_minions now resolves the
local cluster_id via load_topology_config, caching per-opts.
Falls back through opts[cluster_id] -> opts[master_cluster_id]
-> topology.conf.
- salt/channel/server.py: PubServerChannel.publish_payload strips
C@ scope on topology-enabled masters so a minion without the
master_cluster_id grain still sees a well-formed compound.
FU-D (lifecycle polish):
- salt/topology/link.py: PeerMasterLink.quiesce rewritten with
drain-exit semantics: duration = topology_detach_quiesce
(default publish_timeout); exit on (no breadcrumb references
this link) OR timer elapsed; mid-send send_return completes
before transition; WARNING log on timer-elapsed path with
undelivered jids.
- salt/topology/breadcrumbs.py: new jids_for_link helper used by
the drain-exit check.
- salt/cluster/consensus/raft/topology.py: new NotLeaderError;
TopologyStateMachine.next_hop raises it on followers (where
link_manager has no live state) instead of ambiguous None.
Added PEER_STATE_SCHEMA_VERSION = 1 + schema-version checks
on apply + restore; snapshots now stamp per-peer version.
build_peer_attach_entry helper used by migration.
- salt/topology/link_manager.py: is_owner() helper for leader
detection.
- salt/topology/migration.py: routes MASTER_PEER_ATTACH through
build_peer_attach_entry so migration-time attaches get the
schema version stamped.
FU-E (cache GC + returners):
- salt/utils/mmap_cache.py: atomic_rebuild gains unlink_delay
kwarg; rename-aside + daemon-thread unlink after delay.
close() joins pending threads.
- salt/topology/breadcrumbs.py: cleanup passes
_staleness_check_interval as unlink_delay so MWorkers get a
chance to detect the swap.
- salt/topology/router.py: forward_return_once LRU-based
idempotency guard against duplicate upstream forwarding when
a reader resolves a cleaned-up breadcrumb during the mmap
staleness window.
- salt/returners/{local_cache,postgres,pgjsonb,postgres_local_cache}.py:
schema extended with cluster_path annotation (additive); existing
rows read cleanly.
New tests across all 4 teams: 10 (quiesce) + 9 (next_hop) + 12
(peerstate schema) + 11 (breadcrumb GC) + 6+5+4+4 (returner
cluster_path) + 13 (compound fuzz + nodegroup C@) + 11 (CLI e2e
companion tests) = 85 new tests.
Full regression on this commit:
- Unit: 464 passing
- Scenarios: 127 passing + 1 strict-xfail (CLI e2e C@west —
pre-existing two-master-handshake harness bug) + 1 flaky
(test_cli_e2e C@east — same handshake pollution; reproduces
on FU-B's own worktree, not a merge regression)
- Pre-commit clean on all touched files.
Flipped xfails: upgrade gate x2 (via FU-C in 2e5693f0120),
protocol-gate related. Not yet flipped: CLI e2e C@west (flaky
on handshake), plus the 4 pre-existing stsuite-pollution
functional failures (unchanged, environmental).
* master topology: residual cleanup — 3 production bugs + docs + load test
The 'environmental test harness pollution' turned out to be three
real production bugs that the harness exposed. Fixing them is
not optional — operators would hit the same races.
PRODUCTION BUG 1: MasterPubServerChannel.pre_fork ordering race
salt/channel/server.py:
process_manager.add_process calls process.start() synchronously,
so the EventPublisher forked BEFORE link_manager.pre_fork ran.
Child's open_writer() raced the parent's _init_index_file,
yielding partially-written mmap files (observed sizes 7.7MB /
24MB / 27MB vs expected 96MB). Fix: swap the two blocks so
pre_fork materialises all four MmapCache files BEFORE any fork.
PRODUCTION BUG 2: Minion-side cluster_id gating broken
salt/crypt.py:AsyncAuth.handle_signin_response:
Gated the auth-response cluster_id lift on
self.opts.get('topology_enabled') and
self.opts.get('topology_push_cluster_grain'), but both are
master-side opts with no minion schema entries — always falsy
on a minion. Grain never arrived on any minion. Fix: drop the
minion-side gate; master-side _topology_cluster_id_for_auth
holds the policy of whether to emit the field. Tests updated
to assert the corrected invariant.
PRODUCTION BUG 3: TopologyRouter.route_publish ignored nodegroups
salt/topology/router.py:
Called extract_cluster_scope(tgt) with no nodegroups kwarg,
so N@east_web (where east_web = 'C@east and web-*') extracted
no scope and flooded instead of routing to east. FU-A added
the kwarg but the router didn't pass it. Fix: pass
self.opts.get('nodegroups').
ITEM 2 — Signal-safety documentation (RFC follow-up #8):
Added 'Signal-safety invariant' sections to module docstrings
of salt/topology/registry.py, salt/topology/breadcrumbs.py,
and a new module docstring on salt/utils/mmap_cache.py. Each
spells out 'no subprocess spawn while flock held' with
fork-inheritance rationale.
ITEM 3 — MWorker->publish-daemon durability (RFC follow-up #4):
Added tests/pytests/stress/master_subprocess/eventpublisher/
test_topology_return_handoff.py — drives 10,000
salt/topology/return/east/<jid> payloads at the real
EventPublisher subprocess puller->subscriber wire path.
Measured: 29,083 returns/sec sustained, 0 drops, 0 duplicates,
0 reordering. Drop rate <0.0001% at 29x the target 1000/sec.
No persistent-queue needed; test parked under explicit stress
gate as a regression tripwire.
ITEM 4 — RFC follow-ups section updated:
Struck-through resolved items (expand nodegroups, MWorker
durability, signal-safety docs). Added 'Also resolved during
the final-cleanup pass' subsection documenting the three
production bugs. Remaining open items (6): strip_cluster_scope
fuzzing, LinkHealth.QUIESCING drain window, next_hop on
followers, PeerState NamedTuple schema version, atomic_rebuild
grace period, returner cluster_path schemas.
Final topology-suite result on this commit:
- test_two_master_handshake_e2e: PASSING (was failing)
- test_grain_present_on_topology_minion: PASSING (was failing)
- test_grain_survives_grains_items: PASSING (was failing)
- test_grain_matcher_targets_master_cluster_id: PASSING (was failing)
- test_scenario_cli_c_at_local_publish_round_trip: PASSING (was flaky)
948/948 topology tests pass + 1 strict-xfail (CLI e2e C@west, now
the only known-open xfail across all topology tests).
Pre-commit clean on all 10 touched files.
* master topology: fix three mesh-dedup bugs in router
Three bugs in salt/topology/router.py surfaced only on mesh (non-tree)
topologies, where the same publish/summary arrives at a non-origin
cluster twice via distinct paths:
1. forward_publish did not skip onward peers already in the
authenticated envelope["path"]. In a triangle a-b-c, b's forward
loop (after receiving a's publish via a-link) would include c even
though a already sent a direct copy to c. Mirror the existing
check in ingest_summary.
2. forward_publish did not dedup by jid. If c receives a's publish
directly AND again via b, the second arrival would overwrite the
breadcrumb (routing returns through b instead of a) and refan the
publish to the rest of the mesh. Check lookup_breadcrumb(jid)
before appending self to path; first arrival wins.
3. ingest_summary did not dedup by origin_seq. Every path through
the mesh triggered a redundant registry.set_peer + re-forward.
Track the highest seq seen per origin in router-local soft state
(self._last_origin_seq); drop stale and duplicate seqs, strictly
newer seqs still overwrite. No schema bump needed --- the seq
map lives on the router instance only.
Add tests/pytests/scenarios/topology/test_mesh_dedup_scenarios.py
with six scenarios drive the real router against real breadcrumbs /
registry MmapCaches with stub inbound links. Confirmed 5/5 regression
tests fail pre-fix; all 6 pass post-fix (6th is a positive control for
"strictly-newer origin_seq overwrites").
* master topology: fix 5 cascading production bugs on the peer-link wiring path
Each fix addresses a real gap that kept the ``salt -C 'C@west' test.ping``
scenario at HEAD from exercising the forward-publish path end-to-end.
Each is independently testable via the existing unit/functional suites;
no behaviour on paths that were already passing is changed.
* ``link_manager.start`` normalises the incoming io_loop via
:func:`salt.utils.asynchronous.aioloop` so later
``call_soon_threadsafe`` dispatches work against both the publish
daemon's tornado ``AsyncIOMainLoop`` and the bare
``asyncio.AbstractEventLoop`` passed in by functional tests.
* ``link_manager.start`` projects :class:`TopologyConfig.cluster_id` onto
the opts dict handed to each :class:`PeerMasterLink` so solo masters
(which never set ``opts["cluster_id"]`` - that is the 3008.x master-cluster
primitive) do not send ``cluster_id=None`` in the outbound
``topology/_master_auth`` handshake. Receivers were rejecting those
via :func:`_reserved_cluster_id` and every solo-to-solo link stuck in
retry.
* New :func:`_register_connected_link` runs after
:meth:`PeerMasterLink.connect` completes successfully: it re-keys
``_LINKS`` from the ``__pending__:host:port`` provisional key to the
real ``peer_cluster_id`` AND populates ``router._links`` so
:meth:`TopologyRouter.route_publish` can find the outbound link.
Previously ``router._links`` was initialised to ``{}`` and nothing
wrote to it, so every ``route_publish`` returned an empty link list
even when outbound ``_LINKS`` was fully wired.
* :func:`_handle_inbound` grows a wire-envelope unwrap step
(``_unwrap_inbound_envelope``) so dispatches work on both the raw
topology envelope (in-process callers) and the full ReqServerChannel
envelope ``{"enc": ..., "load": {...}, "version": N}`` that lands on
the inbound socket. New :func:`_handle_inbound_channel` wrapper
returns the ``(ret, {"fun": "send_clear"})`` tuple
:meth:`ReqServerChannel.handle_message` expects.
* :func:`_open_inbound_listener` forces ``worker_pools_enabled=False``
so the inbound listener uses the plain :class:`ReqServerChannel`
instead of :class:`PoolRoutingChannel`. The pooled routing path
dispatches to MWorkers via per-pool IPC and never honours the
topology-local ``payload_handler``; the dispatch table lives in the
publish-daemon process and requires the request to come back there.
Harness: ``TopologyCluster`` gains a :meth:`restart` helper so scenario
tests that mutate :file:`topology.conf` after boot (via
:meth:`config_peer`) can re-enter the master so the new peers take
effect on the next :func:`link_manager.start`.
The C@west CLI scenario stays strict=False xfail with a precise reason
naming the remaining gap: the outbound ``AsyncReqChannel`` and the
inbound :class:`ReqServerChannel` transport do not meet on the wire for
``topology/_master_auth`` even after this patch — the publish-daemon
never sees the inbound dispatch invocation. That is an orthogonal
wire-format / transport gap that belongs in its own commit.
* master topology: fix 2 router BUGs from config audit (#2b, #13g)
Audit `rfcs/master-topology-config-audit.md` found two BUG classifications
in `salt/topology/router.py`. Both are addressed here without any
public-API change.
BUG #2b --- non-adjacent scoped routing silently dropped at origin.
Chain `A <-> B <-> C`, operator on A runs
`salt -C 'C@c and web-*' test.ping`. Pre-fix: `route_publish` filtered
outbound links by direct `peer_cluster_id` membership in destinations;
A has no direct link to C so `links=[]` and the publish is a silent
drop. Post-fix: a `_routes` table populated by `ingest_summary` from
each accepted summary's `path` field (next hop = `path[-1]`, hop count
= `len(path)`) lets `route_publish` resolve non-adjacent destinations
to a direct transit hop. Unresolved destinations trigger a FLOOD
fallback with a WARNING log, matching syndic's "broadcast when
you don't know" semantics. Freshness: strictly-newer `origin_seq`
overwrites the previous route (same freshness gate as the registry
write).
BUG #13g --- `C@east or web-*` collapsed to `destinations={east}` and
dropped `web-*` minions on OTHER clusters. Pre-fix: positive C@
tokens populated the destination set regardless of the surrounding
operator, so an OR adjacent to a C@ silently narrowed fan-out.
Post-fix: new `_c_at_adjacent_to_or` walks tokens tracking paren
depth and returns True when any C@ sits at the same depth as an
adjacent `or` operator. `extract_cluster_scope` returns None
(flood) when the predicate fires. Semantic nuance:
`C@east and (web-* or db-*)` keeps `destinations={east}` because
the inner `or` is at a deeper paren depth than the top-level `C@`.
`C@east and web-* or C@west and db-*` floods (top-level `or`
crosses two C@ scopes).
Scenario tests: 7 cases in
`tests/pytests/scenarios/topology/test_mesh_routing_scenarios.py`
covering direct-hop transit, flood fallback, mixed destinations,
shortest-path freshness, top-level OR with C@, paren-isolated OR,
and OR crossing C@ scopes. All assert the exact pre-fix vs.
post-fix behavior.
Fixes BUG #2b (and the subsumed findings #3, #8, #9 that share the
same root cause). Fixes BUG #13g.
* topology: close transport-wire gap for cross-cluster publish
Seven interlocking bugs blocked the C@west CLI publish round-trip
scenario (test_scenario_cli_c_at_peer_publish_round_trip_with_peered_topology)
end-to-end. Closing all seven flips that test from strict-xfail to
passing.
* Coroutine scheduling: MasterPubServerChannel._publish_daemon
scheduled link_manager.start via tornado spawn_callback, which
does not drive an async-def body on a tornado IOLoop (the
coroutine object is scheduled as a bare callable and never
stepped). Switched to aio_loop.create_task, matching the
publisher + Raft bootstrap patterns used earlier in the same
function.
* Listener binding: zeromq.RequestServer.post_fork does not bind
the external ret_port -- it connect()s to the master's
workers.ipc as a worker peer, and the external bind is normally
done by a separate MWorkerQueue process that topology never
starts. Added a direct_bind kwarg to RequestServer.post_fork
and opted into it from link_manager._open_inbound_listener.
Dropped the pre_fork TCP reservation (the inherited bound fd in
the parent would cause EADDRINUSE on the publish daemon's zmq
bind).
* Server-side inbound registration: _handle_master_auth replied
"ok" with the session AES but never recorded _INBOUND[peer] on
the server side, so every follow-on topology/pub|ret|evt|sum
frame failed _verify_session. Added a _InboundLink record
(peer_cluster_id, session_generation, session_aes) populated in
_handle_master_auth before the ok reply, mirroring the sender's
session_generation counter.
* cluster_id projection: TopologyRouter.__init__ and
PeerMasterLink both read opts["cluster_id"], which is unset on
solo (non-3008.x cluster) masters even when topology is
configured. Outbound envelopes went on the wire with
origin=None, path=[None] and the peer rejected them as tampered.
Project cfg.cluster_id into opts in start() for both the router
and per-peer links.
* Handshake retry on transport error: PeerMasterLink.connect
returned immediately on any transport exception; a peer master
briefly unreachable at connect time (restart window, listener
still binding, network blip) was permanently fatal. The
transport-error branch now backs off and retries, rebuilding
the AsyncReqChannel between attempts (zmq REQ sockets go into
a bad state after a failed send; the socket FSM must reset).
* Lazy inbound re-registration: zmq REQ-REP silently reconnects
on the client when the peer master restarts -- the queued send
is delivered to the fresh server with no transport error
signaled back to the sender -- so the sender never re-triggers
_master_auth. _handle_inbound now lazy-registers
_INBOUND[origin] when the frame is non-handshake, the peer key
is accepted on disk (masters/<cluster_id>.pub), and no
in-process record exists. The accepted-key file is the auth
boundary.
* Return plumbing: forwarded minion returns arrive on the origin
as topology/pub frames with cmd='_return' (via west's event-
forwarding mechanism; the topology/ret path depends on a
pub-daemon event-bus subscriber that doesn't exist yet). Four
pieces land here: _dispatch_pub routes return-shaped loads to
salt.utils.job.store_job instead of local-minion fan-out;
_store_forwarded_return also writes save_minions so the CLI's
local_cache lookup matches; salt.client.LocalClient
_check_pub_data no longer short-circuits with "no minions
matched" when topology_enabled (origin can't know peer-cluster
targets at pub-time); and get_iter_returns no longer early-exits
on the 0 >= 0 trap when topology_enabled with empty minions,
waiting the full timeout so cross-cluster returns can arrive.
_LOCK discipline hardening: mutations of _INBOUND in
_handle_master_auth and _maybe_lazy_register_inbound now hold the
module RLock, same as the Raft-SM apply thread's remove_link.
Two regression tests under tests/pytests/unit/topology/
test_link_manager.py use a _LockWitnessDict that counts
__setitem__ calls made while _LOCK is not owned by the current
thread; they fire if a future change drops the lock discipline
from either write path.
* doc: add sphinx stub for salt.runners.topology
The pre-commit "Check Docs" hook on the nightly build flagged the
master-topology runner as missing its reference-doc counterpart:
The module at salt/runners/topology.py does not have a sphinx
stub at doc/ref/runners/all/salt.runners.topology.rst
The module index at doc/ref/runners/all/index.rst is missing
the following modules: topology
Add the stub + index entry, matching the shape of every other
runner module's rst (e.g. salt.runners.cluster.rst).
* topology: fix Windows test collection + fuzz-fallback crash
Two orthogonal CI failures surfaced on the first nightly build and
would recur on every subsequent run; fixing both:
1. ``salt/topology/link_manager.py`` imported ``fcntl`` at module
scope -- which does not exist on Windows. Caused every topology
test module to fail collection on Windows unit, functional, and
scenario jobs (14 failed shards on the last run). The import
was left over from ``_reserve_listener_socket`` which became
dead code when ``_open_inbound_listener`` moved to
:class:`salt.transport.zeromq.RequestServer`'s ``direct_bind``
path. Removed the import, the ``socket`` import (also unused),
and the dead function body. ``_LISTENER_SOCKET`` stays as a
module-level ``None`` so ``_reset_module_state`` and ``stop``'s
compatibility branches continue to compile without warnings.
2. ``tests/pytests/unit/topology/test_strip_cluster_scope_fuzz.py``
crashed at class-collection time when ``hypothesis`` was not
installed (CI's ci-test-onedir venv), raising ``TypeError:
'NoneType' object is not callable`` on the ``@given(expr=
_expr_with_c(...))`` decorator. The existing hypothesis fallback
stubbed ``given``, ``settings``, ``HealthCheck`` -- but not the
``@st.composite``-decorated strategy builders (``_c_token``,
``_atom``, ``_expr_with_c``), which became ``None`` under
``_StStub.__getattr__``'s lambda return. Added a proper
``_StStub.composite`` decorator that preserves callable shape
and a ``_DummyStrategy`` null-object that supports arbitrary
attribute access + chained method calls (so
``st.lists(...).map(...)`` resolves). The ``pytestmark`` skip
still prevents the stubs from ever being executed; this just
lets the module import so pytest can emit the skip.
* requirements: add hypothesis as a declared test dep
``tests/pytests/unit/topology/test_strip_cluster_scope_fuzz.py`` was
the only hypothesis consumer in the tree and the CI ``ci-test-onedir``
venv never installed hypothesis, so the property-based coverage of
``strip_cluster_scope`` never actually ran -- the test file's
``try/except ImportError`` fallback silently skipped it on every CI
shard.
Add ``hypothesis`` to ``requirements/pytest.txt`` and regenerate the
30 affected CI lock files (``requirements/static/ci/py3.{9,10,11,12,
13,14}/{linux,windows,darwin,freebsd,cloud}.lock``) via the
``compile-ci-*-{zmq,cloud}-requirements`` pre-commit hooks.
Hypothesis is pure Python (depends only on ``sortedcontainers``) and
installs cleanly on every platform including Windows.
The ``ImportError`` fallback in the fuzz test stays as defence for
devs running against a minimal local venv; the docstring is updated
to reflect that CI now has hypothesis so the real property-based
path always runs.
* topology: update tests to match current implementation + CI storage
Three categories of fix for failures surfaced on nightly run 40655146312:
1. ``pre_fork`` no longer reserves ``_LISTENER_SOCKET`` (behavior
change landed in the Windows-portability commit that dropped the
``fcntl``-based pre-fork reservation). Updated the tests that
asserted the old contract:
* ``tests/pytests/functional/topology/test_link_manager.py``:
renamed ``test_pre_fork_reserves_listener_socket`` ->
``test_pre_fork_does_not_reserve_listener_socket``; extended the
"pre_fork must not populate module globals" test to also assert
``_LISTENER_SOCKET is None``.
* ``tests/pytests/scenarios/topology/test_adversarial_concurrency.py``:
``test_link_manager_pre_fork_is_idempotent`` now asserts that
neither call reserves a socket (idempotence = "no allocation,"
not "same reference").
2. ``test_union_of_c_at_tokens_in_nodegroup`` and
``test_c_at_outside_nodegroup_unions_with_c_at_inside``
(``test_nodegroup_c_at.py``) asserted that ``C@east or C@west``
expands to the union ``{east, west}``, but
:func:`salt.topology.router.extract_cluster_scope` has conservatively
flooded on any ``_c_at_adjacent_to_or`` match since the OR-adjacency
semantics landed -- the function cannot safely distinguish
``C@east or C@west`` (unionable) from ``C@east or web-*`` (not
unionable) and the documented contract is "any OR-adjacent C@ ->
None (flood)". The tests were testing wished-for behavior; renamed
to ``test_or_adjacent_c_at_in_nodegroup_floods`` /
``test_or_between_nodegroup_and_c_at_floods`` and updated the
assertions to match the actual contract.
3. Two perf-floor assertions in
``tests/pytests/scenarios/topology/test_adversarial_scale.py``
were tuned for dev-box / SSD storage and consistently fail on
GitHub Actions runners' virtualised disks:
* ``test_flood_puts_sustained_rate``: floor dropped from 500/s to
100/s (CI observed 227/s; dev box 4-8 kHz). Still catches a
10x+ regression in the writer path.
* ``test_cleanup_10k_expired_entries``: ceiling raised from 30 s
to 90 s (CI observed 43.5 s; dev box 2.1 s). Still catches a
10x+ regression in the cleanup path.
* requirements: pin hypothesis below 6.131 to dodge AST-constants bug
Nightly run 40727972252 revealed that hypothesis 6.170.12's
``_hypothesis_pytestplugin.pytest_collection_modifyitems`` triggers an
INTERNALERROR at pytest collection time on every zeromq unit shard
(Ubuntu + Windows):
File ".../_hypothesis_pytestplugin.py", line 450,
in pytest_collection_modifyitems
_get_local_constants()
File ".../hypothesis/internal/conjecture/providers.py", line 369,
in _get_local_constants
new_constants |= constants_from_module(module)
TypeError: unhashable type: 'types.SimpleNamespace'
The "local constants" discovery feature was added in hypothesis
6.131.0. It walks every loaded module's AST looking for literal
constants to seed test cases with. Something in salt's module tree
produces a ``SimpleNamespace`` constant via that walk, which the
``Constants | Constants`` union can't hash into its internal sets.
The feature isn't needed for our one fuzz consumer
(``tests/pytests/unit/topology/test_strip_cluster_scope_fuzz.py``);
pin ``hypothesis>=6.0,<6.131`` so we still get the property-based
testing core without the AST-walker. pip-compile resolved the pin to
6.130.13 (the last pre-6.131 release) across all 30 CI lock files.
Separately, we should file a reproducer with upstream hypothesis so
they can harden ``_add_constant`` against unhashable AST payloads, at
which point we can re-expand the pin.
* tests: skip test_adversarial_scale.py on Windows
The module imports POSIX-only ``resource`` at top level for an
``RLIMIT_NOFILE`` sanity check inside
``TestFanOutConcurrency.test_1000_links_no_fd_leak``, which also
reads ``/proc/<pid>/fd`` -- both Linux-only. On Windows the import
raised ``ModuleNotFoundError`` at pytest collection time (observed
on nightly run 40727972252's "Windows 2025 scenarios zeromq" shard):
tests\pytests\scenarios\topology\test_adversarial_scale.py:39:
in <module>
import resource
E ModuleNotFoundError: No module named 'resource'
Guard the import with a try/except so collection succeeds, and
replace the module's ``windows_whitelisted`` mark with
``skip_on_windows`` since the tests themselves assume Linux
semantics (``/proc`` fd listing, POSIX rlimits). No test behaviour
change on Linux -- same tests, same thresholds.
* topology: wire end-to-end return path and transit forwarding
Make cross-cluster + sub-cluster + sub-sub-cluster publishes return
reliably across a mesh of topology-peered masters.
Core fixes landed as one unit because each one is a prerequisite for
the next:
* ``_handle_inbound_channel``: collapse non-dict dispatcher returns
(``PeerMasterLink`` instances from the internal routers) to a
serializable ``{"ok": True}`` ack so the REP send after a successful
recv does not raise ``cannot serialize 'PeerMasterLink' object`` and
deadlock the socket.
* ``_dispatch_pub``: split origin vs transit for return-shaped
frames via a breadcrumb-presence check (``_jid_is_local_origin``).
Origin stores locally; transit forwards up the breadcrumb chain
without re-entering ``forward_publish``. Also fan-out forwarded
publishes to further peers (fire-and-forget via
``asyncio.ensure_future``) so a 3-hop target (east -> west ->
west-sub) actually reaches the leaf.
* ``_dispatch_ret``: implement store-or-forward instead of returning
the breadcrumb link to the (silent) caller. Accepts both single
loads and batched ``{"batch": [...], "topology": {...}}`` bodies.
* ``_start_return_subscriber`` + ``_handle_topology_return_event``:
bridge the ``salt/topology/return/<origin>/<jid>`` event an
MWorker fires on local return (see
``AESFuncs._maybe_fire_topology_return``) to the breadcrumb's
upstream link via ``PeerMasterLink.send_return``. Without this
subscriber the return path terminated at every edge.
* ``_publish_to_local_minions``: pre-seed ``.load.p`` + ``.minions.p``
for a forwarded jid. ``PubServerChannel.publish`` is a pure
transport write; MWorker's ``_return`` later calls
``local_cache.get_load`` which crashes with
``CommandExecutionError`` when ``.minions.p`` is missing, bubbling
out of ``_sync_return`` and skipping the topology hand-off --
the race that produced ~2% rapid-fire flakes.
* ``on_publish``: filter return events (both top-level
``cmd=="_return"`` and the nested ``load["load"]["cmd"]`` shape fired
by ``salt/job/<jid>/ret/<id>``) AND the
``salt/job/<jid>/publish`` meta-notification (recognised by
``minions`` + ``missing`` + no ``ret``). Letting either leak into
topology/pub causes downstream minions to crash with
``KeyError('ret')`` in ``Minion._thread_return``, which
destabilises the SUB pipeline and intermittently loses an entire
publish for one minion -- the 2% rapid-fire flake root cause.
* ``forward_publish``: flood on unresolved destination (mirrors the
origin's ``route_publish`` policy). Without this a 4-hop targeted
publish (``east-sub -> C@west-sub``) is silently dropped at the
first transit when the gossip route table has not yet learnt the
destination.
* ``_maybe_fire_topology_return``: derive the forward target from
the breadcrumb cache when the minion did not echo
``load["topology"]`` back (which is always, because the minion
rebuilds ``load`` from the function result dict in
``_prepare_return_pub``).
* ``PubServerChannel.publish``: on origin, skip the local fan-out
when the ``C@`` target names only non-local clusters -- the
topology forwarder owns the fan. Avoids every ``C@west`` publish
on east also running on east's own minions.
* ``LocalClient.cmd_iter``: fall through to the timeout window on
every topology-enabled publish (not just empty-``minions``
publishes) so cross-cluster returns streaming in via
``_store_forwarded_return`` have time to arrive before the CLI
exits.
* ``RequestServer.request_handler`` (zeromq): phase-split
recv/dispatch/send so a handler exception does not leave the REP
socket in ``expecting send`` state (where the next recv deadlocks).
Each phase catches independently; dispatch failure sends an error
reply instead of hanging.
Validation: 100/100 ``east -> *`` runs at 8/8 in the 3-level
sandbox, full 6x6 targeted matrix (6 origins x 6 cluster
destinations), including the 5-hop longest path
(east-sub-sub -> east-sub -> east -> west -> west-sub ->
west-sub-sub).
* topology: fix Windows atomic rewrite of 0400 files
Two sites that write RSA keypairs with 0400 (private) / 0444
(public) perms were trying to overwrite the already-written
read-only file. POSIX ``os.rename`` doesn't care about target
perms, but Windows refuses the replace / unlink with
``[WinError 5] Access is denied``, breaking identity-key rotation
end-to-end.
* ``salt/crypt.py MasterIdentityKey._write_if_changed``: chmod
the existing file writable (0600) before ``os.unlink`` + the
atomic rewrite. Fixes the three Windows functional failures
in ``tests/pytests/functional/topology/test_identity_key.py``
(``test_exists_false_when_only_pub_present``,
``test_write_rotates_when_bytes_differ``,
``test_fingerprint_changes_on_rotation``).
* ``salt/cluster/consensus/raft/topology.py _write_file_atomic``:
chmod destination writable before ``os.replace``, apply final
mode after. Fixes
``tests/pytests/scenarios/topology/test_adversarial_trust.py::test_identity_rotation_preserves_prior_master_pub_in_peer_masters_dir``.
Both changes keep the final on-disk mode identical to prior
behaviour -- the writable intermediate state is scoped to the
single rename.
* tests: update mmap_cache tests for new TYPE_TAG byte
The on-disk heap record format gained a 1-byte type tag immediately
after the CRC prefix (``[CRC 8][TAG 1][VALUE N]`` with checksums on,
``[TAG 1][VALUE N]`` without) so b…
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do?
What issues does this PR fix or reference?
Previous Behavior
Remove this section if not relevant
New Behavior
Remove this section if not relevant
Tests written?
Yes/No
Commits signed with GPG?
Yes/No
Please review Salt's Contributing Guide for best practices.
See GitHub's page on GPG signing for more information about signing commits with GPG.