Skip to content

Fix cluster cache replication defaults - #70773

Merged
dwoz merged 43 commits into
saltstack:3008.xfrom
dwoz:wip/cache-cluster-replicate
Nov 15, 2026
Merged

dwoz merged 43 commits into
saltstack:3008.xfrom
dwoz:wip/cache-cluster-replicate

Conversation

@dwoz

@dwoz dwoz commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Cross-master cache replication: switch to default N-of-N fan-out for most banks with per-bank routing via cluster_cache_routing (jobs → ring, cluster/consensus / cluster/state_sync → none). Resolver only turns replication on when the cluster uses an isolated per-master filesystem.
  • Cache-facade bulk path (store_many) with mmap driver-native dispatch; MmapCache gains a put_many fast path.
  • mmap-backed persistent trie index for grain-target queries (salt/utils/mmap_trie_index.py) with chunked wide buckets; routed from CkMinions._check_cache_minions for the grains bank and from _augment_grain_match_with_resource_grains for resource_grains.
  • Resource registry: chunked register RPC, TTL-evict for abandoned chunked-register windows, master-side bank-key resource_id enforcement, dedicated cross-master replication event, pillar removed as the minion-side inventory source.
  • Replicator: single MasterEvent handle reused across stores, per-minion peer-apply executor, per-event per-peer publish log demoted to DEBUG.

Test plan

  • Nightly green on this branch (wip/cache-cluster-replicate).
  • 3-master isolated-filesystem cluster: verify jobs ring-routes and grains / resource_grains fan out N-of-N under the new defaults.
  • Grain-target wall-time against 1M-resource / ~333K-unique bank stays sub-second on warm trie.
  • test_cache_replication suite under tests/pytests/integration/cluster/ passes on Ubuntu 24.04 zmq3 (the one previously-flaky job).

twangboy
twangboy previously approved these changes Nov 11, 2026
dwoz added 12 commits November 12, 2026 23:43
Mission 1's commit ``master: enforce resource_id == bank-key id at register
time`` normalizes ``resource_id`` into every grain dict stored by
``__register_resources_sync`` -- the id portion of the bank key
(``<type>:<id>``) is authoritative so grain targeting's
``resource_id:<glob>`` fast path can skip a per-match fetch.

Four ``test_master.py`` assertions compared the stored grain dict to the
raw ``resource_grains`` payload the test sent, which no longer matches
once the register path adds the normalized ``resource_id`` field.
Update each asserted dict to include it.
Make the resource-register entry point defensive about ``self.tok``:
if auth has not populated the token yet, bail (debug-log) and let the
next trigger (pillar_refresh / tune_in) retry.  The attribute is
assigned on a successful ``connect_master`` handshake; a
``pillar_refresh`` that fires before the first handshake, a proxy
minion that has not yet attached its pub channel, or a bare ``Minion``
built for a unit test can all reach ``_send_register_chunk`` without
``tok`` set, which previously crashed with ``AttributeError: 'Minion'
object has no attribute 'tok'``.

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

Also adapt the ``_threaded_minion_61830`` fixture in
``tests/pytests/unit/test_minion.py`` to the opts-driven resource
inventory API (see commit ``resources: remove pillar as
resource-inventory source on the minion``).  The pre-refactor fixture
set resources via pillar; after the refactor
``enabled_resource_types()`` reads ``opts["resource_types"]`` instead,
so the dummy type was never discovered and the sibling-job trigger
never fired -- ``AssertionError: sibling job never ran in the
window``.  Derive ``resource_types`` from the pillar dict and stub
``_iter_resource_ids`` to yield each type's declared IDs, same shim
pattern used in ``test_minion_resources.py``.  Fixes all 6
``test_thread_return_*_resource_job_owns_job_generation_61830``
parametrizations.
The ``resources/`` integration suite still seeded dummy-resource
inventory via ``opts["pillar"]["resources"]``, which earlier branch
commits (64657af, 2e01cc7, c380f5c) removed in favour of
the ``resource_types`` + per-type opts API consumed by
``salt.utils.resources.enabled_resource_types``.  Mirror the
pattern landed in 07c6b0b for the unit suite.

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

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

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

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

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

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

* The dynamic_test fixture keeps its pillar-reading contract (the
  whole point of the synthetic type is "discover() is authoritative";
  it legitimately reads a non-``resources`` pillar key) but now also
  sets ``resource_types: ["dynamic_test"]`` so the opts-driven
  loader enables the type.
The reverse-value index (``index_grain_keys``,
``grain_reverse_index``) covered operator-declared top-level grain
keys via an in-process ``{(grain_key, value) -> [sr_key, ...]}`` map.
The trie index (``enable_grain_trie_index``) subsumes every query
shape it handled -- plus nested paths, undeclared keys, and globs --
and keeps the data on mmap so process RAM stays flat with inventory.

Remove the opt-in config knob, the util module, the dispatch block
in ``CkMinions._augment_grain_match_with_resource_grains``, the
``_reverse_index_lookup`` method, the ``_indexed_grain_predicate``
helper, and the dedicated test suite. ``_augment_grain_match_with_
resource_grains`` now routes directly from the ``resource_id``
fast-path to the trie to the legacy per-key fetch loop; operators
who want fast arbitrary-grain lookups flip
``enable_grain_trie_index: True`` instead of enumerating keys.
``_check_cache_minions`` on the per-minion ``grains`` bank was the
only grain-target entry point still doing an O(N) pickle-fetch loop
after Missions 1-4. Wire ``mmap_trie_index.dispatch_predicate`` in
front of the legacy loop so arbitrary ``<path>:<value>`` and nested
grain predicates hit the same persistent mmap trie that the
``resource_grains`` bank already uses.

The trie is bank-agnostic; no change to the primitive. Dispatch is
gated on ``opts["enable_grain_trie_index"]`` (same knob as the
resource-grains path). When the trie returns ``None`` (cap sentinel,
missing build, shape mismatch) we fall through to the legacy loop so
correctness is preserved even if the index subsystem is broken.
Trie-returned minions are intersected with the starting PKI /
cached-list set so an accepted-key filter is never bypassed by a
stale cached grain dict.
The 3009.0 release notes file and the ``3009.*`` glob in the releases
index were pre-staged for the next release cycle, but they do not
belong on 3008.x -- Sphinx stops warning on the orphan page once the
release stub actually lands on the right branch.  Drop both so the
branch only carries 3008.x-shaped doc artifacts.
Follow-up to 1aea73e.  The template was introduced alongside the
3009.0 release stub; both belong on the next release cycle, not on
3008.x.
Teaches for_bank to read the previously-documented-but-unwired
grain_trie_mmap_size knob and forward it to :class:.
Each bank's sparse trie.idx file is mmap_size * slot_size
bytes; the production default of 2_000_000 slots x 160-byte slots
yields a 320 MiB sparse file per bank. On CI runners with a
tmpfs-backed /tmp, a fleet of ~40 test_mmap_trie_index tests
plus the integration-test setup copying hundreds of MiB of fixtures
exhausts the tmpfs before the trie suite finishes, after which
MmapCache key-store writes silently drop and mm.get(key)
returns None for every lookup. That surfaced as
test_chunk_key_derivation_uses_1d_separator,
test_small_bucket_still_regular_list, and the other wide-bucket
assertions reporting the trie as empty on CI while all tests passed
locally.

The test adapter now passes grain_trie_mmap_size=200_000 (32 MiB
per bank) through the opts dict, and
test_rebuild_swaps_every_rolled_heap_segment which bypasses the
adapter for its grain_trie_mmap_max_segment_bytes override now
also passes grain_trie_mmap_size=50_000. Full file footprint
drops from ~12 GiB to ~1.3 GiB per run.
test_minion_manager_destroy_after_closed_io_loop_does_not_raise closed
its ``manager.io_loop`` without first draining the manager's event
publisher and cancelling background tasks.  The PubServer's per-
subscriber ``_stream_read`` tasks are not part of
``manager._background_tasks``, so they survived loop teardown and
later asyncio emitted ``Task was destroyed but it is pending!`` from
a subsequent test's caplog, breaking saltstack#70748's regression check purely
as a test-cleanup artifact.  On CPython 3.14 the GC timing changed by
the resource-discovery streaming refactor makes the ghost task reach
the later test's capture window deterministically.

Close the event publisher first so each subscriber's ``_stream_read``
exits via ``StreamClosedError``, then cancel + gather the manager's
tracked background tasks, then close the loop.  Mirrors the pattern
already in ``spawn_minions_keeps_task_reference`` and
``bind_keeps_publisher_task_reference``.
Arm64 CI exercised a bootstrap race where master_1 fired a
cluster_aes-encrypted delegate-cache-write before master_2 finished
installing cluster_aes from the founder's join-reply.  master_2
could not decrypt the event, the receiver's handler ran
log.exception("Failed to decrypt..."), and the write was dropped.
Downstream tests expecting the write to have propagated timed out
at 60s.

Two complementary changes:

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

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

Changelog: 70773.
…sites

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

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

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

Strip the per-write suffix so coalescing collapses by stable event
tag.  Loses the per-key label in the WARN; operators keep bank/key
detail via the receiver-side log_decrypt_failure call which already
correlates on cluster_id + source peer.
Two ``asyncio.create_task`` calls added to the cluster event dispatcher
on this branch (``delegate_cache_write``, ``delegate_resource_register_write``)
trip ruff-incremental's RUF006 "store reference to task" rule.  The
sibling dispatches at lines 5091-5121 (sync_roots, collect_from_peers,
shed_unowned_all, delegate_write) are structurally identical and pre-
date the incremental base ref -- ruff treats them as "existing and not
enforced".  Match the existing fire-and-forget style with an inline
noqa so the incremental check passes without churning the surrounding
handler.
dwoz added 4 commits November 13, 2026 01:56
Cluster cache replication (cluster_isolated_filesystem=True) can race
an in-process ``cache.list(bank)`` against a daemon-side
``cache.store(bank, ...)`` fan-out from a peer master.  The current
``localfs.store`` writes the tempfile with ``tempfile.mkstemp(dir=base)``
-- directly inside the bank directory -- so ``localfs.list`` enumerates
the stray ``tmpXXXXXXXX`` while the atomic rename is still in flight.

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

Stage every write in ``<cachedir>/.localfs_tmp/`` first, then
``atomic_rename`` into the bank.  ``atomic_rename`` stays atomic
because both paths are under ``cachedir`` and therefore on the same
filesystem.  Structural fix -- any ``list_()`` scan at any point in
time now sees only ``.p`` cache files and completed sub-banks, never
in-flight mkstemp residue.
The sender-side handshake gate (14ddd5e) correctly refuses to fan
out cluster_aes-encrypted replication events to peers that have not
completed the cluster discover/join handshake, deferring to the
join-time state-sync stream to catch them up.  There is a narrow race,
visible on Arm64 CI under load: a write landing AFTER the state-sync
snapshot but BEFORE the peer enters this master's ``_discover_replies``
(or ``peer_keys``) is dropped by the gate and never caught up.  The
state-sync enumeration is taken synchronously when the join-reply is
emitted; any live write before the peer's ``discover-reply`` arrives
falls into a hole.

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

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

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

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

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

Local commit only; no push per task constraint.
Reviewer flagged "the gate never silently drops data on the floor" as
an overclaim: the pending queue is bounded by
cluster_cache_replicate_pending_max_events (default 10_000/peer) and
cluster_cache_replicate_pending_ttl (default 300s), and both cap-
eviction and TTL-expiry do drop events.  Cap-eviction coalesces a WARN
per peer, TTL-expiry is silent.  Describe the actual bound explicitly
so operators and future readers know the real contract.
Reviewer I-1 (followup-bootstrap-race-reviewer.md) flagged that the
sender-side pending-replication queue retains pre-encrypted events
after a cluster_aes change.  A peer that later installs the new key
cannot decrypt the queued bytes -- the exact ``Failed to decrypt``
silent-loss the gate was meant to prevent.

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

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

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

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

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

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

Call sites:

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

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

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

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

Test results (local, x86):

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

Pre-commit: all hooks clean.

Scope discipline: no changes to salt/crypt, salt/transport, or
salt/cluster/consensus/.  No push.

This branch was previously deployed

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

Labels

test:full Run the full test suite

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants