Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

planner: add newly created col for window projection #52378

Merged
merged 9 commits into from
Apr 9, 2024

Conversation

Rustin170506
Copy link
Member

@Rustin170506 Rustin170506 commented Apr 7, 2024

What problem does this PR solve?

Issue Number: close #42734

Problem Summary:

We will get a panic error during we execute the following SQL:

use test
CREATE TABLE temperature_data (temperature double);
CREATE TABLE humidity_data (humidity double);
CREATE TABLE weather_report (report_id double, report_date varchar(100));
INSERT INTO temperature_data VALUES (1.0);
INSERT INTO humidity_data VALUES (0.5);
INSERT INTO weather_report VALUES (2.0, 'test')
SELECT EXISTS
  (SELECT FIRST_VALUE(temp_data.temperature) OVER weather_window AS first_temperature,
                                                  MIN(report_data.report_id) OVER weather_window AS min_report_id
   FROM temperature_data AS temp_data WINDOW weather_window AS (PARTITION BY EXISTS
                                                                  (SELECT report_data.report_date AS report_date
                                                                   FROM humidity_data AS humidity_data
                                                                   WHERE temp_data.temperature >= humidity_data.humidity ))) AS is_exist
FROM weather_report AS report_data;

The problem happened in the TryToGetChildProp of the LogicalProjection plan.

// TryToGetChildProp will check if this sort property can be pushed or not.
// When a sort column will be replaced by scalar function, we refuse it.
// When a sort column will be replaced by a constant, we just remove it.
func (p *LogicalProjection) TryToGetChildProp(prop *property.PhysicalProperty) (*property.PhysicalProperty, bool) {
	newProp := prop.CloneEssentialFields()
	newCols := make([]property.SortItem, 0, len(prop.SortItems))
	for _, col := range prop.SortItems {
		idx := p.schema.ColumnIndex(col.Col)
+		switch expr := p.Exprs[idx].(type) {
		case *expression.Column:
			newCols = append(newCols, property.SortItem{Col: expr, Desc: col.Desc})
		case *expression.ScalarFunction:
			return nil, false
		}
	}
	newProp.SortItems = newCols
	return newProp, true
}

We cannot find the sort item from the projection's schema.

After I debugged it, I found that we will try to find the Coulmn#14 in the projection's schema. But we don't have it.

What changed and how does it work?

To understand this problem we need to take a look at the query plan after we fixed it :(

+-------------------------------------------+----------+-----------+---------------------+-------------------------------------------------------------------------------------------------------------------+
| id                                        | estRows  | task      | access object       | operator info                                                                                                     |
+-------------------------------------------+----------+-----------+---------------------+-------------------------------------------------------------------------------------------------------------------+
| Projection_15                             | 10000.00 | root      |                     | Column#20                                                                                                         |
| └─Apply_17                                | 10000.00 | root      |                     | CARTESIAN left outer semi join                                                                                    |
|   ├─TableReader_19(Build)                 | 10000.00 | root      |                     | data:TableFullScan_18                                                                                             |
|   │ └─TableFullScan_18                    | 10000.00 | cop[tikv] | table:report_data   | keep order:false, stats:pseudo                                                                                    |
|   └─Shuffle_29(Probe)                     | 10000.00 | root      |                     | execution info: concurrency:2, data sources:[Projection_22]                                                       |
|     └─Window_20                           | 10000.00 | root      |                     | first_value(test.temperature_data.temperature)->Column#16, min(Column#15)->Column#17 over(partition by Column#14) |
|       └─Sort_28                           | 10000.00 | root      |                     | Column#14                                                                                                         |
|         └─ShuffleReceiver_30              | 1.00     | root      |                     |                                                                                                                   |
|           └─Projection_22                 | 10000.00 | root      |                     | test.temperature_data.temperature, Column#14, test.weather_report.report_id->Column#15                            |
|             └─HashJoin_23                 | 10000.00 | root      |                     | CARTESIAN left outer semi join, other cond:ge(test.temperature_data.temperature, test.humidity_data.humidity)     |
|               ├─TableReader_27(Build)     | 10000.00 | root      |                     | data:TableFullScan_26                                                                                             |
|               │ └─TableFullScan_26        | 10000.00 | cop[tikv] | table:humidity_data | keep order:false, stats:pseudo                                                                                    |
|               └─TableReader_25(Probe)     | 10000.00 | root      |                     | data:TableFullScan_24                                                                                             |
|                 └─TableFullScan_24        | 10000.00 | cop[tikv] | table:temp_data     | keep order:false, stats:pseudo                                                                                    |
+-------------------------------------------+----------+-----------+---------------------+-------------------------------------------------------------------------------------------------------------------+
14 rows in set (0.00 sec)

As you can see the window is partitioned by Column#14 and it comes from the Projection_22.

Column#14 evaluates from the exist-subquery:

PARTITION BY EXISTS (
           SELECT
             report_data.report_date AS report_date
           FROM
             humidity_data AS humidity_data
           WHERE temp_data.temperature >= humidity_data.humidity
)

When we built this subquery we found it is a correlated query because we used temp_data.temperature as the predicate.

if b.disableSubQueryPreprocessing || len(ExtractCorrelatedCols4LogicalPlan(np)) > 0 || hasCTEConsumerInSubPlan(np) {
		planCtx.plan, er.err = b.buildSemiApply(planCtx.plan, np, nil, er.asScalar, v.Not, semiJoinRewrite, noDecorrelate)
		if er.err != nil || !er.asScalar {
			return v, true
		}
		er.ctxStackAppend(planCtx.plan.Schema().Columns[planCtx.plan.Schema().Len()-1], planCtx.plan.OutputNames()[planCtx.plan.Schema().Len()-1])

Then the problem came out from the buildByItemsForWindow, because we used the column from the semi-apply plan as our sort item during the expression rewrite then we forget to add this column into the projection's schema:

	for _, item := range items {
		newExpr, _ := item.Expr.Accept(transformer)
		item.Expr = newExpr.(ast.ExprNode)
		it, np, err := b.rewrite(ctx, item.Expr, p, aggMap, true)
		if err != nil {
			return nil, nil, err
		}
		p = np
		if it.GetType().GetType() == mysql.TypeNull {
			continue
		}
		if col, ok := it.(*expression.Column); ok {
+.          // This column comes from the semi-apply
+			retItems = append(retItems, property.SortItem{Col: col, Desc: item.Desc})
+           continue
        }

So the fix is that we need to append this col to the top-level projection schema:

	for _, item := range items {
		newExpr, _ := item.Expr.Accept(transformer)
		item.Expr = newExpr.(ast.ExprNode)
		it, np, err := b.rewrite(ctx, item.Expr, p, aggMap, true)
		if err != nil {
			return nil, nil, err
		}
		p = np
		if it.GetType().GetType() == mysql.TypeNull {
			continue
		}
		if col, ok := it.(*expression.Column); ok {
			retItems = append(retItems, property.SortItem{Col: col, Desc: item.Desc})
+			// If the column is already in the schema, we don't need to add it again.
+			if !proj.schema.Contains(col) {
+				proj.Exprs = append(proj.Exprs, col)
+				proj.schema.Append(col)
+				proj.names = append(proj.names, types.EmptyName)
+			}
			continue
		}

And also we need to avoid adding the same column twice, for example:

   SELECT
     EXISTS (
       SELECT
         FIRST_VALUE(temp_data.temperature) OVER weather_window AS first_temperature,
         MIN(report_data.report_id) OVER weather_window AS min_report_id
       FROM
         temperature_data AS temp_data
       WINDOW weather_window AS (
         PARTITION BY temp_data.temperature 
       )
     ) AS is_exist
   FROM
     weather_report AS report_data;

As you can see we partition the window by itself then we already have it in the projection's
schema. So we don't need to add it again.
The query plan looks like this

+----------------------------------+---------+-----------+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------+
| id                               | estRows | task      | access object     | operator info                                                                                                                             |
+----------------------------------+---------+-----------+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------+
| Projection_11                    | 1.00    | root      |                   | Column#16                                                                                                                                 |
| └─Apply_13                       | 1.00    | root      |                   | CARTESIAN left outer semi join                                                                                                            |
|   ├─TableReader_15(Build)        | 1.00    | root      |                   | data:TableFullScan_14                                                                                                                     |
|   │ └─TableFullScan_14           | 1.00    | cop[tikv] | table:report_data | keep order:false, stats:pseudo                                                                                                            |
|   └─Window_16(Probe)             | 1.00    | root      |                   | first_value(test.temperature_data.temperature)->Column#12, min(Column#11)->Column#13 over(partition by test.temperature_data.temperature) |
|     └─Sort_21                    | 1.00    | root      |                   | test.temperature_data.temperature                                                                                                         |
|       └─Projection_18            | 1.00    | root      |                   | test.temperature_data.temperature, test.weather_report.report_id->Column#11                                                               |
|         └─TableReader_20         | 1.00    | root      |                   | data:TableFullScan_19                                                                                                                     |
|           └─TableFullScan_19     | 1.00    | cop[tikv] | table:temp_data   | keep order:false, stats:pseudo                                                                                                            |
+----------------------------------+---------+-----------+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------+

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

Copy link

ti-chi-bot bot commented Apr 7, 2024

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-triage-completed do-not-merge/needs-tests-checked do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. release-note-none Denotes a PR that doesn't merit a release note. labels Apr 7, 2024
Copy link

tiprow bot commented Apr 7, 2024

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 the size/M Denotes a PR that changes 30-99 lines, ignoring generated files. label Apr 7, 2024
@Rustin170506 Rustin170506 marked this pull request as ready for review April 8, 2024 09:35
@Rustin170506 Rustin170506 changed the title WIP: test: add a test for issue 42734 planner: add newly created col Apr 8, 2024
@ti-chi-bot ti-chi-bot bot removed do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. do-not-merge/needs-triage-completed labels Apr 8, 2024
@Rustin170506
Copy link
Member Author

/retest

@Rustin170506 Rustin170506 changed the title planner: add newly created col planner: add newly created col for window projection Apr 9, 2024
@ti-chi-bot ti-chi-bot bot added approved needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Apr 9, 2024
@@ -6502,6 +6502,14 @@ func (b *PlanBuilder) buildByItemsForWindow(
}
if col, ok := it.(*expression.Column); ok {
retItems = append(retItems, property.SortItem{Col: col, Desc: item.Desc})
// We need to attempt to add this column because a subquery may be created during the expression rewrite process.
Copy link
Contributor

Choose a reason for hiding this comment

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

This 3 lines is same as the under 3 lines from 6515 to 6521.
So should you please change those code more unified ~

Copy link
Member Author

@Rustin170506 Rustin170506 Apr 9, 2024

Choose a reason for hiding this comment

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

Updated. I have reordered the code to make them have the same order.

@ti-chi-bot ti-chi-bot bot added the sig/planner SIG: Planner label Apr 9, 2024
@ti-chi-bot ti-chi-bot bot added the lgtm label Apr 9, 2024
Copy link

ti-chi-bot bot commented Apr 9, 2024

[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

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 removed the needs-1-more-lgtm Indicates a PR needs 1 more LGTM. label Apr 9, 2024
Copy link

ti-chi-bot bot commented Apr 9, 2024

[LGTM Timeline notifier]

Timeline:

  • 2024-04-09 06:34:25.791279538 +0000 UTC m=+944127.318820085: ☑️ agreed by AilinKid.
  • 2024-04-09 07:06:00.997826115 +0000 UTC m=+946022.525366662: ☑️ agreed by hawkingrei.

@ti-chi-bot ti-chi-bot bot merged commit 9b78a23 into pingcap:master Apr 9, 2024
22 of 23 checks passed
@Rustin170506 Rustin170506 deleted the rustin-patch-issue-42734 branch April 9, 2024 12:54
@ti-chi-bot ti-chi-bot added needs-cherry-pick-release-7.5 Should cherry pick this PR to release-7.5 branch. needs-cherry-pick-release-7.1 Should cherry pick this PR to release-7.1 branch. labels Apr 11, 2024
@ti-chi-bot
Copy link
Member

In response to a cherrypick label: new pull request created to branch release-7.5: #52488.

@ti-chi-bot
Copy link
Member

In response to a cherrypick label: new pull request created to branch release-7.1: #52489.

ti-chi-bot pushed a commit to ti-chi-bot/tidb that referenced this pull request Apr 11, 2024
Signed-off-by: ti-chi-bot <ti-community-prow-bot@tidb.io>
@Rustin170506 Rustin170506 added the needs-cherry-pick-release-8.1 Should cherry pick this PR to release-8.1 branch. label Jul 29, 2024
ti-chi-bot pushed a commit to ti-chi-bot/tidb that referenced this pull request Jul 29, 2024
@ti-chi-bot
Copy link
Member

In response to a cherrypick label: new pull request created to branch release-8.1: #55003.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
approved lgtm needs-cherry-pick-release-7.1 Should cherry pick this PR to release-7.1 branch. needs-cherry-pick-release-7.5 Should cherry pick this PR to release-7.5 branch. needs-cherry-pick-release-8.1 Should cherry pick this PR to release-8.1 branch. 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.

Panic triggered at core.(*LogicalProjection).TryToGetChildProp (planner/core/exhaust_physical_plans.go:2500)
5 participants