Skip to content

server: clean up microservice metadata in PD mode#10996

Open
rleungx wants to merge 5 commits into
tikv:masterfrom
rleungx:fix-pd-mode-switch-cleanup
Open

server: clean up microservice metadata in PD mode#10996
rleungx wants to merge 5 commits into
tikv:masterfrom
rleungx:fix-pd-mode-switch-cleanup

Conversation

@rleungx

@rleungx rleungx commented Jul 13, 2026

Copy link
Copy Markdown
Member

What problem does this PR solve?

Issue Number: Close #10990

PD cannot switch from microservice mode to normal mode and then back to
microservice mode because stale keyspace group and microservice metadata
prevents new TSO instances from becoming healthy.

What is changed and how does it work?

Clean up microservice metadata after a PD leader starts in normal mode.

The cleanup removes the default TSO keyspace group, clears default keyspace
group assignments, and deletes stale microservice registry and election keys
while preserving the TSO timestamp. It retries transient failures until the
leader exits.

Reject cleanup when non-default keyspace groups or assignments exist, or when
the default group is splitting or merging.

Add unit tests for cleanup safety and an integration test that switches between
microservice and normal modes multiple times.

Check List

Tests

  • Unit test
  • Integration test

Code changes

  • Has persistent data change

Release note

Fix an issue that prevents PD from switching from microservice mode to normal
mode and then back to microservice mode.

Summary by CodeRabbit

  • New Features
    • Added automatic background cleanup of stale microservice metadata in PD mode, triggered when the PD leader is ready to serve.
    • Cleanup validates current leadership/serving state, waits for leased keys when needed, and retries until successful, then stops.
  • Bug Fixes
    • Ensures microservice-related etcd entries and TSO keyspace assignments are fully removed during PD mode transitions, while rejecting inconsistent non-default assignments.
  • Tests
    • Expanded unit and integration coverage for idempotency, lease-handling, early return/cancellation, large batches, rejection paths, and repeated microservice↔monolith switching.

Signed-off-by: Ryan Leung <rleungx@gmail.com>
@ti-chi-bot ti-chi-bot Bot added dco-signoff: yes Indicates the PR's author has signed the dco. do-not-merge/needs-triage-completed release-note Denotes a PR that will be considered when it comes time to generate release notes. labels Jul 13, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign connor1996 for approval. For more information see the Code Review Process.
Please ensure that each of them provides their approval before proceeding.

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

Details Needs approval from an approver in each of these files:

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 size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. label Jul 13, 2026
@coderabbitai

coderabbitai Bot commented Jul 13, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3e8981e5-de41-4f52-b5b9-749cd98eda15

📥 Commits

Reviewing files that changed from the base of the PR and between ac16bb4 and ee70648.

📒 Files selected for processing (2)
  • server/microservice_cleanup.go
  • server/microservice_cleanup_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/microservice_cleanup.go

📝 Walkthrough

Walkthrough

Adds background cleanup for stale PD microservice metadata, wires it into leader readiness, and tests cleanup validation plus repeated microservice-to-monolith-to-microservice switching.

Changes

PD microservice metadata cleanup

Layer / File(s) Summary
Cleanup scheduling and metadata removal
server/microservice_cleanup.go
Adds retry scheduling, validates default TSO keyspace-group state, removes stale keyspace assignments, deletes the default group, and removes microservice etcd keys.
Leader wiring and cleanup behavior tests
server/server.go, server/microservice_cleanup_test.go
Starts cleanup after PD leader readiness and tests lease handling, scheduling termination, successful cleanup, transition detection, invalid groups or assignments, idempotence, and large metadata batches.
Repeated service-mode switching validation
tests/integrations/mcs/tso/server_test.go
Tests repeated TSO cluster restarts, PD service-mode changes, TSO availability, and complete metadata cleanup.

Estimated code review effort: 4 (Complex) | ~45 minutes

Suggested reviewers: lhy1024, jmpotato

Sequence Diagram(s)

sequenceDiagram
  participant PDServer
  participant KeyspaceStorage
  participant Etcd
  participant TSOCluster
  PDServer->>PDServer: become leader and schedule cleanup
  PDServer->>KeyspaceStorage: validate and clean keyspace metadata
  PDServer->>Etcd: delete microservice metadata
  TSOCluster->>PDServer: switch service mode and request TSO
  PDServer->>Etcd: verify cleanup state
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: cleaning up microservice metadata in PD mode.
Description check ✅ Passed The PR description matches the required template and includes the issue number, changes, tests, code changes, and release note.
Linked Issues check ✅ Passed The changes address issue #10990 by cleaning stale microservice metadata so PD can switch ms -> normal -> ms successfully.
Out of Scope Changes check ✅ Passed The added server logic, scheduling hook, and tests all support the stated microservice cleanup objective.
✨ 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.

@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: 1

🧹 Nitpick comments (1)
server/microservice_cleanup.go (1)

47-129: 🚀 Performance & Scalability | 🔵 Trivial

Consider adding a metric for cleanup outcome/retries.

This background cleanup is on a critical path for the mode-switch fix; a Prometheus counter/gauge for success, rejection, and retry counts would help operators detect a stuck cleanup loop (e.g., the txn-overflow scenario above) without grepping logs.

🤖 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 `@server/microservice_cleanup.go` around lines 47 - 129, The microservice
metadata cleanup loop lacks metrics for its outcomes and retries. Add Prometheus
counters or gauges for successful cleanup, rejected/skipped cleanup, and retry
attempts, and update them in scheduleMicroserviceMetadataCleanup and
cleanupMicroserviceMetadataInPDMode at the corresponding return and retry paths
so operators can detect stuck cleanup loops.
🤖 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 `@server/microservice_cleanup.go`:
- Around line 155-217: Reduce the batch size used by
cleanupDefaultTSOKeyspaceGroupConfig when calling LoadRangeKeyspace, leaving
enough transaction capacity for the SaveKeyspaceMeta operations performed for
loaded entries. Use an appropriate smaller scan limit so a full cleanup
transaction remains within etcd’s operation limit while preserving the existing
pagination and cleanup behavior.

---

Nitpick comments:
In `@server/microservice_cleanup.go`:
- Around line 47-129: The microservice metadata cleanup loop lacks metrics for
its outcomes and retries. Add Prometheus counters or gauges for successful
cleanup, rejected/skipped cleanup, and retry attempts, and update them in
scheduleMicroserviceMetadataCleanup and cleanupMicroserviceMetadataInPDMode at
the corresponding return and retry paths so operators can detect stuck cleanup
loops.
🪄 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: ba4c4a70-d3b5-45e5-8163-4d6454260ade

📥 Commits

Reviewing files that changed from the base of the PR and between 2b3abf1 and 256f11d.

📒 Files selected for processing (4)
  • server/microservice_cleanup.go
  • server/microservice_cleanup_test.go
  • server/server.go
  • tests/integrations/mcs/tso/server_test.go

Comment thread server/microservice_cleanup.go
rleungx added 2 commits July 13, 2026 12:12
Signed-off-by: Ryan Leung <rleungx@gmail.com>
Signed-off-by: Ryan Leung <rleungx@gmail.com>
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
putComment timed out

Signed-off-by: Ryan Leung <rleungx@gmail.com>
@rleungx

rleungx commented Jul 13, 2026

Copy link
Copy Markdown
Member Author

/retest

1 similar comment
@rleungx

rleungx commented Jul 13, 2026

Copy link
Copy Markdown
Member Author

/retest

@codecov

codecov Bot commented Jul 13, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 72.02381% with 47 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.19%. Comparing base (c2a47d8) to head (ee70648).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #10996      +/-   ##
==========================================
- Coverage   79.22%   79.19%   -0.04%     
==========================================
  Files         541      542       +1     
  Lines       75965    76152     +187     
==========================================
+ Hits        60187    60307     +120     
- Misses      11531    11574      +43     
- Partials     4247     4271      +24     
Flag Coverage Δ
unittests 79.19% <72.02%> (-0.04%) ⬇️

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.

@rleungx rleungx requested a review from JmPotato July 13, 2026 07:33
Comment thread server/microservice_cleanup.go Outdated
}
if !needsCleanup && s.client != nil {
getCtx, cancel := context.WithTimeout(ctx, etcdutil.DefaultRequestTimeout)
resp, err := s.client.Get(getCtx, microserviceEtcdPrefix(), clientv3.WithPrefix(), clientv3.WithLimit(1))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[P2] Guard cleanup while microservice keys are still leased

The later full-prefix delete can remove registry keys owned by a still-running TSO. Deleting a leased key does not close that process’s KeepAlive stream, so ServiceRegister never enters renewKeepalive and does not recreate the key. This is a low-probability lifecycle overlap rather than a general TSO outage (default-group clients can fall back to the legacy primary), but registry-dependent paths remain empty until the TSO restarts.

The fix can stay small here: always scan this prefix with WithKeysOnly(), and if any returned KV has Lease != 0, return an error before changing keyspace-group metadata. The existing 5-second cleanup retry will proceed automatically after the microservices stop and their leases disappear. No watcher or registration-side recovery is needed.

Signed-off-by: Ryan Leung <rleungx@gmail.com>
@rleungx

rleungx commented Jul 15, 2026

Copy link
Copy Markdown
Member Author

/retest

@ti-chi-bot

ti-chi-bot Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

@rleungx: The following test failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
pull-unit-test-next-gen-3 ee70648 link true /test pull-unit-test-next-gen-3

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dco-signoff: yes Indicates the PR's author has signed the dco. do-not-merge/needs-triage-completed release-note Denotes a PR that will be considered when it comes time to generate release notes. size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PD microservice mode switch blocked

2 participants