Skip to content

mcs: skip transferring primary to itself#10970

Merged
ti-chi-bot[bot] merged 5 commits into
tikv:masterfrom
lhy1024:lhy/fix-tso-self-transfer-primary
Jul 6, 2026
Merged

mcs: skip transferring primary to itself#10970
ti-chi-bot[bot] merged 5 commits into
tikv:masterfrom
lhy1024:lhy/fix-tso-self-transfer-primary

Conversation

@lhy1024

@lhy1024 lhy1024 commented Jul 2, 2026

Copy link
Copy Markdown
Member

What problem does this PR solve?

Issue Number: Close #10969

When a TSO primary transfer request specifies the current TSO primary itself as new_primary, the current MCS transfer logic treats it as a real transfer rather than a no-op.

That behavior is not expected. It can revoke the expected-primary lease, rewrite the expected-primary key, make the current primary exit the expected-primary watch loop, and force unnecessary primary churn.

This was observed during a TiDB Cloud TiDBX rolling-upgrade investigation. The confirmed TSO log sequence was:

  1. 2026-07-02T12:18:32.177Z: old primary db-b5b0db46-d8u65q started transfer: from=db-b5b0db46-d8u65q, to=db-b5b0db46-bq855y.
  2. 2026-07-02T12:18:32.196Z: db-b5b0db46-bq855y logged campaign tso primary ok.
  3. 2026-07-02T12:18:32.209Z: db-b5b0db46-bq855y received another transfer request: from=db-b5b0db46-bq855y, to=db-b5b0db46-bq855y.
  4. 2026-07-02T12:18:32.216Z: db-b5b0db46-bq855y logged revoke lease failed, primary exit the primary watch loop, and the TSO primary will step down.
  5. 2026-07-02T12:18:33.228Z: db-b5b0db46-bq855y received the same self-transfer request again.
  6. 2026-07-02T12:18:33.249Z: db-b5b0db46-d8u65q logged campaign tso primary ok.
  7. 2026-07-02T12:18:33.260Z: db-b5b0db46-bq855y logged campaign tso primary meets error due to txn conflict.

The rollout was later observed with TSOGroup updatedReplicas=1/2, db-b5b0db46-d8u65q isDefaultPrimary=true, and db-b5b0db46-d8u65q still on the old revision with PodNotUpToDate.

This PR fixes the confirmed PD-side self-transfer behavior. It does not claim that the long-term rollout stuck state was caused only by PD. TCMS artifacts available in this investigation did not include the real controller/reconcile logs. A control-plane owner pointed out a separate likely control-plane issue: after a transfer request succeeds, the rollout expects to poll and observe the leader change; if the primary changes back before polling observes the expected state, the control-plane state machine may fail to continue or retry. That poll/retry behavior should be fixed or confirmed on the control-plane/operator side.

This PR is still needed because transfer-to-current-primary should be a no-op. In this incident, the control plane/operator request was the trigger: after bq855y had already become primary, another transfer request targeting bq855y itself exposed this PD behavior. Removing this unnecessary primary churn avoids creating or amplifying that race window.

What is changed and how does it work?

mcs: skip transferring primary to itself

Treat an explicit transfer request to the current primary as a no-op before
revoking the existing expected-primary lease. This keeps random transfer
(`new_primary == ""`) behavior unchanged while preventing control-plane
self-transfer requests from forcing the active primary to leave the primary role.

The fix detects whether new_primary and oldPrimary refer to the same registered MCS member, either by member name or service address. If they do, TransferPrimary returns success without changing etcd state or closing the current lease.

Validation

Unit tests:

go test ./pkg/mcs/utils -run 'TestTransferPrimary.*' -count=1

TiUP real-process validation:

  • Deployed a local TiUP cluster with PD microservices: 1 PD, 2 TSO, 1 Scheduling, minimal TiDB/TiKV.
  • Current TSO primary: http://127.0.0.1:13380.
  • Simulated the control-plane request:
curl -X POST http://127.0.0.1:13380/tso/api/v1/primary/transfer \
  -H 'Content-Type: application/json' \
  -d '{"new_primary":"tso-127.0.0.1-13380"}'

Before this fix, the request returned HTTP 200, but the primary performed a real self-transfer and left the primary role:

try to transfer primary service=tso from=tso-127.0.0.1-13380 to=tso-127.0.0.1-13380
current leadership is deleted leader-key=.../tso/00000/primary/expected_primary
set expected primary flag primary=http://127.0.0.1:13380
revoke lease failed error="etcdserver: requested lease not found"
primary exit the primary watch loop
no longer be primary because primary have been updated, the TSO primary will step down
campaign tso primary ok name=http://127.0.0.1:13380-00000

After this fix, the same request returns HTTP 200 and only logs the no-op path:

try to transfer primary service=tso from=tso-127.0.0.1-13380 to=tso-127.0.0.1-13380
skip transferring primary to itself service=tso primary=tso-127.0.0.1-13380

No leadership delete, expected-primary rewrite, lease revoke, watch-loop exit, primary role leave, or re-campaign is observed.

Check List

Tests

  • Unit test
  • Manual test (TiUP real-process validation above)

Code changes

  • No configuration change
  • No HTTP API change
  • No persistent data format change

Side effects

  • No expected performance regression
  • No breaking backward compatibility

Related changes

  • A separate control-plane/operator fix may still be needed to handle the transfer-poll race and continue/retry rollout if the primary changes back before polling observes the expected handoff.
  • Need to cherry-pick to the affected release branch if the control-plane rolling-upgrade flow can send this self-transfer request there.

Release note

Fix an issue where a TSO primary transfer request targeting the current primary itself could unnecessarily make the primary leave and re-campaign for the primary role.

Summary by CodeRabbit

  • Bug Fixes
    • Improved primary transfer behavior: when the target primary represents the same member, the expected-primary lease and metadata are preserved (no unnecessary updates).
    • Made primary/member matching more consistent by treating both service name and service address as valid identifiers.
    • Updated secondary-candidate selection logic to use consistent matching, preventing incorrect comparisons.
  • Tests
    • Added coverage for expected-primary lease preservation and correct updates during random/selection-based transfers.

@ti-chi-bot ti-chi-bot Bot added release-note Denotes a PR that will be considered when it comes time to generate release notes. do-not-merge/needs-triage-completed dco-signoff: yes Indicates the PR's author has signed the dco. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Jul 2, 2026
@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

TransferPrimary now treats the current primary as a no-op target when the requested primary matches by name or service address, and the tests verify expected-primary lease and revision behavior for self-transfer and random-transfer paths.

Changes

TSO Self-Transfer No-Op

Layer / File(s) Summary
isSamePrimary helper and candidate selection update
pkg/mcs/utils/expected_primary.go
Adds isSamePrimary matching by Name or ServiceAddr, and updates the newPrimary != "" candidate predicate to use it.
Early self-transfer no-op guard
pkg/mcs/utils/expected_primary.go
Adds an early return in TransferPrimary when newPrimary and oldPrimary resolve to the same member.
Integration tests for transfer behavior
pkg/mcs/utils/expected_primary_test.go
Adds etcd-backed setup helpers plus tests for self-transfer no-op behavior and the existing random-transfer path.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • tikv/pd#10146: Adds the /primary/transfer endpoint that calls utils.TransferPrimary, so it depends on the transfer semantics changed here.

Suggested reviewers: rleungx, bufferflies, niubell

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: skipping self-transfers of the primary.
Description check ✅ Passed The description follows the template closely and includes the issue number, problem, change details, validation, checklist, and release note.
Linked Issues check ✅ Passed The fix makes self-transfer a no-op and preserves the expected-primary lease, matching the requirements in #10969.
Out of Scope Changes check ✅ Passed The changes stay focused on self-transfer handling and tests, with no unrelated or out-of-scope functionality added.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Signed-off-by: lhy1024 <19542290+lhy1024@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
pkg/mcs/utils/expected_primary_test.go (1)

138-144: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Move ctx to the first parameter position.

putRegistryEntry performs an external etcd write with ctx, so context.Context should be the first parameter. Callers at Lines 50-51 and 106-107 need updating accordingly.

As per coding guidelines: "First parameter must be context.Context for external effects; never store contexts in structs".

♻️ Proposed signature change (and call sites)
 func putRegistryEntry(
+	ctx context.Context,
 	re *require.Assertions,
-	ctx context.Context,
 	client *clientv3.Client,
 	name string,
 	serviceAddr string,
 ) {

Update call sites:

-	putRegistryEntry(re, ctx, client, primaryName, primaryAddr)
-	putRegistryEntry(re, ctx, client, secondaryName, secondaryAddr)
+	putRegistryEntry(ctx, re, client, primaryName, primaryAddr)
+	putRegistryEntry(ctx, re, client, secondaryName, secondaryAddr)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/mcs/utils/expected_primary_test.go` around lines 138 - 144, Move the
context.Context argument to the first position in putRegistryEntry since it
performs an external etcd write; update the function signature to take ctx
before re and adjust all call sites that invoke putRegistryEntry accordingly,
including the ones in expected_primary_test.go referenced by the review. Keep
the rest of the parameter order unchanged so the helper remains consistent with
the coding guideline about context-first APIs.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pkg/mcs/utils/expected_primary_test.go`:
- Around line 138-144: Move the context.Context argument to the first position
in putRegistryEntry since it performs an external etcd write; update the
function signature to take ctx before re and adjust all call sites that invoke
putRegistryEntry accordingly, including the ones in expected_primary_test.go
referenced by the review. Keep the rest of the parameter order unchanged so the
helper remains consistent with the coding guideline about context-first APIs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 66d021aa-029b-45bf-80de-1e9e5d1d07f6

📥 Commits

Reviewing files that changed from the base of the PR and between d71c039 and b99c915.

📒 Files selected for processing (2)
  • pkg/mcs/utils/expected_primary.go
  • pkg/mcs/utils/expected_primary_test.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/mcs/utils/expected_primary_test.go`:
- Around line 109-136: The test creates a lease with election.NewLease but never
tears it down, so add a deferred lease.Close() in this test setup just like the
matching lease handling in TestTransferPrimaryToSelfKeepsExpectedPrimaryLease.
Keep the change local to the test that uses lease.Grant and TransferPrimary so
the etcd keep-alive goroutine is cleaned up after the assertions complete.
- Around line 138-153: The helper putRegistryEntry currently violates the revive
context-as-argument rule because context.Context is not the first parameter.
Update the function signature so ctx is the first argument, keeping client,
name, and serviceAddr after it, and then adjust every call site in
expected_primary_test.go and any related test helpers to pass ctx first. Ensure
the change is applied consistently wherever putRegistryEntry is used so CI and
static analysis pass.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 248b7a3d-7d4c-4be0-b535-bb3827329215

📥 Commits

Reviewing files that changed from the base of the PR and between b99c915 and fbbec7e.

📒 Files selected for processing (2)
  • pkg/mcs/utils/expected_primary.go
  • pkg/mcs/utils/expected_primary_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/mcs/utils/expected_primary.go

Comment thread pkg/mcs/utils/expected_primary_test.go Outdated
Comment thread pkg/mcs/utils/expected_primary_test.go
@lhy1024 lhy1024 force-pushed the lhy/fix-tso-self-transfer-primary branch from 5af893a to 08dd912 Compare July 3, 2026 04:13
Signed-off-by: lhy1024 <19542290+lhy1024@users.noreply.github.com>
@lhy1024 lhy1024 force-pushed the lhy/fix-tso-self-transfer-primary branch from 08dd912 to 5196294 Compare July 3, 2026 04:35
@codecov

codecov Bot commented Jul 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.18%. Comparing base (5c811b2) to head (209fd43).
⚠️ Report is 9 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #10970      +/-   ##
==========================================
- Coverage   79.20%   79.18%   -0.02%     
==========================================
  Files         541      541              
  Lines       75450    75640     +190     
==========================================
+ Hits        59762    59899     +137     
- Misses      11456    11495      +39     
- Partials     4232     4246      +14     
Flag Coverage Δ
unittests 79.18% <100.00%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread pkg/mcs/utils/expected_primary.go Outdated
continue
}
if (newPrimary == "" && member.Name != oldPrimary) || (newPrimary != "" && member.Name == newPrimary) {
if (newPrimary == "" && member.Name != oldPrimary) || (newPrimary != "" && isSamePrimary(member, newPrimary)) {

@bufferflies bufferflies Jul 3, 2026

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.

newPrimary != "" can be removed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I don't think the first newPrimary == "" guard can be removed. It separates the random-transfer path from the explicit-transfer path.

Example 1: random transfer.

members: A, B, C
oldPrimary: A
newPrimary: ""

In this case we should select any secondary except the old primary, so B and C are valid candidates. This is what (newPrimary == "" && member.Name != oldPrimary) does.

Example 2: explicit transfer.

members: A, B, C
oldPrimary: A
newPrimary: B

In this case we should only select B. With the current condition, only B is added:

A: false || false -> skipped
B: false || true  -> added
C: false || false -> skipped

If the first newPrimary == "" guard is removed, the condition becomes effectively member.Name != oldPrimary || isSamePrimary(member, newPrimary). Then C would also be added because C != A:

A: false || false -> skipped
B: true  || true  -> added
C: true  || false -> added

Then rand.IntN(len(primaryIDs)) may choose C, so an explicit transfer to B could unexpectedly transfer to C.

If you mean the second newPrimary != "" guard before isSamePrimary(member, newPrimary), that one is redundant because isSamePrimary already checks primary != "". But the first newPrimary == "" guard is still needed to preserve the explicit-transfer semantics.

@bufferflies bufferflies 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.

rest lgtm

lhy1024 added 2 commits July 3, 2026 16:33
Signed-off-by: lhy1024 <19542290+lhy1024@users.noreply.github.com>
Signed-off-by: lhy1024 <19542290+lhy1024@users.noreply.github.com>
@lhy1024

lhy1024 commented Jul 3, 2026

Copy link
Copy Markdown
Member Author

/retest

1 similar comment
@lhy1024

lhy1024 commented Jul 3, 2026

Copy link
Copy Markdown
Member Author

/retest

@ti-chi-bot ti-chi-bot Bot added needs-1-more-lgtm Indicates a PR needs 1 more LGTM. approved labels Jul 3, 2026
Signed-off-by: lhy1024 <19542290+lhy1024@users.noreply.github.com>
@lhy1024

lhy1024 commented Jul 3, 2026

Copy link
Copy Markdown
Member Author

@JmPotato PTAL

@lhy1024 lhy1024 requested a review from JmPotato July 6, 2026 02:20
@ti-chi-bot

ti-chi-bot Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: bufferflies, rleungx

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:
  • OWNERS [bufferflies,rleungx]

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@ti-chi-bot ti-chi-bot Bot added the lgtm label Jul 6, 2026
@ti-chi-bot ti-chi-bot Bot removed the needs-1-more-lgtm Indicates a PR needs 1 more LGTM. label Jul 6, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

[LGTM Timeline notifier]

Timeline:

  • 2026-07-03 09:34:59.566509974 +0000 UTC m=+377641.266889397: ☑️ agreed by bufferflies.
  • 2026-07-06 05:40:59.026454199 +0000 UTC m=+1045.062549245: ☑️ agreed by rleungx.

@ti-chi-bot ti-chi-bot Bot merged commit 8abdf30 into tikv:master Jul 6, 2026
33 checks passed
@lhy1024 lhy1024 deleted the lhy/fix-tso-self-transfer-primary branch July 6, 2026 06:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved dco-signoff: yes Indicates the PR's author has signed the dco. lgtm release-note Denotes a PR that will be considered when it comes time to generate release notes. size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mcs: TSO self-transfer from control plane can force primary to step down

3 participants