Skip to content

pd: replace client with NewClientWithAPIContext#58561

Open
lhy1024 wants to merge 1 commit intopingcap:masterfrom
lhy1024:api-context
Open

pd: replace client with NewClientWithAPIContext#58561
lhy1024 wants to merge 1 commit intopingcap:masterfrom
lhy1024:api-context

Conversation

@lhy1024
Copy link
Copy Markdown
Contributor

@lhy1024 lhy1024 commented Dec 26, 2024

What problem does this PR solve?

Issue Number: close #xxx

Problem Summary:

It is from https://github.com/tidbcloud/tidb-cse/pull/521

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

    • Keyspace name support added across backup, restore, import, and stream operations to enable keyspace-scoped PD interactions.
  • Improvements

    • PD client interactions now use keyspace-aware API contexts where applicable.
    • Retry behavior improved for timestamp generation failures when TSO leader changes (treated as retryable).

@ti-chi-bot ti-chi-bot bot added 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/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Dec 26, 2024
@tiprow
Copy link
Copy Markdown

tiprow bot commented Dec 26, 2024

Hi @lhy1024. Thanks for your PR.

PRs from untrusted users cannot be marked as trusted with /ok-to-test in this repo meaning untrusted PR authors can never trigger tests themselves. Collaborators can still trigger tests on the PR using /test all.

I understand the commands that are listed here.

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.

@codecov
Copy link
Copy Markdown

codecov bot commented Dec 26, 2024

Codecov Report

❌ Patch coverage is 68.62745% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.0000%. Comparing base (d0712ac) to head (53034d8).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #58561        +/-   ##
================================================
+ Coverage   77.5894%   79.0000%   +1.4106%     
================================================
  Files          1982       1992        +10     
  Lines        548964     549144       +180     
================================================
+ Hits         425938     433824      +7886     
+ Misses       122221     113873      -8348     
- Partials        805       1447       +642     
Flag Coverage Δ
integration 46.8498% <52.9411%> (+12.5098%) ⬆️
unit 76.3091% <17.6470%> (-0.0178%) ⬇️

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

Components Coverage Δ
dumpling 61.5065% <ø> (+0.0901%) ⬆️
parser ∅ <ø> (∅)
br 65.9463% <67.8571%> (+5.4291%) ⬆️
🚀 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.

@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot bot commented Apr 17, 2026

[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 d3hunter, 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

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 17, 2026

📝 Walkthrough

Walkthrough

Added keyspace-aware PD integration: New keyspace parameter flows into manager and PD controller constructors, PD clients switch to API-context variants, a keyspace helper was added, and several call sites and tests were updated to pass/accept the keyspace name.

Changes

Cohort / File(s) Summary
BR CLI & Commands
br/cmd/br/debug.go
Inserted cfg.KeyspaceName into task.NewMgr call sites.
BR Task Call Sites
br/pkg/task/backup.go, br/pkg/task/backup_ebs.go, br/pkg/task/backup_raw.go, br/pkg/task/backup_txn.go, br/pkg/task/restore.go, br/pkg/task/restore_data.go, br/pkg/task/restore_raw.go, br/pkg/task/restore_txn.go, br/pkg/task/stream.go
Updated NewMgr/NewStreamMgr invocations to pass cfg.KeyspaceName as the new parameter before PD addresses.
Task Manager & Conn
br/pkg/task/common.go, br/pkg/conn/conn.go
Extended NewMgr signatures to accept keyspaceName string and propagate it into connection/PD controller creation.
PD Utilities & Build
br/pkg/pdutil/pd.go, br/pkg/pdutil/BUILD.bazel
Added keyspaceName param to NewPdController; switched PD client creation to use pd.NewClientWithAPIContext built from the keyspace API context; added //pkg/keyspace dep.
Operator / Restore Helpers
br/pkg/task/operator/checksum_table.go, br/pkg/task/operator/crr_checkpoint.go, br/pkg/task/operator/prepare_snap.go, br/pkg/task/restore_ebs_meta.go
Updated PD controller and manager initializations to include cfg.KeyspaceName.
Keyspace helper & Build
pkg/keyspace/keyspace.go, pkg/keyspace/BUILD.bazel
Added BuildAPIContext(keyspaceName string) returning v1 or v2 API context; added PD client dep to keyspace build.
Lightning / Importer
lightning/pkg/importer/import.go, pkg/lightning/backend/local/local.go, pkg/lightning/backend/local/BUILD.bazel
Stored/used a prebuilt apiContext on importer controller and switched PD client construction to NewClientWithAPIContext; added keyspace dep for local backend.
Executor Importer & Tests
pkg/executor/importer/import.go, pkg/executor/importer/table_import.go, pkg/executor/importer/table_import_test.go, pkg/dxf/importinto/planner_test.go
Replaced NewClientWithContext with NewClientWithAPIContext (APIContext parameter added); updated tests/mocks accordingly.
Store error handling
pkg/store/store.go
Added IsNotTSOLeaderError(err) helper and treated TSO-leader errors as retryable in store retry logic.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as CLI / Caller
  participant Mgr as Manager (task.NewMgr)
  participant Conn as conn.NewMgr / pdutil
  participant PD as PD Client
  participant TiKV as TiKV / Storage

  CLI->>Mgr: call NewMgr(ctx, glue, keyspaceName, pdAddrs, ...)
  Mgr->>Conn: forward keyspaceName + pdAddrs
  Conn->>PD: pd.NewClientWithAPIContext(ctx, BuildAPIContext(keyspaceName), ...)
  PD->>TiKV: keyspace-scoped PD API resolves stores/TSO
  PD-->>Conn: PD client ready
  Conn-->>Mgr: connection manager returned
  Mgr-->>CLI: manager usable for backup/restore/stream ops
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

component/import, component/lightning, size/XXL, ok-to-test

Suggested reviewers

  • wjhuang2016
  • OliverS929
  • GMHDBJD
  • Benjamin2037

Poem

🐰 I threaded keyspace names through every spring and burrow,
PD now greets contexts, no more blind shadow,
Managers hum, clients call with care,
Backups hop safe, restores skip nowhere,
🥕✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is largely incomplete. It lacks a concrete issue number, detailed explanation of what changed and why, test selection, and meaningful context for the changes. Fill in the issue number, provide a detailed explanation of the changes and their rationale, select appropriate test checkboxes, and describe the purpose and impact of replacing the client with NewClientWithAPIContext.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: replacing PD client usage with NewClientWithAPIContext across multiple files.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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.11.4)

Command failed


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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (2)
br/pkg/task/restore_raw.go (1)

77-77: ⚠️ Potential issue | 🟡 Minor

Same flag-registration gap — --keyspace-name isn't wired into raw restore CLI either.

DefineRawRestoreFlags + RestoreRawConfig.ParseFromFlags don't read flagKeyspaceName, so cfg.KeyspaceName passed here is always empty. Call-site itself matches the new NewMgr signature correctly; flag-wiring is the only loose end. See verification comment on backup_txn.go.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@br/pkg/task/restore_raw.go` at line 77, The CLI flag `--keyspace-name`
(flagKeyspaceName) isn't being wired into the raw restore config, so
cfg.KeyspaceName is always empty when calling NewMgr; fix this by adding the
flag registration in DefineRawRestoreFlags and reading the value into
RestoreRawConfig in RestoreRawConfig.ParseFromFlags (set the
RestoreRawConfig.KeyspaceName field from flagKeyspaceName), ensuring the same
flag name/value handling as used by the backup path so that cfg.KeyspaceName is
populated before NewMgr is called.
br/pkg/task/backup_raw.go (1)

142-142: ⚠️ Potential issue | 🟡 Minor

Same flag-registration gap as backup_txn.go.

DefineRawBackupFlags / RawKvConfig.ParseFromFlags don't register or read --keyspace-name, so cfg.KeyspaceName will always be empty for raw backup as well. See the verification comment on backup_txn.go line 121.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@br/pkg/task/backup_raw.go` at line 142, The raw-backup flow is missing
registration/parsing of the --keyspace-name flag, so cfg.KeyspaceName is always
empty; update DefineRawBackupFlags and/or RawKvConfig.ParseFromFlags to register
and read the keyspace-name flag (same fix applied in backup_txn.go) so that
cfg.KeyspaceName is populated before NewMgr is called in backup_raw.go; ensure
the flag name matches usage, add parsing to assign into RawKvConfig.KeyspaceName
(or cfg.KeyspaceName) and include a unit/verification similar to the
backup_txn.go fix.
🧹 Nitpick comments (1)
pkg/keyspace/keyspace.go (1)

94-103: Optional: simplify BuildAPIContext and enrich the doc comment.

The named return with if/else branches can be a single-line return. Additionally, the doc comment restates the name — briefly noting the semantics (empty keyspace → V1, otherwise V2) would help readers.

♻️ Proposed refactor
-// BuildAPIContext is used to build APIContext.
-func BuildAPIContext(keyspaceName string) (apiContext pd.APIContext) {
-	if len(keyspaceName) == 0 {
-		apiContext = pd.NewAPIContextV1()
-	} else {
-		apiContext = pd.NewAPIContextV2(keyspaceName)
-	}
-	return
-}
+// BuildAPIContext returns a PD APIContext for the given keyspace name.
+// An empty keyspaceName yields a V1 context; otherwise a V2 context scoped
+// to the keyspace is returned.
+func BuildAPIContext(keyspaceName string) pd.APIContext {
+	if len(keyspaceName) == 0 {
+		return pd.NewAPIContextV1()
+	}
+	return pd.NewAPIContextV2(keyspaceName)
+}

As per coding guidelines: "Keep exported-symbol doc comments, and prefer semantic constraints over name restatement."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/keyspace/keyspace.go` around lines 94 - 103, Update the BuildAPIContext
function and its doc comment: change the comment to briefly state the semantics
("returns NewAPIContextV1 when keyspaceName is empty, otherwise
NewAPIContextV2") and simplify the implementation to a single-line return that
calls pd.NewAPIContextV1() when keyspaceName == "" else
pd.NewAPIContextV2(keyspaceName); keep the function name BuildAPIContext and the
pd.NewAPIContextV1/pd.NewAPIContextV2 calls as the referenced symbols.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@br/pkg/conn/conn.go`:
- Line 155: The TiKV storage URL is currently built with
config.GetGlobalKeyspaceName() while the PD controller (constructed in NewMgr
with the keyspaceName parameter) uses the passed-in keyspaceName; update the
TiKV storage path construction in NewMgr to use the keyspaceName parameter
instead of config.GetGlobalKeyspaceName() so both PD controller and TiKV codec
operate on the same keyspace (affects code paths used by BackupRaw/RestoreRaw
that don't call config.UpdateGlobal()).

In `@br/pkg/task/backup_txn.go`:
- Line 121: The txn backup CLI never gets a keyspace value because
DefineTxnBackupFlags doesn't register --keyspace-name and
TxnKvConfig.ParseFromFlags doesn't populate cfg.KeyspaceName, yet
cfg.KeyspaceName is passed into NewMgr; add support by registering the
"--keyspace-name" flag in DefineTxnBackupFlags and reading it into
TxnKvConfig.ParseFromFlags so cfg.KeyspaceName is populated (match the same flag
name/behavior used in backup.go), then pass that populated cfg.KeyspaceName to
NewMgr; alternatively, if txn backups truly don't use keyspace scoping, remove
the cfg.KeyspaceName parameter from the NewMgr call and corresponding function
signatures and document the decision.

In `@pkg/store/store.go`:
- Around line 147-153: The current IsNotTSOLeaderError function is too broad
(strings.Contains(err.Error(), "not leader")) and matches non-TSO components;
update IsNotTSOLeaderError to only detect TSO/PD-specific "not leader" errors by
either (a) matching a PD/Tso-specific signature (e.g., look for "tso" or "pd"
context in the message such as "tso: not leader" or "pd: not leader") or
preferably (b) performing a typed check against the PD/TSO client error (use
errors.Is or the PD client error type/constant) inside IsNotTSOLeaderError; keep
the symbol name IsNotTSOLeaderError and ensure isNewStoreRetryableError uses
this narrowed check, or if you intend to keep the broad behavior, rename and
re-document the function to reflect it matches any "not leader" error.

---

Duplicate comments:
In `@br/pkg/task/backup_raw.go`:
- Line 142: The raw-backup flow is missing registration/parsing of the
--keyspace-name flag, so cfg.KeyspaceName is always empty; update
DefineRawBackupFlags and/or RawKvConfig.ParseFromFlags to register and read the
keyspace-name flag (same fix applied in backup_txn.go) so that cfg.KeyspaceName
is populated before NewMgr is called in backup_raw.go; ensure the flag name
matches usage, add parsing to assign into RawKvConfig.KeyspaceName (or
cfg.KeyspaceName) and include a unit/verification similar to the backup_txn.go
fix.

In `@br/pkg/task/restore_raw.go`:
- Line 77: The CLI flag `--keyspace-name` (flagKeyspaceName) isn't being wired
into the raw restore config, so cfg.KeyspaceName is always empty when calling
NewMgr; fix this by adding the flag registration in DefineRawRestoreFlags and
reading the value into RestoreRawConfig in RestoreRawConfig.ParseFromFlags (set
the RestoreRawConfig.KeyspaceName field from flagKeyspaceName), ensuring the
same flag name/value handling as used by the backup path so that
cfg.KeyspaceName is populated before NewMgr is called.

---

Nitpick comments:
In `@pkg/keyspace/keyspace.go`:
- Around line 94-103: Update the BuildAPIContext function and its doc comment:
change the comment to briefly state the semantics ("returns NewAPIContextV1 when
keyspaceName is empty, otherwise NewAPIContextV2") and simplify the
implementation to a single-line return that calls pd.NewAPIContextV1() when
keyspaceName == "" else pd.NewAPIContextV2(keyspaceName); keep the function name
BuildAPIContext and the pd.NewAPIContextV1/pd.NewAPIContextV2 calls as the
referenced symbols.
🪄 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: 45cc2209-f795-47f2-962d-c7d477e3f320

📥 Commits

Reviewing files that changed from the base of the PR and between d0712ac and ef0dd20.

📒 Files selected for processing (28)
  • br/cmd/br/debug.go
  • br/pkg/conn/conn.go
  • br/pkg/pdutil/BUILD.bazel
  • br/pkg/pdutil/pd.go
  • br/pkg/task/backup.go
  • br/pkg/task/backup_ebs.go
  • br/pkg/task/backup_raw.go
  • br/pkg/task/backup_txn.go
  • br/pkg/task/common.go
  • br/pkg/task/operator/checksum_table.go
  • br/pkg/task/operator/crr_checkpoint.go
  • br/pkg/task/operator/prepare_snap.go
  • br/pkg/task/restore.go
  • br/pkg/task/restore_data.go
  • br/pkg/task/restore_ebs_meta.go
  • br/pkg/task/restore_raw.go
  • br/pkg/task/restore_txn.go
  • br/pkg/task/stream.go
  • lightning/pkg/importer/import.go
  • pkg/dxf/importinto/planner_test.go
  • pkg/executor/importer/import.go
  • pkg/executor/importer/table_import.go
  • pkg/executor/importer/table_import_test.go
  • pkg/keyspace/BUILD.bazel
  • pkg/keyspace/keyspace.go
  • pkg/lightning/backend/local/BUILD.bazel
  • pkg/lightning/backend/local/local.go
  • pkg/store/store.go

Comment thread br/pkg/conn/conn.go
Comment thread br/pkg/task/backup_txn.go
Comment thread pkg/store/store.go
Comment on lines +147 to +153
// IsNotTSOLeaderError returns true if the error is caused by not a TSO leader.
func IsNotTSOLeaderError(err error) bool {
if err == nil {
return false
}
return strings.Contains(err.Error(), "not leader")
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# First, confirm the file exists and read the relevant section
if [ -f "pkg/store/store.go" ]; then
  echo "=== Lines 140-160 of pkg/store/store.go ==="
  sed -n '140,160p' pkg/store/store.go
else
  echo "File not found at pkg/store/store.go"
fi

Repository: pingcap/tidb

Length of output: 755


🏁 Script executed:

# Search for IsNotTSOLeaderError usage in the codebase
echo "=== Usage of IsNotTSOLeaderError ==="
rg "IsNotTSOLeaderError" --type go -A 3 -B 1

Repository: pingcap/tidb

Length of output: 678


🏁 Script executed:

# Search for isNewStoreRetryableError to understand the call chain
echo "=== isNewStoreRetryableError function and usage ==="
rg "isNewStoreRetryableError" --type go -B 2 -A 5

Repository: pingcap/tidb

Length of output: 979


🏁 Script executed:

# Check for "not leader" errors in the mentioned files
echo "=== Checking for 'not leader' in autoid_service ==="
if [ -f "pkg/autoid_service/autoid.go" ]; then
  rg "not leader" pkg/autoid_service/autoid.go -B 2 -A 2
else
  echo "File not found"
fi

echo ""
echo "=== Checking for 'not leader' in ingestor ==="
if [ -f "pkg/ingestor/errdef/errors.go" ]; then
  rg "not leader" pkg/ingestor/errdef/errors.go -B 2 -A 2
else
  echo "File not found"
fi

echo ""
echo "=== Checking for 'not leader' in BR ==="
if [ -f "br/pkg/errors/errors.go" ]; then
  rg "not leader" br/pkg/errors/errors.go -B 2 -A 2
else
  echo "File not found"
fi

Repository: pingcap/tidb

Length of output: 2216


🏁 Script executed:

# Search for ErrKVNotLeader in the codebase to understand these errors better
echo "=== ErrKVNotLeader references ==="
rg "ErrKVNotLeader" --type go -B 1 -A 1

Repository: pingcap/tidb

Length of output: 3677


IsNotTSOLeaderError matches unrelated component errors due to broad substring matching.

The function is documented as TSO-leader-specific ("returns true if the error is caused by not a TSO leader"), but strings.Contains(err.Error(), "not leader") will also match "not leader" errors from unrelated components: the AutoID service (pkg/autoid_service/autoid.go), ingestor (pkg/ingestor/errdef/errors.go), and BR (br/pkg/errors/errors.go). Since this check feeds isNewStoreRetryableError, any such error during store initialization will incorrectly trigger store-creation retries.

Consider narrowing the match to a TSO-specific signature (e.g., include a PD-related context or match on a typed PD error) rather than matching any "not leader" substring, or update the function name and documentation to reflect the broader matching behavior if that is intentional.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/store/store.go` around lines 147 - 153, The current IsNotTSOLeaderError
function is too broad (strings.Contains(err.Error(), "not leader")) and matches
non-TSO components; update IsNotTSOLeaderError to only detect TSO/PD-specific
"not leader" errors by either (a) matching a PD/Tso-specific signature (e.g.,
look for "tso" or "pd" context in the message such as "tso: not leader" or "pd:
not leader") or preferably (b) performing a typed check against the PD/TSO
client error (use errors.Is or the PD client error type/constant) inside
IsNotTSOLeaderError; keep the symbol name IsNotTSOLeaderError and ensure
isNewStoreRetryableError uses this narrowed check, or if you intend to keep the
broad behavior, rename and re-document the function to reflect it matches any
"not leader" error.

Squashed from tidbcloud/tidb-cse#1899.

Signed-off-by: lhy1024 <admin@liudos.us>
@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot bot commented Apr 17, 2026

[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

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No code

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

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@br/pkg/task/restore_txn.go`:
- Line 33: runRestoreTxnCommand is not picking up the --keyspace-name flag
because task.Config.ParseFromFlags() doesn't read FlagKeyspaceName; ensure
cfg.KeyspaceName is populated before calling NewMgr by reading the persistent
flag added by DefineRestoreFlags. Fix by retrieving the value of
FlagKeyspaceName from the command flags (e.g.
cmd.Flags().GetString(FlagKeyspaceName) or cmd.PersistentFlags().GetString) or
by invoking the same parsing used by RestoreConfig.ParseFromFlags(), then assign
it into cfg.KeyspaceName so RunRestoreTxn and NewMgr receive the correct
keyspace value.
🪄 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: 030699bc-56dc-410e-8c3a-36c7222f78c6

📥 Commits

Reviewing files that changed from the base of the PR and between ef0dd20 and 53034d8.

📒 Files selected for processing (28)
  • br/cmd/br/debug.go
  • br/pkg/conn/conn.go
  • br/pkg/pdutil/BUILD.bazel
  • br/pkg/pdutil/pd.go
  • br/pkg/task/backup.go
  • br/pkg/task/backup_ebs.go
  • br/pkg/task/backup_raw.go
  • br/pkg/task/backup_txn.go
  • br/pkg/task/common.go
  • br/pkg/task/operator/checksum_table.go
  • br/pkg/task/operator/crr_checkpoint.go
  • br/pkg/task/operator/prepare_snap.go
  • br/pkg/task/restore.go
  • br/pkg/task/restore_data.go
  • br/pkg/task/restore_ebs_meta.go
  • br/pkg/task/restore_raw.go
  • br/pkg/task/restore_txn.go
  • br/pkg/task/stream.go
  • lightning/pkg/importer/import.go
  • pkg/dxf/importinto/planner_test.go
  • pkg/executor/importer/import.go
  • pkg/executor/importer/table_import.go
  • pkg/executor/importer/table_import_test.go
  • pkg/keyspace/BUILD.bazel
  • pkg/keyspace/keyspace.go
  • pkg/lightning/backend/local/BUILD.bazel
  • pkg/lightning/backend/local/local.go
  • pkg/store/store.go
✅ Files skipped from review due to trivial changes (6)
  • br/pkg/pdutil/BUILD.bazel
  • br/pkg/task/restore_raw.go
  • br/pkg/task/operator/checksum_table.go
  • pkg/keyspace/BUILD.bazel
  • br/pkg/task/restore_data.go
  • pkg/lightning/backend/local/BUILD.bazel
🚧 Files skipped from review as they are similar to previous changes (16)
  • br/pkg/task/operator/crr_checkpoint.go
  • br/pkg/task/backup_raw.go
  • br/pkg/task/operator/prepare_snap.go
  • br/pkg/task/backup_ebs.go
  • pkg/executor/importer/import.go
  • br/pkg/task/stream.go
  • br/cmd/br/debug.go
  • br/pkg/task/restore_ebs_meta.go
  • pkg/executor/importer/table_import_test.go
  • pkg/keyspace/keyspace.go
  • pkg/lightning/backend/local/local.go
  • pkg/store/store.go
  • br/pkg/task/restore.go
  • br/pkg/pdutil/pd.go
  • br/pkg/conn/conn.go
  • br/pkg/task/common.go


// Restore raw does not need domain.
mgr, err := NewMgr(ctx, g, cfg.PD, cfg.TLS, GetKeepalive(cfg), cfg.CheckRequirements, false, conn.NormalVersionChecker)
mgr, err := NewMgr(ctx, g, cfg.KeyspaceName, cfg.PD, cfg.TLS, GetKeepalive(cfg), cfg.CheckRequirements, false, conn.NormalVersionChecker)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Locate txn restore flag definitions and confirm whether flagKeyspaceName is registered.
rg -nP '\bDefineRestoreTxn|DefineTxnRestoreFlags|DefineRestoreFlags\b' -C3
# Find the cobra command wiring for RunRestoreTxn
rg -nP '\bRunRestoreTxn\b' -C5
# Check which flag sets register flagKeyspaceName
rg -nP '\bflagKeyspaceName\b' -C2

Repository: pingcap/tidb

Length of output: 4953


🏁 Script executed:

# Get the complete DefineRestoreFlags function
sed -n '366,450p' br/pkg/task/restore.go

# Check how RunRestoreTxn and NewMgr use the keyspace name
sed -n '1,80p' br/pkg/task/restore_txn.go

# Check Config struct to understand the type being used
rg -nP 'type Config struct' br/pkg/task/ -A 30 | head -100

Repository: pingcap/tidb

Length of output: 11195


🏁 Script executed:

# Find FlagKeyspaceName definition
rg -nP '\bFlagKeyspaceName\s*=' br/pkg/task/

# Check Config.ParseFromFlags to see if it reads FlagKeyspaceName
sed -n '600,750p' br/pkg/task/restore.go | grep -A 50 'ParseFromFlags'

# Check the complete backup.go and restore.go for flag constant definitions
rg -nP '^const \(' br/pkg/task/ -A 50 | grep -E 'keyspace|Keyspace'

# Check how TxnKvConfig differs from RestoreConfig
rg -nP 'type TxnKvConfig struct' br/pkg/task/ -A 20

Repository: pingcap/tidb

Length of output: 2230


🏁 Script executed:

# Get the complete Config.ParseFromFlags method from common.go to see if it reads FlagKeyspaceName
rg -nP 'func \(cfg \*Config\) ParseFromFlags' br/pkg/task/common.go -A 100 | head -150

# Also check where the restore command (including txn restore) parses the config
rg -nP 'ParseFromFlags|newTxnRestoreCommand' br/cmd/br/restore.go -B 3 -A 10

Repository: pingcap/tidb

Length of output: 6145


🏁 Script executed:

# Check if TxnKvConfig has its own ParseFromFlags or if it inherits from Config
rg -nP 'func \(cfg \*TxnKvConfig\) ParseFromFlags' br/pkg/task/

# Check where RestoreConfig.ParseFromFlags reads FlagKeyspaceName
rg -nP 'ParseFromFlags.*RestoreConfig' br/pkg/task/restore.go -A 200 | grep -i keyspace

# Check the complete RestoreConfig.ParseFromFlags implementation
sed -n '900,1050p' br/pkg/task/restore.go

# Check if newTxnRestoreCommand actually calls DefineRestoreFlags somewhere
grep -n 'DefineRestoreFlags\|DefineRawRestoreFlags' br/cmd/br/restore.go

Repository: pingcap/tidb

Length of output: 5265


🏁 Script executed:

# Check DefineRawRestoreFlags to see if it registers FlagKeyspaceName
rg -nP 'func DefineRawRestoreFlags' br/pkg/task/ -A 30

# Check if Config.ParseFromFlags reads FlagKeyspaceName (checking more lines)
sed -n '610,750p' br/pkg/task/common.go | grep -i keyspace

# Check what flags are available when runRestoreTxnCommand is called
rg -nP 'runRestoreTxnCommand|newTxnRestoreCommand' br/cmd/br/restore.go -B 5 -A 15

Repository: pingcap/tidb

Length of output: 4203


🏁 Script executed:

# Check if RestoreConfig.ParseFromFlags reads FlagKeyspaceName
rg -nP 'func \(cfg \*RestoreConfig\) ParseFromFlags' br/pkg/task/ -A 100 | head -150

# Check DefineRestoreCommonFlags to understand what flags it registers
rg -nP 'func DefineRestoreCommonFlags' br/pkg/task/ -A 30

Repository: pingcap/tidb

Length of output: 9205


--keyspace-name flag is registered but not parsed for txn restore.

FlagKeyspaceName is registered via DefineRestoreFlags() on the parent restore command's PersistentFlags, so it's available to the txn restore subcommand. However, runRestoreTxnCommand() uses plain task.Config and calls Config.ParseFromFlags(), which does not attempt to read FlagKeyspaceName. Only RestoreConfig.ParseFromFlags() reads this flag (line 510 of restore.go). As a result, even though the flag is registered and available, passing --keyspace-name for txn restore will be silently ignored, leaving cfg.KeyspaceName as an empty string when RunRestoreTxn calls NewMgr().

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@br/pkg/task/restore_txn.go` at line 33, runRestoreTxnCommand is not picking
up the --keyspace-name flag because task.Config.ParseFromFlags() doesn't read
FlagKeyspaceName; ensure cfg.KeyspaceName is populated before calling NewMgr by
reading the persistent flag added by DefineRestoreFlags. Fix by retrieving the
value of FlagKeyspaceName from the command flags (e.g.
cmd.Flags().GetString(FlagKeyspaceName) or cmd.PersistentFlags().GetString) or
by invoking the same parsing used by RestoreConfig.ParseFromFlags(), then assign
it into cfg.KeyspaceName so RunRestoreTxn and NewMgr receive the correct
keyspace value.

@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot bot commented Apr 17, 2026

@lhy1024: 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 53034d8 link true /test pull-unit-test-next-gen

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

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/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.

1 participant