Skip to content

schemastore: fix old table metadata for rename table - #5943

Open
lidezhu wants to merge 10 commits into
masterfrom
ldz/fix-rename-table0810
Open

schemastore: fix old table metadata for rename table#5943
lidezhu wants to merge 10 commits into
masterfrom
ldz/fix-rename-table0810

Conversation

@lidezhu

@lidezhu lidezhu commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

Issue Number: close #5946

What is changed and how it works?

  • Recover the old table identity from DDL job args and the original SQL.
  • Update both the DDL query and ExtraSchemaID, ExtraSchemaName, and ExtraTableName.
  • Use snapshot metadata only as a fallback.

Check List

Tests

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

Questions

Will it cause performance regression or break compatibility?
Do you need to update user documentation, design documentation or monitoring documentation?

Release note

Please refer to [Release Notes Language Style Guide](https://pingcap.github.io/tidb-dev-guide/contribute-to-tidb/release-notes-style-guide.html) to write a quality release note.

If you don't think this PR needs a release note then fill it with `None`.

Summary by CodeRabbit

  • Bug Fixes
    • Improved rename-table event handling when snapshots already contain post-rename metadata.
    • Correctly preserves original schema and table names, including identifier casing.
    • Supports same-schema and cross-schema renames, including legacy formats.
    • Handles ANSI-quoted identifiers and inconsistent schema information more reliably.
    • Ensures filters, blocked names, and persisted rename queries reference the original table identity.
    • Fixed changefeed startup immediately before a table rename, preserving correct downstream table naming and replication health.

@ti-chi-bot

ti-chi-bot Bot commented Aug 10, 2026

Copy link
Copy Markdown

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

@ti-chi-bot ti-chi-bot Bot added do-not-merge/needs-linked-issue do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. release-note Denotes a PR that will be considered when it comes time to generate release notes. labels Aug 10, 2026
@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bd6747ee-468c-4226-942f-f380c4d54b87

📥 Commits

Reviewing files that changed from the base of the PR and between fb7496c and 83127f9.

📒 Files selected for processing (1)
  • tests/integration_tests/rename_table_start_ts/set_gc_safepoint.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/integration_tests/rename_table_start_ts/set_gc_safepoint.go

📝 Walkthrough

Walkthrough

The rename-table handler reconstructs the old schema and table identity from rename metadata, SQL, and database mappings. It stores the recovered identity in persisted event fields and adds unit and integration coverage for rename handling.

Changes

Rename Metadata Recovery

Layer / File(s) Summary
Recover and persist old table identity
logservice/schemastore/persist_storage_ddl_handlers.go
The handler recovers old schema IDs and names from rename arguments, involving-schema metadata, parsed SQL, and databaseMap. It uses snapshot metadata only for incomplete identities and updates the persisted rename event fields.
Validate rename metadata repairs
logservice/schemastore/persist_storage_test.go
Tests cover same-schema and cross-schema renames, legacy TiDB arguments, ANSI-quoted queries, inconsistent schema data, fallback behavior, and filtering.
Validate rename start-timestamp initialization
tests/integration_tests/rename_table_start_ts/*, tests/integration_tests/run_light_it_in_ci.sh
The integration test starts a changefeed before a rename, adjusts the GC safepoint, validates SchemaStore initialization, checks filtered replication, and adds the test to the MySQL light-test group.

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

Suggested labels: lgtm

Poem

A rabbit checks the old table name,
And keeps its schema fields the same.
SQL and metadata now agree,
Tests hop across schemas carefully.
The source identity stays clear to see.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description includes the issue and change summary, but it leaves test selections, review questions, and the release note incomplete. Select the applicable tests, answer both questions, describe the problem, and provide a release note or explicitly state None.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 clearly identifies the primary change: repairing old table metadata for rename-table events.
Linked Issues check ✅ Passed The implementation updates old schema and table metadata, supports OldSchemaID resolution, and adds unit and integration coverage for issue #5946.
Out of Scope Changes check ✅ Passed The code and integration-test changes support the linked issue and the stated objective of fixing rename-table metadata handling.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ldz/fix-rename-table0810

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.

@ti-chi-bot ti-chi-bot Bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. do-not-merge/needs-triage-completed and removed do-not-merge/needs-linked-issue do-not-merge/needs-triage-completed labels Aug 10, 2026
@lidezhu
lidezhu marked this pull request as ready for review August 11, 2026 05:32
@ti-chi-bot ti-chi-bot Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Aug 11, 2026
@lidezhu

lidezhu commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor
⚠️ Action not completed

Already reviewed.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (3)
logservice/schemastore/persist_storage_ddl_handlers.go (2)

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

Track the query-provided schema name with an explicit flag.

Line 879 reads queryInfo.oldSchemaName outside the parsed guard. This works today because parseRenameTableQueryInfo returns a zero-value struct with false. The coupling is implicit. If that function later returns partial data with false, the capitalization branch changes behavior silently.

♻️ Proposed refactor
 	queryInfo, parsed := parseRenameTableQueryInfo(args.job.Query)
+	schemaNameFromQuery := false
 	if parsed {
 		if queryInfo.oldTableName != "" {
 			oldTableName = queryInfo.oldTableName
 		}
 		if queryInfo.oldSchemaName != "" {
 			oldSchemaName = queryInfo.oldSchemaName
 			oldSchemaSource = "query"
+			schemaNameFromQuery = true
 		}
 	}
 
 	// Complete a missing old schema ID or name through databaseMap.
 	if oldSchemaID == 0 && oldSchemaName != "" {
 		oldSchemaID, _ = findSchemaIDByName(args.databaseMap, oldSchemaName)
 	}
-	if queryInfo.oldSchemaName == "" {
+	if !schemaNameFromQuery {
 		if oldSchema, ok := args.databaseMap[oldSchemaID]; ok {
🤖 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 `@logservice/schemastore/persist_storage_ddl_handlers.go` around lines 863 -
885, Track whether the parsed query explicitly provided an old schema using a
local boolean set only when parseRenameTableQueryInfo returns parsed data with a
non-empty oldSchemaName. Use that flag in the databaseMap capitalization
fallback instead of reading queryInfo.oldSchemaName outside the parsed guard,
while preserving the existing oldSchemaName and oldSchemaSource assignments.

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

Reconsider the log level for the query rebuild.

Line 910 emits log.Info for every rename-table job. SchemaStore replays the full DDL history at bootstrap. A cluster with many historical renames produces one info line per rename. Consider log.Debug, or keep log.Info only when the recovered identity differs from the snapshot identity.

The repository guidelines ask to consult docs/agents/logging.md before adding logs. Confirm the wanted level there.

As per coding guidelines: "Logs are operational signals; see docs/agents/logging.md before adding, removing, or rewriting 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 `@logservice/schemastore/persist_storage_ddl_handlers.go` around lines 903 -
925, Review docs/agents/logging.md and adjust the log level in the rename-query
rebuild block around the log call, reducing the per-job message from log.Info to
the repository-approved level (likely log.Debug) unless the recovered identity
differs from the snapshot identity and warrants Info. Preserve the existing
structured fields and query-rebuild behavior.

Source: Coding guidelines

logservice/schemastore/persist_storage_test.go (1)

3233-3285: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the tableMap fallback branch.

Both subtests exercise paths where the job supplies a complete old identity, so the fallback block at persist_storage_ddl_handlers.go lines 887-901 never runs. That block contains the log.Panic paths I flagged on the handler.

Add a subtest with an unparsable job.Query, no InvolvingSchemaInfo, and no decodable args. Assert that the Extra* fields come from tableMap and databaseMap. Add a second case where databaseMap omits the old schema ID, to pin the wanted behavior instead of a panic.

As per coding guidelines: "Prefer focused deterministic tests; see docs/agents/testing.md before adding or changing tests."

🤖 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 `@logservice/schemastore/persist_storage_test.go` around lines 3233 - 3285, Add
focused subtests for the tableMap fallback used by
buildPersistedDDLEventForRenameTable: use an unparsable job.Query with no
InvolvingSchemaInfo and undecodable args, then assert ExtraSchemaID,
ExtraSchemaName, and ExtraTableName are derived from tableMap and databaseMap.
Add a second case with the old schema ID absent from databaseMap and assert the
handler completes with the intended non-panicking fallback behavior.

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.

Inline comments:
In `@logservice/schemastore/persist_storage_ddl_handlers.go`:
- Around line 887-901: Update the fallback block around oldSchemaID,
oldSchemaName, and oldTableName so getSchemaID runs only when oldSchemaID is
zero and getTableName runs only when oldTableName is empty, avoiding helper
calls when tableMap lacks event.TableID. Resolve a missing oldSchemaName
directly from args.databaseMap[oldSchemaID], preserving an empty name for
untracked schema IDs and avoiding getSchemaName; ensure event.Query remains
unchanged when the old schema name is unavailable.

---

Nitpick comments:
In `@logservice/schemastore/persist_storage_ddl_handlers.go`:
- Around line 863-885: Track whether the parsed query explicitly provided an old
schema using a local boolean set only when parseRenameTableQueryInfo returns
parsed data with a non-empty oldSchemaName. Use that flag in the databaseMap
capitalization fallback instead of reading queryInfo.oldSchemaName outside the
parsed guard, while preserving the existing oldSchemaName and oldSchemaSource
assignments.
- Around line 903-925: Review docs/agents/logging.md and adjust the log level in
the rename-query rebuild block around the log call, reducing the per-job message
from log.Info to the repository-approved level (likely log.Debug) unless the
recovered identity differs from the snapshot identity and warrants Info.
Preserve the existing structured fields and query-rebuild behavior.

In `@logservice/schemastore/persist_storage_test.go`:
- Around line 3233-3285: Add focused subtests for the tableMap fallback used by
buildPersistedDDLEventForRenameTable: use an unparsable job.Query with no
InvolvingSchemaInfo and undecodable args, then assert ExtraSchemaID,
ExtraSchemaName, and ExtraTableName are derived from tableMap and databaseMap.
Add a second case with the old schema ID absent from databaseMap and assert the
handler completes with the intended non-panicking fallback behavior.
🪄 Autofix

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a6e0e724-9295-4fd0-8f10-682e3254091c

📥 Commits

Reviewing files that changed from the base of the PR and between 2b82c06 and ac4f992.

📒 Files selected for processing (2)
  • logservice/schemastore/persist_storage_ddl_handlers.go
  • logservice/schemastore/persist_storage_test.go

Comment thread logservice/schemastore/persist_storage_ddl_handlers.go Outdated
@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 Aug 12, 2026
@lidezhu

lidezhu commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator Author

/test pull-error-log-review

@wuhuizuo

Copy link
Copy Markdown
Contributor

/retest

@lidezhu

lidezhu commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator Author

/test pull-error-log-review

@wuhuizuo

Copy link
Copy Markdown
Contributor

/retest

@lidezhu

lidezhu commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator Author

/test pull-error-log-review

@wk989898

Copy link
Copy Markdown
Collaborator

Can we make an integration test case to prove it?

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

ti-chi-bot Bot commented Aug 12, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: 3AceShowHand

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 12, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-08-12 08:11:46.069169403 +0000 UTC m=+3206892.105264469: ☑️ agreed by 3AceShowHand.

@ti-chi-bot ti-chi-bot Bot added the approved label Aug 12, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/integration_tests/rename_table_start_ts/run.sh`:
- Around line 65-66: After the successful gc_worker safepoint update in run.sh,
register an EXIT trap that restores gc_worker_value before invoking stop_test.
Ensure the cleanup runs when run_cdc_server or ensure exits the script, while
preserving the existing stop_test behavior and avoiding duplicate trap
registration.
🪄 Autofix

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 45b02fd1-d882-4a9b-9e88-087d317f0135

📥 Commits

Reviewing files that changed from the base of the PR and between 72a8515 and fb7496c.

📒 Files selected for processing (5)
  • logservice/schemastore/persist_storage_ddl_handlers.go
  • tests/integration_tests/rename_table_start_ts/conf/changefeed.toml
  • tests/integration_tests/rename_table_start_ts/run.sh
  • tests/integration_tests/rename_table_start_ts/set_gc_safepoint.go
  • tests/integration_tests/run_light_it_in_ci.sh
🚧 Files skipped from review as they are similar to previous changes (1)
  • logservice/schemastore/persist_storage_ddl_handlers.go

Comment thread tests/integration_tests/rename_table_start_ts/run.sh Outdated
@lidezhu

lidezhu commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator Author

Can we make an integration test case to prove it?

We cannot add a reliable integration test because SchemaStore initializes from the GC safepoint, whose exact value is difficult to control.

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

Labels

approved needs-1-more-lgtm Indicates a PR needs 1 more LGTM. 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.

schemastore: incorrect old table metadata in single-table RENAME events

4 participants