Skip to content

Enhance cluster stale packet detection to prevent sub-replica and empty primary - #2811

Merged
enjoy-binbin merged 1 commit into
valkey-io:unstablefrom
zhijun42:race-empty-primary-with-test
Apr 2, 2026
Merged

enjoy-binbin merged 1 commit into
valkey-io:unstablefrom
zhijun42:race-empty-primary-with-test

Conversation

@zhijun42

@zhijun42 zhijun42 commented Nov 6, 2025 •

Copy link
Copy Markdown
Contributor

Backporting note: Appears to depend on #2283 which is not present in 8.x, so backporting to 8.x is skipped/paused. Test affected: New replica inherits multiple migrating slots in tests/unit/cluster/slot-migration.tcl

Summary

This PR handles a network race condition that would cause a replica to read stale cluster
packet and then incorrectly promote itself to an empty primary within an existing shard.

Issue

"Migrated replica reports zero repl offset and rank, and fails to win election - sigstop"
the test case in replica-migration.tcl is a known example where the network race condition
can occur.

Here's the timeline:

  • T1: Slot migration β€” R7 and R3 both try to replicate from R0. Only R3 succeeds, triggering
    a BGSAVE on R0, while R7 blocks in receiveSynchronousResponse().

  • T2: While R7 is blocked, R0 is SIGSTOP'd by the test. R4 wins the election and becomes the
    new primary. R4 sends PINGs to R7 - These PINGs land in R7's kernel TCP receive buffer but
    are not read by R7 yet.

  • T3 (5s after T1, due to receiveSynchronousResponse): R7 wakes up:

    • It reads from inbound links and finds out the remote nodes have already closed their end
      (they detected R7 as FAIL), getting "I/O error: connection closed" on each. R7 calls accept()
      for the new connections that were established during the block. These connections carry data
      that was sent seconds ago while R7 was dead.
    • R7's outbound links are still valid, so it sends PING to R4.
  • T4: R7 receives and processes fresh PONG packet from R4 on outbound link, reconfiguring itself
    to follow R4.

  • T5: R7 reads stale PING packet of R4 via inbound link. This packet was generated R4 was following
    R0, so R7 incorrectly believes R4 is still following R0 now. And Reconfiguring itself as a replica
    of R0 from R4.

  • T6: R7 finds R0 is FAIL, so it starts an election and wins, and becomes an empty-primary.

Analyze

So in T4, R4 is the new primary, and R7 is reconfiguring itself as a replica. So in R7's view,
R4 is the primary, and myself (R7) is a replica.

And in T5, there is a stale packet from sender (R4), the stale packet is saying: sender (R4) is
a replica and R0 is the primary.

We originally had a logic for stale packet, meaning we would try to ignore stale packet that
would cause exceptions. So in T5:

  • sender_claims_to_be_primary is false since R4 is saying it is a replica.

  • sender_last_reported_as_primary is true since in R7's view, R4 is a primary.

  • sender_claimed_primary is R0, and sender (R4) and sender_claimed_primary (R0) is in the same shard.

  • nodeEpoch(sender_claimed_primary) is R0's epoch. R0 is an old and dead (not yet) primary.

  • sender_claimed_config_epoch is R0's epoch since R4 is a replica, and R0 is R4's primary.

  • nodeEpoch(sender_claimed_primary) == sender_claimed_config_epoch, so the logic fail and we process
    a stale packet. So in this point, the packet is not a stale packet in R4 and R0's view.

  • But it is a stale packet in myself (R7) view. In R7's local view, R4 is the new primary and it
    should have a bigger epoch, that is nodeEpoch(sender) should > sender_claimed_config_epoch.

Fix

The PR fixes the issue by enhancing the existing guardrail logic against stale packet. Previously
that logic only detects nodeEpoch(sender_claimed_primary) > sender_claimed_config_epoch as stale
packet, now it also checks nodeEpoch(sender) > sender_claimed_config_epoch to make sure we have
up-to-date primary-replica chain.

@codecov

codecov Bot commented Nov 6, 2025 •

Copy link
Copy Markdown

Codecov Report

βœ… All modified and coverable lines are covered by tests.
βœ… Project coverage is 76.80%. Comparing base (839d0c6) to head (fb6257a).
⚠️ Report is 126 commits behind head on unstable.

Additional details and impacted files
@@             Coverage Diff              @@
##           unstable    #2811      +/-   ##
============================================
+ Coverage     74.96%   76.80%   +1.83%     
============================================
  Files           129      159      +30     
  Lines         71318    79704    +8386     
============================================
+ Hits          53467    61218    +7751     
- Misses        17851    18486     +635     
Files with missing lines Coverage Ξ”
src/cluster_legacy.c 87.90% <100.00%> (+<0.01%) ⬆️

... and 90 files with indirect coverage changes

πŸš€ New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • πŸ“¦ JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zhijun42
zhijun42 force-pushed the race-empty-primary-with-test branch 3 times, most recently from 6133920 to e3a98ce Compare November 28, 2025 04:35
@zhijun42

Copy link
Copy Markdown
Contributor Author

@PingXie @enjoy-binbin @hpatro Friendly ping πŸ‘€ Could you take a look at this when you got some time?

@zuiderkwast zuiderkwast left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for finding this bug and explained the scenario and the fix.

The reason I didn't review this until now is the diff is big and it mixes refactoring, changed logging and the actual bug fix.

A bugfix PR needs to be as small as possible, so we can backport the fix without merge conflicts. Valkey versions (8.0, 8.1, 9.0) are all affected by this bug, right?

For the bug fix, we need a small PR with only the fix itself (10 lines) and the test case, if possible. I hope we can find a way to make it stable using some artificial timing, debug commands or similar. It seems that you have managed to reproduce the scenario but it is just flaky.

The other changes: Improved logging, can be in another PR. This one doesn't need to be backported, but we anyway want to avoid changes and keep the diff small.

Comment thread src/cluster_legacy.c Resolved
Comment thread src/cluster_legacy.c Resolved
Comment thread src/cluster_legacy.c Resolved
Comment thread src/cluster_legacy.c Resolved
Comment thread src/cluster_legacy.c Resolved
Comment thread src/cluster_legacy.c Resolved
Comment thread src/cluster_legacy.c Resolved
@zhijun42

Copy link
Copy Markdown
Contributor Author

@zuiderkwast Thanks for the detailed review! You are absolutely right. I have made this PR impossible to review. My apologies. I was aware of it, so I created a new PR #3069 few days ago to remove certain changes, but I didn't update this one correspondingly yet, so I really appreciate your patience diving right into this massive PR right away.

I will address all these feedback and reduce this PR to a reasonable size.

@zhijun42
zhijun42 force-pushed the race-empty-primary-with-test branch from e3a98ce to ecfd21a Compare January 21, 2026 09:46
@zhijun42

Copy link
Copy Markdown
Contributor Author

Still work in progress. Will finish cleaning up and addressing each comment later.

@zhijun42 zhijun42 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reduced this PR to just the fix and removed all non-core changes. I moved the new test to a separate PR #3084.

This is good development hygiene that I learned from the etcd and Kubernetes community - for serious problems, we should send the reproduction PR first to showcase the current buggy behavior, and such PR is valuable in itself, even when we don't have a good solution yet. And such PR separation makes code review much easier.

Comment thread src/cluster_legacy.c Resolved
Comment thread src/cluster_legacy.c Resolved
Comment thread src/cluster_legacy.c Resolved
Comment thread src/cluster_legacy.c Resolved
Comment thread src/cluster_legacy.c Resolved
@zhijun42
zhijun42 force-pushed the race-empty-primary-with-test branch from ecfd21a to abab62d Compare January 21, 2026 14:32
@zhijun42

Copy link
Copy Markdown
Contributor Author

@zuiderkwast

Valkey versions (8.0, 8.1, 9.0) are all affected by this bug, right?

Yes I believe so. As you've pointed out, this is due to sync IO.

Comment thread src/cluster_legacy.c Resolved
@enjoy-binbin enjoy-binbin self-assigned this Feb 25, 2026
@zhijun42
zhijun42 force-pushed the race-empty-primary-with-test branch from abab62d to 459a092 Compare February 26, 2026 11:48
@enjoy-binbin

enjoy-binbin commented Feb 26, 2026 •

Copy link
Copy Markdown
Member

The debug code seems too much, i would like to drop it before the merge (and i am glad you did can proves that it fixed the issue). And btw, does #3084 still have value? We could perhaps add some assertions to our existing test cases, or your new test case, to ensure that this sub-replica situation doesn't occur. (We don't necessarily need to cover it, since it's indeed not easy to reproduce, but our daily CI will eventually be able to reproduce it, just as you discovered it)

Let's also update the title and the top comment, now we are ingoring a stale packet. Please make sure the top comment is include #2811 (comment) and #2811 (comment), so that other reviewer can know the reason and the fix.

@enjoy-binbin enjoy-binbin added release-notes This issue should get a line item in the release notes and removed needs-review Maintainer attention labels Feb 26, 2026
@enjoy-binbin enjoy-binbin moved this to To be backported in Valkey 8.0 Feb 26, 2026
@github-project-automation github-project-automation Bot moved this to To be backported in Valkey 8.0 Jun 2, 2026
@github-project-automation github-project-automation Bot moved this to To be backported in Valkey 8.1 Jun 2, 2026
@zuiderkwast zuiderkwast moved this from To be backported to Don't backport yet in Valkey 8.1 Jun 2, 2026
@zuiderkwast zuiderkwast moved this from To be backported to Don't backport yet in Valkey 8.0 Jun 2, 2026
valkeyrie-ops Bot pushed a commit that referenced this pull request Jun 3, 2026
…ty primary (#2811)

## Summary
This PR handles a network race condition that would cause a replica to read stale cluster
packet and then incorrectly promote itself to an empty primary within an existing shard.

## Issue
"Migrated replica reports zero repl offset and rank, and fails to win election - sigstop"
the test case in `replica-migration.tcl` is a known example where the network race condition
can occur.

Here's the timeline:
- T1: Slot migration β€” R7 and R3 both try to replicate from R0. Only R3 succeeds, triggering
  a BGSAVE on R0, while R7 blocks in `receiveSynchronousResponse()`.
- T2: While R7 is blocked, R0 is SIGSTOP'd by the test. R4 wins the election and becomes the
  new primary. R4 sends PINGs to R7 - These PINGs land in R7's kernel TCP receive buffer but
  are not read by R7 yet.
- T3 (5s after T1, due to receiveSynchronousResponse): R7 wakes up:
  - It reads from inbound links and finds out the remote nodes have already closed their end
    (they detected R7 as FAIL), getting "I/O error: connection closed" on each. R7 calls `accept()`
    for the new connections that were established during the block. These connections carry data
    that was sent seconds ago while R7 was dead.
  - R7's outbound links are still valid, so it sends PING to R4.
- T4: R7 receives and processes fresh PONG packet from R4 on outbound link, reconfiguring itself
  to follow R4.
- T5: R7 reads stale PING packet of R4 via inbound link. This packet was generated R4 was following
  R0, so R7 incorrectly believes R4 is still following R0 now. And Reconfiguring itself as a replica
  of R0 from R4.
- T6: R7 finds R0 is FAIL, so it starts an election and wins, and becomes an empty-primary.

## Analyze
So in T4, R4 is the new primary, and R7 is reconfiguring itself as a replica. So in R7's view,
R4 is the primary, and myself (R7) is a replica.

And in T5, there is a stale packet from sender (R4), the stale packet is saying: sender (R4) is
a replica and R0 is the primary.

We originally had a logic for stale packet, meaning we would try to ignore stale packet that
would cause exceptions. So in T5:
- sender_claims_to_be_primary is false since R4 is saying it is a replica.
- sender_last_reported_as_primary is true since in R7's view, R4 is a primary.
- sender_claimed_primary is R0, and sender (R4) and sender_claimed_primary (R0) is in the same shard.
- nodeEpoch(sender_claimed_primary) is R0's epoch. R0 is an old and dead (not yet) primary.
- sender_claimed_config_epoch is R0's epoch since R4 is a replica, and R0 is R4's primary.
- nodeEpoch(sender_claimed_primary) == sender_claimed_config_epoch, so the logic fail and we process
  a stale packet. So in this point, the packet is not a stale packet in R4 and R0's view.
- But it is a stale packet in myself (R7) view. In R7's local view, R4 is the new primary and it
  should have a bigger epoch, that is nodeEpoch(sender) should > sender_claimed_config_epoch.

## Fix
The PR fixes the issue by enhancing the existing guardrail logic against stale packet. Previously
that logic only detects `nodeEpoch(sender_claimed_primary) > sender_claimed_config_epoch` as stale
packet, now it also checks `nodeEpoch(sender) > sender_claimed_config_epoch` to make sure we have
up-to-date primary-replica chain.

Signed-off-by: Zhijun <dszhijun@gmail.com>
Co-authored-by: Binbin <binloveplay1314@qq.com>
valkeyrie-ops Bot pushed a commit that referenced this pull request Jun 6, 2026
…ty primary (#2811)

## Summary
This PR handles a network race condition that would cause a replica to read stale cluster
packet and then incorrectly promote itself to an empty primary within an existing shard.

## Issue
"Migrated replica reports zero repl offset and rank, and fails to win election - sigstop"
the test case in `replica-migration.tcl` is a known example where the network race condition
can occur.

Here's the timeline:
- T1: Slot migration β€” R7 and R3 both try to replicate from R0. Only R3 succeeds, triggering
  a BGSAVE on R0, while R7 blocks in `receiveSynchronousResponse()`.
- T2: While R7 is blocked, R0 is SIGSTOP'd by the test. R4 wins the election and becomes the
  new primary. R4 sends PINGs to R7 - These PINGs land in R7's kernel TCP receive buffer but
  are not read by R7 yet.
- T3 (5s after T1, due to receiveSynchronousResponse): R7 wakes up:
  - It reads from inbound links and finds out the remote nodes have already closed their end
    (they detected R7 as FAIL), getting "I/O error: connection closed" on each. R7 calls `accept()`
    for the new connections that were established during the block. These connections carry data
    that was sent seconds ago while R7 was dead.
  - R7's outbound links are still valid, so it sends PING to R4.
- T4: R7 receives and processes fresh PONG packet from R4 on outbound link, reconfiguring itself
  to follow R4.
- T5: R7 reads stale PING packet of R4 via inbound link. This packet was generated R4 was following
  R0, so R7 incorrectly believes R4 is still following R0 now. And Reconfiguring itself as a replica
  of R0 from R4.
- T6: R7 finds R0 is FAIL, so it starts an election and wins, and becomes an empty-primary.

## Analyze
So in T4, R4 is the new primary, and R7 is reconfiguring itself as a replica. So in R7's view,
R4 is the primary, and myself (R7) is a replica.

And in T5, there is a stale packet from sender (R4), the stale packet is saying: sender (R4) is
a replica and R0 is the primary.

We originally had a logic for stale packet, meaning we would try to ignore stale packet that
would cause exceptions. So in T5:
- sender_claims_to_be_primary is false since R4 is saying it is a replica.
- sender_last_reported_as_primary is true since in R7's view, R4 is a primary.
- sender_claimed_primary is R0, and sender (R4) and sender_claimed_primary (R0) is in the same shard.
- nodeEpoch(sender_claimed_primary) is R0's epoch. R0 is an old and dead (not yet) primary.
- sender_claimed_config_epoch is R0's epoch since R4 is a replica, and R0 is R4's primary.
- nodeEpoch(sender_claimed_primary) == sender_claimed_config_epoch, so the logic fail and we process
  a stale packet. So in this point, the packet is not a stale packet in R4 and R0's view.
- But it is a stale packet in myself (R7) view. In R7's local view, R4 is the new primary and it
  should have a bigger epoch, that is nodeEpoch(sender) should > sender_claimed_config_epoch.

## Fix
The PR fixes the issue by enhancing the existing guardrail logic against stale packet. Previously
that logic only detects `nodeEpoch(sender_claimed_primary) > sender_claimed_config_epoch` as stale
packet, now it also checks `nodeEpoch(sender) > sender_claimed_config_epoch` to make sure we have
up-to-date primary-replica chain.

Signed-off-by: Zhijun <dszhijun@gmail.com>
Co-authored-by: Binbin <binloveplay1314@qq.com>
valkeyrie-ops Bot pushed a commit that referenced this pull request Jun 10, 2026
…ty primary (#2811)

## Summary
This PR handles a network race condition that would cause a replica to read stale cluster
packet and then incorrectly promote itself to an empty primary within an existing shard.

## Issue
"Migrated replica reports zero repl offset and rank, and fails to win election - sigstop"
the test case in `replica-migration.tcl` is a known example where the network race condition
can occur.

Here's the timeline:
- T1: Slot migration β€” R7 and R3 both try to replicate from R0. Only R3 succeeds, triggering
  a BGSAVE on R0, while R7 blocks in `receiveSynchronousResponse()`.
- T2: While R7 is blocked, R0 is SIGSTOP'd by the test. R4 wins the election and becomes the
  new primary. R4 sends PINGs to R7 - These PINGs land in R7's kernel TCP receive buffer but
  are not read by R7 yet.
- T3 (5s after T1, due to receiveSynchronousResponse): R7 wakes up:
  - It reads from inbound links and finds out the remote nodes have already closed their end
    (they detected R7 as FAIL), getting "I/O error: connection closed" on each. R7 calls `accept()`
    for the new connections that were established during the block. These connections carry data
    that was sent seconds ago while R7 was dead.
  - R7's outbound links are still valid, so it sends PING to R4.
- T4: R7 receives and processes fresh PONG packet from R4 on outbound link, reconfiguring itself
  to follow R4.
- T5: R7 reads stale PING packet of R4 via inbound link. This packet was generated R4 was following
  R0, so R7 incorrectly believes R4 is still following R0 now. And Reconfiguring itself as a replica
  of R0 from R4.
- T6: R7 finds R0 is FAIL, so it starts an election and wins, and becomes an empty-primary.

## Analyze
So in T4, R4 is the new primary, and R7 is reconfiguring itself as a replica. So in R7's view,
R4 is the primary, and myself (R7) is a replica.

And in T5, there is a stale packet from sender (R4), the stale packet is saying: sender (R4) is
a replica and R0 is the primary.

We originally had a logic for stale packet, meaning we would try to ignore stale packet that
would cause exceptions. So in T5:
- sender_claims_to_be_primary is false since R4 is saying it is a replica.
- sender_last_reported_as_primary is true since in R7's view, R4 is a primary.
- sender_claimed_primary is R0, and sender (R4) and sender_claimed_primary (R0) is in the same shard.
- nodeEpoch(sender_claimed_primary) is R0's epoch. R0 is an old and dead (not yet) primary.
- sender_claimed_config_epoch is R0's epoch since R4 is a replica, and R0 is R4's primary.
- nodeEpoch(sender_claimed_primary) == sender_claimed_config_epoch, so the logic fail and we process
  a stale packet. So in this point, the packet is not a stale packet in R4 and R0's view.
- But it is a stale packet in myself (R7) view. In R7's local view, R4 is the new primary and it
  should have a bigger epoch, that is nodeEpoch(sender) should > sender_claimed_config_epoch.

## Fix
The PR fixes the issue by enhancing the existing guardrail logic against stale packet. Previously
that logic only detects `nodeEpoch(sender_claimed_primary) > sender_claimed_config_epoch` as stale
packet, now it also checks `nodeEpoch(sender) > sender_claimed_config_epoch` to make sure we have
up-to-date primary-replica chain.

Signed-off-by: Zhijun <dszhijun@gmail.com>
Co-authored-by: Binbin <binloveplay1314@qq.com>
valkeyrie-ops Bot pushed a commit that referenced this pull request Jun 15, 2026
sarthakaggarwal97 pushed a commit that referenced this pull request Jun 18, 2026
…ty primary (#2811)

## Summary
This PR handles a network race condition that would cause a replica to read stale cluster
packet and then incorrectly promote itself to an empty primary within an existing shard.

## Issue
"Migrated replica reports zero repl offset and rank, and fails to win election - sigstop"
the test case in `replica-migration.tcl` is a known example where the network race condition
can occur.

Here's the timeline:
- T1: Slot migration β€” R7 and R3 both try to replicate from R0. Only R3 succeeds, triggering
  a BGSAVE on R0, while R7 blocks in `receiveSynchronousResponse()`.
- T2: While R7 is blocked, R0 is SIGSTOP'd by the test. R4 wins the election and becomes the
  new primary. R4 sends PINGs to R7 - These PINGs land in R7's kernel TCP receive buffer but
  are not read by R7 yet.
- T3 (5s after T1, due to receiveSynchronousResponse): R7 wakes up:
  - It reads from inbound links and finds out the remote nodes have already closed their end
    (they detected R7 as FAIL), getting "I/O error: connection closed" on each. R7 calls `accept()`
    for the new connections that were established during the block. These connections carry data
    that was sent seconds ago while R7 was dead.
  - R7's outbound links are still valid, so it sends PING to R4.
- T4: R7 receives and processes fresh PONG packet from R4 on outbound link, reconfiguring itself
  to follow R4.
- T5: R7 reads stale PING packet of R4 via inbound link. This packet was generated R4 was following
  R0, so R7 incorrectly believes R4 is still following R0 now. And Reconfiguring itself as a replica
  of R0 from R4.
- T6: R7 finds R0 is FAIL, so it starts an election and wins, and becomes an empty-primary.

## Analyze
So in T4, R4 is the new primary, and R7 is reconfiguring itself as a replica. So in R7's view,
R4 is the primary, and myself (R7) is a replica.

And in T5, there is a stale packet from sender (R4), the stale packet is saying: sender (R4) is
a replica and R0 is the primary.

We originally had a logic for stale packet, meaning we would try to ignore stale packet that
would cause exceptions. So in T5:
- sender_claims_to_be_primary is false since R4 is saying it is a replica.
- sender_last_reported_as_primary is true since in R7's view, R4 is a primary.
- sender_claimed_primary is R0, and sender (R4) and sender_claimed_primary (R0) is in the same shard.
- nodeEpoch(sender_claimed_primary) is R0's epoch. R0 is an old and dead (not yet) primary.
- sender_claimed_config_epoch is R0's epoch since R4 is a replica, and R0 is R4's primary.
- nodeEpoch(sender_claimed_primary) == sender_claimed_config_epoch, so the logic fail and we process
  a stale packet. So in this point, the packet is not a stale packet in R4 and R0's view.
- But it is a stale packet in myself (R7) view. In R7's local view, R4 is the new primary and it
  should have a bigger epoch, that is nodeEpoch(sender) should > sender_claimed_config_epoch.

## Fix
The PR fixes the issue by enhancing the existing guardrail logic against stale packet. Previously
that logic only detects `nodeEpoch(sender_claimed_primary) > sender_claimed_config_epoch` as stale
packet, now it also checks `nodeEpoch(sender) > sender_claimed_config_epoch` to make sure we have
up-to-date primary-replica chain.

Signed-off-by: Zhijun <dszhijun@gmail.com>
Co-authored-by: Binbin <binloveplay1314@qq.com>
sarthakaggarwal97 pushed a commit that referenced this pull request Jun 18, 2026
chideat added a commit to chideat/valkey-operator that referenced this pull request Jul 13, 2026
…coverage (#98)

* test(e2e): cover all supported valkey versions

- supportedVersions now matches the API version enum
  (7.2/8.0/8.1/9.0/9.1); 8.2 was never a valid Version (the CRD enum
  rejects it) so its test groups could never pass
- re-path the upgrade chains through valid versions: 8.1 -> 9.0 (crosses
  the RDB-format boundary guarded by SHUTDOWN NOSAVE) and 9.0 -> 9.1,
  keeping the latency-tracking assertion when landing on 9.0+
- wrap per-version testcases in a version-titled Context labeled
  v<version> so failures are attributable to a version and runs can be
  targeted with --ginkgo.label-filter (e.g. v9.0)

(cherry picked from commit 5fd587ae22a13491814cb9e5570436bdbc280661)

* fix: do not set blockOwnerDeletion on synced configmap owner refs

On clusters with the OwnerReferencesPermissionEnforcement admission
plugin (e.g. cpaas), creating/updating the sync-<pod> nodes.conf
ConfigMap fails with "cannot set blockOwnerDeletion" because the
instance ServiceAccount lacks update permission on the owner CR
finalizers subresource. Without persisted nodes.conf, restarted
cluster nodes rejoin slowly and the pre-stop failover cannot find a
candidate replica in time, shutting down masters unpromoted and
losing all data during rolling restarts.

Copy the StatefulSet owner references with BlockOwnerDeletion cleared;
background garbage collection does not need it.

(cherry picked from commit 01d69b7fc8cb2f8a0a366506fd2c3b14e6660821)

* test(e2e): allow graceful master handoff in killPod replacement wait

Deleting a master pod triggers the pre-stop failover (candidate lookup,
anti-collision sleep, failover, verify) bounded by the 300s termination
grace period, and the StatefulSet cannot recreate the pod until
termination completes. The 2-minute replacement timeout is shorter than
a legitimate graceful handoff; raise it to 8 minutes.

(cherry picked from commit e902129f1d337219637f3018d5c5763cadeaec99)

* fix: escalate to FORCE failover when graceful master shutdown stalls

When a master pod is deleted right after an ACL/password rollout, the
master-replica replication link can still be recovering, and a plain
CLUSTER FAILOVER on the replica keeps failing ("do manual failover
failed"). The shutdown retry loop then burns the entire 300s
termination grace period (each retry also slept a random 1-50s),
the kubelet SIGKILLs the unpromoted master, and its empty restart
wipes the shard via full resync.

Escalate to CLUSTER FAILOVER FORCE after three failed plain attempts:
the node is terminating anyway, and a forced promotion with the
replica's current dataset is strictly better than dying unpromoted.
Also shorten the anti-collision jitter on retries (the large first-try
jitter is kept) so the grace budget is spent failing over, not
sleeping.

(cherry picked from commit cfb87ac24f8c2cd0dfe51dcd022ae5d12b158ff9)

* fix: give cluster failover elections time to collect votes

A failover election needs up to 2x cluster-node-timeout (30s at the
default 15s) to gather votes, and masters refuse to re-vote within the
same window. doValkeyFailover only observed the replica for 15s after
issuing CLUSTER FAILOVER, so the shutdown retry loop re-issued the
command mid-election; valkey then logs "received a new manual failover.
Resetting the election", the prior votes are discarded, and the
election never reaches majority ("Waiting for votes, but majority still
not reached") for the whole termination grace period.

Observe for 70s per attempt instead, covering a full election round
plus one cooldown-blocked round.

(cherry picked from commit a854616200937094a457003373e5022a971197e9)

* fix: rebalance graceful-shutdown failover pacing within the grace period

The previous two fixes interacted badly: with a 70s observation window
per attempt and FORCE escalation only from the fourth attempt, the
three plain attempts consumed the entire 300s termination grace before
FORCE ever fired, and the master still died unpromoted.

Rebalance the budget: observe plain manual failover for 35s (its
protocol window is 2x cluster-node-timeout), escalate to FORCE from the
second attempt with the full 70s election observation, cap the
anti-collision jitter at 15s (first attempt) / 5s (retries), and log
loudly if the loop ends with the master still unpromoted. This fits one
plain plus three full FORCE election rounds within the default grace
period, with vote-cooldown gaps between them.

(cherry picked from commit 02426092cce0d8e13f9e149f3e0f82bc3d90c25a)

* fix: do not re-validate Users that are being deleted

The User validating webhook re-validates the full spec on every
update, including secret existence. Once the referenced password
secret is deleted (e.g. namespace teardown), the finalizer-removing
update issued by the user controller is rejected with "Secret not
found", the finalizer can never be removed, and the User -- and any
namespace containing it -- is stuck terminating forever.

Skip validation for updates to objects that already carry a deletion
timestamp; those updates are metadata-only.

(cherry picked from commit bf54a32b2b07de51e761829aba840998e966ef08)

* fix: stop pre-writing a synthetic shard-id for cluster nodes

Root cause of the valkey 9.1 cluster failover breakage. The helper
pre-wrote nodes.conf on first boot with an operator-derived shard-id
(sha1(namespace/stsName), identical for every pod in a StatefulSet) and
re-forced that shard-id on every recovery. Because a master and its
replica then shared a pre-written shard-id, the replica's first
post-REPLICATE announcement entered valkey's same-shard stale-packet
branch instead of the safe cross-shard-move branch. On valkey 9.1.0 the
tightened check (nodeEpoch(sender) > claimed, valkey-io/valkey#2811),
combined with epoch-collision-resolution assigning the replica a higher
epoch than its primary, made every such announcement be dropped forever
("Ignore stale message ... in shard"). Peers permanently saw the replica
as an empty primary, so failover elections got zero votes
("Failover auth denied ... it is a primary node") and a killed master's
shard was wiped.

shard-id proves shared replication history and is valkey's to assign
(there is no CLUSTER SET-SHARD-ID); the operator must not fabricate it.
Seed only a deterministic node-id on first boot and preserve valkey's
real shard-ids verbatim on recovery. valkey adopts the primary's shard-id
via updateShardId when the node replicates.

Reproduced in isolation (bare pods, operator timing): 0/52 divergence
without shard-id prewrite, 4/4 with it; the fix (node-id only) is 0/4.

Removes: SHARD_ID env (clusterbuilder), the heal shard-id CLI flag, and
the shard-id forcing in generateValkeyCluterNodeRecord / fixClusterNodesConf.

(cherry picked from commit a5d5c511e9d4beea5cdcd56750d4b31b9ccb1538)

* test(e2e): wait for cluster client routability before use

The valkey-go cluster client fetches its slot map lazily, so right
after a topology change (notably the ACL-triggered reconnects during
create-and-delete-users) a slot can momentarily map to no node and an
operation fails with "the slot has no valkey node", aborting the whole
ordered suite. After constructing a cluster client, probe a spread of
keys until routing succeeds (a failed probe forces a slot-map refresh),
bounded to one minute, so callers never observe the transient gap.

(cherry picked from commit 2c6fbad3fa59fab88813c46d07bd68dd36695416)

* test(e2e): retry the whole write loop on transient cluster errors

checkInstanceRead already wraps its loop in Eventually (rebuilding the
client and retrying), but checkInstanceWrite built the client once and
asserted each SET directly, so a transient "the slot has no valkey node"
during ACL-driven connection churn failed the spec. Make the write path
symmetric: rebuild and retry the loop for up to 5 minutes.

(cherry picked from commit a3d5e3fe5aa8ae5edaeb3a3c4e8d1b5b87f4b18a)

* test(e2e): wait for full cluster slot coverage before returning a client

A cluster client caches its slot map at construction. When the cluster is
still settling (e.g. right after a config-propagation pod restart) that
snapshot can miss slots, and every later command on an uncovered slot fails
with "the slot has no valkey node" β€” the client treats the slot as empty
and never re-fetches. The read-only 16-key probe passed on covered slots
while the gap remained, so the 8.1 datatypes extra-test hit it on an HSET.

Gate the returned client on cluster_state:ok (full 16384-slot coverage) and
rebuild it between attempts so it captures a complete topology before any
caller uses it.

(cherry picked from commit 6b13eb4aec3e866f0393b1f647bbd9c7b46eea8f)

* chore: update Helm chart appVersion to v1.1.1 [skip ci]

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
sarthakaggarwal97 pushed a commit that referenced this pull request Jul 14, 2026
…ty primary (#2811)

## Summary
This PR handles a network race condition that would cause a replica to read stale cluster
packet and then incorrectly promote itself to an empty primary within an existing shard.

## Issue
"Migrated replica reports zero repl offset and rank, and fails to win election - sigstop"
the test case in `replica-migration.tcl` is a known example where the network race condition
can occur.

Here's the timeline:
- T1: Slot migration β€” R7 and R3 both try to replicate from R0. Only R3 succeeds, triggering
  a BGSAVE on R0, while R7 blocks in `receiveSynchronousResponse()`.
- T2: While R7 is blocked, R0 is SIGSTOP'd by the test. R4 wins the election and becomes the
  new primary. R4 sends PINGs to R7 - These PINGs land in R7's kernel TCP receive buffer but
  are not read by R7 yet.
- T3 (5s after T1, due to receiveSynchronousResponse): R7 wakes up:
  - It reads from inbound links and finds out the remote nodes have already closed their end
    (they detected R7 as FAIL), getting "I/O error: connection closed" on each. R7 calls `accept()`
    for the new connections that were established during the block. These connections carry data
    that was sent seconds ago while R7 was dead.
  - R7's outbound links are still valid, so it sends PING to R4.
- T4: R7 receives and processes fresh PONG packet from R4 on outbound link, reconfiguring itself
  to follow R4.
- T5: R7 reads stale PING packet of R4 via inbound link. This packet was generated R4 was following
  R0, so R7 incorrectly believes R4 is still following R0 now. And Reconfiguring itself as a replica
  of R0 from R4.
- T6: R7 finds R0 is FAIL, so it starts an election and wins, and becomes an empty-primary.

## Analyze
So in T4, R4 is the new primary, and R7 is reconfiguring itself as a replica. So in R7's view,
R4 is the primary, and myself (R7) is a replica.

And in T5, there is a stale packet from sender (R4), the stale packet is saying: sender (R4) is
a replica and R0 is the primary.

We originally had a logic for stale packet, meaning we would try to ignore stale packet that
would cause exceptions. So in T5:
- sender_claims_to_be_primary is false since R4 is saying it is a replica.
- sender_last_reported_as_primary is true since in R7's view, R4 is a primary.
- sender_claimed_primary is R0, and sender (R4) and sender_claimed_primary (R0) is in the same shard.
- nodeEpoch(sender_claimed_primary) is R0's epoch. R0 is an old and dead (not yet) primary.
- sender_claimed_config_epoch is R0's epoch since R4 is a replica, and R0 is R4's primary.
- nodeEpoch(sender_claimed_primary) == sender_claimed_config_epoch, so the logic fail and we process
  a stale packet. So in this point, the packet is not a stale packet in R4 and R0's view.
- But it is a stale packet in myself (R7) view. In R7's local view, R4 is the new primary and it
  should have a bigger epoch, that is nodeEpoch(sender) should > sender_claimed_config_epoch.

## Fix
The PR fixes the issue by enhancing the existing guardrail logic against stale packet. Previously
that logic only detects `nodeEpoch(sender_claimed_primary) > sender_claimed_config_epoch` as stale
packet, now it also checks `nodeEpoch(sender) > sender_claimed_config_epoch` to make sure we have
up-to-date primary-replica chain.

Signed-off-by: Zhijun <dszhijun@gmail.com>
Co-authored-by: Binbin <binloveplay1314@qq.com>
@valkeyrie-ops valkeyrie-ops Bot moved this from To be backported to Done in Valkey 9.0 Jul 14, 2026
chideat added a commit to chideat/valkey-operator that referenced this pull request Sep 11, 2026
…SHARDS (#106)

* fix: seed a per-pod shard-id so primaries appear in CLUSTER SHARDS

A freshly seeded primary was missing from its own CLUSTER SHARDS reply,
taking the slot range it owns with it. valkey-go reads CLUSTER SHARDS on
servers >= 8 and rebuilds a fresh [16384]conn from one node's answer, so
whenever its background topology refresh happened to query a primary, a
third of the keyspace was left unrouted and every key in it failed with
"the slot has no valkey node".

valkey inserts a node into server.cluster->shards from only two places:
auxShardIdSetter, which runs only when the nodes.conf line actually
carries a "shard-id=" aux field, and a clusterLoadConfig fallback for a
primary "without a persisted shard_id". That fallback is unreachable β€”
auxShardIdPresent() measures strlen(n->shard_id) against the random value
createClusterNode has already written into every node, so it always
reports the id as present. The helper seeded a primary line with a
node-id and no shard-id, so such a node loaded into
server.cluster->nodes but never into server.cluster->shards. Nothing else
gave the state away: CLUSTER NODES, CLUSTER SLOTS, slot coverage and the
on-disk shard-ids all stayed correct and consistent. Replicas escaped it
because CLUSTER REPLICATE re-homes them through updateShardId, and a
restart repaired it because valkey had by then rewritten nodes.conf with
a real shard-id.

Seed a shard-id derived from the pod. It must be unique per pod: this is
not a revert of a5d5c51, which removed a shard-id derived from the
StatefulSet and therefore shared by a primary and its replica from first
boot. That sharing put the replica's first post-REPLICATE announcement on
valkey's same-shard stale-packet branch, where valkey 9.1's tightened
check (valkey-io/valkey#2811) dropped it forever and failover elections
drew zero votes. A per-pod id reproduces what valkey does natively β€”
createClusterNode assigns a random shard-id per node β€” so the
announcement still takes the safe cross-shard-move branch and valkey
re-homes the replica onto its primary's shard-id.

Verified on a 3x2 cluster: every primary now reports all six nodes and
all three slot ranges, and each primary/replica pair is grouped into one
shard, confirming updateShardId still converges them. Full e2e against a
live cluster ran 533 specs across cluster/failover/replica x 7.2/8.0/8.1/
9.0/9.1 x ClusterIP/NodePort with no failures, including the 9.1
master-kill and sentinel-promotion specs that guard the a5d5c51 fix.

(cherry picked from commit 681754759a0e806a00939bcefcb3f32599ae30b8)
(cherry picked from commit ec7f4334cd38356b8b96e3c1a4bae88a0afa99ed)

* chore: update Helm chart appVersion to v1.1.1 [skip ci]

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
valkeyrie-ops Bot pushed a commit that referenced this pull request Nov 12, 2026
…ty primary (#2811)

## Summary
This PR handles a network race condition that would cause a replica to read stale cluster
packet and then incorrectly promote itself to an empty primary within an existing shard.

## Issue
"Migrated replica reports zero repl offset and rank, and fails to win election - sigstop"
the test case in `replica-migration.tcl` is a known example where the network race condition
can occur.

Here's the timeline:
- T1: Slot migration β€” R7 and R3 both try to replicate from R0. Only R3 succeeds, triggering
  a BGSAVE on R0, while R7 blocks in `receiveSynchronousResponse()`.
- T2: While R7 is blocked, R0 is SIGSTOP'd by the test. R4 wins the election and becomes the
  new primary. R4 sends PINGs to R7 - These PINGs land in R7's kernel TCP receive buffer but
  are not read by R7 yet.
- T3 (5s after T1, due to receiveSynchronousResponse): R7 wakes up:
  - It reads from inbound links and finds out the remote nodes have already closed their end
    (they detected R7 as FAIL), getting "I/O error: connection closed" on each. R7 calls `accept()`
    for the new connections that were established during the block. These connections carry data
    that was sent seconds ago while R7 was dead.
  - R7's outbound links are still valid, so it sends PING to R4.
- T4: R7 receives and processes fresh PONG packet from R4 on outbound link, reconfiguring itself
  to follow R4.
- T5: R7 reads stale PING packet of R4 via inbound link. This packet was generated R4 was following
  R0, so R7 incorrectly believes R4 is still following R0 now. And Reconfiguring itself as a replica
  of R0 from R4.
- T6: R7 finds R0 is FAIL, so it starts an election and wins, and becomes an empty-primary.

## Analyze
So in T4, R4 is the new primary, and R7 is reconfiguring itself as a replica. So in R7's view,
R4 is the primary, and myself (R7) is a replica.

And in T5, there is a stale packet from sender (R4), the stale packet is saying: sender (R4) is
a replica and R0 is the primary.

We originally had a logic for stale packet, meaning we would try to ignore stale packet that
would cause exceptions. So in T5:
- sender_claims_to_be_primary is false since R4 is saying it is a replica.
- sender_last_reported_as_primary is true since in R7's view, R4 is a primary.
- sender_claimed_primary is R0, and sender (R4) and sender_claimed_primary (R0) is in the same shard.
- nodeEpoch(sender_claimed_primary) is R0's epoch. R0 is an old and dead (not yet) primary.
- sender_claimed_config_epoch is R0's epoch since R4 is a replica, and R0 is R4's primary.
- nodeEpoch(sender_claimed_primary) == sender_claimed_config_epoch, so the logic fail and we process
  a stale packet. So in this point, the packet is not a stale packet in R4 and R0's view.
- But it is a stale packet in myself (R7) view. In R7's local view, R4 is the new primary and it
  should have a bigger epoch, that is nodeEpoch(sender) should > sender_claimed_config_epoch.

## Fix
The PR fixes the issue by enhancing the existing guardrail logic against stale packet. Previously
that logic only detects `nodeEpoch(sender_claimed_primary) > sender_claimed_config_epoch` as stale
packet, now it also checks `nodeEpoch(sender) > sender_claimed_config_epoch` to make sure we have
up-to-date primary-replica chain.

Signed-off-by: Zhijun <dszhijun@gmail.com>
Co-authored-by: Binbin <binloveplay1314@qq.com>
(cherry picked from commit 8bb8d91)
sarthakaggarwal97 pushed a commit that referenced this pull request Nov 18, 2026
…ty primary (#2811)

## Summary
This PR handles a network race condition that would cause a replica to read stale cluster
packet and then incorrectly promote itself to an empty primary within an existing shard.

## Issue
"Migrated replica reports zero repl offset and rank, and fails to win election - sigstop"
the test case in `replica-migration.tcl` is a known example where the network race condition
can occur.

Here's the timeline:
- T1: Slot migration β€” R7 and R3 both try to replicate from R0. Only R3 succeeds, triggering
  a BGSAVE on R0, while R7 blocks in `receiveSynchronousResponse()`.
- T2: While R7 is blocked, R0 is SIGSTOP'd by the test. R4 wins the election and becomes the
  new primary. R4 sends PINGs to R7 - These PINGs land in R7's kernel TCP receive buffer but
  are not read by R7 yet.
- T3 (5s after T1, due to receiveSynchronousResponse): R7 wakes up:
  - It reads from inbound links and finds out the remote nodes have already closed their end
    (they detected R7 as FAIL), getting "I/O error: connection closed" on each. R7 calls `accept()`
    for the new connections that were established during the block. These connections carry data
    that was sent seconds ago while R7 was dead.
  - R7's outbound links are still valid, so it sends PING to R4.
- T4: R7 receives and processes fresh PONG packet from R4 on outbound link, reconfiguring itself
  to follow R4.
- T5: R7 reads stale PING packet of R4 via inbound link. This packet was generated R4 was following
  R0, so R7 incorrectly believes R4 is still following R0 now. And Reconfiguring itself as a replica
  of R0 from R4.
- T6: R7 finds R0 is FAIL, so it starts an election and wins, and becomes an empty-primary.

## Analyze
So in T4, R4 is the new primary, and R7 is reconfiguring itself as a replica. So in R7's view,
R4 is the primary, and myself (R7) is a replica.

And in T5, there is a stale packet from sender (R4), the stale packet is saying: sender (R4) is
a replica and R0 is the primary.

We originally had a logic for stale packet, meaning we would try to ignore stale packet that
would cause exceptions. So in T5:
- sender_claims_to_be_primary is false since R4 is saying it is a replica.
- sender_last_reported_as_primary is true since in R7's view, R4 is a primary.
- sender_claimed_primary is R0, and sender (R4) and sender_claimed_primary (R0) is in the same shard.
- nodeEpoch(sender_claimed_primary) is R0's epoch. R0 is an old and dead (not yet) primary.
- sender_claimed_config_epoch is R0's epoch since R4 is a replica, and R0 is R4's primary.
- nodeEpoch(sender_claimed_primary) == sender_claimed_config_epoch, so the logic fail and we process
  a stale packet. So in this point, the packet is not a stale packet in R4 and R0's view.
- But it is a stale packet in myself (R7) view. In R7's local view, R4 is the new primary and it
  should have a bigger epoch, that is nodeEpoch(sender) should > sender_claimed_config_epoch.

## Fix
The PR fixes the issue by enhancing the existing guardrail logic against stale packet. Previously
that logic only detects `nodeEpoch(sender_claimed_primary) > sender_claimed_config_epoch` as stale
packet, now it also checks `nodeEpoch(sender) > sender_claimed_config_epoch` to make sure we have
up-to-date primary-replica chain.

Signed-off-by: Zhijun <dszhijun@gmail.com>
Co-authored-by: Binbin <binloveplay1314@qq.com>
(cherry picked from commit 8bb8d91)
enjoy-binbin pushed a commit that referenced this pull request Nov 23, 2026
Fixes #5439 #5458

A node can crash on `debugServerAssert(primary->replicaof == NULL)` in
`clusterNodeGetPrimary()`, reached through `updateShardId()` from
`clusterProcessPacket()`.

### Cause

A node that resumes after a long pause handles a backlog of old gossip:

1. An old packet from R12 says it replicates R15, so the node sets
`R12->replicaof = R15`. The node never learns that R12 became a primary.
2. A newer packet from R15 says it replicates R12. R15 was last seen as
a replica, so this goes through the unguarded "Primary node changed for
this replica?" block, which sets `R15->replicaof = R12`.
3. Now R12 and R15 replicate each other, and the next `updateShardId()`
asserts.

### Fix

Skip a replica claim, and log it at NOTICE, when the claimed primary's
`replicaof` chain already reaches the sender. The claimed primary's own
packet then corrects the view.

- No node is promoted on another node's word, which was the objection to
#2441. This is the same kind of stale-claim handling as #2811, and the
assertion from #651 is unchanged.
- The check walks the whole chain, so it also catches longer loops such
as A β†’ B β†’ C β†’ A. The walk stops after as many steps as there are nodes,
so it ends even if the chain already contains a loop.

### Tests

New `tests/unit/cluster/replicaof-cycle.tcl` sends forged replica-claim
PINGs, as in `failover-nack.tcl`, to create 2-node and 3-node loops on
an observer node.


### Open questions

This PR stops new replicaof cycles from forming at runtime. It does not
handle a cycle that is already saved in `nodes.conf`. A release build
without debug asserts can save one, because this same bug goes unchecked
there.

The risk if such a file is loaded: `clusterLoadConfig()` restores the
links without checking them. With A ↔ B loaded, a claim from another
node C naming A links C under the cycle. `clusterNodeGetPrimary(C)` then
never returns, and the node hangs at 100% CPU. This behaves the same on
`unstable`, so this PR does not make it worse.

1. **Should it be handled in this PR or in a follow-up?**
2. **Repair or reject at load?**
- **Repair:** unlink one node in each cycle, never `myself`, log a
WARNING and save the config. That node stays a replica with no known
primary until its own packets correct the view. Nodes that saved a cycle
on an older build keep starting. This matches how the loader already
fixes a mismatched replica shard_id instead of aborting.
- **Reject:** fail to start with "corrupted cluster config file". This
is stricter, since the file alone can't tell which link is stale. The
cost is that an affected node needs its `nodes.conf` fixed by hand
before it can restart, including after an upgrade.

Signed-off-by: Bara' Hasheesh <bara.hasheesh@gmail.com>
valkeyrie-ops Bot pushed a commit that referenced this pull request Nov 25, 2026
Fixes #5439 #5458

A node can crash on `debugServerAssert(primary->replicaof == NULL)` in
`clusterNodeGetPrimary()`, reached through `updateShardId()` from
`clusterProcessPacket()`.

### Cause

A node that resumes after a long pause handles a backlog of old gossip:

1. An old packet from R12 says it replicates R15, so the node sets
`R12->replicaof = R15`. The node never learns that R12 became a primary.
2. A newer packet from R15 says it replicates R12. R15 was last seen as
a replica, so this goes through the unguarded "Primary node changed for
this replica?" block, which sets `R15->replicaof = R12`.
3. Now R12 and R15 replicate each other, and the next `updateShardId()`
asserts.

### Fix

Skip a replica claim, and log it at NOTICE, when the claimed primary's
`replicaof` chain already reaches the sender. The claimed primary's own
packet then corrects the view.

- No node is promoted on another node's word, which was the objection to
#2441. This is the same kind of stale-claim handling as #2811, and the
assertion from #651 is unchanged.
- The check walks the whole chain, so it also catches longer loops such
as A β†’ B β†’ C β†’ A. The walk stops after as many steps as there are nodes,
so it ends even if the chain already contains a loop.

### Tests

New `tests/unit/cluster/replicaof-cycle.tcl` sends forged replica-claim
PINGs, as in `failover-nack.tcl`, to create 2-node and 3-node loops on
an observer node.

### Open questions

This PR stops new replicaof cycles from forming at runtime. It does not
handle a cycle that is already saved in `nodes.conf`. A release build
without debug asserts can save one, because this same bug goes unchecked
there.

The risk if such a file is loaded: `clusterLoadConfig()` restores the
links without checking them. With A ↔ B loaded, a claim from another
node C naming A links C under the cycle. `clusterNodeGetPrimary(C)` then
never returns, and the node hangs at 100% CPU. This behaves the same on
`unstable`, so this PR does not make it worse.

1. **Should it be handled in this PR or in a follow-up?**
2. **Repair or reject at load?**
- **Repair:** unlink one node in each cycle, never `myself`, log a
WARNING and save the config. That node stays a replica with no known
primary until its own packets correct the view. Nodes that saved a cycle
on an older build keep starting. This matches how the loader already
fixes a mismatched replica shard_id instead of aborting.
- **Reject:** fail to start with "corrupted cluster config file". This
is stricter, since the file alone can't tell which link is stale. The
cost is that an affected node needs its `nodes.conf` fixed by hand
before it can restart, including after an upgrade.

Signed-off-by: Bara' Hasheesh <bara.hasheesh@gmail.com>
Backport-Source-PR: 5452
valkeyrie-ops Bot pushed a commit that referenced this pull request Nov 25, 2026
Fixes #5439 #5458

A node can crash on `debugServerAssert(primary->replicaof == NULL)` in
`clusterNodeGetPrimary()`, reached through `updateShardId()` from
`clusterProcessPacket()`.

### Cause

A node that resumes after a long pause handles a backlog of old gossip:

1. An old packet from R12 says it replicates R15, so the node sets
`R12->replicaof = R15`. The node never learns that R12 became a primary.
2. A newer packet from R15 says it replicates R12. R15 was last seen as
a replica, so this goes through the unguarded "Primary node changed for
this replica?" block, which sets `R15->replicaof = R12`.
3. Now R12 and R15 replicate each other, and the next `updateShardId()`
asserts.

### Fix

Skip a replica claim, and log it at NOTICE, when the claimed primary's
`replicaof` chain already reaches the sender. The claimed primary's own
packet then corrects the view.

- No node is promoted on another node's word, which was the objection to
#2441. This is the same kind of stale-claim handling as #2811, and the
assertion from #651 is unchanged.
- The check walks the whole chain, so it also catches longer loops such
as A β†’ B β†’ C β†’ A. The walk stops after as many steps as there are nodes,
so it ends even if the chain already contains a loop.

### Tests

New `tests/unit/cluster/replicaof-cycle.tcl` sends forged replica-claim
PINGs, as in `failover-nack.tcl`, to create 2-node and 3-node loops on
an observer node.

### Open questions

This PR stops new replicaof cycles from forming at runtime. It does not
handle a cycle that is already saved in `nodes.conf`. A release build
without debug asserts can save one, because this same bug goes unchecked
there.

The risk if such a file is loaded: `clusterLoadConfig()` restores the
links without checking them. With A ↔ B loaded, a claim from another
node C naming A links C under the cycle. `clusterNodeGetPrimary(C)` then
never returns, and the node hangs at 100% CPU. This behaves the same on
`unstable`, so this PR does not make it worse.

1. **Should it be handled in this PR or in a follow-up?**
2. **Repair or reject at load?**
- **Repair:** unlink one node in each cycle, never `myself`, log a
WARNING and save the config. That node stays a replica with no known
primary until its own packets correct the view. Nodes that saved a cycle
on an older build keep starting. This matches how the loader already
fixes a mismatched replica shard_id instead of aborting.
- **Reject:** fail to start with "corrupted cluster config file". This
is stricter, since the file alone can't tell which link is stale. The
cost is that an affected node needs its `nodes.conf` fixed by hand
before it can restart, including after an upgrade.

Signed-off-by: Bara' Hasheesh <bara.hasheesh@gmail.com>
Backport-Source-PR: 5452
ranshid pushed a commit that referenced this pull request Nov 25, 2026
Fixes #5439 #5458

A node can crash on `debugServerAssert(primary->replicaof == NULL)` in
`clusterNodeGetPrimary()`, reached through `updateShardId()` from
`clusterProcessPacket()`.

### Cause

A node that resumes after a long pause handles a backlog of old gossip:

1. An old packet from R12 says it replicates R15, so the node sets
`R12->replicaof = R15`. The node never learns that R12 became a primary.
2. A newer packet from R15 says it replicates R12. R15 was last seen as
a replica, so this goes through the unguarded "Primary node changed for
this replica?" block, which sets `R15->replicaof = R12`.
3. Now R12 and R15 replicate each other, and the next `updateShardId()`
asserts.

### Fix

Skip a replica claim, and log it at NOTICE, when the claimed primary's
`replicaof` chain already reaches the sender. The claimed primary's own
packet then corrects the view.

- No node is promoted on another node's word, which was the objection to
#2441. This is the same kind of stale-claim handling as #2811, and the
assertion from #651 is unchanged.
- The check walks the whole chain, so it also catches longer loops such
as A β†’ B β†’ C β†’ A. The walk stops after as many steps as there are nodes,
so it ends even if the chain already contains a loop.

### Tests

New `tests/unit/cluster/replicaof-cycle.tcl` sends forged replica-claim
PINGs, as in `failover-nack.tcl`, to create 2-node and 3-node loops on
an observer node.

### Open questions

This PR stops new replicaof cycles from forming at runtime. It does not
handle a cycle that is already saved in `nodes.conf`. A release build
without debug asserts can save one, because this same bug goes unchecked
there.

The risk if such a file is loaded: `clusterLoadConfig()` restores the
links without checking them. With A ↔ B loaded, a claim from another
node C naming A links C under the cycle. `clusterNodeGetPrimary(C)` then
never returns, and the node hangs at 100% CPU. This behaves the same on
`unstable`, so this PR does not make it worse.

1. **Should it be handled in this PR or in a follow-up?**
2. **Repair or reject at load?**
- **Repair:** unlink one node in each cycle, never `myself`, log a
WARNING and save the config. That node stays a replica with no known
primary until its own packets correct the view. Nodes that saved a cycle
on an older build keep starting. This matches how the loader already
fixes a mismatched replica shard_id instead of aborting.
- **Reject:** fail to start with "corrupted cluster config file". This
is stricter, since the file alone can't tell which link is stale. The
cost is that an affected node needs its `nodes.conf` fixed by hand
before it can restart, including after an upgrade.

Signed-off-by: Bara' Hasheesh <bara.hasheesh@gmail.com>
Backport-Source-PR: 5452
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-notes This issue should get a line item in the release notes

Projects

Status: Don't backport yet
Status: Don't backport yet
Status: Done
Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants