Skip to content

br: compare collate check privilege - #70258

Open
Leavrth wants to merge 1 commit into
pingcap:release-8.1from
Leavrth:compare_collate_check_privilege_8.1
Open

br: compare collate check privilege#70258
Leavrth wants to merge 1 commit into
pingcap:release-8.1from
Leavrth:compare_collate_check_privilege_8.1

Conversation

@Leavrth

@Leavrth Leavrth commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: close #64667

Problem Summary:
It is needed to restore privileges tables backed up from v6.5 to newly created v7.2+ clusters.

What changed and how does it work?

permit to restore privileges tables from v6.5 to v7.2+ if all the data have the same behavior in utf8mb4_bin and utf8mb4_general_ci.

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

  • Bug Fixes
    • Improved system-table restoration compatibility checks for differing collations.
    • Added validation for MySQL privilege-table schemas, supported collations, required columns, and row counts.
    • System-table checks now run for applicable system-database restores, including partial restores.
    • Prevented incompatible privilege-table data from being restored and provided clearer compatibility errors.
  • Tests
    • Added coverage for compatible and incompatible privilege-table collation scenarios.

Signed-off-by: Jianjun Liao <jianjun.liao@outlook.com>
@ti-chi-bot

ti-chi-bot Bot commented Jul 31, 2026

Copy link
Copy Markdown

This cherry pick PR is for a release branch and has not yet been approved by triage owners.
Adding the do-not-merge/cherry-pick-not-approved label.

To merge this cherry pick:

  1. It must be LGTMed and approved by the reviewers firstly.
  2. For pull requests to TiDB-x branches, it must have no failed tests.
  3. AFTER it has lgtm and approved labels, please wait for the cherry-pick merging approval from triage owners.
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.

@ti-chi-bot ti-chi-bot Bot added release-note-none Denotes a PR that doesn't merit a release note. do-not-merge/cherry-pick-not-approved size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. labels Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The restore flow now separates type and collation compatibility. It validates selected MySQL privilege tables and row counts before replacement, allowing supported utf8mb4_bin to utf8mb4_general_ci transitions without duplicate rows.

Changes

Privilege table restore compatibility

Layer / File(s) Summary
Separate type and collation compatibility
br/pkg/utils/misc.go, br/pkg/utils/misc_test.go
IsTypeCompatible now returns independent type and collation results. Tests cover compatible, incompatible, and collation-only differences.
Validate privilege-table schemas and rows
br/pkg/restore/client.go, br/pkg/restore/systable_restore.go
Restore checks configured columns, supported collations, and restricted upstream/downstream row counts before replacing privilege tables.
Apply checks to system-table restore
br/pkg/task/restore.go
Compatibility checks run when WithSysTable is enabled and the backup contains the system database.
Cover restore compatibility cases
br/pkg/restore/systable_restore_test.go, br/pkg/restore/client_test.go, br/pkg/restore/util_test.go, br/pkg/restore/BUILD.bazel
Tests cover db, tables_priv, and columns_priv case and accent conflicts, schema differences, cleanup, and test-target registration.

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

Sequence Diagram(s)

sequenceDiagram
  participant RestoreTask
  participant Client
  participant PrivilegeCompatibilityCheck
  participant PrivilegeTableSQL
  RestoreTask->>Client: check system-table compatibility
  Client->>PrivilegeCompatibilityCheck: validate privilege-table metadata
  PrivilegeCompatibilityCheck->>PrivilegeTableSQL: query upstream and downstream row counts
  PrivilegeTableSQL-->>PrivilegeCompatibilityCheck: return row counts
  PrivilegeCompatibilityCheck-->>Client: return compatibility result
  Client->>Client: execute REPLACE INTO when compatible
Loading

Possibly related PRs

  • pingcap/tidb#69677 — Both changes modify collation handling and compatibility behavior.

Poem

A rabbit checks each privilege row,
Where collations gently flow.
Bin and general may agree,
If no duplicate hides beneath the tree.
Safe restores hop along—
With tidy tables, right not wrong.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% 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
Linked Issues check ✅ Passed The changes support v6.5 privilege-table restoration to v7.2+ clusters with compatible utf8mb4 collations, as required by issue [#64668].
Out of Scope Changes check ✅ Passed The code, tests, and Bazel updates are directly related to privilege-table collation compatibility during restoration.
Title check ✅ Passed The title identifies the BR privilege-table collation compatibility check, which is the main change.
Description check ✅ Passed The description includes the issue, problem, implementation summary, unit and integration tests, side effects, documentation, and release note sections.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks
🧪 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.

🧹 Nitpick comments (3)
br/pkg/restore/systable_restore.go (2)

318-333: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the collation-compatibility contract on these helpers.

checkSysTableColumnCollateCompatibility and checkPrivilegeTableRowsCollateCompatibility implement a non-obvious contract: only an upstream utf8mb4_bin to downstream utf8mb4_general_ci transition is accepted, and only for the columns listed in collateCompatibilityTables. Add a short doc comment on each function explaining this constraint and why it exists (v6.5-to-v7.2+ default collation change for privilege tables). This helps future readers avoid accidentally widening or narrowing the supported transition without understanding the compatibility guarantee it encodes.

As per coding guidelines, "Comments SHOULD explain non-obvious intent, constraints, invariants, concurrency guarantees, SQL/compatibility contracts, or important performance trade-offs."

Also applies to: 335-379

🤖 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/restore/systable_restore.go` around lines 318 - 333, Add concise doc
comments to checkSysTableColumnCollateCompatibility and
checkPrivilegeTableRowsCollateCompatibility describing that they accept only
utf8mb4_bin-to-utf8mb4_general_ci transitions for columns listed in
collateCompatibilityTables, preserving the v6.5-to-v7.2+ privilege-table
default-collation compatibility contract.

Source: Coding guidelines


64-89: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid hardcoding the temporary database name; add a comment for the compatibility contract.

The literal __TiDB_BR_Temporary_mysql appears six times in these SQL strings. Elsewhere in this package (for example HasBackedUpSysDB), the temporary database name is derived from utils.TemporaryDBName(mysql.SystemDB). Build the SQL from that helper instead of a raw literal, so the queries stay correct if the temporary-database naming convention changes.

Also add a short comment above collateCompatibilityTables explaining the contract: which tables/columns support a collation change, and why only db, tables_priv, and columns_priv (and only specific columns within them) are listed.

As per coding guidelines, "Comments SHOULD explain non-obvious intent, constraints, invariants, concurrency guarantees, SQL/compatibility contracts, or important performance trade-offs."

♻️ Proposed direction
+var mysqlTemporaryDBName = utils.TemporaryDBName(mysql.SystemDB).L
+
+// collateCompatibilityTables lists privilege tables/columns for which a
+// utf8mb4_bin (upstream) -> utf8mb4_general_ci (downstream) collation
+// change is considered safe, provided the backed-up rows remain distinct
+// under utf8mb4_general_ci.
 var collateCompatibilityTables = map[string]map[string]checkPrivilegeTableRowsCollateCompatibilitySQLPair{
 	"mysql": {
 		"db": {
-			upstreamCollateSQL:   "SELECT COUNT(1) FROM __TiDB_BR_Temporary_mysql.db",
-			downstreamCollateSQL: "SELECT COUNT(1) FROM (SELECT Host, DB COLLATE utf8mb4_general_ci, User FROM __TiDB_BR_Temporary_mysql.db GROUP BY Host, DB COLLATE utf8mb4_general_ci, User) as a",
+			upstreamCollateSQL:   fmt.Sprintf("SELECT COUNT(1) FROM %s.db", mysqlTemporaryDBName),
+			downstreamCollateSQL: fmt.Sprintf("SELECT COUNT(1) FROM (SELECT Host, DB COLLATE utf8mb4_general_ci, User FROM %s.db GROUP BY Host, DB COLLATE utf8mb4_general_ci, User) as a", mysqlTemporaryDBName),
 			columns:              map[string]struct{}{"db": {}},
 		},
🤖 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/restore/systable_restore.go` around lines 64 - 89, Update
collateCompatibilityTables to construct each temporary-database reference using
utils.TemporaryDBName(mysql.SystemDB) instead of hardcoding
__TiDB_BR_Temporary_mysql, while preserving the existing SQL and table mappings.
Add a concise comment immediately above the variable describing that only db,
tables_priv, and columns_priv support the collation-change compatibility check,
with only their listed columns included, and explain the compatibility
constraint behind this limited scope.

Source: Coding guidelines

br/pkg/restore/client.go (1)

209-210: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a short comment for the new cross-file flag.

privilegeTableRowsCollateCompatibility is set in client.go and read in systable_restore.go to gate an extra validation step. Add a one-line comment above the field. Explain that it means "at least one privilege-table column has a supported utf8mb4_bin→utf8mb4_general_ci collation change" and that replaceTemporaryTableToSystable uses it to decide when to run the row-collision check.

As per coding guidelines, "Comments SHOULD explain non-obvious intent, constraints, invariants, concurrency guarantees, SQL/compatibility contracts, or important performance trade-offs."

🤖 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/restore/client.go` around lines 209 - 210, Add a one-line comment
directly above privilegeTableRowsCollateCompatibility explaining that it
indicates at least one privilege-table column supports the
utf8mb4_bin→utf8mb4_general_ci collation change and that
replaceTemporaryTableToSystable uses it to trigger row-collision validation.

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 `@br/pkg/restore/client.go`:
- Around line 209-210: Add a one-line comment directly above
privilegeTableRowsCollateCompatibility explaining that it indicates at least one
privilege-table column supports the utf8mb4_bin→utf8mb4_general_ci collation
change and that replaceTemporaryTableToSystable uses it to trigger row-collision
validation.

In `@br/pkg/restore/systable_restore.go`:
- Around line 318-333: Add concise doc comments to
checkSysTableColumnCollateCompatibility and
checkPrivilegeTableRowsCollateCompatibility describing that they accept only
utf8mb4_bin-to-utf8mb4_general_ci transitions for columns listed in
collateCompatibilityTables, preserving the v6.5-to-v7.2+ privilege-table
default-collation compatibility contract.
- Around line 64-89: Update collateCompatibilityTables to construct each
temporary-database reference using utils.TemporaryDBName(mysql.SystemDB) instead
of hardcoding __TiDB_BR_Temporary_mysql, while preserving the existing SQL and
table mappings. Add a concise comment immediately above the variable describing
that only db, tables_priv, and columns_priv support the collation-change
compatibility check, with only their listed columns included, and explain the
compatibility constraint behind this limited scope.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9633ee5a-87e3-4062-9030-4cb777e6e108

📥 Commits

Reviewing files that changed from the base of the PR and between 986af29 and 93c0b26.

📒 Files selected for processing (9)
  • br/pkg/restore/BUILD.bazel
  • br/pkg/restore/client.go
  • br/pkg/restore/client_test.go
  • br/pkg/restore/systable_restore.go
  • br/pkg/restore/systable_restore_test.go
  • br/pkg/restore/util_test.go
  • br/pkg/task/restore.go
  • br/pkg/utils/misc.go
  • br/pkg/utils/misc_test.go

@codecov

codecov Bot commented Jul 31, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0.97087% with 102 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (release-8.1@986af29). Learn more about missing BASE report.

Additional details and impacted files
@@               Coverage Diff                @@
##             release-8.1     #70258   +/-   ##
================================================
  Coverage               ?   37.0692%           
================================================
  Files                  ?       1510           
  Lines                  ?     577508           
  Branches               ?          0           
================================================
  Hits                   ?     214078           
  Misses                 ?     342043           
  Partials               ?      21387           
Flag Coverage Δ
integration 37.0692% <0.9708%> (?)

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

Components Coverage Δ
dumpling ∅ <0.0000%> (?)
parser ∅ <0.0000%> (?)
br 23.6931% <0.0000%> (?)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Leavrth

Leavrth commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

/retest

@ti-chi-bot

ti-chi-bot Bot commented Aug 5, 2026

Copy link
Copy Markdown

@Leavrth: 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
idc-jenkins-ci-tidb/mysql-test 93c0b26 link true /test mysql-test

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.

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

ti-chi-bot Bot commented Aug 7, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: YuJuncen

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:

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 commented Aug 7, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-08-07 02:48:46.54639161 +0000 UTC m=+2755512.582486666: ☑️ agreed by YuJuncen.

@ti-chi-bot ti-chi-bot Bot added the approved label Aug 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved do-not-merge/cherry-pick-not-approved needs-1-more-lgtm Indicates a PR needs 1 more LGTM. 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.

2 participants