Skip to content

planner: fix prepared plan cache after table rename - #71042

Open
tiancaiamao wants to merge 3 commits into
masterfrom
fix/prepared-rename-regression
Open

planner: fix prepared plan cache after table rename#71042
tiancaiamao wants to merge 3 commits into
masterfrom
fix/prepared-rename-regression

Conversation

@tiancaiamao

@tiancaiamao tiancaiamao commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: close #71041

Problem Summary:
A prepared plan cache entry can retain stale table metadata after a table is renamed. If a new table is created with the original name and the renamed table is later dropped, executing the prepared statement can incorrectly return error 8113 for the dropped table.

This is a regression introduced by the metadata-lock support for plan cache:

What changed and how does it work?

After a schema change, re-preprocess the prepared AST with a fresh resolve context and rebuild the schema-dependent metadata.

The metadata-lock/cache-key table set is rebuilt from the complete StmtCtx.RelatedTableIDs dependency set after a fresh plan-builder dependency-discovery pass. This preserves dependencies expanded from views and other resolved plan inputs; the AST-only stmt.tables list is retained only for AST-derived plan-cache information. The table metadata conversion is shared with initial plan-cache construction.

This fixes the rename/drop/create sequence while preserving the original metadata-lock behavior introduced by #51897. The additional discovery build runs only on the schema-change reprepare path.

Regression and release impact

The introducing change is present through equivalent commits in the following code lines, so the rename regression should be considered affected unless this fix is backported:

  • v7.5: 84e2926684 is present from v7.5.2 onward in the inspected tags.
  • v8.1: equivalent backport e39969afee49 / *: add metadata lock when using the plan cache (#51897) #52955 is present.
  • v8.2 and v8.5: the original master-line commit 70a825397f3b is in the release lineage; the pre-fix reprepare path is present in inspected tags.
  • v9.x: the same metadata-lock/revision and reprepare code path is present in inspected tags; this is a code-path assessment, not a claim that the exact 84e object was cherry-picked there.
  • v26.3: the next-gen code still has the corresponding ID/name fallback and reprepare behavior without this metadata rebuild, so it is likely affected based on static inspection; runtime confirmation on that line is still needed.
  • 25.10: no 25.10 tag or branch exists in the repository snapshot used for this analysis, so its impact cannot be confirmed here.

No inspected release ref contains this fix yet.

Check List

Tests

  • Unit test
    • go test -tags=intest ./pkg/executor/test/plancache -run '^TestPreparedPlanCacheRenameCreateDropOldName$' -count=1
    • go test -tags=intest ./pkg/executor/test/plancache -count=1
  • 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.

bugfix: fix prepared plan cache metadata after table rename

Summary by CodeRabbit

  • Bug Fixes

    • Improved prepared statement handling after tables are renamed, recreated, or dropped.
    • Prepared statements now refresh schema information and use the current table definition after schema changes.
    • Reduced stale table references during subsequent prepared statement executions.
  • Tests

    • Added coverage for prepared statements across table rename, recreation, and removal scenarios.
    • Verified statements continue executing correctly after the original table is replaced.

@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. do-not-merge/needs-triage-completed sig/planner SIG: Planner size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Sep 14, 2026
@pingcap-cla-assistant

pingcap-cla-assistant Bot commented Sep 14, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Review Change StackReview 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: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 8a6e9cf1-369f-468d-9210-ec98065d0a44

📥 Commits

Reviewing files that changed from the base of the PR and between 6cc78f4 and bfcb20b.

📒 Files selected for processing (1)
  • pkg/planner/core/plan_cache.go

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


📝 Walkthrough

Walkthrough

The schema-change path resets and rebuilds prepared statement metadata. A shared helper collects current table information. A test covers rename, recreate, and drop operations. The test target shard count increases from 8 to 9.

Changes

Prepared plan cache schema refresh

Layer / File(s) Summary
Rebuild schema-dependent metadata
pkg/planner/core/plan_cache.go, pkg/planner/core/plan_cache_utils.go
The schema-change path clears stale metadata, reprocesses the statement, discovers related tables, and collects current database names, table descriptors, and schema versions through collectPlanCacheTableInfo.
Validate rename and recreate flow
pkg/executor/test/plancache/plan_cache_test.go, pkg/executor/test/plancache/BUILD.bazel
A test verifies that a prepared query uses the recreated t table after t is renamed to bak, and continues to execute after bak is dropped. The test target shard count increases from 8 to 9.

Priority: ➖ Normal

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

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to bfcb2

The schema-refresh change includes coverage for the rename, replacement, and old-table drop flow. No unresolved merge-blocking issue is identified.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise, specific, and accurately describes the main change: fixing prepared plan cache behavior after a table rename.
Description check ✅ Passed The description includes the required issue number, problem summary, implementation details, tests, side effects, documentation impact, and release note. It is complete and aligned with the pull reque…
Linked Issues check ✅ Passed The changes satisfy issue #71041. planCachePreprocess clears schema-dependent metadata, reprocesses the resolved AST, collects the refreshed related table IDs, and rebuilds table metadata. This prev…
Out of Scope Changes check ✅ Passed The changes stay within issue #71041. The production changes repair stale prepared plan cache metadata after a table rename. The helper extraction preserves table metadata collection and error handlin…
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/prepared-rename-regression

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 table trail
Fresh plans hop where old names fail
t returns, while bak sleeps
The cache guards its schema peeps
Tests thump softly: all rows keep

Comment @coderabbitai help to get the list of available commands.

@ti-chi-bot

ti-chi-bot Bot commented Sep 14, 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 time-and-fate 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

@codecov

codecov Bot commented Sep 14, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 59.37500% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 72.4458%. Comparing base (419f965) to head (083097d).
⚠️ Report is 9 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #71042        +/-   ##
================================================
- Coverage   76.3176%   72.4458%   -3.8718%     
================================================
  Files          2041       2102        +61     
  Lines        556081     596713     +40632     
================================================
+ Hits         424388     432294      +7906     
- Misses       130793     163131     +32338     
- Partials        900       1288       +388     
Flag Coverage Δ
integration 40.7368% <59.3750%> (+1.0692%) ⬆️

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

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

@tiancaiamao
tiancaiamao force-pushed the fix/prepared-rename-regression branch from 7a0b49d to 6cc78f4 Compare September 14, 2026 08:37
@ti-chi-bot ti-chi-bot Bot added needs-cherry-pick-release-nextgen-20251011 Should cherry pick this PR to release-nextgen-20251011 branch. needs-cherry-pick-release-nextgen-202603 Should cherry pick this PR to release-nextgen-202603 branch. and removed do-not-merge/needs-triage-completed labels Sep 14, 2026
@tiancaiamao
tiancaiamao force-pushed the fix/prepared-rename-regression branch 4 times, most recently from 098ea1c to 5a00df4 Compare September 14, 2026 10:09
@tiancaiamao
tiancaiamao force-pushed the fix/prepared-rename-regression branch from 5a00df4 to 083097d Compare September 14, 2026 12:45
@tiancaiamao

Copy link
Copy Markdown
Contributor Author

/test check-dev2

1 similar comment
@tiancaiamao

Copy link
Copy Markdown
Contributor Author

/test check-dev2

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

Labels

needs-cherry-pick-release-nextgen-202603 Should cherry pick this PR to release-nextgen-202603 branch. needs-cherry-pick-release-nextgen-20251011 Should cherry pick this PR to release-nextgen-20251011 branch. release-note Denotes a PR that will be considered when it comes time to generate release notes. sig/planner SIG: Planner size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Prepared plan cache incorrectly references renamed table after DROP

2 participants