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

feat: optimise outer joins #15840

Merged
merged 25 commits into from
May 24, 2024
Merged

Conversation

systay
Copy link
Collaborator

@systay systay commented May 4, 2024

Description

This PR introduces enhancements to the query planner, enabling the push down of LIMIT clauses to the right-hand side (RHS) of joins, including outer joins, when the expressions permit. Additionally, logic has been added to push down LIMIT under routes when applicable.

These changes aim to optimize query efficiency and resource utilization, ensuring faster query processing and lower overhead in the presence of outer joins.

For inner joins, we can't push down LIMIT on the left-hand side (LHS) of our nested loop joins (ApplyJoin). For a join to produce a row, we need a match on both sides, and we don't know how many rows we need from the LHS for the join to produce sufficient rows to satisfy the user-set LIMIT. The best we can do is push a LIMIT on the RHS and then also LIMIT on top of the join.

On the other hand, for left outer joins, we know that every row from the LHS will be returned from the join. This means we can push down the LIMIT to the LHS of the join. This is really good and important - we want to run the RHS of the join as few times as possible.

Example

SELECT * 
FROM user 
  JOIN user_extra ON user.col = user_extra.col
LIMIT 10

The first, unoptimized version of the query with the LIMIT looks like this:

Limit
└── ApplyJoin
    ├── Route
    │   └── Table (user.user)
    └── Route
        └── Filter (joinCondition)
            └── Table (user.user_extra)

Now we rewrite by doing iterative tree rewrites until we reach a fixed point. It will look something like this:

Limit (1)
└── ApplyJoin
    ├── Limit (2)
    │   └── Route
    │       └── Limit (3)
    │           └── Table (user.user)
    └── Limit (4)
        └── Route
            └── Limit (5)
                └── Filter (joinCondition)
                    └── Table (user.user_extra)

Here are the reasons for the different LIMIT operations:

  1. This is the top LIMIT. It ensures that the final results do not contain more than 10 rows.
  2. We want to run as few rows through our ApplyJoin as possible, so if the Route under is not a single-sharded Route, we add a LIMIT on top of the LHS of the JOIN.
  3. We know we don't need more than 10 rows from each shard, so we can push down the LIMIT under the route. 🎉
  4. Similar to (2) - if the route under is touching multiple shards, we keep a LIMIT on top of the Route to minimize the number of rows processed by the join.
  5. Finally, we know we don't need more than 10 rows from any shard on the RHS of the join.

Related Issue(s)

Fixes #15828

Checklist

  • "Backport to:" labels have been added if this change should be back-ported to release branches
  • If this change is to be back-ported to previous releases, a justification is included in the PR description
  • Tests were added or are not required
  • Did the new or modified tests pass consistently locally and on CI?
  • Documentation was added or is not required**

Copy link
Contributor

vitess-bot bot commented May 4, 2024

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

@vitess-bot vitess-bot bot added NeedsBackportReason If backport labels have been applied to a PR, a justification is required NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsWebsiteDocsUpdate What it says labels May 4, 2024
@github-actions github-actions bot added this to the v20.0.0 milestone May 4, 2024
@systay systay added Type: Enhancement Logical improvement (somewhere between a bug and feature) Component: Query Serving and removed NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsWebsiteDocsUpdate What it says NeedsIssue A linked issue is missing for this Pull Request NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels May 4, 2024
@systay systay marked this pull request as ready for review May 4, 2024 09:09
Copy link

codecov bot commented May 4, 2024

Codecov Report

Attention: Patch coverage is 86.84211% with 20 lines in your changes are missing coverage. Please review.

Project coverage is 68.25%. Comparing base (a1edaee) to head (4a6ccd1).
Report is 3 commits behind head on main.

Files Patch % Lines
go/vt/vtgate/engine/simple_projection.go 57.89% 8 Missing ⚠️
go/vt/vtgate/planbuilder/operators/limit.go 14.28% 6 Missing ⚠️
.../vt/vtgate/planbuilder/operators/query_planning.go 92.85% 5 Missing ⚠️
go/vt/vtgate/planbuilder/operators/rewriters.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15840      +/-   ##
==========================================
+ Coverage   68.24%   68.25%   +0.01%     
==========================================
  Files        1562     1562              
  Lines      197171   197300     +129     
==========================================
+ Hits       134550   134669     +119     
- Misses      62621    62631      +10     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Comment on lines +36 to +38
func IsOuter(outer JoinOp) bool {
return !outer.IsInner()
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Would it make sense to define this on the JoinOp type? I'm not really sure when we prefer that over a standalone function, so I'm asking mostly out of curiosity. 🙇‍♂️

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I did consider that, but that forces all implementations to have to have an implementation of this method, and that seems silly.

If golang had some way of defining method implementations on interfaces, I'd use that

Copy link
Member

@frouioui frouioui left a comment

Choose a reason for hiding this comment

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

There seems to be an issue with TestAliasesInOuterJoinQueries when running an outer join where the column names returned are different than what MySQL is sending back. Instead of "t0", "t1", "col" we are getting "t0", "t0", "col"

go/vt/vtgate/executor_select_test.go Show resolved Hide resolved
@systay systay self-assigned this May 8, 2024
Copy link
Member

@harshit-gangal harshit-gangal left a comment

Choose a reason for hiding this comment

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

There is no end to end test for this change.
I see MySQL syntax error for

select * from t limit 1 + 2;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '+ 2' at line 1

@systay systay requested a review from deepthi as a code owner May 9, 2024 08:42
systay added 14 commits May 23, 2024 12:25
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
@systay systay mentioned this pull request May 23, 2024
5 tasks
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
Signed-off-by: Andres Taylor <andres@planetscale.com>
@systay systay removed the Benchmark me Add label to PR to run benchmarks label May 23, 2024
Comment on lines +366 to +369
if len(op.Source.GetColumns(ctx)) == len(cols) && offsetInInputOrder(cols) {
cols = nil
}
return newSimpleProjection(cols, colNames, src)
Copy link
Member

Choose a reason for hiding this comment

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

I think we can still do better here by changing a little more on simple projection like checking len(op.Source.GetColumns(ctx)) >= len(cols). And Simple project truncates from the end.

can leave a TODO here if you think it make sense.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

the columns need to be of the expected size. we should not return more columns than what the user asked for

Copy link
Member

Choose a reason for hiding this comment

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

yes, we can do again minimal work of truncate. not important for this PR

@systay systay merged commit 0cc5acd into vitessio:main May 24, 2024
94 checks passed
@systay systay deleted the left-join-optimize branch May 24, 2024 07:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component: Query Serving Type: Enhancement Logical improvement (somewhere between a bug and feature)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bug Report: too many rows fetched by multi-shard left join
5 participants