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

Improve performance for BaseShowTablesWithSizes query. #15713

Merged
merged 3 commits into from
Apr 25, 2024

Conversation

arthurschreiber
Copy link
Contributor

@arthurschreiber arthurschreiber commented Apr 15, 2024

Description

BaseShowTablesWithSizes is executed whenever a vttablet process starts up.

We use vtcombo in our CI environment, with many different keyspaces defined in the topology or created dynamically via CREATE DATABASE. We noticed that when upgrading from MySQL 5.7 to MySQL 8.0 in our CI environment, the vtcombo startup time and the database setup times in our build jobs started to be almost twice as long as with MySQL 8.0.

I was able to trace this down to the differences in the BaseShowTablesWithSizes query.

The MySQL 8.0 version uses two queries combined via UNION. The problem here is that each of the two parts of the UNION ends up joining information_schema.innodb_tablespaces. information_schema.innodb_tablespaces is a MySQL system table that I believe MySQL fills on-demand with all available tablespace data, and then applies any conditions from the WHERE or ON clauses via full table scans. In short, accessing this table is expensive, and accessing it twice in separate queries doubles the cost of accessing it.

On my system, I currently have around 14k tablespaces:

mysql> SELECT COUNT(*) FROM information_schema.innodb_tablespaces;
+----------+
| COUNT(*) |
+----------+
|    14026 |
+----------+
1 row in set (0.18 sec)

Running the original query takes 0.4 seconds:

mysql> SELECT t.table_name,
    -> t.table_type,
    -> UNIX_TIMESTAMP(t.create_time),
    -> t.table_comment,
    -> i.file_size,
    -> i.allocated_size
    -> FROM information_schema.tables t
    -> LEFT JOIN information_schema.innodb_tablespaces i
    -> ON i.name = CONCAT(t.table_schema, '/', t.table_name) COLLATE utf8mb3_general_ci
    -> WHERE
    -> t.table_schema = database() AND not t.create_options <=> 'partitioned'
    -> UNION ALL
    -> SELECT
    -> t.table_name,
    -> t.table_type,
    -> UNIX_TIMESTAMP(t.create_time),
    -> t.table_comment,
    -> SUM(i.file_size),
    -> SUM(i.allocated_size)
    -> FROM information_schema.tables t
    -> LEFT JOIN information_schema.innodb_tablespaces i
    -> ON i.name LIKE (CONCAT(t.table_schema, '/', t.table_name, '#p#%') COLLATE utf8mb3_general_ci )
    -> WHERE
    -> t.table_schema = database() AND t.create_options <=> 'partitioned'
    -> GROUP BY
    -> t.table_schema, t.table_name, t.table_type, t.create_time, t.table_comment\G
Empty set (0.41 sec)

Running the query I'm proposing here takes half the time:

mysql> SELECT t.table_name,
    -> t.table_type,
    -> UNIX_TIMESTAMP(t.create_time),
    -> t.table_comment,
    -> SUM(i.file_size),
    -> SUM(i.allocated_size)
    -> FROM information_schema.tables t
    -> LEFT JOIN information_schema.innodb_tablespaces i
    -> ON i.name LIKE CONCAT(t.table_schema, '/', t.table_name, IF(t.create_options <=> 'partitioned', '#p#%', '')) COLLATE utf8mb3_general_ci
    -> WHERE
    -> t.table_schema = database()
    -> GROUP BY
    -> t.table_schema, t.table_name, t.table_type, t.create_time, t.table_comment
    -> \G
Empty set (0.19 sec)

Related Issue(s)

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

Deployment Notes

Copy link
Contributor

vitess-bot bot commented Apr 15, 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 Apr 15, 2024
@github-actions github-actions bot added this to the v20.0.0 milestone Apr 15, 2024
@arthurschreiber
Copy link
Contributor Author

@shlomi-noach can you take a look? I remember you recently tried to optimize this query as well.

@arthurschreiber arthurschreiber added Backport to: release-17.0 Needs to be back ported to release-17.0 Backport to: release-18.0 Needs to be back ported to release-18.0 Backport to: release-19.0 Needs to be back ported to release-19.0 and removed NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels Apr 15, 2024
Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
@arthurschreiber arthurschreiber force-pushed the arthur/improve-mysql8-table-query branch from af92c65 to 6bd23ca Compare April 15, 2024 14:18
@arthurschreiber arthurschreiber added Type: Performance and removed NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsWebsiteDocsUpdate What it says labels Apr 15, 2024
@shlomi-noach shlomi-noach self-assigned this Apr 15, 2024
Copy link

codecov bot commented Apr 15, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 68.95%. Comparing base (f118ba2) to head (78e5557).
Report is 31 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15713      +/-   ##
==========================================
+ Coverage   68.40%   68.95%   +0.55%     
==========================================
  Files        1556     1558       +2     
  Lines      195121   204509    +9388     
==========================================
+ Hits       133479   141026    +7547     
- Misses      61642    63483    +1841     

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

@arthurschreiber arthurschreiber removed the NeedsIssue A linked issue is missing for this Pull Request label Apr 15, 2024
Copy link
Contributor

@shlomi-noach shlomi-noach left a comment

Choose a reason for hiding this comment

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

In #13375 I made the split to optimize the query -- kudos on being able to unsplit it and optimize even further. It appears like we don't test this query, or perhaps the test is buried deep down. @arthurschreiber would you mind:

  • looking for where this query is tested
  • if not already tested, create tests for both partitioned and unpartitioned scenarios
  • Add a comment to the query, indicating where this is being tested?

@arthurschreiber
Copy link
Contributor Author

@shlomi-noach Thanks for taking a look! I believe this query is implicitly tested via some of the existing test cases, but I can try to find out exactly which test cases cover it.

I'll see if I can add tests that at least cover the partitioned / non partitioned table handling a bit better.

@arthurschreiber
Copy link
Contributor Author

arthurschreiber commented Apr 19, 2024

@shlomi-noach I found some existing test cases here, so I guess no need test cases need to be added? The coverage seems sufficient IMHO.

func TestShowTablesWithSizes(t *testing.T) {
ctx := context.Background()
conn, err := mysql.Connect(ctx, &connParams)
require.NoError(t, err)
defer conn.Close()
setupQueries := []string{
`drop view if exists show_tables_with_sizes_v1`,
`drop table if exists show_tables_with_sizes_t1`,
`drop table if exists show_tables_with_sizes_employees`,
`create table show_tables_with_sizes_t1 (id int primary key)`,
`create view show_tables_with_sizes_v1 as select * from show_tables_with_sizes_t1`,
`CREATE TABLE show_tables_with_sizes_employees (id INT NOT NULL, store_id INT) PARTITION BY HASH(store_id) PARTITIONS 4`,
}
defer func() {
_, _ = conn.ExecuteFetch(`drop view if exists show_tables_with_sizes_v1`, 1, false)
_, _ = conn.ExecuteFetch(`drop table if exists show_tables_with_sizes_t1`, 1, false)
_, _ = conn.ExecuteFetch(`drop table if exists show_tables_with_sizes_employees`, 1, false)
}()
for _, query := range setupQueries {
_, err := conn.ExecuteFetch(query, 1, false)
require.NoError(t, err)
}
expectTables := map[string]([]string){ // TABLE_TYPE, TABLE_COMMENT
"show_tables_with_sizes_t1": {"BASE TABLE", ""},
"show_tables_with_sizes_v1": {"VIEW", "VIEW"},
"show_tables_with_sizes_employees": {"BASE TABLE", ""},
}
rs, err := conn.ExecuteFetch(conn.BaseShowTablesWithSizes(), -1, false)
require.NoError(t, err)
require.NotEmpty(t, rs.Rows)
assert.GreaterOrEqual(t, len(rs.Rows), len(expectTables))
matchedTables := map[string]bool{}
for _, row := range rs.Rows {
tableName := row[0].ToString()
vals, ok := expectTables[tableName]
if ok {
assert.Equal(t, vals[0], row[1].ToString()) // TABLE_TYPE
assert.Equal(t, vals[1], row[3].ToString()) // TABLE_COMMENT
matchedTables[tableName] = true
}
}
assert.Equalf(t, len(expectTables), len(matchedTables), "%v", matchedTables)
}

Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
@arthurschreiber
Copy link
Contributor Author

@shlomi-noach I pushed some light refactoring of the test case.

Copy link
Member

@deepthi deepthi left a comment

Choose a reason for hiding this comment

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

Nice work on improving the tests too!

go/mysql/flavor_mysql.go Outdated Show resolved Hide resolved
Co-authored-by: Deepthi Sigireddi <deepthi@planetscale.com>
Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
@arthurschreiber arthurschreiber merged commit 1de3daa into main Apr 25, 2024
199 checks passed
@arthurschreiber arthurschreiber deleted the arthur/improve-mysql8-table-query branch April 25, 2024 10:43
vitess-bot pushed a commit that referenced this pull request Apr 25, 2024
Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
Co-authored-by: Deepthi Sigireddi <deepthi@planetscale.com>
vitess-bot pushed a commit that referenced this pull request Apr 25, 2024
Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
Co-authored-by: Deepthi Sigireddi <deepthi@planetscale.com>
frouioui pushed a commit that referenced this pull request Apr 25, 2024
…y. (#15713) (#15793)

Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
Co-authored-by: vitess-bot[bot] <108069721+vitess-bot[bot]@users.noreply.github.com>
Co-authored-by: Deepthi Sigireddi <deepthi@planetscale.com>
arthurschreiber added a commit that referenced this pull request Apr 25, 2024
Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
Co-authored-by: Deepthi Sigireddi <deepthi@planetscale.com>
arthurschreiber added a commit that referenced this pull request Apr 25, 2024
Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
Co-authored-by: Deepthi Sigireddi <deepthi@planetscale.com>
arthurschreiber added a commit that referenced this pull request Apr 25, 2024
Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
Co-authored-by: Deepthi Sigireddi <deepthi@planetscale.com>
frouioui pushed a commit that referenced this pull request Apr 25, 2024
…y. (#15713) (#15795)

Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
Co-authored-by: vitess-bot[bot] <108069721+vitess-bot[bot]@users.noreply.github.com>
Co-authored-by: Deepthi Sigireddi <deepthi@planetscale.com>
Co-authored-by: Arthur Schreiber <arthurschreiber@github.com>
arthurschreiber added a commit that referenced this pull request Apr 25, 2024
Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
Co-authored-by: Deepthi Sigireddi <deepthi@planetscale.com>
dbussink pushed a commit that referenced this pull request Apr 26, 2024
…y. (#15713) (#15792)

Signed-off-by: Arthur Schreiber <arthurschreiber@github.com>
Co-authored-by: Arthur Schreiber <arthurschreiber@github.com>
Co-authored-by: Deepthi Sigireddi <deepthi@planetscale.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Backport to: release-17.0 Needs to be back ported to release-17.0 Backport to: release-18.0 Needs to be back ported to release-18.0 Backport to: release-19.0 Needs to be back ported to release-19.0 Component: VTTablet Type: Performance
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants