Skip to content

*: br,lightning,import use meta service group#69780

Open
ystaticy wants to merge 3 commits into
pingcap:masterfrom
ystaticy:msg_br_lighting_import
Open

*: br,lightning,import use meta service group#69780
ystaticy wants to merge 3 commits into
pingcap:masterfrom
ystaticy:msg_br_lighting_import

Conversation

@ystaticy

@ystaticy ystaticy commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: close #xxx

Problem Summary:

What changed and how does it work?

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test
    • I checked and no code files have been changed.

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

Please refer to Release Notes Language Style Guide to write a quality release note.

None

Summary by CodeRabbit

  • New Features
    • Improved etcd connectivity for keyspace-aware deployments.
    • Automatically resolves metadata service group endpoints and applies the correct keyspace namespace when connecting to etcd.
    • Supports secure (TLS) connections while resolving and dialing etcd targets.
  • Tests
    • Added integration coverage validating metadata service group usage and namespace-aware key storage for backup/restore and Lightning import workflows.
    • Added an etcd CLI regression test to ensure namespace derivation and key placement are correct.
  • Chores
    • Updated Bazel build wiring and expanded test dependencies; adjusted test shard configuration.

Signed-off-by: ystaticy <y_static_y@sina.com>
@ti-chi-bot

ti-chi-bot Bot commented Jul 12, 2026

Copy link
Copy Markdown

[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 benjamin2037, yujuncen 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/XL Denotes a PR that changes 500-999 lines, ignoring generated files. label Jul 12, 2026
@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

BR and Lightning etcd dialing now uses PD keyspace metadata to resolve metaservice endpoints and namespaces. Metaservice exposes the resolution API, while integration tests verify namespaced writes in BR, Lightning, and store packages.

Changes

Keyspace-aware etcd resolution

Layer / File(s) Summary
Metaservice etcd dial resolution
pkg/metaservice/etcd.go, pkg/metaservice/BUILD.bazel
Adds EtcdDialInfo and ResolveEtcdDialInfo to resolve endpoints and derive keyspace namespaces.
BR task etcd dialing
br/pkg/task/common.go, br/pkg/task/meta_service_group_test.go, br/pkg/task/BUILD.bazel
BR task dialing loads keyspace metadata, resolves metaservice groups, applies namespaces, and tests namespaced restore registration.
Lightning importer etcd dialing
lightning/pkg/importer/precheck_impl.go, lightning/pkg/importer/meta_service_group_test.go, lightning/pkg/importer/BUILD.bazel
Lightning adopts the same resolution flow and verifies namespaced task registration.
Store namespace validation
pkg/store/etcd_test.go, pkg/store/BUILD.bazel
Store test infrastructure carries a TiKV codec and verifies writes under the derived namespace.

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

Sequence Diagram(s)

sequenceDiagram
  participant Task as dialEtcdWithCfg
  participant PD as PD client
  participant Meta as ResolveEtcdDialInfo
  participant Etcd as etcd client
  Task->>PD: Load keyspace metadata
  Task->>Meta: Resolve endpoints and namespace
  Meta-->>Task: Return EtcdDialInfo
  Task->>Etcd: Connect to resolved endpoints
  Task->>Etcd: Apply keyspace namespace
Loading

Possibly related PRs

  • pingcap/tidb#58561: Related PD client construction and keyspace API context handling.
  • pingcap/tidb#68818: Related metaservice-based etcd dialing and keyspace namespace resolution.

Suggested labels: component/import

Suggested reviewers: D3Hunter, YuJuncen, YangKeao

Poem

I’m a rabbit with keys in my paw,
Guiding etcd by metadata law.
Through PD paths I hop and roam,
Namespaced writes arrive safely home.
BR and Lightning share the trail—
One fluffy leap, one tested tale!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is just the template and lacks the required issue number, problem summary, change details, tests, side effects, and release note. Fill in the issue reference, summary, implementation details, test checklist, side effects, and release note.
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately reflects the main change: switching BR, Lightning, and Import to use the meta service group.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="Running error: context loading failed: failed to load packages: failed to load packages: failed to load with go/packages: context deadline exceeded"
level=error msg="Timeout exceeded: try increasing it by passing --timeout option"


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.

🧹 Nitpick comments (1)
pkg/store/etcd_test.go (1)

83-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider using metaservice.GroupIDKey and metaservice.GroupAddrsKey constants instead of string literals.

The Lightning test (lightning/pkg/importer/meta_service_group_test.go:64-65) uses the metaservice package constants for these config keys, while this test uses raw string literals. If the constant values ever change, this test would break silently. Using the constants would require adding //pkg/metaservice to the store_test BUILD.bazel deps.

♻️ Optional refactor for consistency
 		Config: map[string]string{
 			"gc_management_type":       "keyspace_level",
-			"meta_service_group_id":    "group1",
-			"meta_service_group_addrs": strings.Join(metaCluster.Client(0).Endpoints(), ","),
+			metaservice.GroupIDKey:     "group1",
+			metaservice.GroupAddrsKey:   strings.Join(metaCluster.Client(0).Endpoints(), ","),
 		}

This would also require adding the import and BUILD.bazel dependency:

+	"github.com/pingcap/tidb/pkg/metaservice"

In pkg/store/BUILD.bazel:

+        "//pkg/metaservice",
🤖 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/store/etcd_test.go` around lines 83 - 84, Replace the raw
"meta_service_group_id" and "meta_service_group_addrs" keys in the test
configuration with metaservice.GroupIDKey and metaservice.GroupAddrsKey. Add the
metaservice import and declare the corresponding //pkg/metaservice dependency in
the store_test BUILD.bazel target.
🤖 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/store/etcd_test.go`:
- Around line 83-84: Replace the raw "meta_service_group_id" and
"meta_service_group_addrs" keys in the test configuration with
metaservice.GroupIDKey and metaservice.GroupAddrsKey. Add the metaservice import
and declare the corresponding //pkg/metaservice dependency in the store_test
BUILD.bazel target.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 1b1a3e6e-bb12-4902-80ab-d18c8dda4ab3

📥 Commits

Reviewing files that changed from the base of the PR and between b94006d and d6df859.

📒 Files selected for processing (10)
  • br/pkg/task/BUILD.bazel
  • br/pkg/task/common.go
  • br/pkg/task/meta_service_group_test.go
  • lightning/pkg/importer/BUILD.bazel
  • lightning/pkg/importer/meta_service_group_test.go
  • lightning/pkg/importer/precheck_impl.go
  • pkg/metaservice/BUILD.bazel
  • pkg/metaservice/etcd.go
  • pkg/store/BUILD.bazel
  • pkg/store/etcd_test.go

@codecov

codecov Bot commented Jul 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 25.75758% with 49 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.8561%. Comparing base (b94006d) to head (5580cdb).

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #69780        +/-   ##
================================================
- Coverage   76.3194%   75.8561%   -0.4634%     
================================================
  Files          2041       2082        +41     
  Lines        560102     580342     +20240     
================================================
+ Hits         427467     440225     +12758     
- Misses       131734     137995      +6261     
- Partials        901       2122      +1221     
Flag Coverage Δ
integration 45.7819% <25.7575%> (+6.0766%) ⬆️

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

Components Coverage Δ
dumpling 60.4471% <ø> (ø)
parser ∅ <ø> (∅)
br 63.6790% <90.0000%> (+0.9577%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

ystaticy added 2 commits July 12, 2026 21:45
Signed-off-by: ystaticy <y_static_y@sina.com>
Signed-off-by: ystaticy <y_static_y@sina.com>
@ti-chi-bot

ti-chi-bot Bot commented Jul 12, 2026

Copy link
Copy Markdown

[FORMAT CHECKER NOTIFICATION]

Notice: To remove the do-not-merge/needs-linked-issue label, please provide the linked issue number on one line in the PR body, for example: Issue Number: close #123 or Issue Number: ref #456.

📖 For more info, you can check the "Contribute Code" section in the development guide.


Notice: To remove the do-not-merge/needs-tests-checked label, please finished the tests then check the finished items in description.

For example:

Tests <!-- At least one of them must be included. -->

- [x] Unit test
- [ ] Integration test
- [ ] Manual test (add detailed scripts or steps below)
- [ ] No code

‼️ Must keep the HTML comments <!-- At least one of them must be included. -->

📖 For more info, you can check the "Contribute Code" section in the development guide.

@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)
br/pkg/task/common.go (1)

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

Consider updating the log message to reflect post-connection state.

With grpc.WithBlock() in the dial options, DialEtcdClient blocks until the etcd connection is established. By the time line 222 executes, the connection is already active, so "trying to connect to etcd" is slightly misleading. Consider "connected to etcd" for accuracy.

✏️ Proposed tweak
-	log.Info("trying to connect to etcd", zap.Strings("addr", etcdCLI.Endpoints()))
+	log.Info("connected to etcd", zap.Strings("addr", etcdCLI.Endpoints()))
🤖 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 `@br/pkg/task/common.go` at line 222, Update the log message in DialEtcdClient
after the blocking etcd dial to state that the client is connected rather than
still trying to connect, while preserving the existing endpoint fields.
🤖 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/metaservice/etcd.go`:
- Around line 77-126: Update the missing-metadata error in DialEtcdClient to
include the keyspaceName value, while preserving the existing error path and
message meaning.

---

Nitpick comments:
In `@br/pkg/task/common.go`:
- Line 222: Update the log message in DialEtcdClient after the blocking etcd
dial to state that the client is connected rather than still trying to connect,
while preserving the existing endpoint fields.
🪄 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 78a32d2f-21e3-4bf3-899e-1665759aa001

📥 Commits

Reviewing files that changed from the base of the PR and between d6df859 and 5580cdb.

📒 Files selected for processing (9)
  • br/pkg/task/BUILD.bazel
  • br/pkg/task/common.go
  • br/pkg/task/meta_service_group_test.go
  • lightning/pkg/importer/BUILD.bazel
  • lightning/pkg/importer/meta_service_group_test.go
  • lightning/pkg/importer/precheck_impl.go
  • pkg/metaservice/BUILD.bazel
  • pkg/metaservice/etcd.go
  • pkg/store/etcd_test.go
💤 Files with no reviewable changes (2)
  • lightning/pkg/importer/BUILD.bazel
  • br/pkg/task/BUILD.bazel
🚧 Files skipped from review as they are similar to previous changes (4)
  • lightning/pkg/importer/meta_service_group_test.go
  • br/pkg/task/meta_service_group_test.go
  • pkg/store/etcd_test.go
  • lightning/pkg/importer/precheck_impl.go

Comment thread pkg/metaservice/etcd.go
Comment on lines +77 to +126
// DialEtcdClient resolves the target meta service group and returns a namespaced etcd client.
func DialEtcdClient(
ctx context.Context,
keyspaceName string,
pdAddrs []string,
security pd.SecurityOption,
pdClientFactory PDClientFactory,
callerComponent caller.Component,
pdClientOpts []opt.ClientOption,
etcdCfg clientv3.Config,
) (*clientv3.Client, error) {
if pdClientFactory == nil {
pdClientFactory = pd.NewClientWithAPIContext
}

pdCli, err := pdClientFactory(
ctx, keyspace.BuildAPIContext(keyspaceName), callerComponent, pdAddrs, security, pdClientOpts...,
)
if err != nil {
return nil, err
}
defer pdCli.Close()

var keyspaceMeta *keyspacepb.KeyspaceMeta
if keyspaceName != "" {
keyspaceMeta, err = pdCli.LoadKeyspace(ctx, keyspaceName)
if err != nil {
return nil, err
}
if keyspaceMeta == nil {
return nil, errors.New("keyspace meta not found")
}
}

dialInfo, err := ResolveEtcdDialInfo(ctx, pdCli, keyspaceMeta)
if err != nil {
return nil, err
}

etcdCfg.Context = ctx
etcdCfg.Endpoints = dialInfo.Endpoints
etcdCli, err := clientv3.New(etcdCfg)
if err != nil {
return nil, err
}
if dialInfo.Namespace != "" {
etcd.SetEtcdCliByNamespace(etcdCli, dialInfo.Namespace)
}
return etcdCli, nil
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Include keyspace name in the "not found" error message.

The error at line 107 (errors.New("keyspace meta not found")) is actionable but lacks context — when multiple keyspaces are in play, the operator cannot tell which keyspace failed to resolve. Adding the keyspace name makes triage significantly easier.

🛡️ Proposed fix
 	if keyspaceMeta == nil {
-		return nil, errors.New("keyspace meta not found")
+		return nil, errors.Errorf("keyspace meta not found for keyspace %q", keyspaceName)
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// DialEtcdClient resolves the target meta service group and returns a namespaced etcd client.
func DialEtcdClient(
ctx context.Context,
keyspaceName string,
pdAddrs []string,
security pd.SecurityOption,
pdClientFactory PDClientFactory,
callerComponent caller.Component,
pdClientOpts []opt.ClientOption,
etcdCfg clientv3.Config,
) (*clientv3.Client, error) {
if pdClientFactory == nil {
pdClientFactory = pd.NewClientWithAPIContext
}
pdCli, err := pdClientFactory(
ctx, keyspace.BuildAPIContext(keyspaceName), callerComponent, pdAddrs, security, pdClientOpts...,
)
if err != nil {
return nil, err
}
defer pdCli.Close()
var keyspaceMeta *keyspacepb.KeyspaceMeta
if keyspaceName != "" {
keyspaceMeta, err = pdCli.LoadKeyspace(ctx, keyspaceName)
if err != nil {
return nil, err
}
if keyspaceMeta == nil {
return nil, errors.New("keyspace meta not found")
}
}
dialInfo, err := ResolveEtcdDialInfo(ctx, pdCli, keyspaceMeta)
if err != nil {
return nil, err
}
etcdCfg.Context = ctx
etcdCfg.Endpoints = dialInfo.Endpoints
etcdCli, err := clientv3.New(etcdCfg)
if err != nil {
return nil, err
}
if dialInfo.Namespace != "" {
etcd.SetEtcdCliByNamespace(etcdCli, dialInfo.Namespace)
}
return etcdCli, nil
}
if keyspaceMeta == nil {
return nil, errors.Errorf("keyspace meta not found for keyspace %q", keyspaceName)
}
🤖 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/metaservice/etcd.go` around lines 77 - 126, Update the missing-metadata
error in DialEtcdClient to include the keyspaceName value, while preserving the
existing error path and message meaning.

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

Labels

do-not-merge/needs-linked-issue do-not-merge/needs-tests-checked release-note-none Denotes a PR that doesn't merit a release note. size/XL Denotes a PR that changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant