Skip to content

planner: fix IN-subquery join+agg rewrite duplication with implicit casted RHS keys - #66897

Merged
ti-chi-bot[bot] merged 1 commit into
pingcap:masterfrom
qw4990:fix-64230
Mar 11, 2026
Merged

ti-chi-bot[bot] merged 1 commit into
pingcap:masterfrom
qw4990:fix-64230

Conversation

@qw4990

@qw4990 qw4990 commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: close #64230

Problem Summary: planner: fix IN-subquery join+agg rewrite duplication with implicit casted RHS keys

What changed and how does it work?

Fix a semantic mismatch in IN (subquery) rewrite (tidb_opt_insubq_to_join_and_agg=1) that could duplicate outer rows when the inner comparison key is implicitly cast.

Before this change, TiDB could rewrite:

  • outer_col IN (SELECT inner_col ...)

into INNER JOIN + DISTINCT(inner_col) and deduplicate on raw inner values. In some cases (for example BLOB/string values compared to numeric), different raw inner values become equal after implicit cast during = comparison, so the rewritten join could match multiple inner rows and return duplicated outer rows.

This patch makes deduplication happen on the same RHS comparison key domain used by the join predicate:

  • materialize RHS comparison expression via inner projection when needed
  • apply DISTINCT on that projected key
  • rebuild join condition against the projected key

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 IN-subquery to join conversion to better handle type coercion in certain scenarios.
  • Tests

    • Added test coverage for blob data handling in join operations.
    • Expanded join test scenarios with additional edge cases.

@ti-chi-bot ti-chi-bot Bot added the release-note-none Denotes a PR that doesn't merit a release note. label Mar 11, 2026
@pantheon-ai

pantheon-ai Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

Review failed due to infrastructure/execution failure after retries. Please re-trigger review.

ℹ️ 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 11, 2026
@tiprow

tiprow Bot commented Mar 11, 2026

Copy link
Copy Markdown

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

coderabbitai Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 521d5f7e-8919-4555-b9f7-0edb4446247c

📥 Commits

Reviewing files that changed from the base of the PR and between 11a8d58 and 76e5cfb.

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

📝 Walkthrough

Walkthrough

This PR fixes a row duplication bug in IN-subquery processing by enhancing the query planner's IN-subquery-to-join rewrite logic. It adds support for projecting the RHS key when implicit casting occurs, enabling proper coercion handling. The fix includes comprehensive test cases covering BLOB columns and various join scenarios.

Changes

Cohort / File(s) Summary
Expression Rewriter Enhancement
pkg/planner/core/expression_rewriter.go
Added pre-projection path for IN-subquery rewrites to preserve coercion semantics. Introduces distinctChild and distinctLen tracking, adjusts join condition construction, and conditionally activates enhanced rewriting when no correlated columns exist at the plan level.
Integration Tests
tests/integrationtest/r/executor/jointest/join.result, tests/integrationtest/t/executor/jointest/join.test
Added test cases for BLOB column handling with IN-subqueries using hex representation, plus expanded join test scenarios with various hints (INL_JOIN, INL_HASH_JOIN, INL_MERGE_JOIN) to validate the fix.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

size/L, ok-to-test

Suggested reviewers

  • guo-shaoge
  • hawkingrei
  • terry1purcell

Poem

🐰 A subquery duped, now no more—
The planner's projection opens the door!
BLOB values bloom, distinct and true,
No phantom rows, the count rings through! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the core issue being fixed: a semantic mismatch in IN-subquery join+agg rewrite with implicit casted RHS keys.
Description check ✅ Passed The PR description includes issue number, problem summary, explanation of changes, and test configuration. All required sections are addressed.
Linked Issues check ✅ Passed The PR fixes the row duplication bug in issue #64230 by materializing RHS comparison expressions, applying DISTINCT on projected keys, and rebuilding join conditions [#64230].
Out of Scope Changes check ✅ Passed All changes directly address the bug fix: expression_rewriter.go implements the fix, and join test cases verify the fix works correctly for the reported BLOB duplication 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
  • Post copyable unit tests in a comment

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.

@qw4990 qw4990 added the AI-Correction Bugfix by AI label Mar 11, 2026
@qw4990

qw4990 commented Mar 11, 2026

Copy link
Copy Markdown
Contributor Author

@pantheon-ai please review

@pantheon-ai

pantheon-ai Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

⏳ @qw4990 I've received your follow-up and will continue on this pull request. I'll update this comment when I have something to share.

ℹ️ Learn more details on Pantheon AI.

@codecov

codecov Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.85714% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.4514%. Comparing base (9a618ad) to head (76e5cfb).
⚠️ Report is 7 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #66897        +/-   ##
================================================
- Coverage   77.6785%   77.4514%   -0.2271%     
================================================
  Files          2012       1933        -79     
  Lines        550824     538292     -12532     
================================================
- Hits         427872     416915     -10957     
- Misses       121244     121375       +131     
+ Partials       1708          2      -1706     
Flag Coverage Δ
integration 41.0914% <90.4761%> (-7.0946%) ⬇️
unit 76.5778% <92.8571%> (+0.3233%) ⬆️

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

Components Coverage Δ
dumpling 56.7974% <ø> (ø)
parser ∅ <ø> (∅)
br 48.8807% <ø> (-12.0403%) ⬇️
🚀 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.

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

ti-chi-bot Bot commented Mar 11, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

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

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 11, 2026
@ti-chi-bot

ti-chi-bot Bot commented Mar 11, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-03-11 06:31:09.250390757 +0000 UTC m=+418100.762448408: ☑️ agreed by hawkingrei.
  • 2026-03-11 07:09:59.227110718 +0000 UTC m=+420430.739168379: ☑️ agreed by AilinKid.

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

Labels

AI-Correction Bugfix by AI approved lgtm release-note-none Denotes a PR that doesn't merit a release note. 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.

Subquery in IN clause causes incorrect row duplication

3 participants