Skip to content

planner: fix ErrViewInvalid caused by view constant folding#67123

Merged
ti-chi-bot[bot] merged 2 commits into
pingcap:masterfrom
expxiaoli:fix_65832
Mar 25, 2026
Merged

planner: fix ErrViewInvalid caused by view constant folding#67123
ti-chi-bot[bot] merged 2 commits into
pingcap:masterfrom
expxiaoli:fix_65832

Conversation

@expxiaoli
Copy link
Copy Markdown
Contributor

@expxiaoli expxiaoli commented Mar 18, 2026

What problem does this PR solve?

Issue Number: close #65832

Problem Summary:

When a view containing a constant predicate such as WHERE '' is referenced from an INSERT ... ON DUPLICATE KEY UPDATE subquery, TiDB may incorrectly return ErrViewInvalid in strict SQL mode.

The root cause is that planner-time constant folding in buildSelection inherits the outer DML statement's truncate handling. Evaluating WHERE '' under strict DML can raise ErrTruncatedWrongVal, and this planner error is later wrapped as ErrViewInvalid during view expansion.

What changed and how does it work?

This PR fixes the issue by relaxing truncate handling only for planner-time constant predicate folding in buildSelection.

Instead of mutating the global StatementContext while expanding a view, the fix uses a temporary expression context when evaluating constant predicates. This keeps the change local to planner evaluation and avoids leaking semantics to the outer statement.

A regression test is also added to cover the reported case in executor/insert.

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.

Test commands:

/bin/zsh -lc 'PATH=/Users/xiaoli/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.25.8.darwin-arm64/bin:$PATH GOSUMDB=off make -C ../.. server SERVER_OUT=$PWD/integrationtest_tidb-server RACE_FLAG="-race"'
/bin/zsh -lc 'PATH=/Users/xiaoli/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.25.8.darwin-arm64/bin:$PATH GOSUMDB=off ./run-tests.sh -t executor/insert -s ./integrationtest_tidb-server'
/bin/zsh -lc 'mkdir -p /tmp/tidb-gocache && GOCACHE=/tmp/tidb-gocache GOSUMDB=off /Users/xiaoli/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.25.8.darwin-arm64/bin/go test -run TestPlannerIssueRegressions -tags=intest,deadlock ./pkg/planner/core/issuetest'
/bin/zsh -lc 'mkdir -p /tmp/tidb-gocache && PATH=/Users/xiaoli/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.25.8.darwin-arm64/bin:$PATH GOCACHE=/tmp/tidb-gocache GOSUMDB=sum.golang.org make lint'

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

Fix a bug where `INSERT ... ON DUPLICATE KEY UPDATE` with a subquery referencing a view could incorrectly return `ErrViewInvalid` when planner constant folding evaluated a view predicate such as `WHERE ''` under strict SQL mode.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed incorrect behavior for INSERT ... ON DUPLICATE KEY UPDATE that involved subqueries and views under STRICT_TRANS_TABLES, ensuring correct results and error handling.
  • Tests

    • Added regression tests covering INSERT with subqueries and views to prevent reoccurrence.

@ti-chi-bot ti-chi-bot Bot added the release-note Denotes a PR that will be considered when it comes time to generate release notes. label Mar 18, 2026
@pantheon-ai
Copy link
Copy Markdown

pantheon-ai Bot commented Mar 18, 2026

Review Complete

Findings: 0 issues
Posted: 0
Duplicates/Skipped: 0

ℹ️ Learn more details on Pantheon AI.

@ti-chi-bot ti-chi-bot Bot added sig/planner SIG: Planner size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Mar 18, 2026
@tiprow
Copy link
Copy Markdown

tiprow Bot commented Mar 18, 2026

Hi @expxiaoli. 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.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 18, 2026

📝 Walkthrough

Walkthrough

Modify the planner to ignore truncate errors during constant predicate folding when expanding views by setting a per-build flag and using a wrapped expression context; add regression tests covering INSERT ... ON DUPLICATE KEY UPDATE with a view and STRICT_TRANS_TABLES mode.

Changes

Cohort / File(s) Summary
PlanBuilder state
pkg/planner/core/planbuilder.go
Add unexported boolean field ignoreTruncateErrForViewPredicateFolding to narrow truncate-relaxation behavior to view predicate folding.
View expansion / constant-folding
pkg/planner/core/logical_plan_builder.go
When evaluating constant CNF items for plan cache folding, use a foldEvalCtx derived from b.ctx.GetExprCtx() and, if the flag is set, wrap it with exprctx.CtxWithHandleTruncateErrLevel(..., errctx.LevelIgnore) so expression.EvalBool ignores truncate errors; temporarily set/restore the flag in BuildDataSourceFromView.
Regression tests
tests/integrationtest/t/executor/insert.test, tests/integrationtest/r/executor/insert.result
Add a regression test exercising INSERT ... ON DUPLICATE KEY UPDATE that references a view with a constant predicate under STRICT_TRANS_TABLES, verifying the view expansion and constant-folding behavior and restoring sql_mode afterward.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant PlanBuilder
    participant ViewExpander
    participant ExprCtx
    participant ExprEvaluator

    Client->>PlanBuilder: Build plan for INSERT ... ON DUPLICATE KEY UPDATE
    PlanBuilder->>PlanBuilder: set ignoreTruncateErrForViewPredicateFolding = true
    PlanBuilder->>ViewExpander: BuildDataSourceFromView()
    ViewExpander->>ExprCtx: b.ctx.GetExprCtx()
    Note right of ExprCtx: wrap with CtxWithHandleTruncateErrLevel(LevelIgnore)
    ViewExpander->>ExprEvaluator: EvalBool(constant CNF items) using foldEvalCtx
    ExprEvaluator-->>ViewExpander: evaluation result (ignore truncate errors)
    ViewExpander-->>PlanBuilder: expanded view plan
    PlanBuilder->>PlanBuilder: restore ignoreTruncateErrForViewPredicateFolding
    PlanBuilder-->>Client: final plan
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

ok-to-test

Suggested reviewers

  • hawkingrei
  • winoros
  • guo-shaoge

Poem

🐰 I hopped through plans and views today,
Folded constants in a careful way,
I whispered "ignore" to truncate's fuss,
Now views expand without a cuss,
Hooray—no more errors on the way! 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: fixing an ErrViewInvalid error caused by view constant folding in the planner, which is the core problem addressed in the PR.
Description check ✅ Passed The description is comprehensive and follows the template, including issue number, problem summary, explanation of the fix, test coverage, release notes, and checked items.
Linked Issues check ✅ Passed The PR directly addresses issue #65832 by fixing the ErrViewInvalid error when a view with constant predicate (WHERE '') is used in INSERT...ON DUPLICATE KEY UPDATE subqueries, implementing the required fix in buildSelection and BuildDataSourceFromView.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing issue #65832: adding the ignoreTruncateErrForViewPredicateFolding field, modifying buildSelection and BuildDataSourceFromView logic, and adding regression tests for the specific issue.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

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.3)

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.

🧹 Nitpick comments (1)
tests/integrationtest/t/executor/insert.test (1)

1794-1798: Optional: make setup idempotent for interrupted local reruns.

Consider defensive DROP ... IF EXISTS before CREATE so reruns don't fail early if artifacts remain from a prior aborted run.

♻️ Proposed tweak
 SET `@old_sql_mode_65832` = @@sql_mode;
 SET sql_mode = 'STRICT_TRANS_TABLES';
+DROP VIEW IF EXISTS v_65832;
+DROP TABLE IF EXISTS t_65832_0, t_65832_1;
 CREATE TABLE t_65832_0(c0 BLOB(304));
 CREATE TABLE t_65832_1(c0 CHAR DEFAULT '0');
 CREATE VIEW v_65832(c0) AS SELECT 0.9699394901011086 FROM t_65832_0 INNER JOIN t_65832_0 AS t0_alias ON t_65832_0.c0 WHERE '';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/integrationtest/t/executor/insert.test` around lines 1794 - 1798, Make
the setup idempotent by adding defensive DROP statements before the CREATEs: run
DROP VIEW IF EXISTS v_65832; DROP TABLE IF EXISTS t_65832_1; DROP TABLE IF
EXISTS t_65832_0; then proceed with CREATE TABLE t_65832_0(...), CREATE TABLE
t_65832_1(...), and CREATE VIEW v_65832(...) so interrupted or repeated test
runs won’t fail due to leftover artifacts.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tests/integrationtest/t/executor/insert.test`:
- Around line 1794-1798: Make the setup idempotent by adding defensive DROP
statements before the CREATEs: run DROP VIEW IF EXISTS v_65832; DROP TABLE IF
EXISTS t_65832_1; DROP TABLE IF EXISTS t_65832_0; then proceed with CREATE TABLE
t_65832_0(...), CREATE TABLE t_65832_1(...), and CREATE VIEW v_65832(...) so
interrupted or repeated test runs won’t fail due to leftover artifacts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 03e1d29b-db50-42ae-86ab-688e0ce0d5a0

📥 Commits

Reviewing files that changed from the base of the PR and between 943819a and 206b840.

📒 Files selected for processing (3)
  • pkg/planner/core/logical_plan_builder.go
  • tests/integrationtest/r/executor/insert.result
  • tests/integrationtest/t/executor/insert.test

Copy link
Copy Markdown

@pantheon-ai pantheon-ai Bot left a comment

Choose a reason for hiding this comment

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

✅ Code looks good. No issues found.

@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 18, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.0217%. Comparing base (943819a) to head (94bfd06).
⚠️ Report is 49 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #67123        +/-   ##
================================================
+ Coverage   77.6906%   78.0217%   +0.3311%     
================================================
  Files          2016       1945        -71     
  Lines        552163     543515      -8648     
================================================
- Hits         428979     424060      -4919     
+ Misses       121442     119007      -2435     
+ Partials       1742        448      -1294     
Flag Coverage Δ
integration 43.6929% <100.0000%> (-4.4316%) ⬇️
unit 76.5545% <100.0000%> (+0.3329%) ⬆️

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

Components Coverage Δ
dumpling 57.0098% <ø> (ø)
parser ∅ <ø> (∅)
br 47.5165% <ø> (-13.3380%) ⬇️
🚀 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.

@expxiaoli
Copy link
Copy Markdown
Contributor Author

/retest-required

@tiprow
Copy link
Copy Markdown

tiprow Bot commented Mar 19, 2026

@expxiaoli: 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.

Details

In response to this:

/retest-required

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.

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.

🧹 Nitpick comments (1)
pkg/planner/core/logical_plan_builder.go (1)

5195-5201: Please add a planner-level regression test for this flag.

The executor regression covers the user-visible symptom, but this state toggle now guards planner-only behavior during view expansion. A focused planner test around BuildDataSourceFromView/buildSelection would make future refactors safer.

Based on learnings: Applies to pkg/planner/** : For planner rule or logical/physical plan changes, perform targeted planner unit tests and update rule testdata when needed.

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

In `@pkg/planner/core/logical_plan_builder.go` around lines 5195 - 5201, Add a
planner-level regression test that exercises BuildDataSourceFromView (and/or
buildSelection) to verify the planner-only toggle
ignoreTruncateErrForViewPredicateFolding is applied during view expansion: set
up a view with a folding-eligible constant predicate that would normally raise a
truncate error, invoke the planner routine that expands the view, and assert
that predicate folding proceeds without surfacing a truncate error while the
outer statement semantics remain unchanged; also include a complementary case
ensuring the flag is false outside the expansion. Locate references to
ignoreTruncateErrForViewPredicateFolding, BuildDataSourceFromView, and
buildSelection when adding the test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@pkg/planner/core/logical_plan_builder.go`:
- Around line 5195-5201: Add a planner-level regression test that exercises
BuildDataSourceFromView (and/or buildSelection) to verify the planner-only
toggle ignoreTruncateErrForViewPredicateFolding is applied during view
expansion: set up a view with a folding-eligible constant predicate that would
normally raise a truncate error, invoke the planner routine that expands the
view, and assert that predicate folding proceeds without surfacing a truncate
error while the outer statement semantics remain unchanged; also include a
complementary case ensuring the flag is false outside the expansion. Locate
references to ignoreTruncateErrForViewPredicateFolding, BuildDataSourceFromView,
and buildSelection when adding the test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2df80cd3-d4d1-4a67-a215-402f29669cfa

📥 Commits

Reviewing files that changed from the base of the PR and between 206b840 and 94bfd06.

📒 Files selected for processing (2)
  • pkg/planner/core/logical_plan_builder.go
  • pkg/planner/core/planbuilder.go

@expxiaoli
Copy link
Copy Markdown
Contributor Author

/retest-required

@tiprow
Copy link
Copy Markdown

tiprow Bot commented Mar 20, 2026

@expxiaoli: 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.

Details

In response to this:

/retest-required

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.

@hawkingrei
Copy link
Copy Markdown
Member

@pantheon-bot review

@pantheon-ai
Copy link
Copy Markdown

pantheon-ai Bot commented Mar 23, 2026

Review Complete

Findings: 0 issues
Posted: 0
Duplicates/Skipped: 0

ℹ️ Learn more details on Pantheon AI.

@ti-chi-bot ti-chi-bot Bot added approved needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Mar 23, 2026
@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Mar 25, 2026

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: hawkingrei, winoros

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 added lgtm and removed needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Mar 25, 2026
@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Mar 25, 2026

[LGTM Timeline notifier]

Timeline:

  • 2026-03-23 05:38:42.239925747 +0000 UTC m=+160318.275996008: ☑️ agreed by hawkingrei.
  • 2026-03-25 12:01:27.927887859 +0000 UTC m=+356083.963958109: ☑️ agreed by winoros.

@ti-chi-bot ti-chi-bot Bot merged commit 800b850 into pingcap:master Mar 25, 2026
24 of 35 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm 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.

Unexpected error View references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them

3 participants