Skip to content

ddl: recreate affinity groups when recovering tables - #72689

Open
JmPotato wants to merge 1 commit into
pingcap:masterfrom
JmPotato:fix-affinity-recover
Open

JmPotato wants to merge 1 commit into
pingcap:masterfrom
JmPotato:fix-affinity-recover

Conversation

@JmPotato

@JmPotato JmPotato commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

Issue Number: close #72057

Problem Summary:

Dropping or truncating a table deletes its affinity groups in PD. RECOVER TABLE, FLASHBACK TABLE and FLASHBACK DATABASE restore the table metadata, including its affinity, but did not create the groups again, so the recovered tables silently lost affinity scheduling.

What changed and how does it work?

  • The recovery step creates the affinity groups of the recovered tables (table-level and partition-level) after its checks that can cancel the job, in the same step that restores the metadata.
  • Recovery rescues data that GC deletes soon, so failing to create the groups does not cancel it. The tables are recovered, the error is logged, and the statement returns a warning that names the tables; their groups can be created again with ALTER TABLE ... AFFINITY.
  • Creating groups is idempotent, so retrying the step is safe. A successful retry drops the warning of an earlier attempt.
  • If a retry is cancelled after an earlier attempt created groups, the groups are kept. They are not deleted because the same table ID can be recovered by another job, for example from another DROP of the same table after it was recovered and renamed to another schema, and deleting them would remove the groups of that table. A later recovery or ALTER TABLE ... AFFINITY of the table takes the kept groups over; nothing cleans them up automatically today; the reconciliation planned in ddl: garbage-collect and reconcile affinity groups in PD #72061 is meant to handle them. The log records which job sent a successful group-creation request for which table.
  • The warning uses the generic DDL error class, so a successful retry drops any warning of that class on the job; recovery jobs have no other source of such warnings today.

Relation to #72677: until #72677 is merged, a PD that does not serve the affinity API answers group creation with 404, which TiDB treats as success, so recovery there leaves the tables without groups and without a warning. With #72677, the same case returns the warning above.

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.

Manual test on a local cluster with TiKV v8.5.8 and PD master, running a tidb-server built from this PR, with a table-level affinity table t1 and a partition-level affinity table tp:

  1. DROP TABLE t1 removes _tidb_t_<t1>; RECOVER TABLE t1 restores the rows and the group, without warnings.
  2. DROP TABLE tp removes its partition groups; FLASHBACK TABLE tp TO tp2 restores _tidb_pt_<tp>_p<partition> for both partitions.
  3. DROP DATABASE removes all groups; FLASHBACK DATABASE restores both tables, the rows and all three groups.

Group-creation failure, retry of the recovery step, cancellation after a retry (groups kept and taken over by a later recovery) and two parallel recoveries of the same table are covered by unit tests with failpoints.

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.

Fix the issue that tables restored by `RECOVER TABLE`, `FLASHBACK TABLE` or `FLASHBACK DATABASE` lose their table affinity scheduling.

Summary by CodeRabbit

  • Bug Fixes
    • Affinity groups are now recreated for configured tables and partitions during table and database recovery, including table and database flashbacks.
    • Recovery can proceed when affinity-group creation fails, with a warning identifying affected tables.
    • Retried or parallel recovery jobs preserve affinity groups successfully created by another job, and a later retry can restore groups that previously failed to create.

@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. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Nov 4, 2026
@ti-chi-bot

ti-chi-bot Bot commented Nov 4, 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 d3hunter 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

coderabbitai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Table and schema recovery now attempt to create affinity groups for recovered tables. The helper continues after individual creation failures and records a warning. Tests cover successful recovery, failures, retries, cancellation, and parallel recovery.

Changes: Affinity group recovery

Layer / File(s) Summary
Create affinity groups during recovery
pkg/ddl/affinity.go
A new helper skips tables without affinity and attempts group creation for other recovered tables. It continues after failures, records failed table names and the first error in a warning, and removes the prior unknown-error warning when all attempts succeed.
Wire recovery paths and test outcomes
pkg/ddl/schema.go, pkg/ddl/table.go, pkg/ddl/affinity_test.go
Schema and table recovery call the helper. Tests cover recovered tables and partitions, database recovery, group-creation failures, retries, cancellation, and parallel recovery.

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

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant RecoveryPath
  participant createRecoveredTablesAffinityGroups
  participant PD
  RecoveryPath->>createRecoveredTablesAffinityGroups: pass recovered tables
  createRecoveredTablesAffinityGroups->>PD: create affinity groups
  PD-->>createRecoveredTablesAffinityGroups: return creation results
  createRecoveredTablesAffinityGroups-->>RecoveryPath: return with warning state
Loading

Possibly related issues

  • #72061: Requests deferred affinity-group deletion and reconciliation. This change recreates groups during recovery and retains groups after a canceled retry, but does not implement reconciliation or automatic cleanup.
  • #72058: Reports missing affinity groups after FLASHBACK CLUSTER. This change addresses related recovery paths but does not cover cluster flashback.
  • #72064: Reports PD 404 responses during affinity-group calls. The reported 404 limitation remains unresolved by this change.

Possibly related PRs

  • pingcap/tidb#73751: Defers affinity-group deletion and adds reconciliation, which interacts with this change’s recovery-time group creation.

Suggested reviewers: lhy1024, d3hunter

Merge Risk: Minimal · up to f996a

Recovering tables with RECOVER TABLE, FLASHBACK TABLE, and FLASHBACK DATABASE now recreates their affinity groups. If group creation fails, the tables are still restored and a warning names the affected tables. No blocking risk was found. Required code-owner approvals are still pending.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "ddl: recreate affinity groups when recovering tables" follows the repository's "pkg: what's changed" format. It names the main change: the recovery path recreates PD affinity groups for rec…
Description check Passed The description follows the template. It has a filled Issue Number line (close #72057) and a Problem Summary. The What changed section explains the design, including warning behavior, retry, cancellat…
Linked Issues check Passed Issue #72057 requires that tables restored by RECOVER TABLE, FLASHBACK TABLE, or FLASHBACK DATABASE have their PD affinity groups. At the reviewed head, pkg/ddl/affinity.go defines createRecoveredTabl…
Out of Scope Changes check Passed The changes serve the recovery objective for #72057. pkg/ddl/affinity.go adds the recovery helper and its imports (failpoint, strings, terror, dbterror). Its only new logic is the warning and warning-…
Full details: Title check

Explanation

The title "ddl: recreate affinity groups when recovering tables" follows the repository's "pkg: what's changed" format. It names the main change: the recovery path recreates PD affinity groups for recovered tables. The raw summary and PR objectives both describe this change. The title does not mention FLASHBACK TABLE or FLASHBACK DATABASE, but it is still specific enough for a teammate scanning history.

Full details: Description check

Explanation

The description follows the template. It has a filled Issue Number line (close #72057) and a Problem Summary. The What changed section explains the design, including warning behavior, retry, cancellation, and the dependency on #72677. The checklist marks unit and manual tests. The release note is filled in. The side-effect and documentation checkboxes are unchecked, which is acceptable for this change. The integration test box is unchecked, and the author reports no integration test. This is a minor gap that does not block the check.

Full details: Linked Issues check

Explanation

Issue #72057 requires that tables restored by RECOVER TABLE, FLASHBACK TABLE, or FLASHBACK DATABASE have their PD affinity groups. At the reviewed head, pkg/ddl/affinity.go defines createRecoveredTablesAffinityGroups. For each recovered table with Affinity set, it calls createTableAffinityGroupsInPD. This creates tidb_t<id> for table-level affinity and one tidb_pt<id>_p<partID> group per partition for partition-level affinity. The PR summary states that onRecoverTable (RECOVER and FLASHBACK TABLE) and onRecoverSchema (FLASHBACK DATABASE) call this helper. The helper runs after the cancellable checks, as stated in the PR description. Creation is idempotent, so a retry is safe. On failure, the helper does not cancel the job. It stores a DDL-class warning that names the failed tables and gives the ALTER TABLE ... AFFINITY workaround listed in the issue. A successful retry removes that warning. Cancellation keeps the groups, which is a design choice and not a conflict with the issue. Deferred deletion (#72061) is background only. The known limit (a PD returning 404 is treated as success until #72677 is merged) is disclosed and does not change the code path that the issue requires. Unit tests are reported for creation, failure, retry, cancellation, and parallel recovery. I did not read the test file line by line.

Full details: Out of Scope Changes check

Explanation

The changes serve the recovery objective for #72057. pkg/ddl/affinity.go adds the recovery helper and its imports (failpoint, strings, terror, dbterror). Its only new logic is the warning and warning-clearing behavior for group creation. pkg/ddl/table.go and pkg/ddl/schema.go add the helper call in the recovery steps, per the summary. The summary also reports a GC-barrier renewal error check moved after the helper call in both files. This ordering change sits in the recovery path and does not relate to other DDL behavior. pkg/ddl/affinity_test.go adds tests for creation, failure, retry, cancellation, and parallel recovery. These support the objective. No unrelated behavior change appears in the reviewed summary or in the helper code. I did not inspect the full table.go and schema.go hunks, so the GC-barrier reordering is assessed from the summary only.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
Fix failing CI checks

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

golangci-lint (2.15.0)

golangci-lint failed without an exit code
golangci-lint (2.15.0) exceeded its 180-second time budget. Findings from completed work are retained; remaining checks are incomplete.

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

A rabbit checks the tables restored,
And asks PD to make each group.
If one attempt should fail along the way,
A warning names the table and error.
On retry, groups may appear again,
Then off the rabbit hops to play.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 16c99cd6-71bf-4f89-a352-3ff8131596b6
Commits

Reviewing files that changed from the base of the PR and between ecbe986 and f996a99.

Files selected for processing: 4

  • pkg/ddl/affinity.go
  • pkg/ddl/affinity_test.go
  • pkg/ddl/schema.go
  • pkg/ddl/table.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 43 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.6415%. Comparing base (2698c93) to head (f996a99).
⚠️ Report is 13 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #72689        +/-   ##
================================================
+ Coverage   72.1862%   73.6415%   +1.4553%     
================================================
  Files          2173       2221        +48     
  Lines        601857     612203     +10346     
================================================
+ Hits         434458     450836     +16378     
+ Misses       167397     161362      -6035     
- Partials          2          5         +3     
Flag Coverage Δ
integration 51.7487% <0.0000%> (+5.7112%) ⬆️

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

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

Dropping or truncating a table deletes its affinity groups in PD, but
RECOVER TABLE, FLASHBACK TABLE and FLASHBACK DATABASE restored the table
metadata, including its affinity, without creating the groups again, so
the recovered tables silently lost affinity scheduling.

The recovery step now creates the affinity groups of the recovered
tables after its checks that can cancel the job. Recovery rescues data
that GC deletes soon, so failing to create the groups does not cancel
it: the tables are recovered, the error is logged, and the statement
returns a warning that names the tables, whose groups can be created
again with ALTER TABLE ... AFFINITY. Creating groups is idempotent, so
retrying the step is safe; a successful retry drops the warning of an
earlier attempt. If a retry is cancelled after an earlier attempt
created groups, the groups are kept rather than deleted: the same table
ID can be recovered by another job, whose groups they then are. A later
recovery or ALTER TABLE ... AFFINITY of the table takes them over.

Fixes pingcap#72057

Signed-off-by: JmPotato <github@ipotato.me>
@JmPotato
JmPotato force-pushed the fix-affinity-recover branch from ecbe986 to f996a99 Compare November 26, 2026 10:28
@ti-chi-bot

ti-chi-bot Bot commented Nov 26, 2026

Copy link
Copy Markdown

Protected changes

This pull request adds lines that a repository policy protects. Merge needs an approval from a reviewer listed for it.

File Rule Line
pkg/ddl/affinity.go string_literals logutil.DDLLogger().Error("failed to create affinity groups of a recovered table", zap.Int64("jobID", job.ID), zap.Int64("tableID", recoverInfo.TableInfo.ID…
pkg/ddl/affinity.go variables_and_functions logutil.DDLLogger().Error("failed to create affinity groups of a recovered table", zap.Int64("jobID", job.ID), zap.Int64("tableID", recoverInfo.TableInfo.ID…

Required reviewers: @zanmato1984, @windtalker, @bb7133, @terry1purcell, @cfzjywxk, @niubell, @nongfushanquan, @v01dstar, @XuHuaiyu, @YuJuncen (1 approval(s) needed).
Approved by: none yet.

Update protected-change patterns and approvers at https://github.com/ti-community-infra/configs/blob/main/prow/config/protected_changes_config.yaml.

This comment is updated on every push instead of adding a new one.

@ti-chi-bot ti-chi-bot Bot added size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. and removed size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Nov 26, 2026
@JmPotato

Copy link
Copy Markdown
Member Author

/retest-required

This branch has not been deployed

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

Labels

release-note Denotes a PR that will be considered when it comes time to generate release notes. 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.

ddl: RECOVER / FLASHBACK TABLE / FLASHBACK DATABASE do not restore affinity groups

1 participant