Technical Documentation: pingcap/TiDB
ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference
Overview (README.md)
TiDB
TiDB (/’taɪdiːbi:/, "Ti" stands for Titanium) is an open-source, cloud-native, distributed SQL database designed for high availability, horizontal and vertical scalability, strong consistency, and high performance.
Key Features
Distributed Transactions: TiDB uses a two-phase commit protocol to ensure ACID compliance, providing strong consistency. Transactions span multiple nodes, and TiDB's distributed nature ensures data correctness even in the presence of network partitions or node failures.
Horizontal and Vertical Scalability: TiDB can be scaled horizontally by adding more nodes or vertically by increasing resources of existing nodes, all without downtime. TiDB's architecture separates computing from storage, enabling you to adjust both independently as needed for flexibility and growth.
High Availability: Built-in Raft consensus protocol ensures reliability and automated failover. Data is stored in multiple replicas, and transactions are committed only after writing to the majority of replicas, guaranteeing strong consistency and availability, even if some replicas fail. Geographic placement of replicas can be configured for different disaster tolerance levels.
Hybrid Transactional/Analytical Processing (HTAP): TiDB provides two storage engines: TiKV, a row-based storage engine, and TiFlash, a columnar storage engine. TiFlash uses the Multi-Raft Learner protocol to replicate data from TiKV in real time, ensuring consistent data between the TiKV row-based storage engine and the TiFlash columnar storage engine. The TiDB Server coordinates query execution across both TiKV and TiFlash to optimize performance.
Cloud-Native: TiDB can be deployed in public clouds, on-premises, or natively in Kubernetes. TiDB Operator helps manage TiDB on Kubernetes, automating cluster operations, while TiDB Cloud provides a fully-managed service for easy and economical deployment, allowing users to set up clusters with just a few clicks.
MySQL Compatibility: TiDB is compatible with MySQL 8.0, allowing you to use familiar protocols, frameworks and tools. You can migrate applications to TiDB without changing any code, or with minimal modifications. Additionally, TiDB provides a suite of data migration tools to help easily migrate application data into TiDB.
Open Source Commitment: Open source is at the core of TiDB's identity. All source code is available on GitHub under the Apache 2.0 license, including enterprise-grade features. TiDB is built with the belief that open source enables transparency, innovation, and collaboration. We actively encourage contributions from the community to help build a vibrant and inclusive ecosystem, reaffirming our commitment to open development and accessibility for everyone.
Quick Start
Start a TiDB cluster.
On local playground. To start a local test cluster, refer to the TiDB quick start guide.
On Kubernetes. TiDB can be easily deployed in a self-managed Kubernetes environment or Kubernetes services on public clouds using TiDB Operator. For more details, refer to the TiDB on Kubernetes quick start guide.
Using TiDB Cloud (recommended). TiDB Cloud offers a fully managed version of TiDB with a free plan, no credit card required, so you can get a free cluster in seconds and start easily: Sign up for TiDB Cloud.
Learn about TiDB SQL: To explore the SQL capabilities of TiDB, refer to the TiDB SQL documentation.
Use a MySQL driver or an ORM to Build an App with TiDB.
Explore key features, such as data migration, changefeed, vector search, HTAP, disaster recovery, etc.
Need Help?
You can connect with TiDB users, ask questions, find answers, and help others on our community platforms: Discord, Slack (English, Japanese), Stack Overflow, TiDB Chinese Forum, X @PingCAP
For filing bugs, suggesting improvements, or requesting new features, use Github Issues or join discussions on Github Discussions.
To troubleshoot TiDB, refer to Troubleshooting documentation.
Architecture
Learn more details about TiDB architecture in our Docs.
Contributing
TiDB is built on a commitment to open source, and we welcome contributions from everyone. Whether you are interested in improving documentation, fixing bugs, or developing new features, we invite you to shape the future of TiDB.
See our Contributor Guide and TiDB Development Guide to get started.
If you're looking for issues to work on, try looking at the good first issues or help wanted issues.
The contribution map lists everything you can contribute.
The community repository contains everything else you need.
Don't forget to claim your contribution swag by filling in and submitting this form.
License
TiDB is under the Apache 2.0 license. See the LICENSE file for details.
See Also
- TiDB Online Playground
- TiDB Case Studies: TiDB Customers, TiDB 事例記事, TiDB 中文用户案例
- TiDB User Documentation
- TiDB Design Docs
- TiDB Release Notes
- TiDB Blog
- TiDB Roadmap
Acknowledgments
- Thanks cznic for providing some great open source tools.
- Thanks GolevelDB, BoltDB, and RocksDB for their powerful storage engines.
Agents README (`docs/agents/README.md`)
Agent Docs
This directory is the single top-level home for agent-facing documentation.
Layout
- Cross-cutting runbooks and checklists stay at
docs/agents/*.md
(for exampletesting-flow.md,architecture-index.md, andagents-review-guide.md). - Component-specific notes live under
docs/agents/<component>/.
Current component folders include:docs/agents/ddl/docs/agents/dxf/docs/agents/import-into/
Maintenance
- Keep policy-level requirements in root
AGENTS.md. - Keep operational details in docs under
docs/agents/.
Agents Architecture Index (`docs/agents/architecture-index.md`)
TiDB Architecture Index for Agents
This file is a navigation index for quick subsystem discovery.
Hard requirements remain in the repository root AGENTS.md.
How to Use This Index
- Map the task to one primary subsystem.
- Find existing tests covering the same behavior.
- Reuse existing fixtures/testdata before creating new shapes.
- Expand to adjacent subsystems only when cross-module effects are clear.
Core Subsystems
Planner and optimization
pkg/planner/pkg/planner/core/base/pkg/planner/core/operator/logicalop/pkg/planner/core/operator/physicalop/- Typical changes: rule matching, plan shape, cost-based choices.
- First tests to inspect:
pkg/planner/core/casetest/pkg/planner/core/casetest/rule/testdata/
Execution and expressions
pkg/executor/pkg/expression/- Typical changes: runtime operator semantics, builtin behavior, evaluation edge cases.
- First tests to inspect:
- package unit tests under the same path
pkg/executor/test/materializedview/for materialized view refreshpkg/executor/test/materializedviewlog/for materialized view log purge and related checks- SQL integration tests for user-visible behavior
Import preparation and execution
pkg/executor/importer/: import plans and execution; it must not depend onpkg/planner/core.pkg/executor/import_into.go,pkg/executor/load_data.go: also convert SQL plans to import plans.pkg/dxf/importinto/: distributed import scheduling and step execution.pkg/executor/importer/job.go: import job rows and persisted summaries.pkg/dxf/importinto/taskinfo/: shared task metadata and runtime progress read from the DXF task.pkg/executor/import_into.go: IMPORT INTO task submission;pkg/executormust not importpkg/dxf/importinto.- First tests: importer metadata/option tests,
pkg/dxf/importinto/taskinfo/runtime_info_test.goandpkg/executor/import_into_test.go.
Session, variables, protocol
pkg/session/pkg/sessionctx/pkg/sessionctx/variable/pkg/server/- Typical changes: session lifecycle, statement context behavior, protocol-level behavior.
DDL and metadata
pkg/ddl/pkg/infoschema/pkg/meta/pkg/meta/autoid/- Typical changes: schema evolution, metadata persistence, ID generation.
Storage and distributed execution
pkg/kv/pkg/store/pkg/distsql/pkg/tablecodec/- Typical changes: KV semantics, storage integration, distributed query paths.
Domain and statistics
pkg/domain/pkg/statistics/- Typical changes: schema/statistics lifecycle, cardinality/estimation behavior.
Parser and AST
pkg/parser/- Typical changes: SQL grammar, AST nodes, parser behavior.
Dumpling export
dumpling/export/: export orchestration, source adapters, filtering, and writers.dumpling/dumpservice/: HTTP/2 client and Unix-socket protocol contract.dumpling/internal/kvsource/: TiDB metadata access, row decoding, and SQL-compatible conversion.dumpling/internal/dumpservicetest/: shared dump-service fixtures for source and export tests.- First tests: metadata consumer tests in
kvsourceand dump-service lifecycle/parity tests inexport.
Test Surfaces
- Unit tests: package-local tests under
pkg/**. - Integration tests:
- inputs:
tests/integrationtest/t/ - expected outputs:
tests/integrationtest/r/
- inputs:
- RealTiKV tests:
tests/realtikvtest/- use when behavior depends on real TiKV/PD interaction.
Practical Search Workflow
- Start from symptom:
- SQL keyword
- error message
- variable name
- Find implementation entrypoint:
- planner/executor/expression/session/ddl/store
- Find existing tests around the same behavior.
- Confirm neighboring modules only if call chain crosses boundaries.
Common Cross-Module Paths
- Planner -> Executor -> Expression for query semantics.
- Session/Variables -> Executor for user-visible runtime behavior.
- DDL -> Infoschema/Meta -> Domain for schema lifecycle.
- Store/KV/DistSQL -> Executor for distributed execution behavior.
Notes and Runbooks
- Notes guide:
docs/agents/notes-guide.md - Testing runbook:
docs/agents/testing-flow.md - AGENTS review guide:
docs/agents/agents-review-guide.md - Root execution contract:
AGENTS.md
Design 2020 03 12 Invisible Index (`docs/design/2020-03-12-invisible-index.md`)
Proposal: Invisible index
- Author(s): Deardrops, wjhuang2016
- Last updated: Mar. 12, 2020
- Discussion at: https://github.com/pingcap/tidb/issues/9246
Abstract
MySQL supports invisible indexes; that is, indexes that are not used by the optimizer.
This is a useful feature for dropping an index in a safe way. Invisible indexes make it possible to test the effect of removing an index on query performance, without making a destructive change that must be undone should the index turn out to be required. Dropping and re-adding an index can be expensive for a large table, whereas making it invisible and visible are fast, in-place operations.
Support the option of VISIBLE | INVISIBLE.
CREATE [...] INDEX index_name
[index_type]
ON tbl_name (key_part,...)
[index_option]
index_option:
{VISIBLE | INVISIBLE}Also, the following behaviors need to be supported as well:
- Display information about invisible indexes in the output of
INFORMATION_SCHEMA.STATISTICSorSHOW INDEX. - Index hints need to report errors when used in invisible indexes.
- The primary key cannot be set to an invisible index.
Background
Index has a great influence on the performance of the database. Whether there is an index or whether the optimizer chooses the right index determines the performance of reading and writing the database to a great extent. In some cases, we would like to know the impact of deleting an index on the read-write performance of the database. At present, our method is to tell the optimizer to ignore the index through Index Hint. Although this method can achieve the goal, it is not practical to modify all SQL statements.
Proposal
Adding an option (visible or not) to the index. If it is not visible, it's called Invisible Index. Invisible indexes cannot be used by the optimizer (with the use_invisible_indexes switch on), but the index is maintained during DML operations. For a query statement, invisible indexes have the same effect as ignoring the index through Index Hint.
The option INVISIBLE of an index can be changed by using the following DDL statement:
ALTER TABLE table_name ALTER INDEX index_name { INVISIBLE | VISIBLE };Or by setting option INVISIBLE when creating an index:
CREATE INDEX index_name ON table_name(key) [ INVISIBLE | VISIBLE ];INVISIBLE, VISIBLE is as part of the index option, they can also be set when creating a table.
In order to know whether an index is invisible, it can be read from the INFORMATION_SCHEMA.STATISTICS table or through the SHOW INDEX command.
In addition, add a new flag use_invisible_indexes in system variable optimizer_switch, which determine whether the option INVISIBLE takes effect. If use_invite_indexes is on, the optimizer can still use invisible index.
A table with no explicit primary key may still have an effective implicit primary key if it has any UNIQUE indexes on NOT NULL columns. In this case, the first such index places the same constraint on table rows as an explicit primary key and that index cannot be made invisible.
Rationale
Another solution for implement invisible indexes is: Indicate invisibility by DDL state WriteOnly. This solution has the following problems:
- The logic of schema change needs to be changed, which is relatively complicated to implement.
- Cannot distinguish between indexes that are currently in WriteOnly and invisible indexes.
- Handling the switch is troublesome.
Compatibility and Migration Plan
This the a new feature and it's absolutely compatible with old TiDB versions, also, it does not impact any data migration.
The syntax and functions are basically compatible with MySQL expect:
When use invisible index in `SQL Hint`, and set `use_invisible_indexes = false`, MySQL allow use the invisible index.
But in TiDB, It's **not allowed** and an `Unresolved name` error will be thrown.Implementation
- Add syntax support in parser
- Add a new column
IS_VISIBLEininformation_schema.statistics - Add a new column
VISIBLEinSHOW INDEX FROM tablestatement - Show invisible column information in
SHOW CREATE TABLEstatement - Add
use_invisible_indexesin system variable@@optimizer_switch - Add new error message
ERROR 3522 (HY000): A primary key index cannot be invisible - Ignore invisible index in optimizer and add unit tests
Testing Plan
- Unit test
- Learn from MySQL test cases related to invisible indexes
Open issues
https://github.com/pingcap/tidb/issues/9246
Design 2020 05 08 Cluster Index (`docs/design/2020-05-08-cluster-index.md`)
Proposal: Clustered Index
- Author(s): coocood
- Last updated: 2020-05-08
Abstract
This proposal proposes to support the clustered index feature.
Background
In the current TiDB implementation, we only support clustered index for single integer column primary key.
Every row in a table has one row-key entry that stores the full row data and index entries that point to the row-key.
row key format
t | {table_id} | _r | {handle} // component
1 | 8 | 2 | 8 // byte sizeThe type of table_id and handle are int64, so the row key is always of the same length 19.
non-unique index key format
t | {table_id} | _i | {index_id} | {index_column_values} | encoded_handle // component
1 | 8 | 2 | 8 | size of the values | 9 // byte sizeThe handle is the suffix of the index key.
unique index key format
t | {table_id} | _i | {index_id} | {index_column_values} // component
1 | 8 | 2 | 8 | size of the values // byte sizeThe handle is in the value of the index entry.
On Write
If the primary key is a single integer column,
we use the value of the column as the handle directly.
Otherwise, we allocate a handle internally for the row, then create an extra index entry that points to the row key.
On Point Select
If the primary key is a single integer column,
We construct the row key by the primary key column value directly, do a lookup on TiKV.
Otherwise, we need to construct the index key with the primary key value, read the handle for the index entry,
Then construct the row key and do another lookup on TiKV.
On Range Scan
If the primary key is a single integer column,
We construct the range of the row keys directly, do a single scan on TiKV.
Otherwise, we need to construct the index range, scan index entries on TiKV to collect the handle,
Then do many point lookups On TiKV to read the rows.
Proposal
Support clustered index for not only single integer column primary key but all kinds of primary key.
the Handle interface
package kv
// Handle is the ID of a row.
type Handle interface {
// IsInt returns if the handle type is int64.
IsInt() bool
// IntValue returns the int64 value if IsInt is true, it panics if IsInt returns false.
IntValue() int64
// Next returns the minimum handle that is greater than this handle.
Next() Handle
// Equal returns if the handle equals to another handle, it panics if the types are different.
Equal(h Handle) bool
// Compare returns the comparison result of the two handles, it panics if the types are different.
Compare(h Handle) int
// Encoded returns the encoded bytes.
Encoded() []byte
// Len returns the length of the encoded bytes.
Len() int
// NumCols returns the number of columns of the handle,
NumCols() int
// EncodedCol returns the encoded column value at the given column index.
EncodedCol(idx int) []byte
// String implements the fmt.Stringer interface.
String() string
}
// IntHandle implements the Handle interface for the int64 type handle.
type IntHandle int64
// CommonHandle implements the Handle interface for non-int64 type handle.
type CommonHandle struct {
encoded []byte
colEndOffsets []uint16
}
// HandleMap is the map for Handle.
type HandleMap struct {
ints map[int64]interface{}
strs map[string]strHandleVal
}
type strHandleVal struct {
h Handle
val interface{}
}To extend the handle type, we need to abstract the handle to an interface that has the
needed methods.
There are two concrete types: IntHandle and CommonHandle.
If the primary key is a single column integer, the handle type would be IntHandle.
Otherwise, the handle type would be CommonHandle.
handles are used as map key in many places, one way to adapt to it is to use the encoded bytes as the key, but that would introduce memory allocation for IntHandle, so we use a HandleMap type that has two maps for the two handle types to avoid the memory allocation for IntHandle.
Integer handle row key and index key formats are the same as the current implementation.
We only need to care about the common handle type.
Codec
common handle row key format
t | {table_id} | _r | {common_handle} // component
1 | 8 | 2 | len(common_handle) // byte sizeThe common_handle is the same as index_column_values in the index key.
The row key length can be more than 19.
non-unique index key format
t | {table_id} | _i | {index_id} | {idx_col_vals} | {common_handle} // component
1 | 8 | 2 | 8 | len(idx_col_vals) | len(common_handle) // byte sizeNon-unique index value is unchanged.
unique index value format
{tailLen} | {common_handle_flag} | {common_handle_len} | {common_handle} // component
1 | 1 | 2 | len(common_handle) // byte sizeThe unique index key is unchanged.
For more intuitive information, check the docs
Planner
Handle Primary Key Index differently
For common handle tables, treat the primary index access path is table path instead of index path, builds TableScan plan instead of IndexLookUp plan.
There may be some places implicit assume the TableScan plan use int handle, we need to carefully review the logic.
The cost model may need to be adjusted for clustered index tables.
IndexScan Schema
If any of the primary key columns are used, or it is in an IndexLookUp executor, the index scan schema should be:
{index columns},{primary key columns}
There is no extra handle column for common handle tables.
If only index columns are used, the schema should be:
{index columns}
For example:
create table t (a int, b int, c int, d int, e int, primary key (a, b), index c_d (c, d));The schema of index scan on c_d should be c, d, a, b or c, d depends on whether any primary key column is used.
So if a query doesn't reference column e, the index c_d is a covering index, we can build an IndexScan plan
instead of an IndexLookUp plan.
Coprocessor
Besides codec code, several coprocessor executors need to be changed to support common handle.
IndexScan
If the IndexScan schema doesn't contain primary key columns, the coprocessor logic is unchanged.
If the IndexScan schema contains primary key columns, the coprocessor should decode the common handle
to primary key column values.
The encoded column value can be obtained by the EncodedCol method of the handle.
Analyze Column
If the primary key is multi-column, CMSketch needs to insert prefix column values of the primary key.
Fast Analyze
Since the handle is not integer anymore, we cannot randomly generate the sample key at a given position.
So we need to add a coprocessor request type that samples the key/value pair during the scan and return the statistics result.
Executors
Several executors need to be changed to support common handle
Admin Executors
The admin check/recover table/index executors heavily depend on the assumption that handle is int64 handle,
it needs to do major changes to support common handle.
PointGet/BatchPointGet
We need to decode the common handle to chunk.
Insert
We don't need to encode primary columns into the row value.
Update
If any of the primary key columns changed, we need to delete the row and insert the row.
SplitTableRegion
We need to redesign this executor since we cannot find a middle key based on the region start/end key.
Rationale
The clustered index feature would remove the extra read/write cost for tables with a non-single-integer-column primary key.
An experiment on the tpcC workload by compressing multi-column PK into one integer PK shows a 33% improvement.
Compatibility
This feature doesn't break the backward compatibility.
We add a field IsCommonHandle in the model.TableInfo and a global variable tidb_enable_clustered_index.
When creating a new table, set this field to true if the global variable tidb_enable_clustered_index is set to 1.
All the common handle related logic should check IsCommonHandle field before entering the common handle code block.
For a new cluster, we insert the global variable tidb_enable_clustered_index value 1 in the bootstrap phase, the clustered index feature is supported by default.
For old clusters upgrade to the latest release version, the user needs to explicitly set the global variable to 1 to use the clustered index feature.
Implementation
implement the Handle interface for IntHandle and CommonHandle.
|
+ refactor int64 handle to the Handle interface in all tidb packages.
|
+-+ implement the codec.
|
|-+ support codec in tikv.
| |
| +- support coprocessor indexScan
| |
| +- support coprocessor fastAnalyze
| |
| +- support coprocessor analyzeColumn
|
+-+ support common handle in planner.
|
|-+ support common handle in executors.
|
|-+ support common handle in ddl.
|
+-+ support common handle in other packages thats need minor change.Open Issues
TiFlash and CDC also need to update to support the clustered index feature.
Design 2020 08 04 Global Index (`docs/design/2020-08-04-global-index.md`)
Proposal: Support global index for partition table
- Author(s): ldeng-ustc
- Last updated: Jul. 22, 2020
- Discussion at:
Abstract
This document proposes to support global index for partition table, which can remove some constraints of indexes for partition table.
Background
Local index and global index
Global Index: A global index is a one-to-many relationship, allowing one index partition to map to many table partitions. This means global index can be partitioned by the range or hash method, and it can be defined on any type of partitioned, or non-partitioned, table.
Local Index: A local index is a one-to-one mapping between a index partition and a table partition, which means index is also partition by the same conditions of table.
Partitioned table index in TiDB
In TiDB, index entries are encoded to key-value pairs, like: (In practice, index encoding is more complex, see this article and two proposals about full collations and cluster index for more information.)
Key: tablePrefix{tableID}_indexPrefixSep{indexID}_indexedColumnsValue
Value: rowIDEach partition of the partitioned table is treated as an independent physical table in the TiKV layer, with its own partitionID . Therefore, the index entries of the partitioned table are also encoded as:
Key: tablePrefix{partitionID}_indexPrefixSep{indexID}_indexedColumnsValue
Value: rowIDSo, in the current table partition implementation, a partition and its indexes are encoded to the same key-value range. Or we can say, TiDB only has local index.
That design is compatible with the MySQL, but also makes TiDB have the same constraint as MySQL, which says:
Every unique key on the table must use every column in the table's partitioning expression.
For example, here is a partitioned table:
CREATE TABLE t (
A int,
B int,
UNIQUE KEY (B)
)
PARTITION BY RANGE (A) (
PARTITION p0 VALUES LESS THAN (10),
PARTITION p1 VALUES LESS THAN (20),
PARTITION p2 VALUES LESS THAN (maxvalue)
);Then we insert 2 records into it.
INSERT INTO t (A, B) VALUES (1, 23);
INSERT INTO t (A, B) VALUES (11, 23);The first record will be inserted into p0, the second will be inserted into p1. The index on column B will create two entries which keys are:
p0_idxB_23
p1_idxB_23Because index entries are built on different partitions, the uniqueness of the index is broken. So, In MySQL and current TiDB, these indexes are not allowed.
Proposal
Overview
This document proposes to support the global index for partitioned tables. Global index use tableID instead of partitionID as the prefix of index entries. Since all entries in a partitioned table use the same prefix, it can ensure index entry is unique in the whole table, thus removing the constraint in partitioned tables indexes.
Encoding
Index key-value Layout
We want global index entry keys to begin with TableID, so we have to add PartitionID to another place. New index encoding layout:
Key: tableID_indexID_ColumnValues
Value: handle_partitionIDPros: This key layout is compatible with current index key encoding.
Cons: Hard to drop and exchange partition, because index entries of a partition is not continuous.
**Other Alternative:**
Key: tableID_partitionID_indexID_ColumnValues
Value: handleOr
Key: tableID_indexID_partitionID_ColumnValuesPros: Easy to implement partition operators such as drop partition.
Cons: Since partitionID is unknown when building a query, it needs to scan all partitions of a table when handling point-get or index scan. Also, we need special checks when inserting a row into a table to keep the index unique. It likes another implement of local index but not global index, So we reject it.
Detail of value layout
Now, in TiDB, we have 6 kinds of index value layout and use 3 different functions to decode it. This not only makes it hard to add new features for index (we should add at least two layouts and one function), but also makes the code and comments less readable and confusing (index.Create has an extreme long comment, and is still getting longer).
Here is the new description of the index value layout, which is fully compatible with the current version, but easier to understand and extend. (PartitionID has been added at Global Index Segment )
/* Detailed source-code truncated for AI context efficiency. */DDL operations
Add/Drop Index
All index entries in add by index.Create. We modify it to support new encoding, and add IndexInfo.Global field to notify workers add global index entries.
Same goes for dropping index.
Drop Partition
In global index, all index entries in a partition is not continuous. It is impossible to delete all index entries of a partition in a single range deletion. So, we add a reorg state (just like add index), which scan records in the partition and remove relative index entries.
Exchange Partition
Also, this needs a reorg state. It is not supported for the time being because of complexity.
Drop Table
Add extra one range deletion to clean global indexes.
Read from global index
In TiDB, operators in the partitioned table will be translated to UnionAll in the logical plan phase. But an in-progress project plan to translate operators to new partitioned table executors (see issue: #18016). we will follow this project and add global index support in new executors.
Rationale
Global index in Oracle
Global index in OceanBase
Compatibility
MySQL does not support global index, which means this feature may cause some compatibility issues. We add an option enable-global-index in config.Config to control it. The default value of this option is false, so TiDB will keep consistent with MySQL, unless the user open global index feature manually.
Implementation
DDL operations will be implemented first. Plan and executor supports will be implemented after new PartitionTable executor is completed.
Design 2022 01 04 Integer Shard Index (`docs/design/2022-01-04-integer-shard-index.md`)
Integer shard index
- Tracking Issue: https://github.com/pingcap/tidb/issues/31040
Here is a table definition as bellow. The service writes data monotonically on the field id2, so the index hotIndex becomes a hot index which hinders the scalability of a TiDB cluster. The service executes point SELECT and point UPDATE by the hotIndex.
CREATE TABLE test(id1 INT PRIMARY, id2 INT, id3 INT, UNIQUE KEY hotIndex(id2));
INSERT INTO test values(val1,val2,val3);
UPDATE test SET id3 = val3 WHERE id2 = val2;
SELECT * FROM test WHERE id2 = val2;The Integer shard index realized by this design doc can scatter hotIndex and ensure the service sqls still use the unique key hotIndex. Here is the new table definition including shard index as bellow.
CREATE TABLE test(id1 INT PRIMARY, id2 INT, id3 INT, UNIQUE KEY hotIndex((tidb_shard(id2)),id2));Do we need to modify service sqls above? No, we don't. Optimizer can recognize the shard index and add tidb_shard(id2) = shardVal to the WHERE clause automatically. Here is the final form of service sqls processed by optimizer as bellow. So, we don't need to modify service sqls and theses sqls can still use the unique index hotIndex
UPDATE test SET id3 = val3 WHERE tidb_shard(id2) = 8 AND id2 = 100;
SELECT * FROM test WHERE tidb_shard(id2) = 8 AND id2 = 100;Summary
Hot index reduces the write scalability of the TiDB cluster when the written data is monotonically increasing. We find out a proposal to solve the problem that is using an expression index to scatter the hot index, the new expression index is called a shard index.
The followers is the scalability of hot index and shard index.
| threads | tidb | tikv | tidb CPU | tikv CPU | duration(95) | QPS(K) | scalability | remark |
|---|---|---|---|---|---|---|---|---|
| 800 | 3 | 3 | 4700 | 3350 | insert: 60.5 update:110 | 49.8 | ||
| 800 | 3 | 3 | 4400 | 3000 | insert: 61 update:111 | 49 | ||
| 800 | 3 | 4 | 5000 | 3500 | insert: 57 update:103 | 53 | 19.30% | round1 |
| 800 | 3 | 4 | 5100 | 3600 | insert: 56 update:100 | 54 | 30.60% | round2 |
hot index scalability
| threads | tidb | tikv | tidb CPU | tikv CPU | duration | QPS | scalability | remark |
|---|---|---|---|---|---|---|---|---|
| 800 | 3 | 3 | 5200 | 3100 | insert: 60 update:110 | 47.5 | ||
| 800 | 3 | 3 | 5200 | 3000 | insert: 60 update:110 | 47.2 | ||
| 800 | 3 | 4 | 6200 | 3800 | insert: 56.5 update:88 | 57.5 | 63.20% | round1 |
| 800 | 3 | 4 | 6250 | 3800 | insert: 56.5 update:88 | 58.5 | 71.40% | round2 |
shard index scalability
Computing formula of scalability is as bellow: qps1 is the qps before expansion, tikv1 is the tikv node count before expansion; qps2 is the qps after expansion, tikv2 is the tikv node count afterexpansion.
Detailed design
We made a new built-in function "tidb_shard()" as the expression prefix of shard index. There is only one integer parameter for tidb_shard function. What index is a shard index? It must meet the follower rules.
- It is an unique index
- The first field of index is tidb_shard(
a) , the columnais integer type and is the second field of the index.
When querying based on the original index field, the TiDB optimizer should automatically recognize the shard index and add the expression field tidb_shard(a) = val to the query condition.
How to solve the hot index problem by shard index? For example, the definition of a table is test(id int primary key clustered, a int, b int, unique key idx_a(a)) . The index idx_a is a hot index because of monotonically increasing data. We modify the definition of the index idx_a as follows unique key idx_a((tidb_shard(a)),a). The written data of index idx_a is not monotonically increasing now. But here is a question, how the optimizer of TiDB chooses the index for original queries that are designed for idx_a(a)? e.g. SELECT * FROM test WHERE a = 100, it can't use the unique index 'idx_a((tidb_shard(a)),a' any more. We add a new rule for TiDB optimizer, if the access condition of a query contains all the fields of shard index except the first tidb_shard(a) expression, The optimizer adds the expressiontidb_shard(a) = xxx to the access condition and the new query statement is like SELECT * FROM test WHERE tidb_shard(a) = 8 AND a = 100, so that the query can use the shard index.
tidb_shard function
dsciription
Only support an integer parameter. It transforms an integer number to a value in the range [0, 255]. e.g. tidb_shard(100) is the value 8 .
principle
It calculate the hash value of the input parameter, and get the mod value by 256.
func (b *builtinTidbShardSig) evalInt(row chunk.Row) (int64, bool, error) {
shardKeyInt, isNull, err := b.args[0].EvalInt(b.ctx, row)
if isNull || err != nil {
return 0, true, err
}
var hashed uint64
if hashed, err = vitess.HashUint64(uint64(shardKeyInt)); err != nil {
return 0, true, err
}
hashed = hashed % tidbShardBucketCount
return int64(hashed), false, nil
}Add expression to access condition by optimizer
The optimizer should add the expresion tidb_shard(xxx) = yyy to the access condition, so that a the query can use shard index.
The follower are the functions used to add the expresion tidb_shard(xxx) = yyy to the access condition. They are Introduced in order of function call.
(ds *DataSource) PredicatePushDown
The entry point to add the tidb_shard expression is the function as bellow. We must add it before access condition was pushed down. Maybe this work should be done after sql parse, we do it here just for simplify the work.
func (ds *DataSource) PredicatePushDown(predicates []expression.Expression, opt *logicalOptimizeOp) ([]expression.Expression, LogicalPlan) {
predicates = expression.PropagateConstant(ds.ctx, predicates)
predicates = constraint.DeleteTrueExprs(ds, predicates)
// Add tidb_shard() prefix to the condtion for shard index in some scenarios
// TODO: remove it to the place building logical plan
predicates = ds.AddPrefix4ShardIndexes(ds.ctx, predicates)
ds.allConds = predicates
ds.pushedDownConds, predicates = expression.PushDownExprs(ds.ctx.GetSessionVars().StmtCtx, predicates, ds.ctx.GetClient(), kv.UnSpecified)
appendDataSourcePredicatePushDownTraceStep(ds, opt)
return predicates, ds
}(ds *DataSource) AddPrefix4ShardIndexes
AddPrefix4ShardIndexes is the interface to add expression prefix for shard index. Pay attention, just for shard index!
// AddPrefix4ShardIndexes Add expression prefix for shard index. e.g. an index is test.uk(tidb_shard(a), a).
// It transforms the sql "SELECT * FROM test WHERE a = 10" to
// "SELECT * FROM test WHERE tidb_shard(a) = val AND a = 10", val is the value of tidb_shard(10).
// It also transforms the sql "SELECT * FROM test WHERE a IN (10, 20, 30)" to
// "SELECT * FROM test WHERE tidb_shard(a) = val1 AND a = 10 OR tidb_shard(a) = val2 AND a = 20"
// @param[in] conds the original condtion of this datasource
// @retval - the new condition after adding expression prefix
func (ds *DataSource) AddPrefix4ShardIndexes(sc sessionctx.Context, conds []expression.Expression) []expression.Expression {
if !ds.containExprPrefixUk {
return conds
}
var err error
newConds := make([]expression.Expression, 0, len(conds))
newConds = append(newConds, conds...)
for _, path := range ds.possibleAccessPaths {
if path.IsTablePath() || !path.IsUkShardIndex() {
continue
}
newConds, err = ds.addExprPrefixCond(sc, path, newConds)
if err != nil {
logutil.BgLogger().Error("Add tidb_shard expression failed", zap.Error(err))
return conds
}
}
return newConds
}(ds *DataSource) addExprPrefixCond
addExprPrefixCond is the wrapper for addExprPrefix4ShardIndex
func (ds *DataSource) addExprPrefixCond(sc sessionctx.Context, path *util.AccessPath,
conds []expression.Expression) ([]expression.Expression, error) {
IdxCols, IdxColLens :=
expression.IndexInfo2PrefixCols(ds.Columns, ds.schema.Columns, path.Index)
if len(IdxCols) == 0 {
return conds, nil
}
adder := &exprPrefixAdder{
sctx: sc,
OrigConds: conds,
cols: IdxCols,
lengths: IdxColLens,
}
return adder.addExprPrefix4ShardIndex()
}(adder *exprPrefixAdder) addExprPrefix4ShardIndex
addExprPrefix4ShardIndex is the wrapper for addExprPrefix4DNFCond and addExprPrefix4CNFCond. addExprPrefix4DNFCond is used to process OR expression, addExprPrefix4CNFCond is used to process AND expression.
// if original condition is a LogicOr expression, such as `WHERE a = 1 OR a = 10`,
// call the function AddExprPrefix4DNFCond to add prefix expression tidb_shard(a) = xxx for shard index.
// Otherwise, if the condition is `WHERE a = 1`, `WHERE a = 1 AND b = 10`, `WHERE a IN (1, 2, 3)`......,
// call the function AddExprPrefix4CNFCond to add prefix expression for shard index.
func (adder *exprPrefixAdder) addExprPrefix4ShardIndex() ([]expression.Expression, error) {
if len(adder.OrigConds) == 1 {
if sf, ok := adder.OrigConds[0].(*expression.ScalarFunction); ok && sf.FuncName.L == ast.LogicOr {
return adder.addExprPrefix4DNFCond(sf)
}
}
return adder.addExprPrefix4CNFCond(adder.OrigConds)
}(adder *exprPrefixAdder) addExprPrefix4DNFCond
- function declaration
// add the prefix expression for DNF condition, e.g. `WHERE a = 1 OR a = 10`, ......
// The condition returned is `WHERE (tidb_shard(a) = 214 AND a = 1) OR (tidb_shard(a) = 142 AND a = 10)`
// @param[in] condition the original condtion of the datasoure. e.g. `WHERE a = 1 OR a = 10`.
// condtion is `a = 1 OR a = 10`
// @return - the new condition after adding expression prefix. It's still a LogicOr expression.
func (adder *exprPrefixAdder) addExprPrefix4DNFCond(condition *expression.ScalarFunction) ([]expression.Expression, error)- Function Process
- Extract evrey binary expression from
conditionto a expression.Expression slicednfItems. - Make a new expression.Expression slice
newAccessItemsto store new conditions after processing tidb_shard prefix. - Traverse every
itemin slicednfItems, if it's aLogicAndexpression, extracts every binary expression from it to a slicecnfItemsand calls functionaddExprPrefix4CNFCond(cnfItems)to add tidb_shard prefix if need; if it's aast.EQor aast.Inexpression, calls functionaddExprPrefix4CNFCond([]Expression{item})to add tidb_shard prefix if need. - Make a new
LogicORcondition bynewAccessItems, return it.
- Extract evrey binary expression from
(adder *exprPrefixAdder) addExprPrefix4CNFCond
Call the function ranger.AddExpr4EqAndInCondition to process AND expression.
// add the prefix expression for CNF condition, e.g. `WHERE a = 1`, `WHERE a = 1 AND b = 10`, ......
// @param[in] conds the original condtion of the datasoure. e.g. `WHERE t1.a = 1 AND t1.b = 10 AND t2.a = 20`.
// if current datasource is `t1`, conds is {t1.a = 1, t1.b = 10}. if current datasource is
// `t2`, conds is {t2.a = 20}
// @return - the new condition after adding expression prefix
func (adder *exprPrefixAdder) addExprPrefix4CNFCond(conds []expression.Expression) ([]expression.Expression, error) {
newCondtionds, err := ranger.AddExpr4EqAndInCondition(adder.sctx,
conds, adder.cols)
return newCondtionds, err
}AddExpr4EqAndInCondition
The core function that adds tidb_shard(x) = xxx to the accessCond.
- function declaration
// AddExpr4EqAndInCondition add the `tidb_shard(x) = xxx` prefix
// Add tidb_shard() for EQ and IN function. e.g. input condition is `WHERE a = 1`,
// output condition is `WHERE tidb_shard(a) = 214 AND a = 1`. e.g. input condition
// is `WHERE a IN (1, ,2 ,3)`, output condition is `WHERE (tidb_shard(a) = 214 AND a = 1)
// OR (tidb_shard(a) = 143 AND a = 2) OR (tidb_shard(a) = 156 AND a = 3)`
// @param[in] conditions the original condition to be processed
// @param[in] cols the columns of shard index, such as [tidb_shard(a), a, ...]
// @param[in] lengths the length for every column of shard index
// @retval - the new condition after adding tidb_shard() prefix
func AddExpr4EqAndInCondition(sctx sessionctx.Context, conditions []expression.Expression,
cols []*expression.Column) ([]expression.Expression, error)- Function Process
- Traverse every
condin sliceconditions, place thecondto a new sliceaccessesaccording to the index definition field order. - Traverse every
condin sliceaccesses, if thecondis not aast.EQorast.Inexpression, do nothing and return, otherwise extract the column value fromcondand store it to slicecolumnValues. - Call the function
NeedAddGcColumn4ShardIndexto judge if necessary to addtidb_shardprefix forconditions, if not, do nothing and return; otherwise call functionAddGcColumnCondto addtidb_shardprefix forconditions.
- Traverse every
NeedAddGcColumn4ShardIndex
Check whether to add tidb_shard(x) = xxx to the access condition.
- function declaration
// NeedAddGcColumn4ShardIndex check whether to add `tidb_shard(x) = xxx`
// @param[in] cols the columns of shard index, such as [tidb_shard(a), a, ...]
// @param[in] accessCond the conditions relative to the index and arranged by the index column order.
// e.g. the index is uk(tidb_shard(a), a, b) and the where clause is
// `WHERE b = 1 AND a = 2 AND c = 3`, the param accessCond is {a = 2, b = 1} that is
// only relative to uk's columns.
// @param[in] columnValues the values of index columns in param accessCond. if accessCond is {a = 2, b = 1},
// columnValues is {2, 1}. if accessCond the "IN" function like `a IN (1, 2)`, columnValues
// is empty.
// @retval - return true if it needs to addr tidb_shard() prefix, ohterwise return false
func NeedAddGcColumn4ShardIndex(
cols []*expression.Column,
accessCond []expression.Expression,
columnValues []*valueInfo) bool- Function Process
- The columns of shard index shoude be more than 2, like
(tidb_shard(a),a,...). - The first column of index must be a generated column and the expression must be
tidb_shardbuilt-in function. - The argument of
tidb_shardmust be a column other than expression or else, and it must be the second column of the index.
- The columns of shard index shoude be more than 2, like
AddGcColumnCond
AddGcColumnCond is the wrapper function for AddGcColumn4EqCond and AddGcColumn4InCond.
// AddGcColumnCond add the `tidb_shard(x) = xxx` to the condition
// @param[in] cols the columns of shard index, such as [tidb_shard(a), a, ...]
// @param[in] accessCond the conditions relative to the index and arranged by the index column order.
// e.g. the index is uk(tidb_shard(a), a, b) and the where clause is
// `WHERE b = 1 AND a = 2 AND c = 3`, the param accessCond is {a = 2, b = 1} that is
// only relative to uk's columns.
// @param[in] columnValues the values of index columns in param accessCond. if accessCond is {a = 2, b = 1},
// columnValues is {2, 1}. if accessCond the "IN" function like `a IN (1, 2)`, columnValues
// is empty.
// @retval - []expression.Expression the new conditions after adding `tidb_shard() = xxx` prefix
// error if error gernerated, return error
func AddGcColumnCond(sctx sessionctx.Context,
cols []*expression.Column,
accessesCond []expression.Expression,
columnValues []*valueInfo) ([]expression.Expression, error) {
if cond := accessesCond[1]; cond != nil {
if f, ok := cond.(*expression.ScalarFunction); ok {
switch f.FuncName.L {
case ast.EQ:
return AddGcColumn4EqCond(sctx, cols, accessesCond, columnValues)
case ast.In:
return AddGcColumn4InCond(sctx, cols, accessesCond)
}
}
}
return accessesCond, nil
}AddGcColumn4EqCond
Add the tidb_shard(x) = xxx prefix for equal access condition.
- function declaration
// AddGcColumn4EqCond add the `tidb_shard(x) = xxx` prefix for equal condition
// For param explanation, please refer to the function `AddGcColumnCond`.
// @retval - []expression.Expression the new conditions after adding `tidb_shard() = xxx` prefix
// []*valueInfo the values of every columns in the returned new conditions
// error if error gernerated, return error
func AddGcColumn4EqCond(sctx sessionctx.Context,
cols []*expression.Column,
accessesCond []expression.Expression,
columnValues []*valueInfo) ([]expression.Expression, error)- Function Process
- Traverse every
ColumnValuein slicecolumnValues, calculate the value oftidb_shardbyColumnValueand store it to the variableevaluated. - Make a new expression
tidb_shard(columnName) = evaluatedand store it toaccessesCond[0]
- Traverse every
AddGcColumn4InCond
Add the tidb_shard(x) = xxx for IN condition.
- function declaration
// AddGcColumn4InCond add the `tidb_shard(x) = xxx` for `IN` condition
// For param explanation, please refer to the function `AddGcColumnCond`.
// @retval - []expression.Expression the new conditions after adding `tidb_shard() = xxx` prefix
// error if error gernerated, return error
func AddGcColumn4InCond(sctx sessionctx.Context,
cols []*expression.Column,
accessesCond []expression.Expression) ([]expression.Expression, error)- Function Process
Traverse every argument from In expression, calculate the value of tidb_shard with argument and make a new expression tidb_shard(columnName) = value, then make a LogicAnd like tidb_shard(a) = 8 AND a = 100. When process the second or above argument , add the LogicAnd to the LogicOR expression, like tidb_shard(a) = 8 AND a = 100 OR tidb_shard(a) = 8 AND a = 100.
Drawbacks
Using the shard index to replace the hot index my decrease a little of the performance when the TiDB cluster is small and the pressure of workload is not high, But it can increase the scalability obviously.
Alternatives
We can use expression index directly other than as the prefix of a index. e.g. replace index idx(a) to indx idx(expr(a)) , it seems more simpler. But expr(a) and (a) don't correspond one to one, the PointGet plan becomes IndexRangeScan and the selection operation WEHRE a = xxx must be executed in the tidb-server or tikv. So the performance may be dropped a lot.
Unresolved questions
Shard Index Only Support Unique Secondary Index
The shard index is only valid for unique secondary index, not for primary key or non-unique secondary index, and it must meet the follower rules.
- It is an unique index
- The first field of index is tidb_shard(
a) , the columnais integer type and is the second field of the index.
Non-equivalent Condition Can't Use Index
The proposal only adds expression tidb_shard(?) = ? for equivalent condition in WHERE clause. e.g. If there is a unique index uk(a) on table A , optimizer chooses index scan by uk(a) for query SELECT * FROM A WHERE a > 100.The index definition is changed to uk(tidb_shard(a), a) by this proposal, optimizer doesn't choose index for the query above any more.
`AND` Expression Mixing With `OR` Expression Can't Use Index
The proposal only adds expression tidb_shard(?) = ? for all "AND" expression or all "OR" expression or none of them in WHERE clause. If "and" expression mixing with "or" expression in WHERE clause, it can't use index. e.g. If there is a unique index uk(a) on table A , optimizer chooses index scan by uk(a) for query SELECT * FROM A WHERE ((a=100 and b = 100) or a = 200) and b = 300. The index definition is changed to uk(tidb_shard(a), a) by this proposal, optimizer doesn't choose index for the query above any more.
Group By Can't Use Index
The proposal only adds expression tidb_shard(?) = ? for equivalent condition in WHERE clause. It does nothings for GROUP BY clause. e.g. If there is a unique index uk(a) on table A , optimizer chooses index scan by uk(a) for query SELECT SUM(a) FROM A GROUP BY a. The index definition is changed to uk(tidb_shard(a), a) by this proposal, optimizer doesn't choose index for the query above any more and it needs to be grouped in tidb-server.
Order By Can't Use Index
The proposal only adds expression tidb_shard(?) = ? for equivalent condition in WHERE clause. It does nothing for ORDER BY clause. e.g. If there is a unique index uk(a) on table A , optimizer chooses index scan by uk(a) for query SELECT a FROM A ORDER BY a. The index definition is changed to uk(tidb_shard(a), a) by this proposal, optimizer doesn't choose index for the query above any more and it needs to be orderedin tidb-server.
Join Condition Can't Use Index
The proposal only adds expression tidb_shard(?) = ? for equivalent condition in WHERE clause. It does nothing for the ON clause. e.g. If there is a unique index uk(a) on table A , optimizer chooses index scan by uk(a) for query SELECT * FROM B JOIN A ON B.a = A.a. The index definition is changed to uk(tidb_shard(a), a) by this proposal, optimizer doesn't choose index for the query above any more.
Where Subquery Can't Use Index
The proposal only adds expression tidb_shard(?) = ? for equivalent condition in WHERE clause. It does nothing for the sub-query clause. e.g. If there is a unique index uk(a) on table A , optimizer chooses index scan by uk(a) for query SELECT * FROM A WHERE A.a IN (SELECT B.a FROM B WHERE B.a > 100) . The index definition is changed to uk(tidb_shard(a), a) by this proposal, optimizer doesn't choose index for the query above any more.
Joint Index May Be Invalid
The proposal only adds expression tidb_shard(?) = ? for equivalent condition in WHERE clause. If the access condition in WHERE clause only use part of a joint index, this proposal may leads to index useless. e.g. If there is a unique index uk(a) on table A , optimizer chooses index scan by uk(a, b) for query SELECT * FROM A WHERE A.a = 10. The index definition is changed to uk(tidb_shard(a), a, b) by this proposal, optimizer doesn't choose index for the query above any more.
FastPlan May Be Invalid
It can't adds expression tidb_shard(?) = ? to access condition in the FastPlan process. So, the FastPlan process is invalid for shard index. e.g. If there is a unique index uk(a) on table A , optimizer makes a PointGet plan by FastPlan process for query SELECT * FROM A WHERE A.a = 100. The index definition is changed to uk(tidb_shard(a), a) by this proposal, FastPlan can't recognize it is a shard index field in WHERE clause.
Shard Index Can't Use Prepare Plan Cache
If there is a generated column on a table, the queries about this table can't use prepare plan cache. Shard index uses the expression tidb_shard(a) as the first field, and it makes a generated column. So the table with shard index can't use prepare plan cache.
Design 2023 03 14 Multi Valued Index (`docs/design/2023-03-14-multi-valued-index.md`)
Multi-valued index Design Documents
- Author(s): Xiong Jiwei, Zhang Yuanjia
Table of Contents
Introduction
This document introduces the technical design of implementing 'Multi-valued index' in TiDB.
Motivation or Background
Multi-valued index is a new feature introduced in MySQL 8.0.17, which allows defining indexes on a JSON array and use the index via JSON functions, similar to MongoDB in Multikey Indexes. e.g
CREATE TABLE t1 (data JSON);
CREATE INDEX zips ON t1((CAST(data->'$.zip' AS UNSIGNED ARRAY)));
INSERT INTO t1 VALUES
('{"id":1, "zip": [0,111,333]}'),('{"id":2, "zip": [123,456,0]}'),
('{"id":3, "zip": [123,123,111]}'),
('{"id":4, "zip": [456,567,222]}'),
('{"id":5, "zip": []}');
mysql> SELECT * FROM t1 WHERE 123 MEMBER OF (data->'$.zip');
+-----------------------------------+
| data |
+-----------------------------------+
| {"id": 2, "zip": [123, 456, 0]} |
| {"id": 3, "zip": [123, 123, 111]} |
+-----------------------------------+
2 rows in set (0.01 sec)That is: N index records point to one row record (N: 1)
A common scenario involves having rows with associated tags and the need to efficiently query all data containing a specific tag.
Detailed Design
Overview
- Using
cast(... as ... array)to define a multi-valued index, which is essentially an expression index whose virtual column type is "array with type". The index is encoded in the same way as normal secondary indexes. - The update of the multi-valued index behaves the same as the normal secondary index but the modification of one row may produce changes to multiple index records. If the type of array element is not satisfied the index definition, an error will be reported.
- Use
MEMBER OF,JSON_CONTAINS(subset),JSON_OVERLAPS(intersection)functions in where condition to using the multi-valued index.
Encoding
The encoding of each index record is identical to the normal secondary index(see TiDB Index Key/Value Format for more details).
For string types, the encoding result in TiDB is collation-aware, we could use binary collation for strings(in MySQL it is utf8mb4_0900_as_cs and behaves almost the same as binary).
- A row record may have multiple index records corresponding to it
row ('pk1', [1, 1, 2])
produces index records
1 -> 'pk1'
2 -> 'pk1'- Multi-valued index can be a compound index
row ('pk1', c1, [1, 1, 2], c2)
produces index records
(c1,1,c2) -> 'pk1'
(c1,2,c2) -> 'pk1'- Multi-valued index can be a unique index
Parser
New syntax: use cast(... as... array) to create the index. Add an Array field in FuncCastExpr indicate the use of this syntax.
type FuncCastExpr struct {
//...
Array bool
}Expression
Use JSONBinary type as the return type of expression cast(... as... array). In the FieldType structure, add an array field indicates whether the type is an array, and tp represents the type of elements in the array.
type FieldType struct {
// tp is type of the array elements
tp byte
// array indicates whether the type is an array
array bool
}Implement new built-in functions castAsTypedArrayFunctionSig, MEMBER OF and JSON_OVERLAPS.
DML
Data changes cause index changes, which are handled in the same way as normal secondary indexes.
- Insert: insert a new row record and add index records for each element in the array.
- Delete: delete the row record and delete index records for each element in the array.
- Update: delete the old index records and add new index records.
DDL
- Multi-valued index can be composite index, but only one JSON array can be used in the index definition.
- Multi-valued index is an expression index, so it has the same restrictions as expression index.
- Multi-valued index can be a unique index, but the uniqueness is not guaranteed within the same JSON array.
Planner
Column substitute
The column in the where condition will substituted with the corresponding expression in the index definition if the query meet the following 3 requirements
- Where condition contains any of the 3 functions:
MEMBER OF/JSON_CONTAINS/JSON_OVERLAPS. - Functions' parameter type must consistent with multi-valued index definitions.
- The expression is consistent with multi-valued index definition.
For example, the index definition is create index idx on t((cast(data->'$.zip' as unsigned array))), the where condition is where 123 member of (data->'$.zip'), the column data->'$.zip' is substituted with cast(data->'$.zip' as unsigned array).
Index selection is the same as normal secondary index.
Build the operator
For any of the 3 functions, we can use IndexMerge operator to fetch the data:
MEMBER OF ( )
IndexMerge
IndexRangeScan(<const>)
TableRowIDScan- JSON_CONTAINS(
, [ , , , ...])
IndexMerge(AND)
IndexRangeScan(<c1>)
IndexRangeScan(<c2>)
IndexRangeScan(<c3>)
...
TableRowIDScan- JSON_OVERLAPS(
, [ , , , ...])
IndexMerge(OR)
IndexRangeScan(<c1>)
IndexRangeScan(<c2>)
IndexRangeScan(<c3>)
...
TableRowIDScanEach IndexRangeScan is a PointGet like operator. It will fetch the row record by the index record. Since different indexes could match the same primary key, we need to use IndexMerge to filter the duplicated row records. For JSON_CONTAINS we should use AND type of IndexMerge, because only the primary key that contained in all the IndexRangeScan can be filtered. For JSON_OVERLAPS we should use OR to filter the row records.
If the multi-valued index is unique, it can be further optimized to PointGet.
Impacts & Risks
Limitations, and Characteristics
- Multi-valued index will only be used when the where condition contains any of the functions
MEMBER OF/JSON_CONTAINS/JSON_OVERLAPS. So even if SQL contains hint, force index, use index, etc., it is not necessarily possible to force multi-valued index. cast(... as ... array)can only appear once in the composite index definition, and the casted column must be a JSON column.- If multi-valued index is a unique index, then we have
-- Allowed:
INSERT INTO t1 VALUES('[1,1,2]');
INSERT INTO t1 VALUES('[3,3,3,4,4,4]');
-- Disallowed, report dup-key error:
INSERT INTO t1 VALUES('[1,2]');
INSERT INTO t1 VALUES('[2,3]');- Nullability
- If the write data is an empty array, there will be no corresponding index record. Therefore:
not xxxcannot use the index, because empty array data cannot access through the index.- workaround:
select * from t where pk not in (select pk from t where a member of (xxx)).
- workaround:
- If a column is null, add a null index record.
- Null is not allowed as an array item, trying to write will report an error.
- If the write data is an empty array, there will be no corresponding index record. Therefore:
- The type of multi-valued index cannot be
BINARY,JSON, andYEAR. - Multi-valued index cannot be a primary key or a foreign key.
- Storage Space and Performance:
- average number of array items * secondary index uses space.
- Compared to normal indexes, DML will produce more changes to multi-valued index records, so the Multi-valued index will bring more performance impact than normal indexes.
- All other limitations in expression index.
Design 2024 07 12 Support Vector Index (`docs/design/2024-07-12-support-vector-index.md`)
Proposal: Vector Index
- Author: zimulala
- Tracking issue: https://github.com/pingcap/tidb/issues/55693
**Introduction**
Vector Index refers to constructing a time and space efficient data structure for vector data based on a certain mathematical quantization model, to efficiently retrieve several vectors that are as similar as possible to the target vector. Currently, we plan to support the HNSW series of vector indexing methods.
**Motivation or Background**
This document plans to support the same processing of vector indexes as ordinary indexes, its specific functions are as follows :
- Support adding and using vector indexes, including adding vector indexes during and after table creation.
- Support dropping and renaming vector indexes.
**Detailed Design**
The process of adding a vector index is similar to that of adding an ordinary index. However, since the actual vector index data is added to TiFlash, there is no process for populating the index data to TiKV.
The following figure takes the add vector index operation as an example and briefly describes its execution process.
**TiDB**
**Parser**
Syntax required to create a vector index:
- Adding a new ConstraintElem syntax creates a vector index when creating a table.
CREATE TABLE foo (
id INT PRIMARY KEY,
data VECTOR(5),
data64 VECTOR64(10),
-- "WITH OPTION" is not supported in Phase 1
VECTOR INDEX idx_name USING HNSW ((VEC_COSINE_DISTANCE(data))) [WITH OPTION "m=16, ef_construction=64"]
);- By
IndexKeyTypeOptaddVECTORindex type, andIndexTypeOptaddHNSWoption type, and add vector index after creating the table.
CREATE VECTOR INDEX idx_name USING HNSW ON foo ((VEC_COSINE_DISTANCE(data)))
-- Proposal 1, "WITH OPTION" is not supported in Phase 1
[WITH OPTION "m=16, ef_construction=64"];
-- Proposal 2, "VECTOR_INDEX_PARAM" is not supported in Phase 1
[VECTOR_INDEX_PARAM "m=16, ef_construction=64"];
ALTER TABLE foo ADD VECTOR INDEX idx_name USING HNSW ((VEC_COSINE_DISTANCE(data)))
-- "WITH OPTION" is not supported in Phase 1
[WITH OPTION "m=16, ef_construction=64"];- The syntax is similar to a normal index, and there are several ways to create an index
CREATE VECTOR INDEX idx ON t ((VEC_COSINE_DISTANCE(a))) USING HNSW;
CREATE VECTOR INDEX IF NOT EXISTS idx ON t ((VEC_COSINE_DISTANCE(a))) TYPE HNSW;
CREATE VECTOR INDEX ident ON db.t (ident, ident ASC ) TYPE HNSW;
ALTER TABLE t ADD VECTOR ((VEC_COSINE_DISTANCE(a))) USING HNSW COMMENT 'a';
ALTER TABLE t ADD VECTOR INDEX ((VEC_COSINE_DISTANCE(a))) USING HNSW COMMENT 'a';
ALTER TABLE t ADD VECTOR INDEX IF NOT EXISTS ((VEC_COSINE_DISTANCE(a))) USING HNSW COMMENT 'a';**Planner && Executor**
- Support to choose vector index by CBO and
USE INDEXhint. - The vector index only obtains the top n values through similarity. The following is the syntax for using a vector index when querying.
SELECT *
FROM foo
ORDER BY VEC_COSINE_DISTANCE(data, '[3,1,2]')
LIMIT 5;Currently, the use of vector indexing is supported on the master branch and supports the explain function.
- Protobuf adds the new field of `indexId` when TiDB interacts with TiFlash.
type ANNQueryInfo struct {
QueryType ANNQueryType `protobuf:"varint,1,opt,name=query_type,json=queryType,enum=tipb.ANNQueryType" json:"query_type"`
DistanceMetric VectorDistanceMetric `protobuf:"varint,2,opt,name=distance_metric,json=distanceMetric,enum=tipb.VectorDistanceMetric" json:"distance_metric"`
TopK uint32 `protobuf:"varint,3,opt,name=top_k,json=topK" json:"top_k"`
ColumnName string `protobuf:"bytes,4,opt,name=column_name,json=columnName" json:"column_name"`
ColumnId int64 `protobuf:"varint,5,opt,name=column_id,json=columnId" json:"column_id"`
RefVecF32 []byte `protobuf:"bytes,6,opt,name=ref_vec_f32,json=refVecF32" json:"ref_vec_f32,omitempty"`
MaxDistance float64 `protobuf:"fixed64,10,opt,name=max_distance,json=maxDistance" json:"max_distance"`
HnswEfSearch uint32 `protobuf:"varint,20,opt,name=hnsw_ef_search,json=hnswEfSearch" json:"hnsw_ef_search"`
// new fields
IndexId int64 `protobuf:"varint,5,opt,name=column_id,json=columnId" json:"column_id"`
}The analyze statement is not supported at the moment.
**DDL**
**Limitations and Constraints**
- A replica of TiFlash is required
- Cluster must have a TiFlash replica
- About the TiFlash replica of the table for which the vector index needs to be created
- When a table is created with an index, the TiFlash replica of the table is set to 1 by default in the first stage (serverless is greater than or equal to minReplica in the configuration item).
- After creating a table, creating an index requires a TiFlash replica.
- Cannot be created on TiFlash nodes with static encryption enabled
- Cannot be a primary key index
- Cannot be a composite index
- Create several index constraints for the same column
- There can be different vector indexes defined using different
distance functions - Different vector indexes defined by the same
distance functionwill not exist
- There can be different vector indexes defined using different
- Same name processing as the ordinary index
- Vector index requires support for functions
| function | Phase 1 | Phase 2 | Phase 3 |
|---|---|---|---|
| VEC_L1_DISTANCE | TBD | ||
| VEC_L2_DISTANCE | v | ||
| VEC_NEGATIVE_INNER_PRODUCT(名字待定) VEC_NEGATIVE_INNER_PRODUCT (name to be determined) | v | ||
| VEC_COSINE_DISTANCE | v |
- Incompatibility with other features(This operation is not supported in the first phase of this design, but it can be considered for support in the future).
- Setting invisible properties is not supported
- Dropping a column with a vector index is not supported, and creating multiple indexes together is not supported. Also, modifying column types with vector indexes is not supported (lossy changes).
- Workaround, split it into multiple operations: for example, we can first drop all vector indexes on the column, and then drop the column.
**Meta Information**
Add the VectorIndexInfo information field to describe and store information about vector indexes. In addition, add relevant information to the existing IndexInfo to record information about vector indexes.
// VectorIndexInfo is the information on the vector index of a column.
type VectorIndexInfo struct {
// Kind is the kind of vector index. Currently, only HNSW is supported.
Kind VectorIndexKind `json:"kind"`
// Dimension is the dimension of the vector.
Dimension uint64 `json:"dimension"` // Set to 0 when initially parsed from comment. Will be assigned to flen later.
// DistanceMetric is the distance metric used by the index.
DistanceMetric DistanceMetric `json:"distance_metric"`
}
// IndexInfo provides meta data describing a DB index.
type IndexInfo struct {
ID int64 `json:"id"`
Name CIStr `json:"idx_name"` // Index name.
...
// VectorInfo is the vector index information.
VectorInfo *VectorIndexInfo `json:"is_vector"`
}**Add Vector Index**
- Consider adding
ActionAddVectorIndexDDL job type, through the existing DDL framework, to achieve the operation of adding a vector index.- The middle state is consistent with adding a normal index (None -> Delete-Only -> Write-Only -> Write-Reorg -> Public).
- When in the Write-Reorg state, do not use the runReorgJob mechanism of this state, that is, do not enable backfilling or check execution progress logic in the background.
- Sync
VectorIndexInfoto TiFlash. - Wait for TiFlash to fill in the HNSW Index data.
- We can check whether the operation has been completed by checking whether the
ROWS_STABLE_NOT_INDEXEDvalue of the table corresponding to the added vector index on thesystem.dt_local_indexestable on TiFlash is 0. - Obtain error info from indexStat to determine if there is an error during execution.
- Sync
- Compatible with Cancel, Pause, and Resume operations
- The Pause operation needs to consider pausing the operation during the reorg phase.
- Not supported in the first phase
- Implement Rollback related operations.
The IsRollbackablecheck is the same as a general index.- Like general indexes, if you roll back during the Write-Reorg phase, you also need to delete the index data that has been added.
- The Pause operation needs to consider pausing the operation during the reorg phase.
**Drop Vector Index**
- No need to add a DDL job type, similar to deleting a general index operation.
- The middle state is consistent with deleting a general index (None - > Write-Only - > Delete-Only - > Delete-Reorg - > None).
- Judgment, if it is a vector index
- Delete-Reorg state
- No need to wait for HNSW Index data deletion on TiFlash to complete .
- There is no need to add this metadata to
MySQL.gc_delete_range
- Delete-Reorg state
- Compatible with Cancel, Pause, and Resume operations
- The Pause operation needs to consider pausing the operation during the reorg phase.
- Not supported in the first phase
- Implement Rollback related operations.
The IsRollbackablecheck is the same as a general index.
- The Pause operation needs to consider pausing the operation during the reorg phase.
**Rename Vector Index**
No need to add a DDL job type, just like renaming a general index operation. We don't have to wait for TiFlash's synchronization operation, just return directly after the TiKV operation is completed.
**Display**
- Compatible with
admin show ddlto display the progress of DDL operation execution- The display way is considered the same as the general DDL display way, and the
ROWS_STABLE_INDEXEDinformation of the corresponding table of theinformation_schema.tiflash_indexestable on TiFlash can be filled into theROW_COUNTinformation of the DDL job.
- The display way is considered the same as the general DDL display way, and the
- Add or update relevant system table information
- information_schema tiflash_tables (already supported)
- information_schema tiflash_segments (already supported)
- information_schema tiflash_indexes (already supported)
- Add columns index_name and index_id.
- Add columns error_msg and error_count.
- information_schema.tidb_indexes
- Support
show create table The admin check table/indexandadmin repair tableoperations do not currently consider processing of vector indexes.- Add relevant metrics
- Because
ActionAddVectorIndexis a new DDL job type, the monitoring information for adding a vector index operation needs to be handled the same as adding a general index. - Because dropping or renaming a vector index does not add a DDL job type, monitoring these two operations does not require special handling.
- Because
**TiFlash**
**Add Vector Index**
Adding an index operation mainly consists of two steps:
- Synchronize schema operations to add index data. Currently, there are two main ways for TiFlash to obtain schema from TiKV during operation: the first is that the Background Sync Thread is responsible for regularly calling Schema Syncer to update the Local Schema Copy module; the second is that the read and write operations in TiFlash will also call Schema Syncer for updates when needed.
- Since adding a vector index does not trigger the synchronization schema of the second method, currently we can only rely on regularly synchronizing the schema to synchronize the metadata to TiFlash.
- Notify TiFlash to perform the load schema operation through HTTP.
syncTableSchemahandles synchronization Schema operations, and if new index information is found, it needs to be synchronized to the table.
- Since adding a vector index does not trigger the synchronization schema of the second method, currently we can only rely on regularly synchronizing the schema to synchronize the metadata to TiFlash.
- Create the vector index data.
- Constraints that require creating an index. That is, when the index status is Write-Reorg.
- Timing for generating index data:
- When synchronizing to add index information, obtain all segment information under the corresponding table to generate the HNSW Index.
- Use segments as task units and put them into LocalIndexerScheduler (already supported) for parallel processing tasks.
- Other operations that may trigger the generation of index data: merging delta and stable, merging/splitting/ingesting segments.
- Due to the uncontrollable timing of such triggering operations, consider separating the index generation from the existing stable layer. The plan is to wait until the index status is public to truly trigger the index generation.
- When synchronizing to add index information, obtain all segment information under the corresponding table to generate the HNSW Index.
- Execute index data generation, with segments as the unit of index data generation.
- Create a vector index for DMFile that does not have a corresponding index. Currently, only the data of the stable layer is created with a vector index.
- The real file name for creating the index is similar to: {idx_id} .idx.
- This naming convention is different from the existing naming convention {col_id} .idx. If compatibility is a concern, it is best to add a prefix.
- The real file name for creating the index is similar to: {idx_id} .idx.
- Create a
VectorIndexHNSWBuilderto read column data and populate the corresponding index data (already supported). - Update the relevant metadata in the segment, including the index information stored on the DMFile.
- Wait for index data generation on all relevant segments to complete.
- Create a vector index for DMFile that does not have a corresponding index. Currently, only the data of the stable layer is created with a vector index.
**Drop Vector Index**
- This operation is similar to the add vector index operation, except that this operation processes dropping the vector index.
- Most of the process is the same as creating a vector index.
- Drop the vector index data.
- When
syncTableschemahandles synchronous Schema operations, it needs to remove the corresponding index. - The difference with the add vector index is that the constraint for triggering the operation is that the index state is Delete-Reorg state.
- In addition, when triggering the actual deletion operation, if it is found that there is no corresponding vector index (i.e. metadata without vector index), and the corresponding vector index data file still exists, it is necessary to delete the index data.
- When
**Display**
Add or update relevant system table information.
- information_schema tiflash_indexes needs to add some columns:
- Add columns index_name and index_id.
- Add columns error_msg and error_count.
**Compatibility**
**Tools**
- BR
- TiCDC
- DM
- No need for support
- Lighting
- Dumpling
**MySQL 9.0**
Follow-up MySQL supports MySQL 9.0 vector, whether we need to consider compatibility later.
- For the time being, we don't need to be compatible with this syntax
**Test Design**
**Functional Tests**
It’s used to ensure the basic feature function works as expected. Both the integration test and the unit test should be considered.
**Scenario Tests**
- Create multiple vector indexes on various tables. It tests the speed and resource usage when numerous vector indexes are added in parallel.
- Test whether index data can be deleted in sync schema (Drop vector index) when the index is deleted.
**Compatibility Tests**
A checklist to test compatibility:
- Compatibility with other features, like partition table, drop column, etc.
- Compatibility with other components, like BR, TiCDC, Dumpling, BR, DM, Lighting, etc.
- Upgrade compatibility
Design README (`docs/design/README.md`)
TiDB Design Documents
Many changes, including bug fixes and documentation improvements can be implemented and reviewed via the normal GitHub pull request workflow.
Some changes though are "substantial", and we ask that these be put through a bit of a design process and produce a consensus among the TiDB community.
The process described in this page is intended to provide a consistent and controlled path for new features to enter the TiDB projects, so that all stakeholders can be confident about the direction the projects is evolving in.
Who should initiate the design document?
Everyone is encouraged to initiate a design document, but before doing it, please make sure you have an intention of getting the work done to implement it.
Before creating a design document
A hastily-proposed design document can hurt its chances of acceptance. Low-quality proposals, proposals for previously-rejected features, or those that don't fit into the near-term roadmap, may be quickly rejected, which can be demotivating for the unprepared contributor. Laying some groundwork ahead of the design document can make the process smoother.
Although there is no single way to prepare for submitting a design document, it is generally a good idea to pursue feedback from other project developers beforehand, to ascertain that the design document may be desirable; having a consistent impact on the project requires concerted effort toward consensus-building.
The most common preparations for writing and submitting a design document for now is creating an issue for discussion, which is going to be converted into a tracking issue of the design implementation.
What is the process?
- Create a pull request with a design document based on the template under this directory as
YYYY-MM-DD-my-feature.md. - Discussion takes place, and the text is revised in response.
- The design document is accepted or rejected when at least two committers reach consensus and no objection from the committer.
- If accepted, create a tracking issue for the design document or convert one from a previous discuss issue. The tracking issue basically tracks subtasks and progress. And refer the tracking issue in the design document replacing placeholder in the template.
- Merge the pull request of design.
Please update the tracking issue according to the progress of succeeding implementation pull requests.
An example that almost fits into this model is the proposal "Support global index for partition table", without following the latest template.
- Its tracking issue: https://github.com/pingcap/tidb/issues/18032
- Its pull request: https://github.com/pingcap/tidb/pull/18982
- Its design document: https://github.com/pingcap/tidb/blob/master/docs/design/2020-08-04-global-index.md
Agents Ddl 06 Add Index (`docs/agents/ddl/06-add-index.md`)
Add Index Deep Dive (online DDL + reorg/backfill)
This doc focuses on ActionAddIndex (and closely related ActionAddPrimaryKey). Add index is special because it’s a reorg/backfill DDL: it needs a schema state machine + background data backfill while DML continues.
Entry points (start here)
SQL → DDL module:
- SQL dispatch:
pkg/executor/ddl.go(type DDLExec,(*DDLExec).Next) - Statement → job:
pkg/ddl/executor.go:CreateIndex,pkg/ddl/executor.go:createIndex
Job creation (what’s persisted):
- Job skeleton:
pkg/ddl/executor.go:buildAddIndexJobWithoutTypeAndArgs - Job version:
job.Version = model.GetJobVerInUse()(insidecreateIndex) - Job type:
job.Type = model.ActionAddIndex(insidecreateIndex) - Reorg meta init:
pkg/ddl/reorg_util.go:initJobReorgMetaFromVariables - Args (v2 typed job args):
model.ModifyIndexArgswithOpType = model.OpAddIndex(insidecreateIndex)
Job args and features (global/partial/expression/presplit)
Add index is a “normal” DDL action in terms of SQL surface, but the job args carry a lot of complexity:
- Global index validation:
pkg/ddl/executor.go:checkCreateGlobalIndex - Partial index predicate:
- Build:
pkg/ddl/executor.go:CheckAndBuildIndexConditionString - Apply:
pkg/ddl/index.go:onCreateIndex(restoresConditionExprStringon the builtIndexInfo)
- Build:
- Expression / generated-key indexes may introduce hidden columns:
- Build:
pkg/ddl/executor.go:checkIndexNameAndColumns - Publish:
pkg/ddl/index.go:moveAndUpdateHiddenColumnsToPublic(done when movingStateNone→StateDeleteOnly)
- Build:
- Pre-split index regions (optional
PRE_SPLIT_REGIONSindex option):- Manual forms persist either a region count, explicit
BYvalues, orBETWEENbounds with a region count in eachmodel.IndexArgSplitOpt. PRE_SPLIT_REGIONS AUTOpersists a per-index AUTO marker and derives boundaries only from the leading index column's existing Analyze V2 statistics.- AUTO is best-effort: ineligible statistics or failures while loading, decoding, or planning the complete leading-column distribution, or while splitting or scattering, are logged and do not fail add-index. AUTO never plans with a partial distribution. It may skip partitioned or partial indexes, leading string prefix indexes, small tables, or missing, pseudo, outdated, unhealthy, or non-V2 statistics. Therefore, successful add-index does not guarantee that AUTO split any Regions.
- One shared AUTO deadline starts before the first index and covers all AUTO indexes. Its duration is the 30-second statistics-load allowance plus
tidb_wait_split_region_timeout. Manual pre-splitting keeps its original context and per-index timeout, but its wall time consumes the shared AUTO budget. - AUTO samples the distribution at fixed 2% intervals, producing at most 49 distribution-derived split keys per index, plus an index-start key where applicable. Every eligible AUTO index is split and scattered separately, so a multi-index statement can multiply the number of Regions even when indexes share the same leading column.
- Fast reorg splits the temporary index keyspace. After GC removes the temporary index data, empty Regions may remain until PD's
split-merge-intervalhas elapsed (one hour by default); actual merging remains subject to PD's normal merge conditions. - Manual pre-splitting is strict: invalid options or runtime split failures are returned to the add-index job instead of being ignored.
- Parse:
pkg/ddl/executor.go:buildIndexPreSplitOpt - Execute:
pkg/ddl/index_presplit.go:preSplitIndexRegions
- Manual forms persist either a region count, explicit
Owner scheduling + worker:
- Reorg worker pool:
pkg/ddl/job_scheduler.go(routesmysql.tidb_ddl_job.reorg=1jobs toreorgWorkerPool) - Worker type:
pkg/ddl/job_worker.go(addIdxWorker) - Add-index handler:
pkg/ddl/index.go:onCreateIndex
The reorg routing flag is decided at submission time:
- Insert path:
pkg/ddl/job_submitter.go:insertDDLJobs2Table(jobW.MayNeedReorg()→mysql.tidb_ddl_job.reorg)
State machine: index visibility (online DDL)
The add-index job drives an index state and a corresponding job schema state. The core transitions happen in pkg/ddl/index.go:onCreateIndex:
StateNone→StateDeleteOnlyStateDeleteOnly→StateWriteOnlyStateWriteOnly→StateWriteReorganization(reorg/backfill)StateWriteReorganization→StatePublic
The job records the corresponding “schema state” on job.SchemaState (e.g. StateDeleteOnly, StateWriteOnly, StateWriteReorganization) so other parts of the framework can reason about compatibility windows.
At each boundary, the worker updates table metadata and schema version so all nodes observe the same compatibility window before the next step.
Reorg stage = backfill + optional ANALYZE
StateWriteReorganization is not “just backfill”. In pkg/ddl/index.go:onCreateIndex, the worker:
- Runs reorg/backfill until done:
pkg/ddl/index.go:doReorgWorkForCreateIndex - Decides whether to run
ANALYZE(based on job vars and job context):- State machine:
job.ReorgMeta.AnalyzeState(seepkg/ddl/index.go:onCreateIndex) - Execution:
pkg/ddl/index.go:startAnalyzeAndWait
- State machine:
Only after analyze is done/skipped/timeout/failed does the worker finalize the index to StatePublic and finish the job.
Reorg meta: what controls backfill mode
Before the job is submitted, add index initializes job.ReorgMeta from global/session variables:
- Implementation:
pkg/ddl/reorg_util.go:initJobReorgMetaFromVariables - Key toggles:
tidb_ddl_enable_fast_reorg(vardef.EnableFastReorg)tidb_enable_dist_task(vardef.EnableDistTask) — requires fast reorg; otherwise the job rejects (ErrUnsupportedDistTask)
job.ReorgMeta also carries persisted reorg parameters (concurrency, batch size, max write speed) and (for dist-task) target scope / max node count.
Choosing a backfill process (txn vs txn-merge vs ingest)
The reorg/backfill implementation picks a reorg type once and persists it in job.ReorgMeta.ReorgTp:
- Selection logic:
pkg/ddl/index.go:pickBackfillType
High level:
- If fast reorg is disabled →
ReorgTypeTxn(traditional transactional backfill) - If fast reorg is enabled:
- If ingest/Lightning environment is available →
ReorgTypeIngest - Else → fallback to
ReorgTypeTxnMerge(still a fast-reorg pipeline, without Lightning)
- If ingest/Lightning environment is available →
The reorg loop itself is coordinated from pkg/ddl/index.go:doReorgWorkForCreateIndex.
Backfill-merge process (temporary index + BackfillState)
Fast-reorg pipelines use a backfill-merge state machine persisted on the index (IndexInfo.BackfillState):
- Definition and semantics:
pkg/meta/model/reorg.go:BackfillState - Driver:
pkg/ddl/index.go:doReorgWorkForCreateIndex
States:
BackfillStateRunning: backfill is running; writes/deletes are redirected to (or maintained in) a temporary index.BackfillStateReadyToMerge: temp index is ready; publish this state so all TiDB nodes start copying writes/deletes for merge safety.BackfillStateMerging: merge temp index records back to the origin index.BackfillStateInapplicable: exit the backfill-merge process (and prevent double-write on the temp path).
This state machine exists to keep correctness under: cross-node schema propagation, online writes during backfill, retries, and owner transfer.
Persistence: where “progress” lives
For resumability (owner transfer/retry), progress must be persisted. Add index uses:
- Job record:
mysql.tidb_ddl_job(job_meta,reorg,processing) - Reorg handle table:
mysql.tidb_ddl_reorg(range + element + reorg meta)- Access helpers:
pkg/ddl/job_scheduler.go:getDDLReorgHandle,pkg/ddl/job_scheduler.go:initDDLReorgHandle,pkg/ddl/job_scheduler.go:deleteDDLReorgHandle
- Access helpers:
If you change what’s stored for reorg/backfill, ensure it’s:
- encoded/decoded compatibly across job versions,
- written transactionally with the step’s meta updates,
- sufficient to continue without re-scanning from zero.
Failure, cancellation, rollback (what to keep invariant)
Add index must be safe under partial failure and retries:
- A job step may be re-run (owner transfer, retryable errors). Treat each step as idempotent.
- If backfill fails with non-retryable error (including duplicate key in ingest), the code may convert to rollback:
- See rollback conversion usage in
pkg/ddl/index.go(e.g.convertAddIdxJob2RollbackJobcall sites).
- See rollback conversion usage in
When adding new fast-reorg/ingest behavior, also verify rollback paths don’t leak temp index artifacts and that BackfillState transitions remain monotonic and persisted.
Practical debugging anchors
SQL:
ADMIN SHOW DDL JOBSADMIN SHOW DDL JOB QUERIESADMIN CANCEL DDL JOBS <job_id>
Tables:
mysql.tidb_ddl_job(queue)mysql.tidb_ddl_history(history)mysql.tidb_ddl_reorg(reorg handle/progress)
Code:
- Job creation and args:
pkg/ddl/executor.go:createIndex - State transitions:
pkg/ddl/index.go:onCreateIndex - Reorg/backfill loop:
pkg/ddl/index.go:doReorgWorkForCreateIndex - Ingest backend:
pkg/ddl/ingest/*(see alsodocs/design/2022-06-07-adding-index-acceleration.md)
Common pitfalls checklist (before you send a PR)
- Backfill progress or
BackfillStatenot persisted → reorg restarts or double-writes after retry. - Missed schema sync boundary when transitioning index states → nodes observe incompatible DML rules.
- Job args incompatibility across versions (v1/v2) → existing jobs can’t be decoded after upgrade/downgrade.
- Adding a partial index requires fast reorg to be enabled. The supported backfill paths are ingest and
ReorgTypeTxnMergeon standalone TiDB backed by unistore. The standalone transactional path rejectsTIMESTAMPcomparison predicates before publishing the index because backfill and DML can use different time zones;IS NULLandIS NOT NULLpredicates remain supported. Transactional backfill evaluates each supported index predicate against the decoded row, including default column values.
Agents Ddl README (`docs/agents/ddl/README.md`)
DDL Execution: Read-First Index
TiDB DDL is job-based and owner-driven: a SQL DDL statement is converted into a persistent DDL job, then the DDL owner schedules and runs the job on workers, gradually changing schema states and waiting for schema version synchronization across TiDB nodes.
The most common mistake is to implement “DDL behavior” directly in pkg/executor/ (SQL executor layer). That usually bypasses:
- Job persistence / owner failover (resumability).
- Schema state machine (
delete only→write only→reorg→public). - Schema version + diff update, and cluster-wide schema sync.
- MDL / lease based safety mechanisms.
This doc set is meant to be the first thing to read before touching DDL-related code.
Caveat (debugging and drift)
- Debugging: You may use these docs as a starting point, but you MUST validate conclusions against code/tests. Treat unverified statements as hypotheses (avoid hallucination/outdated assumptions).
- Drift: If implementation and
docs/agents/ddl/*diverge during design/development, you MUST update the docs to match reality and call it out in the PR/issue.
Agent preflight (questions)
Before touching pkg/ddl/, answer these explicitly (write them down in the PR/issue if possible):
- Is it job-based (persist/resume/failover) or a metadata-only fast path?
- Does it require schema state transitions (and which ones), or can it stay
publicthroughout? - Does it require a reorg/backfill scan (read/write workload), and what is the checkpoint/persistence point?
- What are the cancel/rollback semantics? Which step(s) are reversible, and which need delete-range GC?
- How does it affect schema version + schema diff and follower schema sync?
- What are the system tables / durable metadata involved (
mysql.tidb_ddl_job,mysql.tidb_ddl_reorg, ...)? Which fields must be backward compatible? - What is the expected online behavior (MDL / blocking, write conflicts, phase boundaries)?
- What is the minimal regression test (unit/integration), and which failpoints can make it deterministic?
Index (by task)
- Understand end-to-end call chain:
docs/agents/ddl/01-execution-flow.md - Job state machine / schema state machine / schema sync:
docs/agents/ddl/02-job-lifecycle.md - Any reorg/backfill (ingest, checkpoint, distributed backfill):
docs/agents/ddl/03-reorg-backfill.md - Where-to-change + test patterns:
docs/agents/ddl/04-dev-checklist.md - “Where is this implemented?” file map:
docs/agents/ddl/05-file-map.md - Add-index behavior (fast reorg, ingest, backfill-merge):
docs/agents/ddl/06-add-index.md - Modify-column behavior (reorg types, null/not-null, type change):
docs/agents/ddl/07-modify-column.md - Partition DDL (add/drop/truncate/reorganize/exchange):
docs/agents/ddl/08-partition-ddl.md
Operation index (jump table)
Column DDL
- Modify column / change column:
model.ActionModifyColumn→docs/agents/ddl/07-modify-column.md
Index DDL
- Add index / add primary key:
model.ActionAddIndex,model.ActionAddPrimaryKey→docs/agents/ddl/06-add-index.md
Partition DDL
- Add/drop/truncate partition:
model.ActionAddTablePartition,model.ActionDropTablePartition,model.ActionTruncateTablePartition→docs/agents/ddl/08-partition-ddl.md - Reorganize / exchange partition:
model.ActionReorganizePartition,model.ActionExchangeTablePartition→docs/agents/ddl/08-partition-ddl.md
Mental model (one-minute skim)
pkg/executor/ddl.go(DDLExec) receives a DDL AST node and calls into the DDL module.pkg/ddl/executor.goconverts the statement to amodel.Job(or multiple jobs), then submits it viaJobSubmitter.JobSubmitterallocates IDs, writes the job intomysql.tidb_ddl_job, and notifies the owner-side scheduler.- Only the DDL owner runs
jobScheduler, which dispatches jobs into worker pools. - Workers run the job step-by-step (meta changes + schema state transitions), update global schema version, then wait for followers to sync.
- When done, the job is moved to history; the submitting session is unblocked and returns success/failure.
Execution flow diagram
sequenceDiagram
participant S as Session
participant X as DDLExec (pkg/executor/ddl.go)
participant E as DDL executor (pkg/ddl/executor.go)
participant J as JobSubmitter (pkg/ddl/job_submitter.go)
participant T as mysql.tidb_ddl_job
participant O as DDL Owner (jobScheduler)
participant W as ddl workers
participant V as Syncer (pkg/ddl/schemaver/syncer.go)
S->>X: Execute DDL statement (AST)
X->>E: ddl.Executor.*(stmt)
E->>J: deliver job(s) via limit channel
J->>T: allocate IDs + insert job record
J-->>O: notifyNewJobSubmitted()
O->>W: schedule & run job steps
W->>V: OwnerUpdateGlobalVersion + WaitVersionSynced
W->>T: move to history + delete from queue
W-->>E: close jobDone channel / notify
E-->>S: return resultDatabase read-only restore exception
Ordinary SQL and unauthenticated internal sessions do not gain a read-only write
bypass from SUPER or from internal-SQL execution. An explicitRESTRICTED_REPLICA_WRITER_ADMIN grant permits ordinary writes.
Trusted BR restore is a separate exception: SQL RESTORE first uses its existing
SUPER/RESTORE_ADMIN authorization, while standalone BR uses its trusted restore
entrypoint. Restore can recreate tables, replay incremental DDL, and restore
sequence state after the source database's ReadOnly flag has been restored.
Incremental DDL authorization covers its recorded write dependencies; other
restore operations authorize their current target database. The previous session
state is restored before return or reuse, without granting later SQL writes.
Releasing existing table locks is exempt from the read-only job check; acquiring
new locks retains that check.
The contract is implemented by pkg/privilege/privilege.go,pkg/executor/brie_utils.go, andbr/pkg/restore/internal/prealloc_db/db.go. Boundary coverage lives inTestBRIECreateTable/TrustedRestoreReadOnlyBoundary andTestCreateTablesWithPlanPreservesSourceMetadata. Incremental DDL replay and
cross-database authorization boundaries are covered by TestDB_ExecDDL2.
Diagnostic schema loading
Diagnostic mode continues to use the ordinary Etcd schema syncer. The Domain
schema-sync loop and InfoSchema reloads remain active so a diagnostic instance
can load the existing schema, while MDL checking is skipped. Diagnostic startup
requires an already bootstrapped keyspace and reads persisted startup settings
without writing them back.
serverinfo.Syncer does not register or refresh server and topology records in
diagnostic mode; the independent Domain server-ID lease remains active. Its
server-info sync loop returns immediately, also skipping that loop's
min-start-ts reporting.
Diagnostic session bootstrap calls Domain.StartDiagnostic instead ofDomain.Start, bypassing DDL.Start and its execution resources. DDL.Start,EnableDDL, and DisableDDL themselves have no diagnostic-mode guard;SwitchMDL returns diagnosticmode.ErrDDLNotAllowed. Cross-keyspace runtimes
skip server-info, MDL, and min-job-ID refresher background loops in diagnostic
mode.
Code map (where to look first)
Front-end (SQL executor layer)
pkg/executor/ddl.go:type DDLExec,(*DDLExec).Nextdispatches AST → DDL module; handles transaction boundary and converts schema-outdated errors.
DDL module (job-based execution)
pkg/ddl/ddl.go:NewDDLwires everything;(*ddl).Startstarts submit loop and campaigns owner.pkg/ddl/executor.go:type Executor(called by SQL layer); converts statements → jobs;DoDDLJobWrapperwaits for job completion.pkg/ddl/job_submitter.go:type JobSubmitterbatches submission, allocates IDs, inserts into job table, and notifies scheduler.pkg/ddl/job_scheduler.go: owner-only scheduler;ownerListener.OnBecomeOwnerstartsjobSchedulerand worker pools.pkg/ddl/job_worker.go: worker logic;transitOneJobStep/runOneJobStepdrive state transitions and meta updates.pkg/ddl/schema_version.go+pkg/ddl/job_worker.go:updateGlobalVersionAndWaitSynced: global schema version update +WaitVersionSynced.pkg/ddl/schemaver/syncer.go:type Syncerimplements schema version synchronization (etcd-based).pkg/ddl/systable/manager.go: storage access for job/MDL related system tables.
Cluster integration
pkg/domain/domain.go: creates DDL viaddl.NewDDL(...); initializes infosync + schema syncer, and orchestrates startup order.
Reading order
docs/agents/ddl/01-execution-flow.md— end-to-end call chain and responsibilities.docs/agents/ddl/02-job-lifecycle.md— job/version/state machines, schema sync, owner/failover.docs/agents/ddl/03-reorg-backfill.md— reorg/backfill and distributed backfill overview.docs/agents/ddl/04-dev-checklist.md— where-to-change, testing, and common pitfalls.docs/agents/ddl/05-file-map.md— quick “where is this implemented?” map insidepkg/ddl/.docs/agents/ddl/06-add-index.md— add-index deep dive (fast reorg, ingest, backfill-merge).docs/agents/ddl/07-modify-column.md— modify-column deep dive (reorg types, state machine).docs/agents/ddl/08-partition-ddl.md— partition DDL deep dive (state machine, reorg, GC).
Related design docs (deep dives)
- Distributed DDL reorg:
docs/design/2022-09-19-distributed-ddl-reorg.md - Add index acceleration / ingest:
docs/design/2022-06-07-adding-index-acceleration.md - Multi-schema change:
docs/design/2022-04-15-multi-schema-change.md - Pause/Resume DDL:
docs/design/2023-04-15-ddl-pause-resume.md - Pause user DDL while upgrading:
docs/design/2023-04-11-pause-user-ddl-when-upgrading.md - Dist task framework:
docs/design/2023-04-11-dist-task.md
Agents Dxf README (`docs/agents/dxf/README.md`)
DXF Notes
This note is a navigation map for DXF (Distributed eXecution Framework).
Use it to quickly find:
- the core framework implementation under
pkg/dxf/ - business integrations that use DXF but live outside
pkg/dxf/
Scope
- Core framework:
pkg/dxf/framework/ - IMPORT INTO DXF app:
pkg/dxf/importinto/ - DDL distributed backfill DXF app:
pkg/ddl/ - SQL/user-facing import entry:
pkg/executor/andpkg/executor/importer/ - Runtime bootstrap and ownership loops:
pkg/session/andpkg/domain/
Reading Rule
- If a package has package-level docs (
doc.go), read that first.- For DXF framework, start with
pkg/dxf/framework/doc.go.
- For DXF framework, start with
Core DXF Framework Map
pkg/dxf/framework/proto/: task type/step constants, task-subtask models,
and state machine enums.pkg/dxf/framework/handle/: task submission/control APIs (submit, wait,
pause/resume, cancel, modify).pkg/dxf/framework/storage/: task manager and dist-task table persistence.pkg/dxf/framework/scheduler/: owner-side scheduler manager and task
scheduler extension interfaces.pkg/dxf/framework/taskexecutor/: node-side executor manager and task
executor extension interfaces.pkg/dxf/framework/planner/: logical-plan to physical-plan/task creation
helpers used by DXF apps.pkg/dxf/operator/: operator/pipeline utilities reused by DXF apps.
High-Signal Entry Files
Runtime bootstrap and loops:
pkg/session/session.go: registers IMPORT INTO DXF scheduler/executor in
bootstrap (proto.ImportInto).pkg/ddl/ddl.go: registers DDL backfill DXF scheduler/executor and cleanup
hooks (proto.Backfill).pkg/domain/domain.go: starts executor manager on all nodes and starts/stops
scheduler manager based on DDL owner role.
IMPORT INTO integration:
pkg/executor/import_into.go: DXF task submission for IMPORT INTO jobs.pkg/dxf/importinto/taskinfo/runtime_info.go: IMPORT INTO job progress from its DXF task.pkg/dxf/importinto/planner.go: IMPORT INTO logical/physical planning by DXF
step.pkg/dxf/importinto/scheduler.go: IMPORT INTO scheduler extension.pkg/dxf/importinto/task_executor.goandpkg/dxf/importinto/subtask_executor.go: executor + step executors.pkg/executor/import_into.goandpkg/executor/importer/import.go: SQL
executor/planning and user-facing behavior around IMPORT INTO.
DDL backfill integration:
pkg/ddl/index.go: add-index flow that prepares/uses distributed backfill.pkg/ddl/backfilling_dist_scheduler.go: backfill scheduler extension.pkg/ddl/backfilling_dist_executor.go: backfill task executor extension.pkg/ddl/backfilling_clean_s3.go: backfill cleanup hook implementation.
Framework internals:
pkg/dxf/framework/proto/task.go: task rank/order (priority,create_time,id), slot-related task fields, and runtime slot calculation.pkg/dxf/framework/proto/step.go: task-type step definitions and step-order
contracts (includes compatibility notes on step constants).pkg/dxf/framework/scheduler/scheduler_manager.go: owner-side task admission,
slot reservation, cleanup/historical transfer loops.pkg/dxf/framework/taskexecutor/manager.go: node-side executor start/stop,
preemption handling, and meta recovery loop.pkg/dxf/framework/scheduler/slots.goandpkg/dxf/framework/taskexecutor/slot.go: slot/stripe reservation logic and
preemption decisions.
Learning/edge-case references:
docs/agents/import-into/README.md: IMPORT INTO conflict-resolution and
cleanup troubleshooting map.pkg/dxf/example/: minimal DXF app skeleton (scheduler + executor extension
wiring) useful when adding a new task type.
Runtime Flow (Cheatsheet)
- Business logic builds task metadata/logical plan and submits a DXF task.
- Framework persists task/subtask state through
framework/storage. Domainstarts executor-manager loop on every TiDB node.- Scheduler-manager loop runs only while the local node is DDL owner.
- Scheduler extension advances steps and dispatches subtasks.
- Executor extension executes subtasks and reports state/summary.
New Task Type Checklist
- Define/extend task type and step enums in
pkg/dxf/framework/proto/first.- Keep step values backward-compatible (
step.goexplicitly forbids changing
existing constant values).
- Keep step values backward-compatible (
- Implement scheduler extension (
scheduler.Extension) and task executor extension
(taskexecutor.Extension) for the new task type. - Register all required factories:
- owner side:
scheduler.RegisterSchedulerFactory(...) - node side:
taskexecutor.RegisterTaskType(...) - optional cleanup:
scheduler.RegisterCleanerFactory(...)
- owner side:
- Keep
GetNextStepdeterministic from task base state (avoid relying on mutable
task meta there), and keep subtask generation stable when using batch switch APIs.
Invariants and Pitfalls
- Task rank drives both scheduling and preemption: higher rank means smaller
(priority, create_time, id)tuple. RequiredSlotsis the reservation baseline, while runtime execution may use a
lower slot count throughExtraParams.MaxRuntimeSlots+TargetSteps.- Empty target scope prefers
"background"nodes when present; otherwise it falls
back to empty-scope nodes. - Scheduler manager processes normal runnable states with slot allocation, but at
MaxConcurrentTasklimit it switches to no-resource states only (for fast handling
of pausing/cancelling/reverting/modifying tasks). - Task executor can exit after a period with no runnable subtasks (about 10s),
then be restarted by manager loops; this is expected behavior for resource reuse.
Debug Focus Areas
- Task state transitions and scheduling-state handlers:
pkg/dxf/framework/scheduler/state_transform.goandpkg/dxf/framework/scheduler/scheduler.go. - Slot reservation / preemption decisions:
pkg/dxf/framework/scheduler/slots.go,pkg/dxf/framework/taskexecutor/slot.go, andpkg/dxf/framework/taskexecutor/manager.go. - Keyspace/scope routing (classic vs nextgen service behavior):
pkg/domain/domain.go,pkg/dxf/framework/handle/handle.go, andpkg/dxf/framework/storage/task_table.go.
Problem-Oriented Read Order
"How does task state/lifecycle work?"
framework/proto->framework/storage->framework/scheduler->framework/taskexecutor.
"Where is submit/pause/resume/cancel implemented?"
framework/handlefirst, then follow call sites inpkg/dxf/importinto/
andpkg/ddl/.
"How does IMPORT INTO use DXF?"
pkg/dxf/importinto/first, thenpkg/executor/import_into.goandpkg/executor/importer/.
"How does DDL backfill use DXF?"
pkg/ddl/index.go->pkg/ddl/backfilling_dist_scheduler.go->pkg/ddl/backfilling_dist_executor.go, and cross-checkdocs/agents/ddl/README.md.
Navigation Queries
- Find DXF registration points:
rg --line-number --glob '*.go' 'RegisterSchedulerFactory|RegisterCleanerFactory|RegisterTaskType' pkg/session pkg/ddl pkg/dxf - Find framework control APIs and main call sites:
rg --line-number --glob '*.go' 'SubmitTask|WaitTask|CancelTask|PauseTask|ResumeTask|ModifyTaskByID' pkg/dxf pkg/executor pkg/ddl - Find IMPORT INTO integration points:
rg --line-number --glob '*.go' 'proto.ImportInto|importinto' pkg/dxf pkg/executor pkg/session - Find DDL distributed backfill integration points:
rg --line-number --glob '*.go' 'proto.Backfill|backfill' pkg/ddl
Test Surfaces
- Framework tests:
pkg/dxf/framework/integrationtests/and sibling framework
package tests. - IMPORT INTO DXF tests:
pkg/dxf/importinto/. - DDL backfill DXF tests:
pkg/ddl/backfilling_*_test.goand related
distributed-backfill tests underpkg/ddl/.
Agents Import Into README (`docs/agents/import-into/README.md`)
IMPORT INTO Notes
This note is a navigation and troubleshooting map for IMPORT INTO in DXF.
It focuses on conflict-resolution and cleanup behavior that is easy to miss
when only reading one package at a time.
Scope
- IMPORT INTO job/task lifecycle (
mysql.tidb_import_jobs+ DXF task). - Global-sort conflict detection, conflict collection, and conflict resolution.
- Post-process checksum and cleanup behavior.
High-Signal Entry Files
- Job submit/runtime bridge:
pkg/executor/import_into.gopkg/dxf/importinto/taskinfo/runtime_info.go
- Scheduler and step transitions:
pkg/dxf/importinto/scheduler.gopkg/dxf/framework/proto/step.go
- Step planning and conflict-spec generation:
pkg/dxf/importinto/planner.go
- Step executors:
pkg/dxf/importinto/task_executor.gopkg/dxf/importinto/collect_conflicts.gopkg/dxf/importinto/conflict_resolution.gopkg/dxf/importinto/subtask_executor.go
- Cleanup and metadata redaction:
pkg/dxf/importinto/clean_up.go
- Conflict-KV semantics and examples:
pkg/dxf/importinto/conflictedkv/doc.go
Step Flow Cheatsheet
- Local sort path:
StepInit->ImportStepImport->ImportStepPostProcess->StepDone
- Global sort path:
StepInit->ImportStepEncodeAndSort->ImportStepMergeSort(optional
subtasks) ->ImportStepWriteAndIngest->ImportStepCollectConflicts
(optional subtasks) ->ImportStepConflictResolution(optional subtasks) ->ImportStepPostProcess->StepDone
Conflict-Resolution Troubleshooting
"Why are collect-conflicts / conflict-resolution steps skipped?"
generateCollectConflictsSpecsandgenerateConflictResolutionSpecsreturn
no specs whencollectConflictInfosfinds no recorded conflicts.- Check whether previous step metas have
RecordedConflictKVCount > 0in:ImportStepMetaMergeSortStepMetaWriteIngestStepMeta
"Why is checksum verification skipped in post-process?"
- In collect-conflicts,
TooManyConflictsFromIndexis set when the bounded
in-memory row-key set exceeds its limit. - Limit source: collect-conflicts uses about half of step memory for row-key
tracking (sizeLimitOfRowKeysFromIndex = resource mem / 2). - Post-process checks this flag and skips final checksum verification.
- In collect-conflicts,
"Where are conflicted rows persisted?"
- Collect-conflicts writes conflict-row files under:
conflicted-rows/<task-id>/<subtask-id>- - The prefix is intentionally outside
<task-id>/cleanup path, so users can
inspect conflict rows after task cleanup.
- Collect-conflicts writes conflict-row files under:
"Where is each part executed?"
- Conflict row/checksum collection:
collect_conflicts.go - Conflict KV deletion:
conflict_resolution.go - Core conflict KV semantics:
conflictedkv/doc.go
- Conflict row/checksum collection:
Cleanup Troubleshooting
- Cleanup entrypoint is
ImportCleaner.Cleaninclean_up.go. - Classic kernel behavior:
- Attempts to switch table mode back to normal.
- Ignores
infoschema.ErrTableNotExistsduring cleanup.
- Database read-only mode is checked at IMPORT INTO statement entry. Enabling
read-only does not fence or cancel a physical import already in progress;
ingestion may keep writing after the read-only transition succeeds. Classic
FROM SELECT does not register a separate read-only draining transaction.
Classic completion and cancellation can still reset table mode to Normal in a
read-only database, and explicit replica-writer authorization is propagated to
the internal mode claim. - Global-sort artifact cleanup:
- Deletes task-scoped files via
globalsort.CleanUpFiles(..., <task-id>). - Does not delete
conflicted-rows/...files by design.
- Deletes task-scoped files via
- Nextgen metering:
- On succeed state, cleanup tries to send metering data based on post-process
subtask meta.
- On succeed state, cleanup tries to send metering data based on post-process
- Metadata redaction:
- Cleanup path/redaction clears sensitive task fields before task transfer.
Cross-Keyspace Job Status Notes
- Scheduler updates import job state through task-keyspace task manager
(getTaskMgrForAccessingImportJob). - On user keyspace tasks, cross-keyspace session-pool retrieval failures are
wrapped aserrGetCrossKSSessionPool, and treated as retryable.
Navigation Queries
- Find step transitions and job-state updates:
rg --line-number --glob '*.go' 'GetNextStep|startJob|job2Step|finishJob|failJob|cancelJob' pkg/dxf/importinto - Find conflict planning and skip conditions:
rg --line-number --glob '*.go' 'generateCollectConflictsSpecs|generateConflictResolutionSpecs|RecordedConflictKVCount|collectConflictInfos' pkg/dxf/importinto - Find conflict executor paths:
rg --line-number --glob '*.go' 'CollectConflictsStepMeta|ConflictResolutionStepMeta|TooManyConflictsFromIndex|conflicted-rows' pkg/dxf/importinto - Find cleanup behavior:
rg --line-number --glob '*.go' 'ImportCleaner|CleanUpFiles|sendMeterOnClean|redactSensitiveInfo' pkg/dxf/importinto pkg/dxf/framework/scheduler
Test Surfaces
pkg/dxf/importinto/conflict_resolution_test.gopkg/dxf/importinto/collect_conflicts_test.gopkg/dxf/importinto/task_executor_test.gopkg/dxf/importinto/scheduler_test.gopkg/dxf/importinto/scheduler_testkit_test.go
Pkg Parser Docs Quickstart (`pkg/parser/docs/quickstart.md`)
Quickstart
This parser is highly compatible with MySQL syntax. You can use it as a library, parse a text SQL into an AST tree, and traverse the AST nodes.
In this example, you will build a project, which can extract all the column names from a text SQL.
Prerequisites
- Golang version 1.13 or above. You can follow the instructions in the official installation page (check it by
go version)
Create a Project
mkdir colx
cd colx
go mod init colx
touch main.goImport Dependencies
First, you need to use go get to fetch the dependencies through git hash. The git hashes are available in release page. Take v7.5.0 as an example:
go get -v github.com/pingcap/tidb/pkg/parser@069631eNOTE
The parser was merged into TiDB repo since v5.3.0. So you can only choose version v5.3.0 or higher in this TiDB repo.
You may want to use advanced API on expressions (a kind of AST node), such as numbers, string literals, booleans, nulls, etc. It is strongly recommended using the
typespackage in TiDB repo with the following command:bashgo get -v github.com/pingcap/tidb/pkg/types/parser_driver@069631eand import it in your golang source code:
goimport _ "github.com/pingcap/tidb/pkg/types/parser_driver"
Your directory should contain the following three files:
.
├── go.mod
├── go.sum
└── main.goNow, open main.go with your favorite editor, and start coding!
Parse SQL text
To convert a SQL text to an AST tree, you need to:
- Use the
parser.New()function to instantiate a parser, and - Invoke the method
Parse(sql, charset, collation)on the parser.
package main
import (
"fmt"
"github.com/pingcap/tidb/pkg/parser"
"github.com/pingcap/tidb/pkg/parser/ast"
_ "github.com/pingcap/tidb/pkg/parser/test_driver"
)
func parse(sql string) (*ast.StmtNode, error) {
p := parser.New()
stmtNodes, _, err := p.ParseSQL(sql)
if err != nil {
return nil, err
}
return &stmtNodes[0], nil
}
func main() {
astNode, err := parse("SELECT a, b FROM t")
if err != nil {
fmt.Printf("parse error: %v\n", err.Error())
return
}
fmt.Printf("%v\n", *astNode)
}Test the parser by running the following command:
go run main.goIf the parser runs properly, you should get a result like this:
&{{{{SELECT a, b FROM t}}} {[]} 0xc0000a1980 false 0xc00000e7a0 <nil> 0xc0000a19b0 <nil> <nil> [] <nil> <nil> none [] false false 0 <nil>}NOTE
Here are a few things you might want to know:
To use a parser, a
parser_driveris required. It decides how to parse the basic data types in SQL.You can use
github.com/pingcap/tidb/pkg/parser/test_driveras theparser_driverfor test. Again, if you need advanced features, please use theparser_driverin TiDB (rungo get -v github.com/pingcap/tidb/types/parser_driver@069631eand import it).The instantiated parser object is not goroutine safe and not lightweight. It is better to keep it in a single goroutine, and reuse it if possible.
Warning: the
parser.resultobject is being reused without being properly reset or copied. This can cause unexpected behavior or errors if the object is used for multiple parsing operations or concurrently in multiple goroutines. To avoid these issues, make a copy ofparser.resultobject before callingparser.Parse()again or before using it in another goroutine, or create a newparserobject altogether for each new parsing operation.
Traverse AST Nodes
Now you get the AST tree root of a SQL statement. It is time to extract the column names by traverse.
Parser implements the interface ast.Node for each kind of AST node, such as SelectStmt, TableName, ColumnName, etc. ast.Node provides a method Accept(v Visitor) (node Node, ok bool) to allow any struct that has implemented ast.Visitor to traverse itself.
ast.Visitor is defined as follows:
type Visitor interface {
Enter(n Node) (node Node, skipChildren bool)
Leave(n Node) (node Node, ok bool)
}Now you can define your own visitor, colX(columnExtractor):
type colX struct{
colNames []string
}
func (v *colX) Enter(in ast.Node) (ast.Node, bool) {
if name, ok := in.(*ast.ColumnName); ok {
v.colNames = append(v.colNames, name.Name.O)
}
return in, false
}
func (v *colX) Leave(in ast.Node) (ast.Node, bool) {
return in, true
}Finally, wrap colX in a simple function:
func extract(rootNode *ast.StmtNode) []string {
v := &colX{}
(*rootNode).Accept(v)
return v.colNames
}And slightly modify the main function:
func main() {
if len(os.Args) != 2 {
fmt.Println("usage: colx 'SQL statement'")
return
}
sql := os.Args[1]
astNode, err := parse(sql)
if err != nil {
fmt.Printf("parse error: %v\n", err.Error())
return
}
fmt.Printf("%v\n", extract(astNode))
}Test your program:
go run main.go 'select a, b from t'[a b]You can also try a different SQL statement as an input. For example:
$ go run main.go 'SELECT a, b FROM t GROUP BY (a, b) HAVING a > c ORDER BY b'
[a b a b a c b]
$ go run main.go 'SELECT a, b FROM t/invalid_str'
parse error: line 1 column 19 near "/invalid_str"Enjoy!
Tidb Http Api (`docs/tidb_http_api.md`)
TiDB HTTP API
TiDBIP is the ip of the TiDB server. 10080 is the default status port, and you can edit it in tidb.toml when starting the TiDB server.
Diagnostic mode availability
When TiDB starts with --diagnostic-mode and status.report-status is enabled,
the status listener exposes only the following GET endpoints:
| Endpoint | Purpose and parameters | Example |
|---|---|---|
/status |
Local readiness, connection count, version and statistics initialization status. No parameters. | curl http://127.0.0.1:10080/status |
/metrics |
Local Prometheus metrics. No parameters. | curl http://127.0.0.1:10080/metrics |
/debug/pprof/ |
Index of available local runtime profiles. | curl http://127.0.0.1:10080/debug/pprof/ |
/debug/pprof/cmdline |
Process command line. No parameters. | curl http://127.0.0.1:10080/debug/pprof/cmdline |
/debug/pprof/profile |
CPU profile; optional seconds controls collection duration. |
curl -o cpu.pprof 'http://127.0.0.1:10080/debug/pprof/profile?seconds=5' |
/debug/pprof/symbol |
Resolve program counters supplied in the query string. GET only. | curl http://127.0.0.1:10080/debug/pprof/symbol |
/debug/pprof/trace |
Runtime trace; optional seconds controls collection duration. |
curl -o trace.out 'http://127.0.0.1:10080/debug/pprof/trace?seconds=1' |
/debug/pprof/{profile} |
Named runtime profile, such as goroutine or heap; optional debug selects text output. |
curl 'http://127.0.0.1:10080/debug/pprof/goroutine?debug=1' |
Other management endpoints described below, including /info and /settings,
are unavailable in this mode and return HTTP 404. The diagnostic listener does
not serve gRPC/MPP services. Requests using unsupported methods are rejected.
Cluster TLS and certificate verification settings also apply to this listener;
TLS advertises HTTP/1.1 only. Disabling status.report-status disables the
listener entirely. Normal-mode HTTP API availability is unchanged.
HTTP endpoints
The normal status listener routes HTTP/1.1 requests, including PATCH, to the HTTP
API handlers. Each endpoint determines which methods and parameters it accepts.
Get the current status of TiDB, including the connections, version, and
git_hash.shellcurl http://{TiDBIP}:10080/statusshell$curl http://127.0.0.1:10080/status { "connections": 0, "git_hash": "f572e33854e1c0f942f031e9656d0004f99995c6", "version": "5.7.25-TiDB-v2.1.0-rc.3-355-gf572e3385-dirty", "status":{ "init_stats_percentage":100 } }Get all metrics of TiDB
shellcurl http://{TiDBIP}:10080/metricsIn Starter deployment mode, every exported metric includes a
keyspace_idlabel, including Go runtime and process metrics. Starter obtains the ID from the initialized storage codec; metric registration does not query PD for the ID. Its value is an empty string until storage initialization provides an ID, or when no keyspace is configured. Existing per-metric keyspace IDs are preserved. Starter metrics sent to Pushgateway include the same label, although pushes before storage initialization use an empty value. Classic, Premium, and Premium Reserved retain their existing metric labels. Standalone BR is outside this Starter-specific change: it retains its existing constant labels, and its Go/process and other collectors are not automatically givenkeyspace_id.Get the metadata of all regions
If PD cannot find a requested region, TiDB returns an error containing its decimal ID, such as
region not found for regionID 123.shellcurl http://{TiDBIP}:10080/regions/metashell$curl http://127.0.0.1:10080/regions/meta [ { "leader": { "id": 5, "store_id": 1 }, "peers": [ { "id": 5, "store_id": 1 } ], "region_epoch": { "conf_ver": 1, "version": 2 }, "region_id": 4 } ]Get the table/index of hot regions
shellcurl http://{TiDBIP}:10080/regions/hotshell$curl http://127.0.0.1:10080/regions/hot { "read": [ ], "write": [ { "db_name": "sbtest1", "table_name": "sbtest13", "index_name": "", "flow_bytes": 220718, "max_hot_degree": 12, "region_count": 1 } ] }Get the information of a specific region by ID
shellcurl http://{TiDBIP}:10080/regions/{regionID}shell$curl http://127.0.0.1:10080/regions/4001 { "end_key": "dIAAAAAAAAEk", "frames": [ { "db_name": "test", "is_record": true, "table_id": 286, "table_name": "t1" } ], "region_id": 4001, "start_key": "dIAAAAAAAAEe" }Get regions Information from db.table
shellcurl http://{TiDBIP}:10080/tables/{db}/{table}/regionsshell$curl http://127.0.0.1:10080/tables/test/t1/regions { "id": 286, "indices": [], "name": "t1", "record_regions": [ { "leader": { "id": 4002, "store_id": 1 }, "peers": [ { "id": 4002, "store_id": 1 } ], "region_epoch": { "conf_ver": 1, "version": 83 }, "region_id": 4001 } ] }Get schema Information about all db
shellcurl http://{TiDBIP}:10080/schemashell$curl http://127.0.0.1:10080/schema [ { "charset": "utf8mb4", "collate": "utf8mb4_bin", "db_name": { "L": "test", "O": "test" }, "id": 266, "state": 5 }, . . . ]Get schema Information about db
shellcurl http://{TiDBIP}:10080/schema/{db}shellcurl http://{TiDBIP}:10080/schema/{db}?id_name_only=true [ { "id": 119, "name": { "O": "t1", "L": "t1" } }, { "id": 125, "name": { "O": "t2", "L": "t2" } } ]Get schema Information about db.table, and you can get schema info by tableID (tableID is the unique identifier of table in TiDB)
shellcurl http://{TiDBIP}:10080/schema/{db}/{table} curl http://{TiDBIP}:10080/schema?table_id={tableID} curl http://{TiDBIP}:10080/schema?table_ids={tableID,...}Get database information, table information and tidb info schema version by tableID.
shellcurl http://{TiDBIP}:10080/db-table/{tableID}Get MVCC Information of the key with a specified handle ID
shellcurl http://{TiDBIP}:10080/mvcc/key/{db}/{table}/{handle}shell$curl http://127.0.0.1:10080/mvcc/key/test/t/1 { "key": "74800000000000006E5F728000000000000001", "region_id": 4, "value": { "info": { "writes": [ { "start_ts": 448662063415296001, "commit_ts": 448662063415296003, "short_value": "gAABAAAAAQEAAQ==" } ] } } }If the handle is clustered, specify the primary key column values in the query string
shell$curl "http://{TiDBIP}:10080/mvcc/key/{db}/{table}?${c1}={v1}&${c2}=${v2}"shell$curl "http://127.0.0.1:10080/mvcc/key/test/t?a=aaa&b=2020-01-01" { "key": "7480000000000000365F72016161610000000000FA0419A5420000000000", "region_id": 52, "value": { "info": { "writes": [ { "type": 1, "start_ts": 423158426542538752, "commit_ts": 423158426543587328 }, { "start_ts": 423158426542538752, "commit_ts": 423158426543587328, "short_value": "gAACAAAAAQMDAAQAYWFhZA==" } ], "values": [ { "start_ts": 423158426542538752, "value": "gAACAAAAAQMDAAQAYWFhZA==" } ] } } }Hint: The meaning of the MVCC operation type:
protobufenum Op { Put = 0; Del = 1; Lock = 2; Rollback = 3; // insert operation has a constraint that key should not exist before. Insert = 4; PessimisticLock = 5; CheckNotExists = 6; }Hint: On a partitioned table, use the
table(partition)pattern as the table name,t1(p1)for example:shell$curl http://127.0.0.1:10080/mvcc/key/test/t1(p1)/1Hint: The method to convert the Hex format key returned by TiDB API into the format recognized by tikv-ctl.
Step 1: Get the hex format of the key you need. For example you could find the key by the following TiDB API.
shell$curl http://127.0.0.1:10080/mvcc/key/test/t1/1 { "key": "7480000000000008C65F728000000000000001", "region_id": 10, "value": { "info": { "writes": [ { "start_ts": 445971968923271174, "commit_ts": 445971968923271175, "short_value": "gAACAAAAAgMIAAkAc2hpcmx5YTQi" }, { "start_ts": 445971959499980803, "commit_ts": 445971959499980804, "short_value": "gAACAAAAAgMIAAkAc2hpcmx5YTQL" } ] } } }Step 2: Convert the key from hex format to escaped format with tikv-ctl
shell./tikv-ctl --to-escaped '7480000000000008C65F728000000000000001' t\200\000\000\000\000\000\010\306_r\200\000\000\000\000\000\000\001Step 3: Encode the key to make it memcomparable in tikv with tikv-ctl
shell./tikv-ctl --encode 't\200\000\000\000\000\000\010\306_r\200\000\000\000\000\000\000\001' 7480000000000008FFC65F728000000000FF0000010000000000FAStep 4: Convert the key from hex format to escaped format again since most
tikv-ctlcommands only accept keys in escaped format while the--encodecommand outputs the key in hex format.shell./tikv-ctl --to-escaped '7480000000000008FFC65F728000000000FF0000010000000000FA' t\200\000\000\000\000\000\010\377\306_r\200\000\000\000\000\377\000\000\001\000\000\000\000\000\372Step 5: Add a prefix "z" to the key. Then the key can be recognized by tikv-ctl. For example, use the following command to scan from tikv.
text
/* Detailed source-code truncated for AI context efficiency. */
12. Get MVCC Information of the first key in the table with a specified start ts
```shell
curl http://{TiDBIP}:10080/mvcc/txn/{startTS}/{db}/{table}
```
```shell
$curl http://127.0.0.1:10080/mvcc/txn/405179368526053377/test/t1
{
"info": {
"writes": [
{
"commit_ts": 405179368526053380,
"short_value": "CAICAkE=",
"start_ts": 405179368526053377
}
]
},
"key": "dIAAAAAAAAEzX3KAAAAAAAAAAQ=="
}
```
13. Get MVCC Information by a hex value
```shell
curl http://{TiDBIP}:10080/mvcc/hex/{hexKey}
```
14. Get MVCC Information of a specified index key, argument example: column_name_1=column_value_1&column_name_2=column_value2...
```shell
curl "http://{TiDBIP}:10080/mvcc/index/{db}/{table}/{index}/{handle}?${c1}={v1}&${c2}=${v2}"
```
*Hint: For the index column which column type is timezone dependent, e.g. `timestamp`, convert its value to UTC
timezone.*
```shell
$curl "http://127.0.0.1:10080/mvcc/index/test/t1/idx/1?a=A"
{
"info": {
"writes": [
{
"commit_ts": 405179523374252037,
"short_value": "MA==",
"start_ts": 405179523374252036
}
]
}
}
```
*Hint: On a partitioned table, use the `table(partition)` pattern as the table name, `t1(p1)` for example:*
```shell
$curl "http://127.0.0.1:10080/mvcc/index/test/t1(p1)/idx/1?a=A"
```
If the handle is clustered, also specify the primary key column values in the query string
```shell
$curl "http://{TiDBIP}:10080/mvcc/index/{db}/{table}/{index}?${c1}={v1}&${c2}=${v2}"
```
```shell
$curl "http://127.0.0.1:10080/mvcc/index/test/t/idx?a=1.1&b=111&c=1"
{
"key": "74800000000000003B5F69800000000000000203800000000000000105BFF199999999999A013131310000000000FA",
"region_id": 59,
"value": {
"info": {
"writes": [
{
"start_ts": 424752858505150464,
"commit_ts": 424752858506461184,
"short_value": "AH0B"
}
],
"values": [
{
"start_ts": 424752858505150464,
"value": "AH0B"
}
]
}
}
}
15. Scatter regions of the specified table, add a `scatter-range` scheduler for the PD and the range is same as the table range.
```shell
curl http://{TiDBIP}:10080/tables/{db}/{table}/scatter
```
*Hint: On a partitioned table, use the `table(partition)` pattern as the table name, `test(p1)` for example.*
**Note**: The `scatter-range` scheduler may conflict with the global scheduler, do not use it for long periods on the larger table.
16. Stop scatter the regions, disable the `scatter-range` scheduler for the specified table.
```shell
curl http://{TiDBIP}:10080/tables/{db}/{table}/stop-scatter
```
*Hint: On a partitioned table, use the `table(partition)` pattern as the table name, `test(p1)` for example.*
17. Get TiDB server settings
```shell
curl http://{TiDBIP}:10080/settings
```
18. Get TiDB server information.
```shell
curl http://{TiDBIP}:10080/info
```
```shell
$curl http://127.0.0.1:10080/info
{
"ddl_id": "f7e73ed5-63b4-4cb4-ba7c-42b32dc74e77",
"git_hash": "f572e33854e1c0f942f031e9656d0004f99995c6",
"ip": "",
"is_owner": true,
"lease": "45s",
"listening_port": 4000,
"status_port": 10080,
"version": "5.7.25-TiDB-v2.1.0-rc.3-355-gf572e3385-dirty"
}
```
19. Get TiDB cluster all servers information.
```shell
curl http://{TiDBIP}:10080/info/all
```
```shell
$curl http://127.0.0.1:10080/info/all
{
"servers_num": 2,
"owner_id": "29a65ec0-d931-4f9e-a212-338eaeffab96",
"is_all_server_version_consistent": true,
"all_servers_info": {
"29a65ec0-d931-4f9e-a212-338eaeffab96": {
"version": "5.7.25-TiDB-v4.0.0-alpha-669-g8f2a09a52-dirty",
"git_hash": "8f2a09a52fdcaf9d9bfd775d2c6023f363dc121e",
"ddl_id": "29a65ec0-d931-4f9e-a212-338eaeffab96",
"ip": "",
"listening_port": 4000,
"status_port": 10080,
"lease": "45s",
"binlog_status": "Off"
},
"cd13c9eb-c3ee-4887-af9b-e64f3162d92c": {
"version": "5.7.25-TiDB-v4.0.0-alpha-669-g8f2a09a52-dirty",
"git_hash": "8f2a09a52fdcaf9d9bfd775d2c6023f363dc121e",
"ddl_id": "cd13c9eb-c3ee-4887-af9b-e64f3162d92c",
"ip": "",
"listening_port": 4001,
"status_port": 10081,
"lease": "45s",
"binlog_status": "Off"
}
}
}
```
20. Enable/Disable TiDB server general log
```shell
curl -X POST -d "tidb_general_log=1" http://{TiDBIP}:10080/settings
curl -X POST -d "tidb_general_log=0" http://{TiDBIP}:10080/settings
```
21. Change TiDB server log level
```shell
curl -X POST -d "log_level=debug" http://{TiDBIP}:10080/settings
curl -X POST -d "log_level=info" http://{TiDBIP}:10080/settings
```
22. Change TiDB DDL slow log threshold
The unit is millisecond.
```shell
curl -X POST -d "ddl_slow_threshold=300" http://{TiDBIP}:10080/settings
```
23. Get the column value by an encoded row and some information that can be obtained from a column of the table schema information.
Argument example: rowBin=base64_encoded_row_value
```shell
curl http://{TiDBIP}:10080/tables/{colID}/{colFlag}/{colLen}?rowBin={val}
```
*Hint: For the column which field type is timezone dependent, e.g. `timestamp`, convert its value to UTC timezone.*
24. Resign the ddl owner, let tidb start a new ddl owner election.
```shell
curl -X POST http://{TiDBIP}:10080/ddl/owner/resign
```
**Note**: If you request a TiDB that is not ddl owner, the response will be `This node is not a ddl owner, can't be resigned.`
25. Get the TiDB DDL job history information.
```shell
curl http://{TiDBIP}:10080/ddl/history
```
**Note**: When the DDL history is very very long, system table may containing too many jobs. This interface will get a maximum of 2048 history ddl jobs by default. If you want get more jobs, consider adding `start_job_id` and `limit`.
26. Get count {number} TiDB DDL job history information.
```shell
curl http://{TiDBIP}:10080/ddl/history?limit={number}
```
27. Get count {number} TiDB DDL job history information, start with job {id}
```shell
curl "http://{TIDBIP}:10080/ddl/history?start_job_id={id}&limit={number}"
```
28. Download TiDB debug info
```shell
curl http://{TiDBIP}:10080/debug/zip?seconds=60 --output debug.zip
```
zip file will include:
- Go heap pprof(after GC)
- Go cpu pprof(10s)
- Go mutex pprof
- Full goroutine
- TiDB config and version
Param:
- seconds: profile time(s), default is 10s.
29. Get statistics data of specified table.
```shell
curl http://{TiDBIP}:10080/stats/dump/{db}/{table}
```
30. Download a plan replayer file.
```shell
curl http://{TiDBIP}:10080/plan_replayer/dump/{filename} --output plan_replayer.zip
```
Method: `GET`. `{filename}` is the file token that `PLAN REPLAYER DUMP` returns, or a `token` value in `mysql.plan_replayer_status`.
The response is the ZIP file. If this TiDB instance does not have the file, it requests the file from the other TiDB instances. If no instance has the file, the API returns HTTP 404.
TiDB returns the file as it is stored and does not add statistics to it. A `capture_replayer_*` file from an older TiDB version can have no statistics, if `tidb_enable_historical_stats_for_capture` was `ON` when TiDB captured it. TiDB writes a warning to its log for each request for a `capture_replayer_*` file.
31. Resume the binlog writing when Pump is recovered.
```shell
curl http://{TiDBIP}:10080/binlog/recover
```
Return value:
- timeout, return status code: 400, message: `timeout`
- If it returns normally, status code: 200, message example:
```text
{
"Skipped": false,
"SkippedCommitterCounter": 0
}
```
`Skipped`: false indicates that the current binlog is not in the skipped state, otherwise, it is in the skipped state
`SkippedCommitterCounter`: Represents how many transactions are currently being committed in the skipped state. By default, the API will return after waiting until all skipped-binlog transactions are committed. If this value is greater than 0, it means that you need to wait until them are committed .
Param:
- op=nowait: return after binlog status is recoverd, do not wait until the skipped-binlog transactions are committed.
- op=reset: reset `SkippedCommitterCounter` to 0 to avoid the problem that `SkippedCommitterCounter` is not cleared due to some unusual cases.
- op=status: Get the current status of binlog recovery.
32. Enable/disable async commit feature
```shell
curl -X POST -d "tidb_enable_async_commit=1" http://{TiDBIP}:10080/settings
curl -X POST -d "tidb_enable_async_commit=0" http://{TiDBIP}:10080/settings
```
33. Enable/disable one-phase commit feature
```shell
curl -X POST -d "tidb_enable_1pc=1" http://{TiDBIP}:10080/settings
curl -X POST -d "tidb_enable_1pc=0" http://{TiDBIP}:10080/settings
```
34. Enable/disable the mutation checker
```shell
curl -X POST -d "tidb_enable_mutation_checker=1" http://{TiDBIP}:10080/settings
curl -X POST -d "tidb_enable_mutation_checker=0" http://{TiDBIP}:10080/settings
```
35. Get/Set the size of the Ballast Object
```shell
# get current size of the ballast object
curl -v http://{TiDBIP}:10080/debug/ballast-object-sz
# reset the size of the ballast object (2GB in this example)
curl -v -X POST -d "2147483648" http://{TiDBIP}:10080/debug/ballast-object-sz
```
36. Set deadlock history table capacity
```shell
curl -X POST -d "deadlock_history_capacity={number}" http://{TiDBIP}:10080/settings
```
37. Set whether deadlock history (`DEADLOCKS`) collect retryable deadlocks
```shell
curl -X POST -d "deadlock_history_collect_retryable={bool_val}" http://{TiDBIP}:10080/settings
```
38. Set transaction_id to digest mapping minimum duration threshold, only transactions which last longer than this threshold will be collected into `TRX_SUMMARY`.
```shell
curl -X POST -d "transaction_id_digest_min_duration={number}" http://{TiDBIP}:10080/settings
```
Unit of duration here is ms.
39. Set transaction summary table (`TRX_SUMMARY`) capacity
```shell
curl -X POST -d "transaction_summary_capacity={number}" http://{TiDBIP}:10080/settings
```
40. The commands are used to handle smooth upgrade mode(refer to the [TiDB Smooth Upgrade](https://github.com/pingcap/docs/blob/4aa0b1d5078617cc06bd1957c5c93e86efb4668d/smooth-upgrade-tidb.md) for details) operations. We can send these upgrade operations to the cluster. The operations here include `start`, `finish` and `show`.
```shell
curl -X POST http://{TiDBIP}:10080/upgrade/{op}
```
```shell
$curl -X POST http://{TiDBIP}:10080/upgrade/start
"success!"
```
41. Set split & scatter regions concurrency before ingest, and ingest request concurrency. Value ranges:
- `max-batch-split-ranges`: `[1, 9223372036854775807]`, default `2048`
- `max-split-ranges-per-sec`: `[0, 9223372036854775807]`, default `0` (no limit)
- `max-ingest-per-sec`: `[0, 9223372036854775807]`, default `0` (no limit)
- `max-ingest-inflight`: `[0, 9223372036854775807]`, default `0` (no limit)
```shell
curl http://{TiDBIP}:10080/ingest/max-batch-split-ranges
curl http://{TiDBIP}:10080/ingest/max-split-ranges-per-sec
curl http://{TiDBIP}:10080/ingest/max-ingest-per-sec
curl http://{TiDBIP}:10080/ingest/max-ingest-inflight
```
```shell
curl http://{TiDBIP}:10080/ingest/max-batch-split-ranges -X POST -d "{\"value\": 1024}"
curl http://{TiDBIP}:10080/ingest/max-split-ranges-per-sec -X POST -d "{\"value\": 16}"
curl http://{TiDBIP}:10080/ingest/max-ingest-per-sec -X POST -d "{\"value\": 0.5}"
curl http://{TiDBIP}:10080/ingest/max-ingest-inflight -X POST -d "{\"value\": 2}"
```
42. Get TiDB transaction GC states:
```shell
curl http://{TiDBIP}:10080/txn-gc-states
```
43. Get the live TiFlash replica summary for this TiDB.
Method: `GET` only. Counts **logical** tables that currently have `TiFlashReplica` metadata on this TiDB's InfoSchema. Dropped or truncated leftovers are not included.
Optional query `reload` (default `false` when omitted): `false` uses the in-memory InfoSchema (cheap default). `true` will sync the schema first to reduce lease-lag under-counts TiFlash replica on non-DDL-owner nodes; invalid values return HTTP 400. Reload can be slow on a large schema. This is a **best-effort** snapshot for operators. Even with `reload=true`, a concurrent `SET TIFLASH REPLICA` after the read can invalidate the `table_count` and `can_disable`.
Next-gen: the count is for the keyspace bound to this TiDB. Query a user-keyspace instance to inspect that logical cluster; a SYSTEM instance only reports SYSTEM.
```shell
curl http://{TiDBIP}:10080/tiflash/replica
curl 'http://{TiDBIP}:10080/tiflash/replica?reload=true'
```
Example response:
```json
{
"keyspace": "ks1",
"keyspace_id": 123,
"tidb_columnar_storage_enabled": "ON",
"columnar_store_type": "columnar",
"can_disable": false,
"table_count": 2,
"reloaded": false
}
```
/* Detailed source-code truncated for AI context efficiency. */
```shell
curl --cacert ca.pem --cert client.pem --key client-key.pem \
-X POST "https://{TiDBIP}:10080/internal/v1/users" \
-H 'Content-Type: application/json' \
-d '{"username":"tmp_user","password":"Passw0rd!"}'
```
```json
{
"status": "success",
"username": "tmp_user",
"created_at": "2026-12-02T20:00:00Z"
}
```
1. Reset the password of a user
`POST /internal/v1/users/{username}/reset-password` with body
`{"new_password": "..."}`. The password is set to `new_password`. Returns
HTTP 200, HTTP 400 if `new_password` is missing, or HTTP 404 if the user does
not exist.
```shell
curl --cacert ca.pem --cert client.pem --key client-key.pem \
-X POST "https://{TiDBIP}:10080/internal/v1/users/tmp_user/reset-password" \
-H 'Content-Type: application/json' \
-d '{"new_password":"N3w-Passw0rd!"}'
```
```json
{
"status": "success",
"message": "Password reset done."
}
```
1. Grant roles to a user
`POST /internal/v1/users/{username}/roles` with body `{"roles": [...]}` or
`{"role": "..."}`. A role is `name` (host `%`) or `name@host`. Returns HTTP
200, HTTP 400 if the role list is empty or a role is malformed, or HTTP 404
if the user does not exist.
Roles are granted one by one, and each grant emits its own audit event. The
request is not atomic: if a grant fails (for example, the role does not
exist), the API returns HTTP 500 and the roles granted before it remain
granted.
```shell
curl --cacert ca.pem --cert client.pem --key client-key.pem \
-X POST "https://{TiDBIP}:10080/internal/v1/users/tmp_user/roles" \
-H 'Content-Type: application/json' \
-d '{"roles":["diagnoser_role"]}'
```
```json
{
"status": "success",
"message": "Roles granted to user."
}
```
1. Delete a user
`DELETE /internal/v1/users/{username}`. Returns HTTP 204, also when the user
does not exist. Returns HTTP 409 if the whole cluster has at most one account
that is not locked (this check applies even when the account being deleted
is itself locked), or if another delete request holds the delete lock.
```shell
curl --cacert ca.pem --cert client.pem --key client-key.pem \
-X DELETE "https://{TiDBIP}:10080/internal/v1/users/tmp_user"
```
## Standby activation
`POST /tidb-pool/activate` activates a TiDB process running in standby mode. Send the request to its status port. The response waits until the server is ready to accept connections.
```shell
curl -X POST "http://{TiDBIP}:10080/tidb-pool/activate" \
-H 'Content-Type: application/json' \
-d '{"keyspace_name":"ks"}'keyspace_name is required. Starter obtains the metric keyspace_id from the initialized storage codec, so the activation request does not need to supply it. Activation fields such as metadata, export_id, max_idle_seconds, run_auto_analyze, and tidb_enable_ddl are also supported.
Test-only APIs (enableTestAPI failpoint)
These APIs are only registered when the enableTestAPI failpoint is enabled.
Enable
Build tidb-server with the failpoint enabled, then run with:
GO_FAILPOINTS="github.com/pingcap/tidb/pkg/server/enableTestAPI=return" ./bin/tidb-serverDelete row key or index key
You can use those APIs to mock dangling row or index keys case for test.
Row key:
curl -X POST "http://{TiDBIP}:10080/test/delete/rowkey/{db}/{table}?handle={intHandle}"
# For clustered common handle tables:
curl -X POST "http://{TiDBIP}:10080/test/delete/rowkey/{db}/{table}?{pkCol}={pkVal}[&{pkCol2}={pkVal2}...]"Index key:
curl -X POST "http://{TiDBIP}:10080/test/delete/indexkey/{db}/{table}/{index}?handle={intHandle}&{idxCol}={idxVal}[&{idxCol2}={idxVal2}...]"
# For clustered common handle tables:
curl -X POST "http://{TiDBIP}:10080/test/delete/indexkey/{db}/{table}/{index}?{idxCol}={idxVal}[&{idxCol2}={idxVal2}...]"APIs unique to TiDB X
Get global system variables
GET /variables/global returns global system variables for operator inspection. It is available only in NextGen (TiDB X), on the status port of both SYSTEM-keyspace and tenant-keyspace TiDB instances. It reports the current keyspace of the TiDB process handling the request, not an aggregation across keyspaces.
Method: GET only. Parameters: none.
curl http://{TiDBIP}:10080/variables/globalThe response is a JSON object mapping variable names to string values. Example response excerpt:
{
"autocommit": "ON",
"max_connections": "0",
"tidb_cloud_storage_uri": "s3://bucket/path?access-key=xxxxxx&secret-access-key=xxxxxx",
"tidb_exp_embed_openai_api_key": "******",
"validate_password.length": "8"
}/* Detailed source-code truncated for AI context efficiency. */
# curl -XPOST "http://{TiDBIP}:10080/ddl/check/{db}/{table}/{index}"
{
"check_sql": "admin check index `test`.`t` `primary`",
"db": "test",
"index": "primary",
"result": "success",
"table": "t"
}APIs unique to TiDB X SYSTEM keyspace
These APIs are registered only on TiDB instances running in the TiDB X SYSTEM keyspace. All examples in this section assume {TiDBIP}:10080 belongs to a TiDB process in that SYSTEM keyspace.
The /dxf/... APIs are for DXF (Distributed eXecution Framework) operator observability and emergency runtime tuning. In TiDB X, DXF runs as a shared SYSTEM-keyspace service for resource-intensive work such as IMPORT INTO and distributed add index, so some APIs are called on a SYSTEM-keyspace TiDB process but target a user keyspace parameter.
List DXF nodes
This API lists the TiDB nodes registered with DXF. The response is ordered by host and omits the internal keyspace_id field.
Usage:
curl http://{TiDBIP}:10080/dxf/nodesParameters: none.
Response fields:
host: The TiDB execution ID inIP:PORTform.role: The node's configured TiDB service scope.dxf_serviceis the normal value for TiDB X DXF nodes;background, an empty string, or another configured scope can also appear.cpu_count: The number of CPU slots available to DXF on the node.
Example response:
[
{
"host": "192.168.1.10:5000",
"role": "dxf_service",
"cpu_count": 8
},
{
"host": "192.168.1.11:5000",
"role": "background",
"cpu_count": 16
}
]If no DXF nodes are registered, the response is [].
Get the DXF schedule status
This API returns the scheduler view used by cluster controllers to decide how many DXF worker nodes are needed. It includes the number of scheduled tasks, current and required TiDB/TiKV worker counts, busy DXF nodes, and temporary scheduler flags such as pause_scale_in.
Usage:
curl http://{TiDBIP}:10080/dxf/schedule/statusParameters: none.
Example response:
{
"version": 1,
"task_queue": {
"scheduled_count": 2
},
"tidb_worker": {
"cpu_count": 10,
"required_count": 2,
"current_count": 3,
"busy_nodes": [
{
"id": "192.168.1.10:5000",
"is_owner": true
}
]
},
"tikv_worker": {
"required_count": 2
},
"flags": {
"pause_scale_in": {
"enabled": true,
"ttl": 3600000000000,
"expire_time": "2025-08-22T16:58:23.092864+08:00"
}
}
}Pause or resume DXF worker scale-in
This API writes a temporary DXF schedule flag. Use it when scale-in conflicts with DXF subtask scheduling, for example when subtasks keep being moved away from nodes selected for scale-in and task completion becomes slower. pause_scale_in asks the cluster controller to stop scaling in DXF workers for a limited time. resume_scale_in clears that request.
Usage:
curl -X POST "http://{TiDBIP}:10080/dxf/schedule?action=pause_scale_in"
curl -X POST "http://{TiDBIP}:10080/dxf/schedule?action=pause_scale_in&ttl=5h"
curl -X POST "http://{TiDBIP}:10080/dxf/schedule?action=resume_scale_in"Parameters:
action: Required. Valid values arepause_scale_inandresume_scale_in.ttl: Optional forpause_scale_in. Uses Go duration syntax such as10m,1h, or2h45m. The default is1h. Ignored byresume_scale_in.
Example response for pause_scale_in:
{
"enabled": true,
"ttl": 18000000000000,
"expire_time": "2025-08-22T21:13:01.276282+08:00"
}Example response for resume_scale_in:
{
"expire_time": "0001-01-01T00:00:00Z"
}Get or update DXF schedule tuning factors
This API gets or updates the resource tuning factors for a target keyspace. The scheduler uses these factors when calculating resource-related parameters for new DXF tasks such as IMPORT INTO and distributed add index tasks. Updating amplify_factor can make the scheduler reserve more resources for newly planned work in that keyspace.
Usage:
curl "http://{TiDBIP}:10080/dxf/schedule/tune?keyspace={keyspace}"
curl -X POST "http://{TiDBIP}:10080/dxf/schedule/tune?keyspace={keyspace}&lify_factor={number}&ttl={duration}"Parameters:
keyspace: Required for bothGETandPOST. The target keyspace whose DXF resource calculation should be read or tuned.amplify_factor: Required forPOST. A floating-point number in the range[1.0, 10.0].ttl: Optional forPOST. Uses Go duration syntax such as10m,1h, or2h45m. The default is1h. After the TTL expires,GETreturns the default tuning factor.
Example GET response:
{
"amplify_factor": 1
}Example POST response:
{
"ttl": 7200000000000,
"expire_time": "2025-09-15T22:36:24.591155+08:00",
"amplify_factor": 2
}Get active DXF task counts
This API returns the number of active DXF tasks in mysql.tidb_global_task, grouped by keyspace. It is useful before maintenance or upgrades because it shows tasks that have not yet finished or moved to history. This differs from /dxf/schedule/status, which only counts tasks currently considered schedulable by the scheduler.
Usage:
curl http://{TiDBIP}:10080/dxf/task/activeParameters: none.
Example response:
{
"total": 3,
"per_keyspace": {
"SYSTEM": 1,
"keyspace1": 2
}
}List DXF history tasks
This API lists rows from mysql.tidb_global_task_history in descending task ID order. Use it to inspect completed, reverted, or failed DXF tasks across keyspaces. The API uses keyset pagination: pass the previous response's NextPageToken as the next request's page_token.
Usage:
curl "http://{TiDBIP}:10080/dxf/task/history"
curl "http://{TiDBIP}:10080/dxf/task/history?keyspace={keyspace}&page_size=50"
curl "http://{TiDBIP}:10080/dxf/task/history?keyspace={keyspace}&page_size=50&page_token={NextPageToken}"Parameters:
keyspace: Optional. If set, only returns history tasks from that keyspace.page_size: Optional. Default is20. Valid range is[1, 200].page_token: Optional. Must be a positive task ID returned asNextPageTokenby the previous page.
Example response:
{
"Items": [
{
"ID": 30001,
"Key": "keyspace1/ddl/backfill/9",
"Type": "backfill",
"State": "reverted",
"Step": 1,
"Priority": 512,
"RequiredSlots": 1,
"TargetScope": "dxf_service",
"CreateTime": "2026-04-13T11:30:10+08:00",
"MaxNodeCount": 1,
"ExtraParams": {},
"Keyspace": "keyspace1",
"ErrorCode": "kv:1062",
"ErrorCategory": "data-error",
"StartTime": "2026-04-13T11:30:13+08:00",
"StateUpdateTime": "2026-04-13T11:30:17+08:00",
"EndTime": "2026-04-13T11:30:16+08:00"
}
],
"HasMore": false,
"NextPageToken": 0,
"ApproxTotalCount": 1
}ErrorCode contains the effective RFC error code when the stored task error provides one, and is empty for a plain error. ErrorCategory is failed, cancelled, or data-error for a task with an error, and is empty when the task has no error. The response does not include the task error message.
Get IMPORT INTO history job details
This API returns detailed history for one completed IMPORT INTO job in a target keyspace. It reads DXF history tables and returns task status, resource settings, file and KV sizes, speeds, row counts, and per-step durations. It returns 404 Not Found if the matching history task is not found.
Usage:
curl http://{TiDBIP}:10080/dxf/import-into/history/job/{keyspace}/{job_id}Parameters:
keyspace: Required path parameter. The keyspace where the IMPORT INTO job ran.job_id: Required path parameter. The positive integer IMPORT INTO job ID.
Example response:
{
"job_id": 2,
"keyspace": "SYSTEM",
"task_id": 2,
"state": "succeed",
"concurrency": 1,
"max_node_count": 1,
"distsql_scan_concurrency": 15,
"index_count": 4,
"column_count": 12,
"file_size": "241.4MiB",
"data_kv_size": "249.4MiB",
"index_kv_size": "40.05MiB",
"per_core_speed": "24.97GiB/core/hour",
"overall_speed": "24.97GiB/hour",
"row_count": 250000,
"row_length": 1013,
"duration": {
"total": "34s",
"encode": "2s",
"merge_sort": "",
"ingest": "25s",
"collect_conflicts": "",
"resolve_conflicts": "",
"post_process": "4s"
}
}Get or update the DXF max concurrent task limit
This API gets or updates the process-local maximum number of DXF tasks that can be scheduled concurrently. The value is kept in memory only, is not persisted to TiKV, and is reset when the TiDB process restarts. When updating the value, send the request to the current DXF owner.
Get the current value:
curl http://{TiDBIP}:10080/dxf/schedule/max_concurrent_taskExample response:
{
"max_concurrent_task": 16,
"persistence": "memory_only"
}Update the value:
curl -X POST "http://{TiDBIP}:10080/dxf/schedule/max_concurrent_task?value={number}"value must be an integer in the range [16, 1000]. The response uses the same format as the GET request:
{
"max_concurrent_task": 128,
"persistence": "memory_only"
}Get or update the DXF task cleanup batch size
This API gets or updates the maximum number of finished DXF tasks returned by each cleanup query, independently of the scheduler concurrency limit. It is available only on a TiDB server that uses the SYSTEM keyspace. The value applies only to the TiDB process that handles the request, is kept in memory only, and is reset when that process restarts. Send requests to the current DXF owner to inspect or update the effective value.
Get the current value, which defaults to 20:
curl http://{TiDBIP}:10080/dxf/schedule/task_cleanup_batch_sizeExample response:
{
"task_cleanup_batch_size": 20,
"persistence": "memory_only"
}Update the value:
curl -X POST "http://{TiDBIP}:10080/dxf/schedule/task_cleanup_batch_size?value={number}"The value parameter is required and must be an integer in the range [1, 1000]. The response uses the same format as the GET request:
{
"task_cleanup_batch_size": 128,
"persistence": "memory_only"
}Update a DXF task's max runtime slots
This API updates the MaxRuntimeSlots extra parameter for one DXF task. Use it as an emergency task-level throttle, for example when a task step causes TiDB memory pressure or repeated restarts. The new value takes effect when the task executor reads the updated task metadata, commonly after the related TiDB node restarts or the task step is retried.
Usage:
curl -X POST "http://{TiDBIP}:10080/dxf/task/{taskID}/max_runtime_slots?value={number}"
curl -X POST "http://{TiDBIP}:10080/dxf/task/{taskID}/max_runtime_slots?value={number}&target_step={step}&target_step={step}"Parameters:
taskID: Required path parameter. The positive integer DXF task ID.value: Required. A positive integer lower than the task'srequired_slots.target_step: Optional and repeatable. A numeric business step for the task type. If omitted, the limit applies to all business steps of the task.
For IMPORT INTO tasks, common target_step values are:
| Value | Step |
|---|---|
1 |
import |
2 |
post-process |
3 |
encode |
4 |
merge-sort |
5 |
ingest |
6 |
collect-conflicts |
7 |
conflict-resolution |
For distributed add index backfill tasks, common target_step values are:
| Value | Step |
|---|---|
1 |
read-index |
2 |
merge-sort |
3 |
ingest |
4 |
merge-temp-index |
Example response:
{
"task_id": 2,
"task_key": "SYSTEM/ImportInto/2",
"required_slots": 7,
"max_runtime_slots": 5,
"target_steps": [
"post-process",
"encode"
]
}/* Detailed source-code truncated for AI context efficiency. */
curl "http://{TiDBIP}:10080/regions/cache/status?store_id={id}"
curl -X POST "http://{TiDBIP}:10080/regions/cache/refresh?store_id={id}"
curl -X POST "http://{TiDBIP}:10080/regions/cache/refresh?store_id={id}&reset=1"Parameters:
store_id: required positive integer. Missing, zero, or non-integer values return HTTP 400.reset: optional onPOSTonly.1ortrueclears leftover failures from a previous rolling or TTL fallback, then refreshes. If a refresh is in progress, the store is left running and the response is not ready. Omit it during an in-progress rolling.detail: optional on either route.1ortrueincludes per-store entries instores; otherwisestoresis omitted.
The status route accepts only GET. The refresh route accepts only POST. Other methods return HTTP 405.
Example GET response with detail=1:
{
"failed": 0,
"remaining": 9,
"ready": false,
"observed_at": 1720000000,
"stores": [
{
"cluster_id": 123,
"failed": 0,
"remaining": 9,
"ready": false,
"observed_at": 1720000000
}
]
}stores is one entry per in-process TiKV store (each keyspace / PD cluster). Top-level counters are the sum of those entries and are not labeled with a single keyspace.
Example POST response with detail=1:
{
"failed": 0,
"remaining": 9,
"ready": false,
"in_progress": true,
"observed_at": 1720000000,
"stores": [
{
"cluster_id": 123,
"failed": 0,
"remaining": 9,
"ready": false,
"in_progress": true,
"observed_at": 1720000000
}
]
}Active jobs across keyspaces
POST /keyspaces/jobs/active counts DDL jobs in the queue and active IMPORT INTO
jobs in a batch of user keyspaces. It is available only on a NextGen TiDB server
running in the SYSTEM keyspace. Classic TiDB, user-keyspace servers, and
diagnostic mode do not expose this endpoint.
Send a JSON object with these fields:
| Field | Meaning |
|---|---|
keyspaces |
Required array of 1 to 1,000 valid user-keyspace names. Duplicates count toward the limit and are checked once, in first-occurrence order. SYSTEM is not accepted. |
concurrency |
Optional integer limiting simultaneous keyspace checks per request. Defaults to 1. Values below 1 become 1; values above four times the process's usable CPU count become that limit. |
curl -X POST 'http://{TiDBIP}:10080/keyspaces/jobs/active' \
-H 'Content-Type: application/json' \
-d '{"keyspaces":["tenant_a","tenant_b"],"concurrency":2}'Example HTTP 200 response:
{
"keyspaces": [
{"keyspace": "tenant_a", "ddl_jobs": 2, "import_jobs": 1},
{"keyspace": "tenant_b", "error": "failed to check keyspace"}
]
}Each successful result includes both counts, including zeros. An unsuccessful
result contains error and omits both counts; successful results from other
keyspaces are preserved. Results follow the input order after deduplication.
The JSON request body can be up to 256 KiB, including whitespace. Split larger
bodies or lists longer than 1,000 entries across requests. Oversized or
malformed requests return HTTP 400 before any keyspace is checked. Methods
other than POST that reach the HTTP status router return HTTP 405.
Only one active-jobs request can check keyspaces at a time in a TiDB process.
An overlapping valid request returns HTTP 429 before checking any keyspaces.
Retry with backoff after the active request's checks finish. This limit remains
in effect until all of that request's checks finish, including initialization
that outlives its deadline. The limit is released before writing the response,
so a slow client receiving results does not block later polls. Use smaller
batches when cold keyspaces take too long to check, and avoid overlapping polls
to the same server.
DDL counts include every row in mysql.tidb_ddl_job. A job counts until DDL
removes it from the queue during finalization, including while a job markeddone awaits schema synchronization. IMPORT INTO counts include pending and
running jobs in each user keyspace's import-job table. Pausing an underlying
DXF task keeps its import job active. Finished, failed, and cancelled imports are
excluded. Counts are observations made during the request, not a cluster-wide
atomic snapshot.
PD keyspace lookups, SQL queries, waits for another caller to open or close a
runtime, and storage-open retry delays honor request cancellation. They share
one two-minute timeout across the batch, subject to any earlier request deadline.
Individual runtime and session initialization operations and teardown can take longer.
The handler returns the borrowed session to the pool on success and discards it
if a query fails, including during result-set cleanup. It then releases its
runtime holder and closes the runtime immediately if that was the last holder,
without waiting for idle eviction. Teardown is part of the request's work: the
response and admission of other polls wait until cleanup finishes, even if the
request is cancelled or its deadline expires. A runtime still held by DXF remains
available to that task and follows its holder's release policy. Cold checks and
DXF startup for the same keyspace still serialize store opening and teardown;
different keyspace names can proceed independently.
Agents Agents Review Guide (`docs/agents/agents-review-guide.md`)
AGENTS.md Review Guide
This document is a repeatable review guide for changes to AGENTS.md and related agent runbooks.
Normative requirements (MUST/SHOULD/MAY/MUST NOT) remain in root AGENTS.md.
When to Use
Run this guide before merging changes to:
AGENTS.md- Repository skills under
.agents/skills/ - Any added/updated/removed agent-facing docs under
docs/agents/
Document Boundaries (Source of Truth)
AGENTS.md: policy and contract (normative behavior).docs/agents/: supporting runbooks, indexes, and review checklists (for example architecture index and testing flow).
Review gate:
- Any new MUST/SHOULD/MAY/MUST NOT policy lives in
AGENTS.mdfirst. - Supporting docs only explain or exemplify policy; they do not introduce new policy scope.
- Normative keywords keep a consistent style (MUST/SHOULD/MAY/MUST NOT are not wrapped in backticks).
Review Workflow
1) Precedence and Scope
- Confirm precedence wording remains clear (MUST/SHOULD/MAY, root-first precedence).
- If subtree-specific guidance is added, ensure it does not conflict with root
AGENTS.md.
2) Structure and Duplication
-
AGENTS.mdremains concise: policy-focused, not overloaded with step-by-step runbook detail. - Detailed workflows are linked from
AGENTS.mdtodocs/agents/*instead of copied inline. - Policy statements are not duplicated across sections or docs; keep one source-of-truth line and reference it elsewhere if needed.
- No duplicated checklist documents with overlapping normative rules.
- Changed skill descriptions, bodies, and their direct references agree on trigger scope, authorization, and completion. Check representative matching and non-matching requests; a shorter description must retain supported entrypoints.
3) High-Risk Policy Gates
Validate these first because they caused prior drift/regressions:
- Bazel metadata rule is explicit and unambiguous (no ambiguous wildcard wording).
- PR requirements include the
Issue Number:line withclose #<id>orref #<id>. - Agent notes follow the location and update rules in
docs/agents/notes-guide.md. - Testing policy in
AGENTS.mdmatches testing runbook guidance underdocs/agents/(no contradiction).
4) Testing and Validation Consistency
-
Task -> Validation Matrixstill defines minimal required test surfaces by change scope. -
Testing Policyremains policy-level and points to command playbooks underdocs/agents/. - Delivery checks follow change type, including documentation and build changes; read-only analysis does not trigger code checks, and still-applicable evidence can be reused.
- RealTiKV rule still requires background start and mandatory cleanup.
- Bug-fix policy still requires regression tests with fail-before-fix/pass-after-fix evidence (or explicit infeasibility note).
5) PR/Issue Policy Consistency
- PR title format rules are intact.
- PR description still requires
.github/pull_request_template.md. - HTML comment preservation requirement remains intact.
- English language requirement remains intact for issues and PRs.
6) Reference and Path Hygiene
- Every mentioned path exists.
- Removed files are not referenced anywhere.
- Cross-links between
AGENTS.mdand docs underdocs/agents/remain valid. - Shell snippets are copy-paste safe (especially quoted patterns containing backticks).
- Any
make <target>mention in docs is verified againstMakefile. - Related examples stay parameter-consistent across snippets.
Fast Verification Commands
Use from repository root.
# Check critical policy anchors in AGENTS.md
rg -n "Issue Number:" .agents/skills/tidb-pr-metadata-guard/SKILL.md
grep -n "Task -> Validation Matrix\|Testing Policy\|make bazel_prepare" AGENTS.md
# Ensure normative keywords are not wrapped in backticks in policy docs.
rg -n -P '\x60(MUST(?: NOT)?|SHOULD|MAY)\x60' AGENTS.md docs/agents/agents-review-guide.md
# Check cross-doc source-of-truth boundaries in docs/agents/
grep -R -n 'root `AGENTS.md`' --include="*.md" docs/agents
# Ensure deleted/renamed paths in this change are not referenced in Markdown docs.
# Replace with the PR base branch if needed.
git diff --name-status ...HEAD | \
awk '$1=="D"{print $2} $1 ~ /^R[0-9]*/{print $2}' | \
while read -r old_path; do
[ -n "${old_path}" ] && rg -n --fixed-strings "${old_path}" --glob '*.md' . || true
doneAcceptance Criteria for AGENTS-related Changes
A review is complete only when all are true:
- No policy contradiction across
AGENTS.mdand the changed docs underdocs/agents/. - No ambiguous wording for critical rules (especially test/build and PR gates).
- No stale path references.
-
AGENTS.mdpreserves policy-level clarity and does not re-accumulate large runbook detail. - Final review comment includes concrete evidence (paths and exact commands run).
Reviewer Output Template
Use this summary format in review comments:
- Files reviewed.
- Drift/contradiction findings.
- Commands run to verify references/rules.
- Required fixes before merge.
- Optional follow-ups (non-blocking).
Agents Notes Guide (`docs/agents/notes-guide.md`)
TiDB Notes Flow for Agents
This document provides operational guidance for writing and maintaining notes under docs/agents/.
Policy-level requirements remain in the repository root AGENTS.md.
Location and Layout
- Notes live under
docs/agents/<component>/. - Keep notes close to the owning component and reuse existing folders before creating new ones.
- If you add a new
docs/agents/<component>/folder, add a short entry to this document so the new location is discoverable. - Do not maintain a full inline list of component folders here; treat
docs/agents/
as the source of truth for current folder names.
Update Rules
- Update existing sections when the topic/root cause overlaps.
- Append a new dated section only for a genuinely new topic.
Splitting Large Notes
- If a notes file grows beyond 2000 lines, split it by functionality and update any references that pointed to the old path.
IMPORT INTO Notes
- IMPORT INTO notes live at
docs/agents/import-into/README.md.
Agents Testing Flow (`docs/agents/testing-flow.md`)
TiDB Testing Flow for Agents
This document provides command playbooks for test execution.
Root AGENTS.md is the source of truth for policy-level requirements; this file is operational guidance.
Use AGENTS.md -> Task -> Validation Matrix first, run the smallest valid command set, and report exact commands.
Detailed command snippets in this file are the canonical operational reference; skills under .agents/skills/ should point here rather than duplicating long command blocks.
Unit tests (`/pkg/...`)
pushd pkg/
go test -run <TestName> -tags=intest,deadlock
popd- If execution succeeds, review changed result/testdata files.
- Prefer targeted runs (
-run <TestName>); use package-wide runs only when needed. - Use
-recordonly for test suites that explicitly support it.
Failpoint decision for unit tests
- Policy reference:
AGENTS.md->Quick Decision Matrix(Unit tests in a package that uses failpoints).
rg -n --fixed-strings -- "failpoint." pkg/
rg -n --fixed-strings -- "testfailpoint." pkg/
# If BUILD.bazel exists, also check failpoint dependency.
test -f pkg//BUILD.bazel && rg -n --fixed-strings -- "@com_github_pingcap_failpoint//:failpoint" pkg//BUILD.bazel- Use the checks above as the default decision basis.
- If
rgfinds matches, run with failpoints enabled. - If
rgfinds no matches, run without failpoint enable/disable and state the check evidence in the final report. -tags=intest,deadlockdoes not enable failpoints.
Failpoint-enabled run
./tools/check/failpoint-go-test.sh pkg/ -run <TestName>- The script enables failpoints, runs
go test, and always disables failpoints during cleanup. - The underlying enable/disable path is serialized by
tools/check/failpoint-state.sh; do not invoketools/bin/failpoint-ctldirectly from parallel agent tasks in the same worktree. - Pass additional
go testflags after the package path, for example./tools/check/failpoint-go-test.sh pkg/<package_name> -run <TestName> -count=1. - If
-tagsis omitted, the script defaults to-tags=intest,deadlock. - Pass
-tags=intest,deadlock,nextgenwhen a test run also needsnextgen. - If running Bazel directly (for example
bazel test), runmake bazel-failpoint-enablefirst, thenmake bazel-failpoint-disableafter tests. - If using
make bazel_test, do not runmake bazel-failpoint-enableseparately becausebazel_testalready depends on it; still runmake bazel-failpoint-disableafter tests.
Related guidance
- Bug-fix regression policy lives in
AGENTS.md->Quick Decision Matrix(Bug fix). - Include exact test commands in PR description under
Testswhen preparing a PR update.
Integration tests (`/tests/integrationtest`)
- Test inputs are in
tests/integrationtest/t. - Expected results are in
tests/integrationtest/r.
pushd tests/integrationtest
./run-tests.sh -r <TestName>
popd- Review changed files in
tests/integrationtest/rand confirm each diff matches expected behavior. - Result files usually do not need manual edits; if edits are necessary, keep them minimal and verify correctness before reporting.
- Mapping example: if you modify
t/planner/core/binary_plan.test, thenTestNameisplanner/core/binary_plan.
RealTiKV tests (`/tests/realtikvtest`)
- Use for cases requiring real TiKV/TiUP Playground behavior and tests under
tests/realtikvtest/. - Policy reference:
AGENTS.md->Quick Decision Matrix(RealTiKV tests).
Start playground in background:
tiup playground --mode tikv-slim --tag realtikvtest &
PLAYGROUND_PID=$!Default PD is 127.0.0.1:2379; if it is unavailable, use a non-default port or port offset.
Using --tag realtikvtest keeps data under ${HOME}/.tiup/data/realtikvtest after exit; remove it during cleanup.
tiup playground --mode tikv-slim --tag realtikvtest --pd.port 12379 &
PLAYGROUND_PID=$!
# or
tiup playground --mode tikv-slim --tag realtikvtest --port-offset 10000 &
PLAYGROUND_PID=$!PD_ADDR=127.0.0.1:2379
# If started with `--pd.port 12379` or `--port-offset 10000`, use:
# PD_ADDR=127.0.0.1:12379
curl -f "http://${PD_ADDR}/pd/api/v1/version"
until curl -sf "http://${PD_ADDR}/pd/api/v1/version" >/dev/null; do sleep 1; donego test -run <TestName> -tags=intest,deadlock ./tests/realtikvtest/<dir>/...
# non-default PD example
go test -run <TestName> -tags=intest,deadlock ./tests/realtikvtest/<dir>/... -args \
-tikv-path "tikv://127.0.0.1:12379?disableGC=true"- If failpoints are used, enable before running and disable afterward.
- Do not add
-vby default; add it only for debugging.
[ -n "${PLAYGROUND_PID:-}" ] && kill "${PLAYGROUND_PID}" 2>/dev/null || true
[ -n "${PLAYGROUND_PID:-}" ] && wait "${PLAYGROUND_PID}" 2>/dev/null || true
rm -rf "${HOME}/.tiup/data/realtikvtest"# Cleanup check: PD endpoint should be unreachable after teardown.
! curl -sf "http://${PD_ADDR}/pd/api/v1/version"Cleanup-safe template (recommended for long local debug runs):
PD_ADDR=127.0.0.1:2379
(
cleanup() {
[ -n "${PLAYGROUND_PID:-}" ] && kill "${PLAYGROUND_PID}" 2>/dev/null || true
[ -n "${PLAYGROUND_PID:-}" ] && wait "${PLAYGROUND_PID}" 2>/dev/null || true
rm -rf "${HOME}/.tiup/data/realtikvtest"
}
trap cleanup EXIT INT TERM
tiup playground --mode tikv-slim --tag realtikvtest &
PLAYGROUND_PID=$!
until curl -sf "http://${PD_ADDR}/pd/api/v1/version" >/dev/null; do sleep 1; done
go test -run <TestName> -tags=intest,deadlock ./tests/realtikvtest/<dir>/...
)
! curl -sf "http://${PD_ADDR}/pd/api/v1/version"- For fmt-only PRs, follow
Quick Decision Matrixand skip costlyrealtikvtest. - Alternative RealTiKV workflows are available in
tests/realtikvtest/scripts/classic/andtests/realtikvtest/scripts/next-gen/.
Design 2018 07 01 Refactor Aggregate Framework (`docs/design/2018-07-01-refactor-aggregate-framework.md`)
Proposal: A new aggregate function execution framework
- Author(s): @zz-jason
- Last updated: 2018-07-01
- Discussion at: https://github.com/pingcap/tidb/pull/6852
Abstract
This proposal proposes a new execution framework for the aggregate functions, to improve the execution performance of aggregate functions.
Background
In release-2.0, the framework of aggregate functions is located in the “expression/aggregation” package. In this framework, all the aggregate functions implement the Aggregation interface. It uses the AggEvaluateContext to store partial result for all the aggregate functions with all kind of possible argument types. The DistinctChecker in the AggEvaluateContext uses a []byte as the key of map, which is used to de-duplicate the values in the same group. During the execution, the Update interface is called to update the partial result for every input record. It enumerates every possible state during the execution of every aggregate function, which introduces a lot of CPU branch predictions.
It’s easy to implement a new aggregate function under this framework. But it has some disadvantages as well:
Updateis called for every input record. The per record function call could bring a huge overhead, especially when the execution involves tens of thousands of input records.Updateis called for every possible aggregate state, which also introduces a lot of CPU branch predictions. For example, functionAVGbehaves different when the state isPartial1andFinal, it has to make aswitchstatement to handle all the possible states.GetResultreturns atypes.Datumas the final result of a group. Currently, TiDB usesChunkto store the records during the query execution. The returnedDatumhas to be converted toChunkoutside the aggregate framework, which introduces a lot of data conversions and object allocations.AggEvaluateContextis used to store every possible partial result and maps, which consumes more memory than what is actually needed. For example, theCOUNTonly need aint64field to store the row count it concerns.distinctCheckeris used to de-duplicate values, and uses[]byteas key. The encoding and decoding operations on the input values also bring a lot of CPU overhead, which can be avoided by directly using the input value as the key of thatmap.
Proposal
In this PR: https://github.com/pingcap/tidb/pull/6852, a new framework was proposed. The new framework locates in the “executor/aggfuncs” package.
In the new execution framework, every aggregate function implements the AggFunc interface. It uses the PartialResult, which is actually a unsafe.Pointer, as the type of the partial result for every aggregate function. unsafe.Pointer allows the partial result to be any kind of data object.
The AggFunc interface contains the following functions:
AllocPartialResultallocates a specific data structure to store the partial result, initializes it, converts it toPartialResultand returns it back. Aggregate operator implementation, for example, stream aggregate operator, should hold this allocatedPartialResultfor further operations involving the partial result such asResetPartialResult,UpdatePartialResult, etc.ResetPartialResultresets the partial result to the original state for a specific aggregate function. It converts the inputPartialResultto the specific data structure which stores the partial result and then resets every field to the proper original state.UpdatePartialResultupdates the specific partial result for an aggregate function using the input rows which all belong to the same data group. It converts thePartialResultto the specific data structure which stores the partial result and then iterates on the input rows and updates that partial result according to the functionality and the state of the aggregate function.AppendFinalResult2Chunkfinalizes the partial result and appends the final result directly to the inputChunk. Like other operations, it converts the inputPartialResultto the specific data structure firstly, calculates the final result and appends that final result to theChunkprovided.MergePartialResultevaluates the final result using the inputPartialResults. Suppose the inputPartialResultsnames aredstandsrcrespectively. It convertsdstandsrcto the same data structure firstly, merges the partial results and store the result indst.
The new framework uses the Build() function to build an executable aggregate function. Its input parameters are:
aggFuncDesc: the aggregate function representation used by the planner layer.ordinal: the ordinal of the aggregate functions. This is also the ordinal of the output column in theChunkof the corresponding aggregate operator.
The Build() function builds an executable aggregate function for a specific input argument type, aggregate state, etc. The more specific, the better.
Rationale
Advantages:
- The partial result under the new framework can be any type. Aggregate functions can allocate the memory according to the exact need without any wasting. The OOM risk can also be reduced when it is used in the hash aggregate operator.
- That the partial result can be any type also means the aggregate functions can use a map with the specific input type as keys. For example, use
map[types.MyDecimal]to de-duplicate the input decimal values. In this way, the overhead on the encoding and decoding operations on the old framework can be reduced. UpdatePartialResultis called with a batch of input records. The overhead caused by the per record function call on the framework can be saved. Since all the execution operators are usingChunkto store the input rows, in which the data belonging to the same column is stored consecutively in the memory, the aggregate functions should be executed one by one, take full utilization of the CPU caches, reduce the cache misses, and improve the execution performance.- For every state and every kind of input type, a specific aggregate function should be implemented to handle it. This means the CPU branch predictions on the aggregate state and input value types can reduce during the execution of
UpdatePartialResult, utilize the CPU pipelines, and improve the execution speed. AppendFinalResult2Chunkdirectly finalizes the partial result to the chunk, without converting it toDatumand then converting theDatumback intoChunk. This saves a lot of object allocation, reduces the overhead of golang’s gc worker, and avoids the unnecessary value conversions betweenDatumandChunk.
Disadvantages:
- An aggregate function need to be implemented for every possible state and input type. This could introduces a lot of development work. And it takes more coding work to add a new aggregate function.
Compatibility
For now, the new framework is only supported in the stream aggregate operator. If the Build() function returns a nil pointer, it rolls back to the old framework.
So this new framework can be tested during the development, and all the results should be the same with the old framework.
Implementation
- Implement the new framework, including the
AggFuncinterface and theBuild()function. @zz-jason - Implement the
AVGfunction under the new framework. @zz-jason - Implement other aggregate functions under the new framework. @XuHuaiyu
- Add more integration tests using the random query generator. @XuHuaiyu
- Add unit tests for the new framework. @XuHuaiyu
- Infer input parameter type for new aggregate functions when extracting a
Projectoperator under theAggregateoperator. @XuHuaiyu - Use the new framework in the hash aggregate operator. @XuHuaiyu
Open issues (if applicable)
Design 2018 07 19 Row Format (`docs/design/2018-07-19-row-format.md`)
Proposal: A new storage row format for efficient decoding
- Author(s): Yuxing ZHOU
- Last updated: 2018-07-19
Abstract
This proposal proposes a new row format for efficient decoding.
Background
In the current row format, each column is encoded with the column ID followed by the column value and multiple columns are concatenated together. In order to find a specific column in the row, we need to start from the beginning and decode each column ID and the length of each value until we find the matched column. This decoding method is inefficient especially when the number of columns in a row is not small and the complexity is O(N).
Proposal
The new format is defined as follows:
1 byte codec version
Its value starts from 128, so we can upgrade TiDB in a compatible way.
1 byte row type flag containing the following attribute:
1 bit IsBig
A row is big if the max column ID is greater than 255 or the total size of the values is greater than 65535. We can add more types in this byte later if needed, for example storing 2 bytes column ID.
2-byte number of not-null columns
2-byte number of null columns
We can store 65536 columns in a row and this number is much larger than the upper limit in TiDB.
not-null column ID array
If the row is big, each column ID takes 4 bytes, otherwise the column ID takes 1 byte. The IDs array is sorted in an ascending order.
null column ID array
This array stores the IDs of all the columns with value
null. The IDs array is sorted in an ascending order.offset array
Specifies the end offset of each not-null column value, relative to the start of the first column value. If the row is big, one offset takes 4 bytes, otherwise it takes 2 bytes.
column values
For integer values, we store {byte, uint16, uint32, uint64} instead of varint for fast decoding. The type can be inferred by the column value size.
The string value is stored as it is. Other types are encoded in the old way without the first type flag byte.
To find a column in a row, we can perform a binary search on the not-null column ID array. If it’s not found, then we perform a binary search on the null column ID array.
The complexity is O(logN).
If the column ID can not be found in the row, we use the column default value in the schema.
Rationale
The new format has better read performance but we need to consider the space efficiency.
In most of the cases, column IDs are less than 255 and the total length of the values is less than 64KB, so we only compare the small row type with the old format.
In the current row format, a string type column takes 1 (varint flag) + 1(colID) + 1 (bytes flag) + 1(varint len) + len(val). In the new row format, a string type column takes 1(colID) + 2(offset) + len(val), one byte less compared with the old row format. So the string type is more space efficient and varint is more space efficient.
But for the decoding performance, I choose the dynamic size of 1, 2, 4, 8 to store the integers. The space efficiency depends on the value of the integer. It is more space efficient in most of the cases and it’s less space efficient in rare cases, for example if the value is slightly greater than MaxInt32.
The null column IDs array is separated from not-null column IDs, so we don’t need to store offsets to null columns. It saves a lot of space when most of the columns are null.
And we can not omit the null column ID because if the column ID is not found in the row, we will use the default value in the schema which may not be null.
Compatibility
We can make the new row format compatible with the old row format. Because every row starts with the same varint flag byte for the column ID, with the first byte codec version that is different from the varint flag, we can support both the new row and the old row at the same time. Later in compaction process, we can rewrite the old row to the new row. After full compaction, all rows will be stored in the new format.
In order to maintain the compatibility in the old cluster, we need 2 phase upgrade. The first upgrade makes the TiDB cluster able to read the new row format, but TiDB will not write data in the new row format. When all components in the cluster are upgraded in the first phase, we can do a second upgrade and after that, TiDB will write data in the new row format.
TiDB tools projects need to be upgraded to support the new row format.
Implementation
I implemented the new row format benchmark that decodes an encoded row into a Chunk. As a result, the performance of decoding one integer column from a row is improved up to 77x when there are 255 columns in a row. When a row has only two columns, the performance of decoding the two columns is improved 2x.
The prototype decodes the row into a chunk instead of Datum because it is more efficient, but the chunk execution is not implemented in TiKV yet, so we can do it in mockTiKV first. When chunk execution is implemented in TiKV, we can then implement it in TiKV. An alternative approach is to change the row format before chunk execution in TiKV, then some of the work will be discarded when chunk execution is implemented.
Design 2018 07 22 Enhance Propagations (`docs/design/2018-07-22-enhance-propagations.md`)
Proposal: Enhance constraint propagation in TiDB logical plan
- Author(s): @bb7133, @zz-jason
- Last updated: 2018-07-22
- Discussion at: https://docs.google.com/document/d/1G3wVBaiza9GI5q9nwHLCB2I7r1HUbg6RpTNFpQWTFhQ/edit#
Abstract
This proposal tries to illustrate some rules that can be added to current constraint/filter propgation optimizations in TiDB logcial plan.
Background
Currently, most of the constraint propagation work in TiDB is done by propagateConstantSolver, which does:
- Find the
column = constantexpression and substitute the constant for the column, as well as try to fold the substituted constant expression if possible, for example:
Given a = b and a = 2 and b = 3, it becomes 2 = 3 after substitution and leads to a final false constant.
- Find the
column A = column Bexpression (which happens injoinstatements mostly) and propagate expressions likecolumn op constant(as well asconstant op column) based on the equality relation. The supported operators are:
ast.LT('<')ast.GT('>')ast.LE('<=')ast.GE('>=')ast.NE('!=')
The propagateConstantSolver makes more detailed/explicit filters/constraints, which can be used within other optimization rules. For example, in the predicate-pushdown optimization, it generates more predicates that can be pushed closer to the data source (TiKV), and thus reduces the amount of data in the whole data path.
We can further do the optimization by introducing more rules and inferring/propagating more constraints from the existing ones, which helps us build a better logical plan.
Proposal
Here are proposed rules we can consider:
- Infer more filters/constraints from column equality relation
We should be able to infer a set of data constraints based on column equality, that is, any constraint on a now applies to b as long as:
- The constraint is deterministic
- The constraint doesn’t have any side effect
- The constraint doesn't include
isnull()expression:isnull()constraint cannot be propagated through equality - The constraint doesn't include
cast()/convert()expression: type cast may break the equality relation
For example,
| original expressions | propagated filters |
|---|---|
| a = b and a < 5 | b < 5 |
| a = b and a in (12, 13) and b in (14, 15) | a in (14, 15) and b in (12, 13) |
| a = b and cast(a, varchar(20)) rlike 'abc' | cast(b, varchar(20)) rlike 'abc' |
Equality propagation should also be included:
| original expressions | propagated filters |
|---|---|
| a = b and abs(a) = 5 | abs(b) = 5 |
But following predicates cannot be propagated:
| unpropagateable expressions | reason |
|---|---|
| a = b and a < random() | the expression is non-deterministic |
| a = b and a < sleep() | the expression has side effect |
| a = b and isnull(a) | isnull() cannot be propagated |
| a = b and cast(a as char(10)) = '+0.0' | type cast expression cannot be propagated |
- Infer
NotNULLfilters from null-rejected scalar expression
We can infer NotNULL constraints from a scalar expression that doesn’t accept NULL, then we can know that involved columns cannot be NULL and add NotNull filter to them:
| original expressions | inferred filters |
|---|---|
| a = b | not(isnull(a)) and not(isnull(b)) |
| a != b | not(isnull(a)) and not(isnull(b)) |
| a < 5 | not(isnull(a)) |
| abs(a) < 3 | not(isnull(a)) |
NOTE: Those columns should not have NotNULL constraint attribute, or the inferred filters are unnecessary.
- Fold the constraints based on their semantics to avoid redundancy
After the propagations we may produce some duplicate predicates, and they can be combined. We should analyze all of the conditions and try to make the predicates clean:
| original expressions | combined expression |
|---|---|
| a = b and b = a | a = b |
| a < 3 and 3 > a | a < 3 |
| a < 5 | not(isnull(a)) |
| a < 5 and a > 5 | false |
| a < 10 and a <= 5 | a <= 5 |
| isnull(a) and not(isnull(a)) | false |
| a < 3 or a >= 3 | true |
| a in (1, 2) and a in (3, 5) | false |
| a in (1, 2) or a in (3, 5) | a in (1, 2, 3, 5) |
- Filter propagation for outer join
When doing an equality outer join, we can propagate predicates on outer table in where condition to the inner table in on condition.
For example:
select * from t1 left join t2 on t1.a=t2.a where t1.a in (12, 13);
TiDB(localhost:4000) > desc select * from t1 left join t2 on t1.a=t2.a where t1.a in (12, 13);
+-------------------------+----------+------+-------------------------------------------------------------------------+
| id | count | task | operator info |
+-------------------------+----------+------+-------------------------------------------------------------------------+
| HashLeftJoin_7 | 25.00 | root | left outer join, inner:TableReader_12, equal:[eq(test.t1.a, test.t2.a)] |
| ├─TableReader_10 | 20.00 | root | data:Selection_9 |
| │ └─Selection_9 | 20.00 | cop | in(test.t1.a, 12, 13) |
| │ └─TableScan_8 | 10000.00 | cop | table:t1, range:[-inf,+inf], keep order:false, stats:pseudo |
| └─TableReader_12 | 10000.00 | root | data:TableScan_11 |
| └─TableScan_11 | 10000.00 | cop | table:t2, range:[-inf,+inf], keep order:false, stats:pseudo |
+-------------------------+----------+------+-------------------------------------------------------------------------+
6 rows in set (0.00 sec) NOTE: in this case, t1.a in (12, 13) works on the result of the outer join and we have pushed it down to the outer table.
But we can further push this filter down to the inner table, since only the records satisfying t2.a in (12, 13) can make join predicate t1.a = t2.a positive in the join operator. So we can optimize this query to:
select * from t1 left join t2 on t1.a=t2.a and t2.a in (12, 13) where t1.a in (12, 13);
And the join predicate t2.a in (12, 13) can be pushed down:
TiDB(localhost:4000) > desc select * from t1 left join t2 on t1.a=t2.a and t2.a in (12, 13) where t1.a in (12, 13);
+-------------------------+-------+------+-------------------------------------------------------------------------+
| id | count | task | operator info |
+-------------------------+-------+------+-------------------------------------------------------------------------+
| HashLeftJoin_7 | 0.00 | root | left outer join, inner:TableReader_13, equal:[eq(test.t1.a, test.t2.a)] |
| ├─TableReader_10 | 0.00 | root | data:Selection_9 |
| │ └─Selection_9 | 0.00 | cop | in(test.t1.a, 12, 13) |
| │ └─TableScan_8 | 2.00 | cop | table:t1, range:[-inf,+inf], keep order:false, stats:pseudo |
| └─TableReader_13 | 0.00 | root | data:Selection_12 |
| └─Selection_12 | 0.00 | cop | in(test.t2.a, 12, 13) |
| └─TableScan_11 | 2.00 | cop | table:t2, range:[-inf,+inf], keep order:false, stats:pseudo |
+-------------------------+-------+------+-------------------------------------------------------------------------+
7 rows in set (0.00 sec)Rationale
Constraint propagation is commonly used as logical plan optimization in traditional databases. For example, this doc explains some details of constant propagations in MySQL. It is also widely adopted in distributed analytical engines, like Apache Hive, Apache SparkSQL, Apache Impala, et al. Those engines usually query on a huge amount of data.
Advantages:
Constraint propagation brings more detailed, explicit constraints to each data source involved in a query. With those constraints, we can filter data as early as possible, and thus reduce disk/network I/O and computational overheads during the execution of a query. In TiDB, most propagated filters can be pushed down to the storage level (TiKV), as a Coprocessor task, and leads to the following benefits:
Apply the filters at each storage segment (Region), which make the calculation distributed.
When loading data, skip some partitions of a table if the partitioning expression doesn't pass the filter.
For the columnar storage format to be supported in the future, we may apply some filters directly when accessing the raw storage.
Reduce the data transferred from TiKV to TiDB.
Disadvantages:
Constraint propagation may bring unnecessary filters and lead to unnecessary overheads during a query. This is mostly due to the fact that logical optimization doesn't take data statistics into account, for example:
For a query select * from t0, t1 on t0.a = t1.a where t1.a < 5, we get a propagation t0.a < 5, but if all t0.a is greater than 5, applying the filter brings unnecessary overheads.
Considering the trade-off, we still gain a lot of benefits from constraint propagation in most of cases; hence it still can be treated as useful.
Compatibility
All rules mentioned in this proposal are logical plan optimization, which do not change the semantics of a query, and thus this proposal will not lead to any compatibility issue
Implementation
Here are rough ideas about possible implementations:
For proposal #1, we can extend the current
propagateConstantSolverto support wider types of operators from column equality.For proposal #2,
propagateConstantSolveris also an applicable way to addNotNULLfilter(not(isnull())), but should examine whether the column has theNotNULLconstraint already.For proposal #3, the ranger may be useful to help us collect and fold comparison constraints
For proposal #4, current rule PredicatePushDown may be enhanced to achieve it
Open issues (if applicable)
Related issues:
https://github.com/pingcap/tidb/issues/7098 - the very issue that inspires this proposal
Related PRs:
https://github.com/pingcap/tidb/pull/7276 - Related to proposal #1
https://github.com/pingcap/tidb/pull/7643 - Related to proposal #1 and #3
Design 2018 08 10 Restore Dropped Table (`docs/design/2018-08-10-restore-dropped-table.md`)
Proposal: A new command to restore dropped table
- Author(s): winkyao
- Last updated: 2018-08-10
Abstract
This proposal proposes to support the ADMIN RESTORE TABLE table_id command, to restore the table that is dropped by a faulty operation.
Background
At present, if we drop the table in production environment, we will realize whether the operation is faulty immediately. Before we support the proposed command, we can only read data from history versions to relieve the disaster. But it needs to read all the data in the storage and it takes too much time to just restore the dropped the table.
Proposal
We can add a new command ADMIN RESTORE TABLE table_id to just make the dropped table public again. If the data is not deleted by GC worker, this command can work. So it is better to enlarge the GC life time with update mysql.tidb set variable_value='30h' where variable_name='tikv_gc_life_time';, before we execute the statement. The table and the original table data can be restored in a few seconds and it is a lot faster than before. It also can reduce the complexity of the operations and dissolve the artificial operation error.
Rationale
Let's take a look at the workflow of the DROP TABLE statement. The DROP TABLE statement first removes the dropping table meta data from the coresponding database meta data. After the schemas are synced by all the TiDB instances, in worker.deleteRange, TiDB will insert a deleted range of the first row key to the end row key of the dropping table into the table mysql.gc_delete_range. At most max(gcDefaultRunInterval, gcLifeTimeKey) time later, the GC worker will delete the table data finally.
The meta data of the table is not really deleted. The meta key format is Table:table_id. As long as we can find out the ID of the dropped table, we can recover the table information. The admin show ddl jobs statement can retrieve the table ID:
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+
| JOBS | STATE |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+
| ID:44, Type:drop table, State:synced, SchemaState:none, SchemaID:1, TableID:39, RowCount:0, ArgLen:0, start time: 2018-08-11 11:23:53.308 +0800 CST, Err:<nil>, ErrCount:0, SnapshotVersion:0 | synced |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+As you can see, if we can restore the table before the GC worker deletes the table data, we can restore the table completely. If the table data is deleted, we can only restore an empty table.
Before we run ADMIN RESTORE TABLE table_id, you must:
- Ensure that no GC task is running and then you can figure this by using TiDB logs and metrics.
- Increase
tikv_gc_life_timeto a sufficient value.
Compatibility
It's a new command and will not lead to compatibility issues.
Implementation
ADMIN RESTORE TABLE table_idwill enqueue a new DDL job to TiDB general DDL queue.- Before we start to do this job, we need to check if the table name already exists (created a new table with the same table name after you drop it). If it exists, return the
ErrTableExistserror. - Find out whether the delete-range of the dropped table is still in
mysql.gc_delete_range. If not, it means that the GC worker has cleaned up the data. In this situation, we cannot restore the table successfully but return an error to the client. If it is still there, we remove the record in themysql.gc_delete_rangetable. If we successfully remove the record, continue to Step 4; otherwise, we return an error to the client to indicate the command cannot be executed safely. - Use the previous table meta information of the table_id to insert the meta data into the schema meta data, like what
Meta.CreateTabledoes. And set the table information state tomodel.StatePublic, then the restoration will be finished after the schema is synced by all the TiDB instances. - If the command is canceled or rollbacked, and the delete-range record is already removed, we need to insert it into
mysql.gc_delete_rangeagain, like whatDrop Tabledoes inworker.finishDDLJob.
Design 2018 08 29 New Planner (`docs/design/2018-08-29-new-planner.md`)
Proposal: A SQL Planner based on the Volcano/Cascades model
- Author(s): zz-jason
- Last updated: 2018-08-29
- Discussion at:
Abstract
The proposed new planner enlarges the plan search space, takes transformation
rules into the cost model, and finds the best execution plan among all the
equivalent expressions. There might be some performance regression on the
QPS/TPS in some OLTP scenarios because the optimization phase takes a longer
time than before.
Background
At present, the optimization procedure of the planner is separated into two
phases. The first phase, namely the "Logical Optimization", only applies the
rules which are always beneficial. The second phase, which is called the
"Physical Optimization", takes the cost of different physical operator
implementations into consideration and chooses the best physical plan with the
lowest cost.
However, there are some other transformations which are not always beneficial
for all the scenarios. For example, aggregate push down, aggregate pull up, in
subquery unfold, etc.
Another drawback of the current planner is the poor extensibility. It's hard to
add a new rule even if it's beneficial for all the scenarios, because we have to
consider the order of different optimization rules carefully.
The physical optimization for the operators on the storage layer also suffers
from the poor extensibility. In the present planner, we use "root" and "cop"
tasks to distinguish the operators executed on TiDB and the storage layer, which
is TiKV at present. "cop" task is highly tied with the "root" task. It's very
hard to push-down another operator to TiKV or support another storage engine in
the future.
Glossary
Expression
In this proposal, expression is used to specify a logical plan. Expression
can be expressed to a tree-like structure and the child of an expression is
also an expression.Expression Group (or Group)
Expression group is used to store all the logically equivalent expressions.
It's a set of Group Expressions.Group Expression
Group expression is used to store all the logically equivalent expressions
which have the same root operator. Different from a normal expression, the
children of a group expression are expression Groups, not expressions.
Another property of group expression is that the child group references will
never be changed once the group expression is created.With the concept of Group and Group Expression, all the logically
equivalent expressions can be stored in a root Group.Transformation Rule
The transformation rule is used to transform a logical plan to another
equivalent logical plan. It is used to explore all the logically equivalent
query plans belonging to an expression group.Implementation Rule
The implementation rule is used to implement a logical expression operator to
a physical operator. For example, with implementation rules, a logicalJoin
operator can be implemented toHashJoin/MergeJoin/IndexJoin, etc.Enforcing Rule
Rule to construct an enforcer to satisfy the required physical properties.
Pattern
Pattern describes a piece of a logical expression. It's a tree-like structure
and each node in the tree represents a logical expression operator in the
logical expression. The node, or the logical expression operator, is called
Operand. Different from expression, only the type of the expression node
is concerned in the pattern.Operand
As discussed above, the operand represents a logical expression operator. It
can be some concrete operator types, for example,Join/Project/Filter.The expression node holds the full information about an expression operator,
while the pattern node only holds the operator type information.Logical Property
Logical properties can be derived from the logical algebra expression, for
example: the schema of the expression, the constraints and statistics of the
columns in the schema, etc. All the group expressions in the same group share
the same logical property.Physical Property
Physical properties depend on the implementation algorithms, or physical
operators. Typical physical properties include order and distribution.
Proposal
The new planner is composed of 2 phases: exploration and implementation. The
basic idea comes from the volcano optimizer generator and the optimizations
mentioned in the cascades project.
Optimization phase: exploration
A typical lifecycle of a SQL Query before this phase is:
SQL Query -> AST -> Logical Plan -> Expression GroupAfter building the expression group from the input logical plan, the exploration
optimization phase begins. The target of this phase is to explore all the
logically equivalent expressions by:
- Exploring all the equivalent group expressions of each group.
- Exploring all the potential groups.
The group and group expression can be defined as:
type StringSet = map[string]struct{}
type Group struct {
equivalents []*GroupExpr
fingerprints StringSet
explored bool
...
}
type GroupExpr struct {
exprNode LogicalPlan
children []*Group
explored bool
...
}The difficult and complex part is how we continually apply some push-down and
pull-up rules. A simple idea is to traverse the groups and group expressions
twice: a top-down traverse and a bottom-up traverse. The push-down rules are
applied during the top-down traverse and the pull-up rules are applied in the
bottom-up traverse.
But there might be some scenarios where a certain push-down rule can also be
triggered after the second bottom-up traverse. In order to explore all
optimization possibilities, the traverse on the groups should not be stopped
until there is no rule can be matched:
Some limitations can be added to reduce the total exploration time or ensure
that the expression exploration is convergent. For example, certain rules can
not be applied multiply times on the same group or group expression or limit the
number of total transformation moves in a group or group expression.
func OnPhaseExploration(rootGroup *Group) error {
for !rootGroup.explored {
err := exploreGroup(rootGroup)
}
}The explored field in the Group and GroupExpr is used to avoid unnecessary
traverse on the sub-tree of the groups and the group expressions. If a new group
expression is inserted into a group, the new group expression and the group it
belongs to will be marked as un-explored, to enable further exploration on the
new group expression and all the antecedent groups. The pseudo code to explore
an expression group is:
func exploreGroup(g *Group) {
if g.explored { return }
g.explored = true
for _, curExpr := range g.equivalents {
if curExpr.explored { continue }
// Explore child groups firstly.
curExpr.explored = true
for _, childGroup := range curExpr.children {
exploreGroup(childGroup)
curExpr.explored = curExpr.explored && childGroup.explored
}
eraseCur := findMoreEquiv(curExpr, g)
if eraseCur {
curGroup.erase(cur)
} else {
g.explored = g.explored && curExpr.explored
}
}
}The child of GroupExpr is Group. There are many candidate child expressions
for a group expression. All the possible expressions have to be enumerated to
check whether a group expression matches a transformation rule and apply the
rule on that expression once matched.
To conveniently enumerate all the equivalent expressions for a group expression,
the ExprIter is introduced:
// ExprIter enumerates all the equivalent expressions in the group according to
// the expression pattern.
type ExprIter struct {
// The group and ordinal field solely identify a group expression.
group *Group
ordinal int
// operand is the node of the pattern tree. The operand type of the group
// expression must be matched with it, otherwise the group expression is
// ignored during the iteration.
operand int
// children is used to iterate the child expressions.
children *ExprIter
}To simplify and reduce the work of enumeration, we only consider the pattern
that matches a rule. The pattern is a tree-like data structure which identifies
the operator type for every node in the expression tree:
type Pattern struct {
operand int
children []*Pattern
}The ExprIter should be created with a GroupExpr and the Pattern of a rule:
func NewExprIter(g *GroupExpr, p *Pattern) *ExprIterWith the help of the above components, the pseudo code of the functionfindMoreEquiv is:
// Find and apply the matched transformation rules.
func findMoreEquiv(cur *GroupExpr, curGroup *Group) (eraseCur bool) {
for _, rule := range GetTransformationRules(cur.exprNode) {
// Create a binding of the current group expression and the pattern of
// the transformation rule to enumerate all the possible expressions.
exprIter := NewExprIter(cur, rule.getPattern())
for exprIter.Next() {
if !rule.match(exprIter) {
continue
}
newExpr, erase, err := rule.onTransform(exprIter)
eraseCur = eraseCur || erase
if !curGroup.insert(newExpr) {
continue
}
// If the new group expression is successfully inserted into the
// current group, we mark the group expression and the group as
// unexplored to enable the exploration on the new group expression
// and all the antecedent groups.
newExpr.explored = false
curGroup.explored = false
}
}
return eraseCur
}According to the former discussion, the interface of the transformation rule can
be defined as:
type transformation interface {
getpattern() *Pattern
match(expr *ExprIter) (matched bool, err error)
onTransform(old *ExprIter) (new *GroupExpr, eraseOld bool, err error)
}At the very beginning, there is only one group expression in a Group. After
applying some transformation rules on certain expressions of the Group, all
the equivalent expressions are found and stored in the Group. This procedure
can be regarded as searching for a weak connected component in a directed graph,
where nodes are expressions and directed edges are the transformation rules.
Optimization phase: implementation
The target of this phase is searching the best physical plan for a Group which
satisfies the physical property that the parent operator requires.
In this phase, we need to enumerate all the applicable implementation rules for
each expression in each group under the required physical property. A memo
structure is used for a group to reduce the repeated search on the same required
physical property. The search engine used in the new planner can be expressed to
the pseudo code:
func implGroup(g *Group, reqPhysProp *PhysicalProperty, costLimit float64) (groupImpl PhysicalPlan) {
if g.implemented(reqPhysProp) {
return g.getImplementation(reqPhysProp)
}
// Handle implementation rules for each equivalent expression.
...
// Handle enforcing rules for the required physical property.
...
g.insertImpl(reqPhysProp, groupImpl)
return groupImpl
}In order to find the best physical implementation for the group, we need to
enumerate all the possible implementations for each group expression under the
required physical property. The procedure to handle the implementation rules for
each equivalent expression is:
// Handle implementation rules for each equivalent expression.
for _, curExpr := range g.equivalents {
for _, impl := range implGroupExpr(curExpr) {
impl.setCumCost(impl.getSelfCost())
for i, childGroup := range curExpr.children {
childImpl := implGroup(childGroup, impl.getChildReqProp(i), costLimit-impl.getCumCost())
if childImpl == nil {
cumCost = math.MaxFloat64
break
}
impl.setChild(i, childImpl)
impl.setCumCost(impl.getCumCost() + childImpl.getCumCost())
}
if groupImpl.getCumCost() > impl.getCumCost() {
groupImpl = impl
}
}
}To enumerate all the implementations for an expression, we have to enumerate all
the applicable implementation rules on that expression, and calculate the
self-cost for physical implementation:
func implGroupExpr(cur *GroupExpr, reqPhysProp *PhysicalProperty) (impls []PhysicalPlan) {
for _, rule := range GetImplementationRules(cur.exprNode) {
if !rule.match(cur, reqPhysProp) {
continue
}
impl := rule.onImplement(cur)
impl.calcSelfCost(cur.children)
impls = append(impls, impl)
}
return impls
}Also, the enforcing rules should be considered:
// Handle enforcing rules for the required physical property.
for _, rule := range getEnforcerRules(reqPhysProp) {
impl, newReqPhysProp := rule.onEnforce(reqPhysProp)
impl.calcSelfCost(g)
impl.setCumCost(impl.getSelfCost())
childImpl := implGroup(g, newReqPhysProp, costLimit-impl.getCumCost())
impl.setChild(0, childImpl)
impl.setCumCost(impl.getCumCost() + childImpl.getCumCost())
if groupImpl.getCumCost() > impl.getCumCost() {
groupImpl = impl
}
}Rationale
Compatibility
No
Implementation
Adding a session variable named
tidb_enable_volcano_plannerto control
whether to use the new planner. Once this variable is set, all the
optimization steps are handed to the new planner. The procedure of converting
the abstract syntax tree to a logical plan is remained unchanged. The
constructed physical plan is also compatible with the existing physical plan.
It only affects the optimization algorithm.Implementing the framework of the new planner, including the conceptions
described above:Group/GroupExpr/ExprIter/Pattern, the interfaces
liketransformation/implementation/enforcing, and the functions likeexploreGroup/findMoreEquiv/implGroup/implGroupExpr.Adding some simple transformation/implementation/enforcing rules and tests to
make the new planner framework basically available.Adopting the "Adaptor" conception to rewrite the operator push-down logical
for different storages.Adding some rules which are not easy or can not be added in the old planner
to improve the performance in certain scenarios.
Open issues (if applicable)
- https://github.com/pingcap/tidb/issues/7205
- https://github.com/pingcap/tidb/issues/7395
- https://github.com/pingcap/tidb/issues/6895
- https://github.com/pingcap/tidb/issues/6933
Design 2018 09 04 Histograms In Plan (`docs/design/2018-09-04-histograms-in-plan.md`)
Proposal: Maintain statistics in `Plan`
- Author: Yiding CUI
- Last updated: 2018-09-04
Abstract
This proposal proposes to maintain the histogram in Plan’s statistics information.
Background
Currently, TiDB only uses statistics when deciding which physical scan method a table should use. And TiDB only stores simple statistics in the plan structure. But when deciding the join order and considering some other optimization rules, we need more detailed statistics.
So we need to maintain the statistics in the plan structure to get sufficient statistics information to do optimizations.
Proposal
The new statsInfo of plan should be something like the following structure:
type statsInfo struct {
// This two attributes are already used in current statsInfo.
count float64
// The number of distinct value of each column.
ndv []float64
// HistColl collects histograms of columns.
histColl statistics.HistColl
}This struct will be maintained when we call deriveStats.
How to maintain it.
We maintain the histogram in Projection, Selection, Join, Aggregation, Sort, Limit and DataSource operators.
`Selection`
Just use it to calculate the selectivity.
And we can get the range information of each column and index involved in filters. Then we can use the range information to cut the histogram bucket of these columns.
For column/index not matched in the filter. The NDV and totalCnt of each bucket can just multiply the total selectivity of filters(based on independent assumption).
`Projection`
Change the reflection of the map we maintained.
`Join`
There're several kinds of joins.
Inner join
Use histograms to do the row count estimation with the join key condition. It can be described as the following procedures:
- Align the histogram buckets so that each bucket boundary in one histogram can be matched in the other histogram. For example(the following figure), bucket
b1andc1's left boundary is the same. But the right boundary is different. So we can splitc1into two buckets. The first one's boundary is totally the same withb1. The second one starts from where the first one ends. - Since the boundary of the bucket have been aligned. Then we can estimate the join's size bucket by bucket by the well-know way.
Original:

Step 1:

Step 2:
The calculation inside the bucket can be calculated as this formula 
Where
.
The ndvAfterJoin can be
or a more detailed one if we can calculate it.
Since it won’t have one side filter, we only need to consider the composite filters after considering the join key. We can simply multiply selectionFactor if there are other composite filters since Selectivity cannot calculate selectivity of an expression containing multiple columns.
One side outer join
It's almost the same as inner join's behavior. But we need to consider two more thing:
- The unmatched row will be filled as
NULL. This should be calculated in the new histogram. The null count can be calculated when we estimate the matched count bucket by bucket. - There will be one side filters of the outer table. If the filter is about join key and can be converted to range information, it's can be easily involved when we do the calculation bucket by bucket. Otherwise it's a little hard to deal with it. Don't consider this case currently.
Semi join
It’s something similar to inner join. But no data expanding occurs. So the total can be adjusted easily.
Anti semi join
Same with semi join.
`Aggregate`
Just read the NDV information from the statsInfo to decide the row count after aggregate. If there's index can fully match the group-by items, we will just use its NDV. Otherwise we will multiply the ndv of each column(or index that can match part of the group-by item).
If some of the group-by items are also in the select field, we will create new histograms by modifying the totalCnt of each bucket(set it the same with NDV).
`Sort`
We can just copy children's statsInfo without doing any change, since the data distribution is not changed.
`Limit`
Currently we won't maintain histogram information for it. But it can be considered in the future.
`DataSource`
Our DataSource is actually source of data + select. So if it’s a non-partitioned table, we just maintain the map and do what Select does. If it’s a partitioned table, we now only store the statistics of each partition. So we need to merge them into one histogram so the upper plan can use it. We need a cache or something else to ensure that we won’t merge them each time we need it.
Others
For other plan operators or DataSource which do not contain any histogram, we just use the original way to maintain statsInfo. We won’t maintain histograms for them.
Rationale
How other systems solve the same issue?
I’ve looked into Spark. They only maintain the max and min values, won't create new histogram after Select/Join/Aggregate. And they don’t have the index, so maintaining the column’s max/min value is much easier to solve comparing with us.
As for Orca and Calcite, I haven’t discovered where they maintain this information. But there’s something about statistics in Orca’s paper. According to the paper, I think they construct new histograms during planning and cache it to avoid building too many times.
What is the disadvantage of this design?
This may have side effects on OLTP performance. (Currently totally changing a histogram whose number of bucket is 256 and content is int value costs 7000ns. So we can create 143 histograms at 1ms currently)
For now, only join reorder and the position after logical optimize before physical optimize will trigger this mechanism and it’s controlled by tidb_optimizer_selectivity_level which is disabled by default. It will opened by default after we test it carefully.
After we switch to the cascade-like planner, the rule that needs cost to make decision is still a small set of all. And the existence of Group can also help us. If we lazily construct the statsInfo, this may not be the bottleneck.
And thanks to predicate push down and some other optimization rules. The single column(column directly from the DataSource not one the generated by Project's complex Expr) filters(Only this type of expression can be calculated to range information) can be all pushed down to the DataSource or the Selection on the DataSource. So simple querys won't create many new histograms.
What is the impact of not doing this?
Many cases reported by our customer already prove that we need more accurate statistics to choose a better join order and a proper join algorithm. Only maintaining a number about row count and a slice about NDV is not enough for making that decision.
If we don’t do this, we cannot fix some cases except we use hints.
Compatibility
There’s no compatibility issue.
Implementation
First, maintain the histogram in DataSource. In this step, there will be some changes in the statistics package to make it work. It may take a little long time to do this. PR#7385
Then, all changes will be things inside statsInfo, which won’t affect other parts. It may not take too much time to implement this part. Like PR#7595
The future work will depend on the benchmark result of the join reorder algorithm.
Design 2018 09 10 Adding Tz Env (`docs/design/2018-09-10-adding-tz-env.md`)
Proposal: Infer the System Timezone of a TiDB cluster via TZ environment variable
- Author(s): Zhexuan Yang
- Last updated: 2018/09/09
- Discussion at: Not applicable
Abstract
When it comes to time-related calculation, it is hard for the distributed system. This proposal tries to resolve two problems: 1. timezone may be inconsistent across multiple TiDB instances, 2. performance degradation caused by pushing System down to TiKV. The impact of this proposal is changing the way of TiDB inferring system's timezone name. Before this proposal, the default timezone name pushed down to TiKV is System when session's timezone is not set. After this, TiDB evaluates system's timezone name via TZ environment variable and the path of the soft link of /etc/localtime. If both of them are failed, TiDB then push UTC to TiKV.
Background
After we solved the daylight saving time issue, we found the performance degradation of TiKV side. Thanks for the investigation done by engineers from TiKV. The root cause of such performance degradation is that TiKV infers System timezone name via a third party lib, which calls a syscall and costs a lot. In our internal benchmark system, after this PR, our codebase is 1000 times slower than before. We have to address this.
Another problem needs also to be addressed is the potentially incosistent timezone name across multiple TiDB instances. TiDB instances may reside at different timezone which could cause incorrect calculation when it comes to time-related calculation. Just getting TiDB's system timezone could be broken. We need find a way to ensure the uniqueness of global timezone name across multiple TiDB's timezone name and also to leverage to resolve the performance degradation.
Proposal
Firstly, we need to introduce the TZ environment. In POSIX system, the value of TZ variable can be one of the following three formats. A detailed description can be found in this link
* std offset
* std offset dst [offset], start[/time], end[/time]
* :charactersThe std means the IANA timezone name; the offset means timezone offset; the dst indicates the leading timezone having daylight saving time.
In our case, which means both TiDB and TiKV, we need care the first and third formats. For answering why we do not need the second format, we need to review how Golang evaluates timezone. In time package, the method LoadLocation reads tzData from pre-specified sources(directories may contain tzData) and then builds time.Location from such tzData which already contains daylight saving time information.
In this proposal, we suggest setting TZ to a valid IANA timezone name which can be read from TiDB later. If TiDB can't get TZ or the supply of TZ is invalid, TiDB just falls back to evaluate the path of the soft link of /etc/localtime. In addition, a warning message telling the user you should set TZ properly will be printed. Setting TZ can be done in our tidb-ansible project, it is also can be done at user side by export TZ="Asia/Shanghai". If both of them are failed, TiDB will use UTC as timezone name.
The positive side of this change is resolving performance degradation issue and ensuring the uniqueness of global timezone name in multiple TiDB instances.
The negative side is just adding a config item which is a very small matter and the user probably does not care it if we can take care of it and more importantly guarantee the correctness.
Rationale
We tried to read system timezone name by checking the path of the soft link of /etc/localtime but, sadly, failed at a corner case. The failed case is docker. In docker image, it copies the real timezone file and links to /usr/share/zoneinfo/utc. The timezone data is correct but the path is not. Regarding of UTC, Golang just returns UTC instance and will not further read tzdata from sources. This leads to a fallback solution. When we cannot evaluate from the path, we fall back to UTC.
Compatibility
It does not have compatibility issue as long as the user deploys by tidb-ansible. We may mention this in our release-node and the message printed before tidb quits, which must be easy to understand.
The upgrading process need to be handled in particular. TZ environment variable has to be set before we start new TiDB binary. In this way, the following bootstrap process can benefit from this and avoid any hazard happening.
Implementation
The implementation is relatively easy. We just get TZ environment from system and check whether it is valid or not. If it is invalid, TiDB evaluates the path of soft link of /etc/localtime. In addition, a warning message needs to be printed indicating user has to set TZ variable properly. For example, if /etc/localtime links to /usr/share/zoneinfo/Asia/Shanghai, then timezone name TiDB gets should be Asia/Shanghai.
In order to ensure the uniqueness of global timezone across multiple TiDB instances, we need to write timezone name into variable_value with variable name system_tz in mysql.tidb. This cached value can be read once TiDB finishes its bootstrap stage. A method loadLocalStr can do this job.
Open issues (if applicable)
PR of this proposal: https://github.com/pingcap/tidb/pull/7638/files
PR of change TZ loading logic of golang: https://github.com/golang/go/pull/27570
Design 2018 09 21 Radix Hashjoin (`docs/design/2018-09-21-radix-hashjoin.md`)
Proposal: Implement Radix Hash Join
- Author(s): XuHuaiyu
- Last updated: 2018-09-21
Abstract
This proposal proposes to implement radix hash join in TiDB, aimed to improve the performance of the HashJoin executor.
Background
Currently, TiDB uses non-partitioning hash join to implement HashJoinExec. This algorithm starts by building a single global hash table for the inner relation which is known as the build phase. After the hash table is built, probe phase assigns equal-sized sub-relations (chunks) of the outer relation to multiple threads to probe against the global hash table simultaneously.
Shatdal et al. identify that when the hash table is larger than the cache size, almost every access to the
hash table results in a cache miss. So the build phase and probe phase of non-partitioning hash join might cause considerable cache miss when writing or reading the single global hash table.
Partitioning the hash table into cache-sized chunks can reduce cache misses and improve performance, partition-based hash join introduces the partition phase for hash join. Partition phase partitions the input relations into small pairs of partitions where one of the partitions typically fits into one of the CPU caches. During the build phase, a separate hash table is built for each partition respectively. During the probe phase, a sub-partition of outer relation will only be probed against the corresponding hash table which can be totally stored in the CPU cache.
The overall goal of this proposal is to minimize the ratio of cache misses when building and probing hash table in HashJoinExec.
Proposal
In a nutshell, we need to introduce a partition phase for HashJoinExec.
- Partition algorithm
We can use the parallel radix cluster algorithm raised by Balkesen et al. to do the partitioning work. This algorithm clusters on the leftmost or rightmost B bits of the integer hash-value and divides a relation into H sub-relations parallel, where H = 1 << B.
The original algorithm does the clustering job using multiple passes and each pass looks at a different set of bits, to ensure that opened memory pages will be no more than the TLB entries at any point of time. As a result, the TLB miss, caused by randomly writing tuples to a large number of partitions, can be avoided. The original algorithm normally would involve two or three passes to create cache-sized partitions, and in each pass, data will be copied, thus it may has high OOM risk. We decide to choose simple 1-pass radix cluster algorithm to avoid OOM risk.
Furthermore, partition phase can be executed parallelly by subdividing both relations into sub-relations that and assigning them to different threads, but there will be contention when different threads write tuples to the same partition simultaneously, especially when data is skewed heavily. In order to resolve this problem, we scan both input relations twice. The first scan computes a set of histograms over the input data, so the exact output size is known for each thread and each partition. Next, a contiguous memory space is allocated for the output. Finally, all threads perform their partitioning without any synchronization. In addition, we use []*chunk.List to store every partition. For every column in a chunk.Chunk, the null-value info is stored in column.nullBitmap which is actually a byte slice. Every element of column.nullBitmap stores the null-value info for 8 values. We cannot concurrently write to different bits of a same byte, so we also need to pre-build the column.nullBitmap when building the histogram during the first scan.
Obviously, if the input data is skewed heavily, the partition phase will become redundant, especially when all the data belongs to the same partition. We can determine to choose the non-partitioning hash join when we get the histogram after the first scan and the size of some partitions exceeds the threshold value.
To sum up, we use a parallel 1-pass radix cluster algorithm to partition the relations.
- Parameters of radix clustering
Since L3 cache is often shared between multiple processors, we'd better make the size of every partition be no more than L2 cache. The size of L2 cache which is supposed to be L can be obtained from a third-party library, and we can set the size of every partition to L * 3/4 to ensure that one partition of inner relation, one hash table and one partition of outer relation fit into the L2 cache when the input data obeys the uniform distribution.
The number of partitions is controlled by the number of radix bits which is affected by the total size of inner relation. Suppose the total size of inner relation is S, the number of radix bits is B, we can infer B = log(S / L).
Others
3.1 We can define the partition as type chunk.List, thus
HashJoinExecshould maintain an attribute *partitions []chunk.List.3.2 For outer relation,
partition phaseandprobe phasewill be done batch-by-batch. The size of every batch should be configurable for exploring better performance.3.3 After all the partitions have been built, we can parallelly build the hash tables.
Rationale
This proposal introduces a partition phase into HashJoinExec to partition the input relations into small partitions where one of the partition typically fits into the L2 cache. Through this, the ratio of cache miss during build phase and probe phase can be reduced and thus improve the total performance of HashJoinExec.
The side effect is that the memory usage of HashJoinExec might increase since the partition phase copies the input data.
Compatibility
This proposal has no effect on the compatibility.
Implementation
- Investigate the third-party libraries for fetching the L2 cache size and calculate the number of radix bits before
build phase. @XuHuaiyu - Partition the inner relation parallelly. @XuHuaiyu
- Build hash table parallelly. @XuHuaiyu
- Partition the outer relation and probe against the corresponding hash table parallelly. @XuHuaiyu
Open issues (if applicable)
https://github.com/pingcap/tidb/issues/7762
Design 2018 10 08 Online DDL (`docs/design/2018-10-08-online-DDL.md`)
TiDB DDL architecture
- Author(s): zimuxia (Xia Li)
- Last updated: 2018-10-08
Overview
This article will describe the architecture of the Online DDL implemented in TiDB.
Background
Many databases lock tables when performing DDL operations. During this time, many transactions involved in this table are blocked (some databases support reading operations, but at the expense of consuming a large amount of memory). The larger the table is, the longer it affects the transactions.
To simplify the design, the entire system allows only one node to make schema changes at the same time.
- TiDB server: It contains TiDB's MySQL Protocol layer and TiDB SQL layer. Figure 1 mainly describes the basic modules involved in asynchronous schema changes at the TiDB SQL layer.
- load schema: Creating a goroutine at the start of each node is in order to load the schema after each interval reached or a schema version update being found. The load failure here includes a load timeout.
- job: Every DDL operation can be considered a job. At the beginning of a DDL operation, the operation is categorized into two types (general job and add index job) and encapsulated into one job to be stored into the general job queue or add index job queue. When this operation is completed, the job will be deleted from the corresponding job queue and stored in the history job queue, which is convenient for viewing historical jobs. By the way, all jobs except the add index job are the general job.
- general job queue: It is a queue to store general jobs, staying at the KV layer. Logically, there is only one such queue for the entire system.
- add idx job queue: It is a queue to store add index jobs, staying at the KV layer. Logically, there is only one such queue for the entire system.
- job history queue: It is a queue to store the jobs that have been processed, staying at the KV layer. Logically, there is only one such queue for the entire system.
- start job: It assigns an ID to the job after the TiDB SQL layer receives the request. The jobs are divided into two types. Then it stores the job to the KV layer's general job queue or add index job queue based on the job type. After that, wait for the job processing to complete and return the processing result.
- owner: You can take it as a role. The information (including information of the node currently elected for this role) is stored in the Placement Driver (PD). Only one node in the entire system can be elected as the owner role. Each node can be elected to be this role, and workers will have the right to process jobs only when they are elected as the owner.
- workers: Each node has 2 workers to process jobs. They will take the job from the corresponding job queue and process it. Workers will periodically check whether there are tasks that need to be processed. If the server receives the request while the owner role is on the same server, the start job module also tells the corresponding worker to process the job.
- meta data: To simplify the design, we bring in system databases and system tables to record some metadatas in the process of asynchronous schema changes.
- state: According to the change process of asynchronous schema, some states are introduced in this process, which are bound to column, index, table, and database. These states includes none, delete only, write only, write reorganization, and public. The former order is generally the order in which the operations are created. The state of the delete operation is the reverse of the creating order. Change the write reorganization to delete reorganization. Although they are all reorganization states, the visible level is different. So they are divided into two status flags.
- lease: At the same time, there are at most two different versions of the schema on the same table for all nodes of the system. That is, there are at most two different states. As a result, every normal node in a lease will automatically load schema information. If this node cannot be loaded normally during the lease, SQL cannot be processed normally.
Rationale
To dive deep into DDL processing, you need to understand the overall architecture of the DDL module. This module is operated on the TiDB Server, but it also involves the use of two other components of the TiDB cluster (PD Server and TiKV Server).
Preparation
Concept overview
DDL jobs have multiple state changes during processing. All TiDB servers in a cluster have at most two states at the same time. Then the cluster is in this scenario when the owner just modified the state to TiKV. So before entering the next state change, we should make sure that all currently available TiDB servers are synchronized to the current state.
So you can simply think that each TiDB server needs two modules to ensure that this condition is met.
- One is the load schema module. In order to process SQL normally, each TiDB server needs to be loaded into the latest schema within a lease.
- The other one is the handle DDL job module. This module is executed only after the current TiDB server is elected to the owner. Process the job and change the schema. After the owner writes the currently changed schema state to TiKV, we can assume that all TiDB servers in the cluster that can handle SQL after waiting for 2*lease have been updated to this schema.
Initial configuration
The TiDB server which starts first establishes the latest version of information path in PD, which contains the latest schema version number.
All TiDB servers need to do the following when starting up:
- Register your DDL ID (which ensures a unique ID) and the initial self version number to PD.
- Perform a load schema operation and update the self version number after successful execution.
- Monitor for the latest version information.
Process introduction
- The MySQL Client sends a DDL operation request to the TiDB server.
- When a TiDB server receives a request (the MySQL Protocol layer receives a request for parsing optimization), it will reach the TiDB SQL layer for execution. This step is mainly after the TiDB SQL layer receives the request. The module that starts the start job module encapsulates it into a specific DDL job according to the request, and then classifies the jobs according to the statement type and stores them into the corresponding DDL job queue of the KV layer. This module also notifies the corresponding worker that there is a job to be processed.
- The worker that receives the job notification will judge whether itself is the owner role. If it is the owner role, it will process the job directly. If it is not in this role, it will exit without doing any processing. Assuming this TiDB server is not this role, then one of the other nodes must be the owner. The worker at the owner role node will check for a job to be executed by a periodic detection mechanism. If a job is found, the worker will handle it.
- When the owner worker finishes processing the job, it will remove the job from the job queue corresponding to the KV layer and puts it into the job history queue. The start job module which previously packaged the job will periodically check the job history queue to see whether there is a job with the same ID as the job placed in the job queue in step 2. If so, the entire DDL operation ends.
- The TiDB server returns the response to the MySQL Client.
Detailed steps
State change process
Each DDL job requires multiple state changes, such as create table: none -> public, add index: none -> delete only -> write only -> write reorg -> public. The schema version is modified after each state change, and each schema version needs to wait for other TiDB servers to synchronize the schema. The process of this process on the owner is shown in the opt section of Figure 2.
The main logic of this part can be divided into two parts:
- All TiDB servers will watch the latest schema version at current, which is the global schema version of the cluster. When a TiDB receives a notification of the latest schema version update, it loads the latest schema and updates its corresponding schema version to the PD. If it does not receive a notification, it will also load the schema periodically to prevent the watch message from delay or lost.
- After the owner updates a state, it updates the latest schema version to PD and waits for 10 milliseconds to confirm that all TiDB servers are updated to the latest schema information. Then it uses the PD to check if all TiDB servers are updated the corresponding schema. If all TiDB servers are updated successfully, then go directly to the next process. Otherwise, the owner will continue to probe until it exceeds 2 * lease.
Flow of deleting data
There are many operations in DDL that need to delete data, such as drop table requests. The table may have hundreds of millions of rows, at this time, this operation needs to be processed for a long time. Then we need to do some optimizations for this type of DDL operations. The current optimizations in TiDB include Drop Index, Drop Table, Drop Database, and Truncate Table. In implementation, these operations will have one more logic than other DDL operations. That is, after a normal schema change, we store the information we need to delete the data into the gc_delete_range table, and then process them until the GC stage. This logic can be divided into two parts:
- State transitions are the same as normal DDL logic. To clean up the data, only clean up the metadata (no metadata, can not access this table, and the table ID is guaranteed to be globally unique, so it will not be accessed), and store this meta information in the gc_delete_range table, and then enter the next process.
- After the GC Worker reaches the GC time, it will get the data key corresponding to the data to be deleted from the table gc_delete_range, and then send a request to the TiKV server to perform the delete operation.
Parallel flow
Currently, only the add index operation in TiDB takes a long time to execute, so an add index operation may block other DDL operations. In order to solve this problem preliminarily and steadily, we have implemented the parallel operation between the general operation and the add index operation between the tables. That is, between different tables, the general operation and the add index operation can be performed in parallel.
Optimization function
General DDL operation
Add column operation
In order to speed up this operation, we actually did not populate this column data. This operation does not care about the number of data rows in the table, and only needs to change 5 states throughout the process. The specific implementation is as follows: save the default value of the newly added column to a field named original default value; in the following reading operation, we read the data in this column, and if TiKV reads that the value of this column is null and the value in the field is not empty, then the value in this field is filled to the response and returns from TiKV.
Modify column operation
In order to reduce the execution time of this operation and facilitate the operation, only the modification between integer types is supported at present, and only the length of the original type can be lengthened. In addition, there are restrictions on modifying the type definition and other aspects. For details, please refer to the compatibility section. The implementation is to directly change the column field type. If there is an index, the corresponding index field type should also be modified, but the original data does not need to be modified. This method only supports the same type conversion of the codec format because the format of the codec is different.
Add index operation
This operation requires writing the corresponding column data in the table to the new index records. This function is actually divided into two parts, the first part is to read data from the corresponding column. The second part is to backfill the data into the index. In order to speed up this operation, we handle this operation in batches concurrently. The simple steps are as follows:
- Acquire the range of handles corresponding to this table, namely start handle and end handle.
- Split the range into multiple small ranges by the Region (the basic unit of data actually stored).
- Each goroutine sweeps the data within the corresponding small range and then writes the data to the index. If a goroutine fails to process a small range, the previous small range will be recorded. The last successful end handle is the start handle for the next backfill of the data. By default, there are 16 goroutines to handle this step concurrently.
To reduce the impact on other read and write operations, its default priority is low.
Compatibility
About specific compatibility, you can view MySQL’s compatibility.
Design 2018 10 19 Table Partition (`docs/design/2018-10-19-table-partition.md`)
Proposal: Table Partition
- Author(s): tiancaiamao
- Last updated: 2018-10-19
- Discussion at: https://github.com/pingcap/tidb/issues/7907
Abstract
This proposal proposes to support the table partition feature.
Background
MySQL has the table partition feature. If this feature is supported in TiDB, many issues could be addressed. For example, drop ranged partitions could be used to remove old data; partition by hash could address the hot data issue thus improve the write performance; query on partitioned table could be faster than on unpartitioned tables because of the partition pruning.
Proposal
Implement the table partition feature step by step. Partition by range first, then partition by hash.
For current implementation in this proposal, subpartition is not considered. Reorganize partition involving data movement remains unsupported.
Rationale
The new table partition feature should be problem-solving oriented, and it may not cover all MySQL counterpart at first.
The syntax should be always MySQL compatible, as TiDB's promise from the beginning.
For those partitioned tables which contain unimplemented features, TiDB parses the SQL but ignores its partition attributes, regards the table as a normal one.
Compatibility
In the old version, TiDB parses create table ... partition by ... and handles it as a normal table; the partition by ... option is discarded.
Now that table partition is added, and we have to consider the following cases:
- New TiDB runs on the old cluster data
- Old TiDB runs on the new cluster data
- The upgrading phases during part of the features is implemented
A new PartitionInfo.Enable flag is introduced to the TableInfo, and it's persisted.
New TiDB running on the old cluster will check this flag and find PartitionInfo.Enable is false, so it handles the table as before.
Old TiDB will not be able to run with partitioned table data, so the upgrading is incompatible. (Note that if no partitioned table is created with the new TiDB, i.e, the feature is not used, the cluster is still able to be degraded)
If partition by range is implemented while partition by hash is not, TiDB will not set PartitionInfo.Enable to true for create table ... partition by hash ..., but it set PartitionInfo.Enable to true for create table ... partition by range ....
In a word, only when the persisted PartitionInfo.Enable is true, and the code could handle partitioned table, will the table partition feature be supported.
Implementation
How the partitioned table is stored
There are two levels of mapping in TiDB: SQL data to a logical key range, logical key range to the physical storage.
When TiDB maps table data to key-value storage, it first encodes table id + row id as key, row data as value. Then the logical key range is split into regions and stored into TiKV.
Table partition works on the first level of mapping, partition ID will be made equivalent of the table ID. A partitioned table row uses partition id + row id as encoded key. Partition ID is unique in cluster scope.
The relationship of Table ID and partition ID should be maintained in the TableInfo.
When a new row is inserted into a partitioned table, if the row doesn't belong to any partition of the table, the operation fails.
Refer to the MySQL document https://dev.mysql.com/doc/refman/8.0/en/partitioning-handling-nulls.html for handling NULL values.
How to read from the partitioned table
create table t (id int) partition by range (id)
(partition p1 values less than (10),
partition p2 values less than (20),
partition p3 values less than (30))This SQL query
select * from tis equal to
select * from (union all
select * from p1 where id < 10
select * from p2 where id < 20
select * from p3 where id < 30)During logical optimize phase, the DataSource operator is translated into UnionAll operator, and then each partition generates its own TableReader in the physical optimize phase.
The drawbacks of this implementation are:
- If the table has many partitions, there will be many readers, then
explainresult is not friendly to user - The
UnionAlloperator can't keep order, so if some operator need ordered result such asIndexReader, an extraSortoperator is needed
If partition selection is used, planner should translate table ID to partition ID, and turn off partition pruning.
Partition pruning
During logical optimization phase, after predicate push down, partition pruning is performed.
For range partition, partition pruning is based on the range filter conditions of the partition column. For hash partition, if the filter condition is something like key = const, partition pruning could work.
How to write to the partitioned table
All the write operations call functions like table.AddRecord eventually, so implement write operation on a partitioned table simply implements this interface method on the PartitionedTable struct.
PartitionedTable implements the table.Table interface, and overloads the AddRecord method. It also comes with a locatePartition method, to decide which partition a row should be insert into.
Each partition maintains its own index data, and the insert operation should keep data and index consistent.
DDL operations
DROP/TRUNCATE/ADD, those three operations works on range partition.
DROP PARTITION is similar to DROP TABLE, except that partition ID is used. TableInfo should be updated after the drop partition operation. Note that if one wants to drop the last partition in a table, he should use drop table rather than drop partition.
Trancate partition truncates all data and indexes in a partition, but keeps the partition itself.
Partition management
There are many statements for partition management, but the current implementation could just parse the SQL and ignore them.
ALTER TABLE ... REBUILD PARTITION ...
ALTER TABLE ... OPTIMIZE PARTITION ...
ALTER TABLE ... ANALYZE PARTITION ...
ALTER TABLE ... REPAIR PARTITION ...
ALTER TABLE ... CHECK PARTITION ...
ALTER TABLE ... DROP/TRUNCATE PARTITION
ALTER TABLE ... ADD PARTITION
SHOW CREATE TABLE
SHOW TABLE STATUS
INFORMATION_SCHEMA.PARTITIONS tableLimitations
Refer to MySQL https://dev.mysql.com/doc/refman/5.7/en/partitioning-limitations.html
The partition key cannot be an integer column, or an expression which resolves to an integer (or NULL).
The partition key must not be a subquery, even a subquery which resolves to an integer.
The maximum partitions count of a table is 8192 in MySQL, but 1024 in TiDB.
Functions allowed in partition expressions https://dev.mysql.com/doc/refman/5.7/en/partitioning-limitations-functions.html
Open issues (if applicable)
https://github.com/pingcap/tidb/issues/7516
Design 2018 10 20 Join Reorder Dp V1 (`docs/design/2018-10-20-join-reorder-dp-v1.md`)
Proposal: Join Reorder Design v1
- Author: Yiding CUI
- Last updated: 2018-10-20
Abstract
This proposal proposes to improve TiDB’s join reorder algorithm when join size is not large.
Background
Currently, TiDB’s join reorder algorithm is introduced before we have CBO. This algorithm is very simple and doesn’t work well in many scenarios.
Proposal
I’ve explored the join reorder algorithms of Orca, Calcite, Spark, MySQL and Postgres. Using DP when the number of nodes are small is an operable strategy.
I implemented two DP algorithms. You can find them here. DP-CPP is introduced in this paper.
My experiment result shows that DP-CCP only has a better performance than DP-SUB when the input is list and circle. It cannot beat the DP-SUB when input is star and clique. This is different with the experiment result posted in the paper. The main reason is that maintaining histograms of join online is very costly. If we use 1μs to get the statistics of one join, the most costly part of star graph will be statistics.
So I suggest using DP-SUB as the first version of join reorder since the performance of DP-CCP is not good enough.
The core DP-SUB algorithm is like the following code, a complete implementation is here:
func dp(int nodeCnt) {
for i := 0; i < nodeCnt; i++ {
bestPlan[1 << i] = planByNodeID[i]
bestCost[1 << i] = 0
}
// Iterate the sub from small to big.
// This can make sure that node set S1 is visited earlier than S2 if S1 belongs to S2.
for state := 1; state < (1 << nodeCnt); state++ {
if bits.OnesCount(i) == 1 || (nodeCnt not connected) {
continue // It’s a single node or not connected, skip it;
}
// This loop can enumerate all its subset.
for sub := (state - 1) & state; sub > 0; sub = (sub - 1) & state {
// Inner join’s left and right have no difference, so we only consider it once.
if sub > remain {
continue
}
// That the dp result is nil means the subset is not connected.
if bestPlan[sub] == nil || bestPlan[state ^ sub] == nil {
continue
}
join := buildJoin(bestPlan[sub], bestPlan[state^sub], edges between them)
if bestCost[state] > join.Cost {
bestPlan[state] = join
bestCost[state] = join.Cost
}
}
}
}Here the set of node is shown as an integer. If the i-th bit of its binary representation is 1, the i-th node will be in this set.
Rationale
How other systems solve the same issue?
DP-SUB is the most commonly used solution in open source databases.
What is the disadvantage of this design?
DP-SUB is hard to prune invalid branches.
And it’s a little hard to enlarge its search space to involve the outer join efficiently.
In a word, DP-SUB cannot be extended easily. The next version of our join reorder will be very likely a new one instead of enhancing DP-SUB.
Compatibility
There’s no compatibility issue.
Implementation
First, extract the join nodes. If the number of nodes is less than x, we go into DP-SUB.
For DP-SUB:
- Enlarge its edges by constant propagation. i.e. If we have
t1.a=t2.a and t2.a=t3.a, we should gett1.a=t3.a. - Number join node from 0 to n. Construct a hash map
pair<int, int> to join key filters. - Do the core dp algo.
- Get the final result.
- Note that we can ignore the
OtherConditionin TiDB since we cannot calculate the selectivity of it. It won’t influence the join reorder’s estimation.
PR#8025 contains step 3 and 4. Step 2 is done when extract the join group. Step 1 and 5 will be involved in the future pull request.
Future
DP-CPP has the ability to prune branches and has an enhanced version involving outer join, semi join and aggregation. You can find it here.
There’s also one way called transformation based join reorder. The benefit of it is that it can be easily involved in Cascade-like optimizer, and can be easily integrated with other rules. Branch pruning will be done by planner not this reorder algorithm itself.
Design 2018 10 22 The Column Pool (`docs/design/2018-10-22-the-column-pool.md`)
Proposal: Support a Global Column Pool
- Author(s): zz-jason
- Last updated: 2018-10-22
- Discussion at:
Abstract
This proposal is aimed to enable a fine-grained buffer reuse strategy. With the
help of the proposed column pool, we can:
- Reduce the total memory consumption during the execution phase.
- Support column-oriented expression evaluation and leverage the power of
vectorized expression execution.
Background
At present, the buffer reuse is in the granularity of Chunk. The disadvantages
of this Chunk-oriented reuse strategy are:
This buffer reuse strategy isn't effective in some scenarios. Some memory
hold by the operators which are inactive can also be reused to reduce total
memory consumption when executing a query.In order to reuse a Chunk, we have to design the resource recycling strategy
for every operator which uses multiple goroutines to exploit the
thread-level parallelism. For example, hash join. It makes the code more
complicated and harder to be maintained.The memory used in the current query can not be reused in the next query
within the same session. Thus the golang GC pressure is increased and the
OLTP performance on a TiDB server is impacted.
Proposal
The main idea of this proposal is to change the Chunk-oriented buffer reuse
strategy to Column-oriented and use a session-level column pool to achieve
that.
The column pool
Considering that the current TiDB only supports a limited number of types, we
only need to consider 5 kinds of columns:
- 4 fixed length columns: 4/8/16/40
- 1 variable length column
The column pool can be accessed by multiple goroutines concurrently, and to
reduce the lock conflict, we can split the pool into shards and randomize the
target shard in each Put/Get operation. Each shard of a column pool is
implemented as a last in first out stack, which helps to release the unused
column in the pool. And in most cases, the required length of a new column is
equal to the previous column put into the column pool.
Rationale
No
Compatibility
No
Implementation
- Implement the column pool firstly.
- Remove the complicated, error-prone resource recycling strategy for each
operator. - Replace each NewChunkWithCapacity() with pool.GetChunk().
Open issues (if applicable)
No
Design 2018 10 24 View Support (`docs/design/2018-10-24-view-support.md`)
Proposal: Implement View Feature
- Author(s): AndrewDi
- Last updated: 2018-12-03
- Discussion at: https://github.com/pingcap/tidb/issues/7974
Abstract
This proposal proposes to implement basic VIEW feature in TiDB, aimed to make SQL easier to write. VIEW's advanced feature would be considered later.
Background
A database view is a searchable object in a database that is defined by a query. Though a view doesn’t store data, some refer to a VIEW as "virtual tables", and you can query a view like you can query a table. A view can combine data from two or more tables, using joins, and also just contain a subset of information. This makes them convenient to abstract, or hide, complicated queries.
Below is a visual depiction of a view:
reference from https://www.essentialsql.com/what-is-a-relational-database-view/
A view is created from a query using the "CREATE OR REPLACE VIEW" command. In the example below we are creating a PopularBooks view based on a query which selects all Books that have the IsPopular field checked. Following is the query:
CREATE OR replace VIEW popularbooks
AS
SELECT isbn,
title,
author,
publishdate
FROM books
WHERE ispopular = 1Once a view is created, you can use it as you query any table in a SELECT statement. For example, to list all the popular book titles ordered by an author, you could write:
SELECT Author, Title FROM PopularBooks ORDER BY AuthorIn general you can use any of the SELECT clauses, such as GROUP BY, in a select statement containing a view.
Proposal
This proposal is prepared to implement the basic VIEW feature, which contains following ddl operations:
CREATE OR REPLACE VIEWSELECT FROM VIEWDROP VIEWSHOW TABLE STATUS
All other unimplemented features will be listed for compatibility and discussed later. And we introduce ViewInfo to store the metadata for view and add an attribute *ViewInfo which named View to TableInfo. If TableInfo.View != nil, then this TableInfo is a view, otherwise this TableInfo is a base table:
type ViewInfo struct {
Algorithm ViewAlgorithm `json:"view_algorithm"`
Definer UserIdentity `json:"view_definer"`
Security ViewSecurity `json:"view_security"`
SelectStmt string `json:"view_select"`
CheckOption ViewCheckOption `json:"view_checkoption"`
Cols []model.CIStr `json:"view_cols"`
}- Algorithm
The view SQLAlGORITHMcharacteristic. The value should be one ofUNDEFINED,MERGEORTEMPTABLE. If noALGORITHMclause is present,UNDEFINEDis the default algorithm.
Currently, we will only implement theMERGEalgorithm. - Definer
The account of the user who created the view, in'user_name'@'host_name'format. - Security
The view SQLSECURITYcharacteristic. The value is one ofDEFINERorINVOKER. - CheckOption
TheWITH CHECK OPTIONclause can be given to an updatable view to prevent inserts to rows for which theWHEREclause in the select_statement is not true. It also prevents updates to rows for which theWHEREclause is true but the update would cause it to be not true (in other words, it prevents visible rows from being updated to nonvisible rows).
In aWITH CHECK OPTIONclause for an updatable view, theLOCALandCASCADEDkeywords determine the scope of check testing when the view is defined in terms of another view. When neither keyword is given, the default isCASCADED. - SelectStmt
This string is the originSELECTSQL statement. - Cols
Thismodel.CIStrarray stores view's column alias names. - TableInfo.Columns
TableInfo.Columnsonly stores view's column origin names.
Rationale
- Create VIEW
This proposal only supports the following grammar to create view:sqlCREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = { user | CURRENT_USER }] [SQL SECURITY { DEFINER | INVOKER }] VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION]- Parse the create view statement and build a logical plan for select clause part. If any grammar error occurs, return errors to parser.
- Examine view definer's privileges. Definer should own both
CREATE_VIEW_PRIVprivilege and base table'sSELECTprivilege. We will reuseCREATE_PRIVprivilege when implementCREATE VIEWfeature and will supportCREATE_VIEW_PRIVcheck later. - Examine create view statement. If the
ViewFieldListclause part is empty, then we should generate view column names from SelectStmt clause. Otherwise check len(ViewFieldList) == len(Columns from SelectStmt). And then we save column names toTableInfo.Columns.
- DROP VIEW
ImplementDROP VIEWgrammar, and delete the existing view tableinfo object. This function should reuseDROP TABLEcode logic. - SELECT FROM VIEW
In functionfunc (b *PlanBuilder) buildDataSource(tn *ast.TableName) (LogicalPlan, error), iftn *ast.TableNameis a view, then we build a selectLogicalPlanfrom view'sSelectStmtstring. But this solution meets a problem, and here is the example:Once we query from viewsqlcreate table t(a int,b int); create view v like select * from t; select * from t;v, database will rewrite view'sSelectStmtfromselect * from tintoselect a as a,b as b from t.
But, if we alter the schema of t like this:Executingsqldrop table t; create table t(c int,d int);select * from vnow is equivalent toselect c as c, d as d from t. The result of this query will be incompatible with the character of VIEW that a VIEW should be "frozen" after being defined.
In order to solve the problem described above, we must build aProjectionat the top of original select'sLogicalPlan, just like we rewrite view'sSelectStmtfromselect * from tintoselect a as a,b as b from (select * from t).
This is a temporary fix and we will implement TiDB to rewrite SQL with replacing all wildcard finally. - Show table status
ModifySHOW TABLE STATUSfunction to support show view status, and we use this command to check ifCREATE VIEWandDROP VIEWoperation is successful. To reuseSHOW TABLE STATUScode logic is preferred.
Compatibility
Support the basic VIEW feature without affecting other existing functions, and make TiDB more compatible with MySQL.
Implementation
Here is the work items list:
| Action | Priority | Deadline | Notes |
|---|---|---|---|
| Extract ViewAlgorithm\ViewDefiner\ViewSQLSecurity\CheckOption to CreateViewStmt struct | P1 | 2019/01/15 | -- |
| Add ViewInfo attribute to TableInfo and add ActionCreateView to ddl actionMap | P1 | 2019/01/15 | -- |
| CREATE [OR REPLACE] VIEW view_name [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [(column_list)] AS select_statement | P1 | 2019/01/15 | This task must be done before any other tasks. |
| SHOW TABLE STATUS | P1 | 2019/01/30 | -- |
| DROP VIEW View | P1 | 2019/01/30 | -- |
| SELECT … FROM VIEW | P1 | 2019/03/10 | -- |
| Add some test cases for CreateView and Select … From View | P1 | 2019/03/30 | Port from MySQL test case |
| Support CREATE_VIEW_PRIV check | P2 | ||
| UPDATE VIEW | P2 | Difficult | |
| INSERT VIEW | P2 | Difficult, dependent on UPDATE VIEW | |
| SHOW CREATE [VIEW | TABLE] | P2 | ||
| ALTER VIEW | P2 | ||
| ALTER | DROP TABLE | P2 | Check if table is a View | |
| Add test cases for UPDATE | INSERT INTO View | P2 | ||
| Add INFORMATION_SCHEMA.VIEWS view | P3 | ||
| CREATE [OR REPLACE] VIEW [DEFINER = { user | CURRENT_USER }] [SQL SECURITY { DEFINER | INVOKER }] AS SELECT_STATEMENT | P3 | ||
| CREATE [OR REPLACE] VIEW [ALGORITHM = {TEMPTABLE}] AS select_statement | P3 | ||
| CREATE [OR REPLACE] VIEW AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION] | P3 | ||
| Support global sql_mode system variable | P3 |
Open issues (if applicable)
https://github.com/pingcap/tidb/issues/7974
Design 2018 10 31 Window Functions (`docs/design/2018-10-31-window-functions.md`)
Proposal: Support Window Functions
- Author(s): Haibin Xie
- Last updated: 2018-10-31
- Discussion at:
Abstract
This proposal aims to support the window functions. Window functions are a widely used feature, so after supporting it, TiDB will be more friendly to users.
Background
A window function calculates results for each row using rows related to it. Let's first take an example to get a concrete feeling:
MySQL [test]> select a, b, sum(b) over(partition by a) as 'sum', avg(b) over(partition by a order by b rows between 1 preceding and 1 following) as 'avg' from t;
+------+------+------+--------+
| a | b | sum | avg |
+------+------+------+--------+
| 1 | 1 | 10 | 1.5000 |
| 1 | 2 | 10 | 2.0000 |
| 1 | 3 | 10 | 3.0000 |
| 1 | 4 | 10 | 3.5000 |
| 2 | 5 | 26 | 5.5000 |
| 2 | 6 | 26 | 6.0000 |
| 2 | 7 | 26 | 7.0000 |
| 2 | 8 | 26 | 7.5000 |
+------+------+------+--------+
8 rows in set (0.01 sec)We can see that different from normal aggregate functions, window functions produce results for each query row. It can also allow users to specify the rows that are used to calculate results, like the case of avg.
A window specification is composed of three optional parts:
partition clause: Partition clause is used to divide query rows into partitions. Each row can only use the rows within the same partition to calculate the result.
order clause: Order clause is used to sort the rows in a partition. It is important for window functions that need order, like
RANK.frame clause: Frame clause defines the subsets of a partition. Most window functions operate on the frame of the current row. However, some functions that only operate on the partition will ignore the frame clause, like
ROW_NUMBER.
Proposal
From the above description, we can know that in order to support window functions, the most important part is organizing the rows according to window specification. In the following parts, the proposal will introduce how to organize rows for a window function and how to optimize the execution order of multiple window functions.
Organize rows for a window function
Let's first take a look at the partition clause and order clause. The simplest way to meet the specification is to sort the rows by combining the two clauses. We can put a Sort operator below the window function. Also, the Sort operator may be removed by the optimizer.
However, we do not need to keep the partitions ordered. So another way is first hashing rows into different partitions, and then performing sorts within each partition.
For frame clause, MySQL does not support dynamic frame endpoints that depend on the value of the current row. This means that, for each row in the partition, the endpoints of the current row will not go backward compared with the previous row. So for each function, it only needs to support operations like pop front, push back and evaluate.
Optimize window functions order
For multiple window functions in the same query, it is important to optimize the order to reduce the number of data reorganizations. For example, if we have three window functions that need to be ordered by (a, b, c), (a, c) and (a,b), then it is better to order them as (a, b, c), (a, b) and finally (a,c). Also, when organizing the rows for (a,c), we can only partially sort on c.
If we only support partition by sorting, the simplest way is to sort the window functions by partition clause and order clause, so that the window function with the same prefix will be at near places.
If we also support partition by hashing, then finding the optimal order turns out to be an NP-hard problem. If the number of window functions is small, we can use a DP algorithm, like the join reorder problem. If the number of window functions is large, we can only use some heuristic algorithm. For example, we can first use some rules to build a partial order for two window functions, and then perform a topo-sort on the partial order graph to get the final order.
Rationale
Window functions have been supported in a number of database systems. Without it, our users have to use some workarounds to get the same result, which is both inefficient and error-prone.
Compatibility
Yes, this proposal makes TiDB more compatible with MySQL 8.0.
Implementation
We can split the implementations into two stages: the first stage to support the window function, but using the easiest way; the second stage to optimize the window function execution cost.
In this first stage, we can support the grammar and functions for window functions and using the Sort operator to organize rows. For multiple window functions, we do not optimize their order and execute them one by one. We should also add tests as many as possible in this stage.
In the second stage, we can mainly focus on the optimization of the window functions. We can first merge the execution of window functions with the same specification. After that, we will support partition by hashing to organize the rows. Finally, we can try to optimize the window functions execution order to reduce the data reorganization cost.
Open issues (if applicable)
Design 2018 11 29 Ast To Sql Text (`docs/design/2018-11-29-ast-to-sql-text.md`)
Proposal: Support restoring SQL text from an AST tree.
- Author(s): Yilin Zhao
- Last updated: 2018-12-05
- Discussion at: https://github.com/pingcap/tidb/issues/8532
Abstract
This proposal aims to support restoring SQL text from any ast.Node.
Background
Some new features in TiDB need all the ast.Node to be restorable to SQL text.
For example, we parse the create view v as select * from t; SQL statement to an AST,
and then expand select of the AST to select test.t.col0, test.t.col1 from test.t;.
The structure of an ast.Node is shown in the following picture (taking ast.CreateUserStmt as an example).
We know there is a Text() method of ast.Node,
in which the parser calls the SetText() method during the parsing process,
and then we can call Text() to get the original input SQL statement.
But the Text() method is incomplete, and only Text() of root nodes can work well.
We should not use it when implementing this proposal.
Proposal
I recommend adding a Restore() method to ast.Node. This is the function defined:
type Node interface {
// Restore AST to SQL text and append them to `ctx`.
// return error when the AST is invalid.
Restore(ctx *RestoreCtx) error
...
}In order to output the SQL text in different formats, I introduced nine flags. There are mutually exclusive groups of RestoreFlags:
[RestoreStringSingleQuotes, RestoreStringDoubleQuotes]
[RestoreStringEscapeBackslash]
[RestoreKeyWordUppercase, RestoreKeyWordLowercase]
[RestoreNameUppercase, RestoreNameLowercase]
[RestoreNameDoubleQuotes, RestoreNameBackQuotes]
The flag in the left position in each group has a higher priority.
This is RestoreCtx struct and DefaultRestoreFlags definition:
// RestoreCtx is Restore context to hold flags and writer
type RestoreCtx struct {
Flags RestoreFlags
In io.Writer
}
const DefaultRestoreFlags = RestoreStringSingleQuotes | RestoreKeyWordUppercase | RestoreNameBackQuotesRationale
We know the AST is a kind of tree whose child node is corresponding to SQL text.
So we can walk through the AST layer by layer, call Restore() of each child node recursively and
splice SQL text according to AST node.
There is the AST parsed from SELECT column0 FROM table0 UNION SELECT column1 FROM table1 WHERE a = 1.
We can splice SQL text as the picture shows.
Compatibility
The AST and SQL text are in a one-to-many relationship, so we can't restore completely equal SQL text.
We only need to ensure that the ASTs parsed from the input SQL statement and the restored SQL statement are equal.
Implementation
Stage
Considering that some ast.Node depends on another ast.Node, we divide sub-tasks into four stages.
Detailed list at pingcap/tidb#8532.
Example
I implemented the Restore function of ast.CreateDatabasesStmt
and ast.DropDatabaseStmt for examples.
// Restore implements Node interface.
func (n *DatabaseOption) Restore(ctx *RestoreCtx) error {
switch n.Tp {
case DatabaseOptionCharset:
ctx.WriteKeyWord("CHARACTER SET")
ctx.WritePlain(" = ")
ctx.WritePlain(n.Value)
case DatabaseOptionCollate:
ctx.WriteKeyWord("COLLATE")
ctx.WritePlain(" = ")
ctx.WritePlain(n.Value)
default:
return errors.Errorf("invalid DatabaseOptionType: %d", n.Tp)
}
return nil
}// Restore implements Node interface.
func (n *DropDatabaseStmt) Restore(ctx *RestoreCtx) error {
ctx.WriteKeyWord("DROP DATABASE ")
if n.IfExists {
ctx.WriteKeyWord("IF EXISTS ")
}
ctx.WriteName(n.Name)
return nil
}There is another example which includes complete implementation and test:
parser#71
Note
Don't depend on
exprNode.Format()Don't depend on
node.Text()
Open issues
https://github.com/pingcap/tidb/issues/8532
Design 2018 12 10 Plugin Framework (`docs/design/2018-12-10-plugin-framework.md`)
Proposal: Support Plugin
- Author(s): lysu
- Last updated: 2018-12-10
- Discussion at:
Abstract
This proposal proposes to introduce the plugin framework to TiDB to support TiDB plugin development.
Background
Many cool customized requirements need to be addressed but it is not convenient to merge them into the main TiDB repository. In addition, Go 1.9+ introduces the new plugin support, so we can add a plugin framework to TiDB to make those requirements addressed, and attract more people to build the TiDB ecosystem together.
Proposal
Add a plugin framework to TiDB.
Rationale
Adding the plugin framework is based on Go's plugin support, but this framework supports uniform plugin manifest, package, and flexible SPI.
The plugin developer can build a TiDB plugin in 7 steps:
- Choose an exists plugin kind or create new plugin kind if not exists
- Create a normal go package, and add
manifest.tomllike example one. - Implement the
validate,init,destroymethods, which are needed for all plugins. - Implement the kind special method to implement the plugin logic.
- Use
cmd/pluginpkgto build plugin binary, and put the plugin binary into the plugin deployment folder. - Start TiDB with the
-plugin-dirand-plugin-loadparameters. - Run
show pluginto check it's load status.
Implementation
Go Plugin
We build the plugin framework based on Go's plugin support. At first, let's see "what is Go's plugin supported?"
Go's plugin support is simple, just as the document at https://golang.org/pkg/plugin/. We can build and use the plugin in three steps:
- Build the plugin via
go build -buildmode=pluginin themainpackage to make plugin.so. - Use
plugin.Opentodlopenthe plugin's.so. - Use
plugin.Lookuptodlsymto find the symbol in the plugin.so.
There is another "undocumented" but important concept: pluginpath. Just as previously said we let our plugin code into the main package and then go build -buildmode=plugin to build a plugin. pluginpath is the package path for a plugin after plugin packaged. For example, we have a method named DoIt and pluginpath be pkg1, and then we can use nm to see the method name be pluginpath.DoIt.
pluginpath can be given by -ldflags -pluginpath=[path-value] or generated by go build(for 1.11.1, it is the package name if pluginpath is built with the package folder or a content hash if built with the source file).
If we load a Go plugin with the same pluginpath twice, the second Load call will get an error, Go plugin use pluginpath to detect duplicate load.
The last thing we need to care about is the Go plugin's dependence. At first, almost all plugins need to depend on TiDB code to do its logic. Go runtime requires that the runtime hash and the link time hash for the dependence package are equal. So we do not need to care about the plugin that depends on some TiDB component. But TiDB code changes, so we need to release a new plugin whenever a TiDB new version is released.
TiDB Plugin
Go plugin gives us a good start point, but we need to do something more to let the plugin be more uniform and easy to use with TiDB.
Manifest
Go Plugin gives us the ability to open a shared library. We need some meta info to self-describe the plugin, and then TiDB can know how to work with the loaded library. The information we need is as follows:
- Plugin name: we need to reload the plugin, so we need to load the same plugin with a different version that is at a much higher level than
pluginpath. - Plugin version: plugin version makes it much easier to maintain.
- Simple Dependence check: Go helps to use a check to build the version, but in the real world it is common that a plugin relies on b plugin's some new logic. We try to maintain a simple Required-Version relationship between different plugins.
- Configuration: the plugin is a standalone module, so every plugin will introduce special sysVars just like normal MySQL variables. A user can use those variables to tweak plugin behaviors just like normal MySQL variables do.
- Stats: the plugin will introduce new stats info. TiDB uses Prometheus, so the plugin can easily push metrics to Prometheus.
- Plugin Category and Flexible SPI: TiDB can have limited plugin categories, a new plugin need choose a category and implement SPI defined by those category.
All of above construct the plugin metadata which we usually call Manifest. Manifest describes the metadata and how others can use the plugin.
We just use the Go plugin mechanism to load the TiDB plugin and the TiDB plugin gives us a Manifest. Then just use manifest to interact with the plugin. (Only load/lookup is heavy CGO call, and later call manifest is normal Golang method call.)
SPI
The SPI (Service Provider Interface) for the plugin is the method that returns manifest and the manifest info itself. The method that returns manifest can be generated by pluginpkg, so implementing SPI work for the developer is to choose and construct different manifest info (pluginpkg also helps with this).
Manifest is the base struct for all other sub manifests. The caller can use Kind and DeclareXXManifest to convert them to sub manifests.
Manifest provides common metadata:
- Kind: the plugin's category. Now we have the audit kind, authentication kind, and so on. It's easy to add more.
- Name: name of the plugin, which is used to identify a plugin, so it cannot duplicate with other plugins.
- Version: we can load multiple versions a plugin into TiDB, but just activate one of them to support hot-fix or hot-upgrade.
- RequireVersion: it will make a simple relationship between different plugins.
- SysVars: it defines the plugin's configuration info.
Manifest also provides three lifecycle extension points:
- Validate: called after loading all plugins but before onInit, so it can do cross plugins check before init.
- OnInit: plugin can prepare resource before real work using OnInit.
- OnShutDown: plugin can clean up its resources before dying using OnShutDown.
So we can image a common manifest code like this:
type Manifest struct {
Kind Kind
Name string
Description string
Version uint16
RequireVersion map[string]uint16
License string
BuildTime string
SysVars map[string]*variable.SysVar
Validate func(ctx context.Context, manifest *Manifest) error
OnInit func(ctx context.Context) error
OnShutdown func(ctx context.Context) error
}Base on Kind, we can define other subManifest for authentication plugin, audit plugin and so on.
Every subManifest will have a Manifest anonymous field as the FIRST field in struct definition, so every subManifest can be used as Manifest (by unsafe.Pointer cast). For example, an audit plugin' manifest will be like this:
type AuditManifest struct {
Manifest
NotifyEvent func(ctx context.Context) error
}The reason we chose the embedded struct + unsafe.Pointer cast instead of the interface way here is that the first way is more flexible and more efficient to access data member than the fixed interface. At last, we also provide the package tools and a helper method to hide those details from the plugin developer.
Package tool
In this proposal, we add a simple tool cmd/pluginpkg to help package a plugin, and also uniform the package format.
Plugin's development event no longer needs to care about previous Manifest and so on, so the developer can just provide a manifest.toml configuration file like this in the package:
name = "conn_ip_example"
kind = "Audit"
description = "just a test"
version = "2"
license = ""
sysVars = [
{name="conn_ip_example_test_variable", scope="Global", value="2"},
{name="conn_ip_example_test_variable2", scope="Session", value="2"},
]
validate = "Validate"
onInit = "OnInit"
onShutdown = "OnShutdown"
export = [
{extPoint="OnGeneralEvent", impl="OnGeneralEvent"}
]name: name of the plugin. It must be unique in the loaded TiDB instance.kind: kind of plugin. It determines the call-point in TiDB. The package tool is also based on it to generate a different manifest.version: the version of a plugin. For the same plugin, the same version is only loaded once.description: description of plugin usage.license: license of the plugin, which will display inshow plugins.sysVars: it defines the variable needed by this plugin with name, scope and default value.validate: it specifies the callback function used to validate before load, e.g. auth plugin check-with-skip-grant-tablesconfiguration.onInit: it specifies the callback function used to init plugin before it joins real work.onShutdown: the callback function will be called when the plugin shuts down to release outer resource held by the plugin, normally TiDB shutdown.export: it defines the callback list for the special kind plugins, e.g. for auth plugin it uses aNotifyEventmethod to implement thenotifyEventextension point.
pluginpkg generates code and the generated code is built as a Go plugin, and using plugin package we also control the plugin binary's format:
- The plugin file name is
[pluginName]-[version].so, so we can know the plugin's version from the filename. pluginpathwill be[pluginName]-[version], and then we can load the same plugin of a different version in the same host program.- The package tool also adds some build time and misc info into Manifest info.
Package tools add an abstract layer over manifest, so we can change manifest easier in future if needed.
Plugin Point
In TiDB code, we can add a new plugin point everywhere and:
- Call
plugin.GetByKindorplugin.Getto find matched plugins. - Call
plugin.Declare[Kind]Manifestto cast Manifest to a special kind. - Call the extension point method for special manifest.
We can see a simple example in clientConn#Run and conn_ip_example plugin implementation.
Adding the new plugin point needs to modify the TiDB code and pass the required context and parameters.
Configuration
Every plugin has its own configurations. TiDB plugin uses system variables to handle configuration management requirement.
In manifest.toml, we can use the sysVar field to provide plugin's variable name and its default value. Plugin's system variable will be registered as TiDB system variable, so the user can read/modify variable just like normal system variables.
Plugin's variable name must use plugin name as the prefix. At last, the plugin cannot be reloaded if we change the plugin's sysVar (include default-value, add or remove variable).
We implement it by adding the plugin variable into variable.SysVars before bootstrap, so later doDMLWorker will handle them just as normal sysVars, and change loadCommonGlobalVarsSQL to load them. (that it cannot unload plugin and cannot modify sysVar during reload makes this implementation easier)
Dependency
Go's plugin mechanism will check all dependency package hash to ensure link time and run time use the same version(see code), so we no longer need to care about compiling package dependency.
But for the real world, there may be logic dependency between plugins. For example, some guy writes an authorization plugin but it relies on vault plugin and only works when vault is enabled but does not directly rely on the vault plugin's source code.
In manifest.toml, we can use requireVersion to declare A plugin requires B plugin in X version, and then plugin runtime will check it during the load or reload phase.
Reload
Go plugin doesn't support unloading a plugin, but this cannot stop us from loading multiple versions of the plugin into the host program and framework, to ensure the last reloaded one will be active, and others aren't unloaded but disabled.
So, we can reload the plugin with a different version that is packaged by pluginpkg to modify the plugin's implementation logic. Although we can not change the plugin's meta info (e.g. sysVars) now, it's still useful.
Management
To add a plugin to TiDB, we need to:
- Add
-plugin-diras the start argument to specify the folder containing plugins, e.g. '-plugin-dir=/data/deploy/tidb/plugin'. - Add
-plugin-loadas the start argument to specify the plugin id (name "-" version) that needs to be loaded, e.g. '-plugin-load=conn_limit-1'.
Then starting TiDB will load and enable plugins.
We can see all the plugins info by:
mysql> show plugins;
+-----------------+--------+-------+----------------------------------------------------+---------+---------+
| Name | Status | Type | Library | License | Version |
+-----------------+--------+-------+----------------------------------------------------+---------+---------+
| conn_limit-1 | Ready | Audit | /data/deploy/tidb/plugin/conn_limit-1.so | | 1 |
+-----------------+--------+-------+----------------------------------------------------+---------+---------+
1 row in set (0.00 sec)To reload a loaded plugin, just use
mysql> admin plugins reload conn_limit-2;Limitations
The TiDB plugin has the following limitations:
- The plugin cannot be unloaded. Once the plugin is loaded into TiDB, it can never be unloaded until the server is restarted, but we can reload the plugin in the limited situation to the hotfix plugin bug.
- Read sysVars in OnInit will get unexpected value but can access
Manifestto get the default config value. - Reloading cannot change the sysVar's default value or add/remove the variable.
- Building the plugin needs the TiDB source code tree, which is different from MySQL that can build plugin standalone (expect Information Schema and Storage Engine plugins)
- The plugin can only be written in Go.
Design 2018 12 11 Sql Plan Management (`docs/design/2018-12-11-sql-plan-management.md`)
Proposal: Support SQL Plan Management
- Author(s): Haibin Xie
- Last updated: 2018-12-11
- Discussion at:
Abstract
This proposal aims to support the SQL plan management. With the help of it, we can force the optimizer to choose a certain plan without modifying the SQL text.
Background
The optimizer chooses a plan based on several environmental factors, such as statistics, optimizer parameters, schema definitions and so on. Once the environment changes, we cannot guarantee that the newly optimized plan is always better than the old plan. Therefore we need to provide ways to bind the plan for applications that cannot take the risk of a changed plan.
Proposal
The following proposal mainly focuses on two parts: how to bind the plan and what is the syntax to manage it.
How to bind the plan
In order to bind the plan, we need to maintain a mapping from normalized SQL text to plan. To normalize the SQL text, we can remove all the blank space, replace the parameters with placement markers, and convert remaining parts to lower cases. The most difficult problem is how we represent and store the plan.
One way to represent the plan is using the optimized physical plan. However, it is difficult to perform the parameters replacement for later SQLs, because some parameters may already be rewritten in the optimized physical plan when doing logical and physical optimizations.
Since the parameters replacement is hard, it is better not doing it. Another way to represent the plan is using the AST of hinted SQL, so the only thing needs to do for later SQLs is to traverse the AST and copy hints.
Syntax to manage the binding plan
To manage the SQL bindings, we need to support basic operations like create, show and drop. We can also support SQL bindings that only exist in the current session. The syntax will be like the following:
- CREATE [GLOBAL|SESSION] BINDING_NAME BINDING FOR
SQLUSINGHINTED SQL - DROP [GLOBAL|SESSION] BINDINGS
- DROP [GLOBAL|SESSION] BINDING BINDING_NAME
- SHOW [GLOBAL|SESSION] BINDINGS [SHOW_LIKE_OR_WHERE]
Rationale
In Oracle, they only store the hints of the optimized query, instead of the whole AST. For TiDB, it requires more work to do it now because we need to generate unique identifiers for the subqueries and lift all hints to the outer most queries. Storing the AST is the simplest way now.
Compatibility
MySQL does not support SQL plan management, so this will add syntaxes that not supported by MySQL.
Implementation
To implement it, we need the following main steps:
- Normalize the SQL text. We can take this https://github.com/pingcap/parser/pull/32 as an example.
- Support the syntax in the parser.
- Store the binding SQL and AST of the hinted SQL in a system table. Since there is a unique mapping from SQL text to AST, we can just store the SQL and parse it to AST for later use. A background goroutine will check if there are new bindings and update the local cache.
- When another SQL comes, we first check if there is a matched SQL in the cache. If so, we can traverse the AST to add hints. Since comparing text for every SQL may affect unrelated SQLs a lot, we can calculate a hash value and first check if there is matching hash values.
Open issues (if applicable)
Design 2019 01 25 Skyline Pruning (`docs/design/2019-01-25-skyline-pruning.md`)
Proposal: Support Skyline Pruning
- Author(s): Haibin Xie
- Last updated: 2019-01-25
- Discussion at:
Abstract
This proposal introduces some heuristics and a general framework for pruning the access paths. With the help of it, the optimizer can avoid some wrong choices on access paths.
Background
Currently, the choice of access path strongly depends on the statistics. We may choose the wrong index due to outdated statistics. However, many of the wrong choices can be eliminated by simple heuristics, for example, if the primary key or unique indices can be fully matched, we can choose it without the referring to the statistics.
Proposal
The most important factors to choose the access paths are the number of rows that need to be scanned, whether or not it matches the physical property and does it require a double scan. Among these three factors, only the scan row count depends on statistics. So how can we compare the scan row count without statistics? Let's take a look at an example:
create table t(a int, b int, c int, index idx1(b, a), index idx2(a));
select * from t where a = 1 and b = 1;From the query and schema, we can know that the access condition of idx1 could strictly cover idx2, therefore the number of rows scanned by idx1 will be no more than idx2, so idx1 will be better than idx2 in this case.
So how can we combine these factors to prune the access paths? Consider two access paths x and y, if x is not worse than y at all factors, and there exists one factor that x is better than y, then we can prune y before referring to the statistics, because x works better than y at all circumstances. This is also called skyline pruning.
Rationale
The skyline pruning is also implemented in other databases, including MySQL and OceanBase. Without it, we may suffer from choosing the wrong access path in some simple cases.
Compatibility
It does not affect the compatibility.
Implementation
Since we need to decide whether the access path matches the physical property, we need to do the skyline pruning when finding the best task for the data source. And usually there won't be too many indices, a naive nested-loops algorithm will suffice. The comparison of any two access paths has been explained in the previous Proposal section.
Open issues (if applicable)
References
Design 2019 04 11 Indexmerge (`docs/design/2019-04-11-indexmerge.md`)
Proposal: Access a table using multiple indexes
- Author(s) : WHU
- Last updated : May 10
- Discussion at :
Abstract
The document proposes using multiple indexes to scan a table when possible, which, in some cases, will improve performance.
Background
In the present TiDB, a SQL statement with conditions that involve multiple indexed attributes only uses one of the conditions as the index filter to build the access condition, while regarding others as table filters. TiDB firstly uses index scan (one index at most) to get handles (rowid in TiDB), which are then used to get rows and check whether the rows satisfy the conditions of table filters. Some relational databases implement a table access path using multiple indexes to improve performance in some cases.
Here is an example to explain it. The table schema is defined as:
CREATE TABLE t1 (a int, b int, c int);
CREATE INDEX t1a on t1(a);
CREATE INDEX t1b on t1(b);
CREATE INDEX t1c on t1(c);A test SQL statement SELECT * FROM t1 where a < 2 or b > 50 is used in the example. Currently, TiDB does a table scan and puts a < 2 or b > 50 as a Selection on top of it. If the selectivity of a < 2 and b > 50 is low, a better approach would be using indexes on columns a and b to retrieve rows respectively, and applying a union operation on the result sets.
Proposal
In short, we can implement access paths using multiple indexes.
Planner
We propose to add the following operators:
IndexMergeReader / PhysicalIndexMergeReaderIndexMergeLookUpReader / PhysicalIndexMergeLookUpReader.
Now consider the following types of queries:
(1)Conditions in conjunctive normal form (CNF), e.g, select * from t1 where c1 and c2 and c3 and …
In this form, each CNF item can be covered by a single index respectively. For example, if we have single column indexes for t1.a, t1.b and t1.c respectively, for SQL select * from t1 where (a < 10 or a > 100) and b < 10 and c > 1000, we can use all the three indexes to read the table handles. The result plan for it is:
PhysicalIndexMergeLookUpReader(IndexMergeIntersect)
IndexScan(t1a)
IndexScan(t1b)
IndexScan(t1c)
TableScanFor the CNF items not covered by any index, we take them as table filters and convert them to selections on top of the scan node. For SQL select * from t1 where (a < 10 or c >100) and b < 10, only item b < 10 can function as an index access condition, so we will use a single index lookup reader.
To compare our demo implementation against the master branch, we set up an experiment for the CNF form. The schema and test SQL form we defined are as below:
Table Schema:
CREATE TABLE T200M(c1 int, c2 int, c3 int, c4 int, c5 int, c6 int, c7 int, c8 int);
CREATE INDEX T200Ma on T200M(a);
CREATE INDEX T200Mb on T200M(b);
Test SQL Form:
CNF-1
SELECT * FROM T200M WHERE C1 < $1 AND C2 > $2;
CNF-2
SELECT * FROM T200M WHERE C1 < $3 AND C2 < $4;In the experiment, we load two million rows into table T200M with one to two million sequence for all columns. $1-$4 is altered to obtain equal selectivity on C1 and C2, while the difference between CNF-1 and CNF-2 is that CNF-1 has no final results. The result can be seen in the following graph:

Note: SELECTIVITYis for the single column.
(2) Conditions in disjunctive normal form (DNF), e.g, select * from t1 where c1 or c2 or c3 or …
In this form, every DNF item must be covered by a single index. If not, IndexMerge scan cannot be used. For example, SQL select * from t1 where a > 1 or ( b >1 and b <10) will generate a possible plan like:
PhysicalIndexMergeLookUpReader(IndexMergeUnion)
IndexScan(t1a)
IndexScan(t1b)
TableScanTo compare our demo implementation against the master branch, we set up an experiment for the DNF form. The schema and test SQL form we defined are as below:
Table Schema:
CREATE TABLE T200(a int, b int, c int);
CREATE INDEX T200a on T2OO(a);
CREATE INDEX T200b on T200(b);
Test SQL Form:
SELECT * FROM T200 WHERE a < $1 OR b > $2;We load two million rows into table T200 with one to two million sequence for all columns. The value of $1 and $2 in the test SQL form is altered to obtain the accurate selectivities. The result can be seen in the following graph:

The structure of PhysicalIndexMergeLookUpReader is designed as:
// PhysicalIndexMergeLookUpReader
type PhysicalIndexMergeLookUpReader struct {
physicalSchemaProducer
//Follow two plans flat to construct executor pb.
IndexPlans []PhysicalPlan
TablePlans []PhysicalPlan
indexPlans []PhysicalPlan
tablePlan PhysicalPlan
IndexMergeType int
}Field
IndexMergeTypeindicates the operations on the results of multiple index scans. Possible values are:- 0: not an IndexMerge scan;
- 1: intersection operation on result sets, with a table scan;
- 2: intersection operation on result sets, without the table scan;
- 3: union operation on result sets; must have a table scan;
In the first version, PhysicalIndexMergeLookUpReader and PhysicalIndexMergeReader will be implemented as one operator.
IndexMergePath Generate
For table paths, we first generate all possible IndexMergeOr paths, then possible IndexMergeIntersection paths.
type IndexMergePath struct {
IndexPath[]
tableFilters
IndexMergeType
}/* Detailed source-code truncated for AI context efficiency. */GetIndexMergeIntersectionPaths(pushDownConditions, usedConditionsInOr, indexInfos) {
var partialPaths
if len(pushDownConditions) - len(usedConditionsInOr) < 2 {
return nil
}
tableFilters := append(tableFilters, usedConditionsInOr...)
newConsiderConditions := remove(pushDownConditions, usedConditionsInOr)
for cond in newConsiderConditions {
indexPaths = buildAccessPath([]{cond}, indexInfos)
if indexPaths == nil {
tableFilters = append(tableFilters,cond)
continue
}
indexPath := GetIndexMergePartialPath(indexPaths,indexInfos)
partialPaths = append(partialPaths, indexPath)
}
if len(partialPaths) < 2 {
return nil
}
return CreateIndexMergeIntersectionPath(partialPaths, tableFilters)
}
// Now, we just use all paths in partialPaths to generate a IndexMergeIntersection.
// We also need to merge possible paths.
// For example:
// index: ix1(a)
// condition: a > 1 and a < 10
// we will get two partial paths and they all use index ix1.
// IndexMergePath.tableFilters:
// <1> tableFilters
// <2> after merge operation, if any indexPath's tableFilter is not nil, we
// should add indexPath’s tableFilter into IndexMergePath.tableFilters
CreateIndexMergeIntersectionPath(partialPaths, tableFilters) {
}Executor
The graph below illustrates an execution of IndexMerge scan.

Every index plan in PhysicalIndexMergeLookUpReader will start an IndexWorker to execute the IndexScan plan and send handles to AndOrWorker. AndOrWorker is responsible for performing set operations (and, or) to getting final handles. Then AndOrWoker sends final handles to TableWorkers to get rows from TiKV.
Here are some designs for index plans in pipeline mode to be executed without considering the order.
(1) IndexMergeIntersection

Take this example: Use set1 to record row IDs returned by ix1 but not sent to tableWorker. Use set2 to record the same thing for ix2.
If new row IDs comes from ix1, first we check if it is in set2. If yes, we delete it from set2 and send it to tableWorker. Otherwise, we add it into set1. For the above figure, we use the following table to show the processing.
| new rowid | set1 | set2 | sent to TableWorker |
|---|---|---|---|
| 2(ix1) | [2] | [ ] | [ ] |
| 1(ix2) | [2] | [1] | [ ] |
| 5(ix1) | [2,5] | [1] | [ ] |
| 5(ix2) | [2] | [1] | [5] |
| 7(ix1) | [2,7] | [1] | [ ] |
| 2(ix2) | [7] | [1] | [2] |
(2) IndexMergeUnion
We have a structure (set) to record which row IDs are accessed. If a new row ID is returned by IndexScan, check if it is in the set. If yes, we just skip it. Otherwise, we add it into the set and send it to tableWorker.
Cost Model
There are three factors to be considered for the cost model: IO, CPU, and Network, as shown below:
IndexMergeType= 1IO Cost = (totalRowCount + mergedRowCount) * scanFactor
Network Cost = (totalRowCount + mergedRowCount) * networkFactor
Cpu Memory Cost = totalRowCount * cpuFactor + totalRowCount * memoryFactor
IndexMergeType= 2IO Cost = (totalRowCount) * scanFactor
Network Cost = totalRowCount * networkFactor
Cpu Memory Cost = totalRowCount * cpuFactor + totalRowCount * memoryFactor
IndexMergeType= 3IO Cost = (totalRowCount + mergedRowCount) * scanFactor
Network Cost = (totalRowCount + mergedRowCount) * networkFactor
Cpu Memory Cost = totalRowCount * cpuFactor + mergedRowCount * memoryFactor
Note:
totalRowCount: sum of handles collected from every index scan.
mergedRowCount: number of handles after set operating.
Compatibility
This proposal has no effect on the compatibility.
Implementation Procedure
- Implement planner operators
- Enhance
explainto display the plan - Implement executor operators
- Testing
Design 2019 11 05 Index Advisor (`docs/design/2019-11-05-index-advisor.md`)
Proposal: Support automatic index recommendation
- Author(s): Zou Huan
- Last updated: Nov. 5, 2019
- Discussion at:
Abstract
This proposal aims at designing a new DBA tool -- index advisor, which automatically recommends indexes for input workloads. With these recommended indexes added to tables, the overall execution time of input workloads is supposed to decrease. The current proposal only considers single-column index recommendation.
Background
Appropriate indexes can speed up query execution a lot. However, in real-world applications, determining proper indexes for a database according to a typical workload purely by hand, is an excessively challenging task. When deciding reasonable indexes for a large-scale database, this task becomes even more tough as one database may contain dozens of tables in which each table may have dozens of columns, whereas in the typical workload thousands of queries are involved in. Fortunately, we already have an excellent tool -- TiDB SQL optimizer that can be utilized to get through this tough task. The main purpose of this proposal is to utilize existing TiDB SQL optimizer to automatically recommend suitable indexes for database given the workload.
To illustrate how SQL optimizer can help us determine suitable indexes, here is an intuitive example:
First assume that all indexes on table persons are available. Then comes a query like SELECT name FROM persons WHERE age > 18. When responding to this query, the SQL optimizer is more likely to output an execution plan which does index_scan upon column age. Now that the output execution plan requires index_scan upon column age, we can tell that age is a more suitable index for current query than name, address, etc. The point here is: by observing the execution plan output by SQL optimizer, we will know which indexes are favored by input queries.
Proposal
Design Overview
For problems like what kind of indexes should be added to schema, how to value these hypothetic (potential / possible) indexes based on execution plan and its cost, they are handled by the top layer logic of index advisor. This logic involves three steps: (1) recommend indexes for single query; (2) calculate a score for each index and get an ordered score list descending with index's score; (3) pick the top n indexes as the initial recommended index set and then launch the Swap and Re-evaluate algorithm. Following details the three steps:
Potential indexes. This proposal only considers single column indexes, thus all columns in a table can be potential indexes and column statistics is the corresponding index's statistics.
Evaluate indexes:
- For each query, compile it and get the execution plan's cost denoted as
original_cost. Then compile the same query again with all potential indexes added to schema, extract selected indexes from output execution plan asLSIs(Local Selected Index) and denote the corresponding cost asvirtual_cost. Calculatereduced_cost = original_cost - virtual_cost. - Respectively add up
LSIs' reduced_costof each query in the workload. Denote the sum asLSIs'final scores. - Get the score list of
LSIsdescending with their corresponding score.
- For each query, compile it and get the execution plan's cost denoted as
Evaluate index set:
- Pick the top
nindexes as the initialrecommended index set. Denote the remaining unselected index set asremaining index set. - Execute the following Swap and Re-evaluate algorithm.
- Pick the top
// GCIS stands for Global Candidate Index Set
sort(GCIS, GCIS.Score, Descend_Order)
recommend_set = GCIS[:N]
remaining_set = GCIS[N:]
min_cost = EvaluateWorkload(workload, recommend_set)
for {
v_recommend_set, v_remaining_set = SwapElements(recommend_set, remaining_set, swap_size)
variant_cost = EvaluateWorkload(workload, v_recommend_set)
if variant_cost < min_cost {
min_cost = variant_cost
recommend_set = v_recommend_set
remaining_set = v_remaining_set
}
......
// loop until specific rounds or timeout, break
}Note that executing Swap and Re-evaluate algorithm is necessary as the reduced_cost sometimes is a joint effect of several indexes and it's hard to tell each index's independent contribution to the final reduced_cost. For example, assume there is an extremely slow query in input workload and the desired indexes for this query is a and b. However, the number of allowed recommended indexes for the whole workload is limited and for some reason, a ranks top n in the final score list while b is not. But there are chances that without b, a can no more optimize that extremely slow query.
A quick example for single-column index recommendation
Workload:
- Query1: SELECT COUNT(*) FROM t1 where a = 1 and b = 5
- Query2: SELECT a FROM t1 ORDER BY c limit 10
- Query3: DELETE FROM t1 WHERE a = 1 AND d = 1where index on column c has already existed.
- Step1: recommend indexes for single query. For each query, compile it and get the
original_costoutput by SQL optimizer. Then add all possible hypothetic indexes a, b, d to the schema, compile the same query again. After the compiling,LSIscan be extracted from output execution plan as well as thevirtual_cost. Denotereduced_costas original_cost - virtual_cost. Assume this step outputs:
Query 1--LSIs: {a, b}, reduced_cost: 4
Query 2--LSIs: {c}, reduced_cost: 4
Query 3--LSIs: {a, d}, reduced_cost: 3- Step2: get the score list. Simply add up
LSIsandreduced_costof each query respectively and then sort the list descending by score. Assume this step outputs:
a: 4+3=7
b: 4
c: 4
d: 3- Step3: evaluate the recommended index set. Assume the number of allowed indexes recommended by index advisor is 2 and the swap size is 1
- The initial
recommended index setis{a, b}, theremaining index setis{c,d} - Add recommended index set
{a, b}to the schema and at the same time mute existed indexc - Compile all queries in the workload and add up each query's cost. Assume the sum is 20 and then assign it variable
min_cost - Randomly exchange 1 element between the recommended set and remaining set. Assume a and c are chosen respectively, now the recommended set is
{c, b}and the remaining set is{a, d}. - Apply recommended index set
{c, b}to the workload and get a sum cost, say 18. - As the cost decreases from 20 to 18, update the recommended set from
{a, b}to{c, b}and updatemin_costto 18. Then try swapping 1 element between{c, b}and{a, d}and execute the re-evaluate process.
- The initial
Note that if the sum cost with {c, b} is 22 (greater than 20), the next swap process should happen between {a, b} and {c, d} instead of between {c, b} and {a, d}. Loop the Swap and Re-evaluate process until timeout.
Rational
In this design, index advisor is implemented in a user friendly way, by adding a new SQL syntax index advise... instead of an independent third-party tool. However, for simplicity, syntax like add virtual index... which serves as building blocks of index advisor is not exposed. Therefore, if DBAs want some functionality like add virtual index or alter invisible index, they cannot benefit directly from current index advisor implementation.
Compatibility
No compatibility issues.
Implementation
**Support from TiDB SQL optimizer**
add hypothetic indexes to schema
- effect: query should be compiled with schema that contains input hypothetic indexes
- constraints: these hypothetic indexes should take effect only within the current index advisor session
- implementation: get a copy of session schema in memory. Then add hypothetic indexes to schema copy and compile the query with this modified schema copy
alter invisible indexes
- effect: input existed indexes on table should be invisible to optimizer
- constraints: only within current index advisor session, input indexes are invisible to optimizer
- implementation: get a copy of session schema in memory. Then delete input indexes from schema copy and compile the query with this modified schema copy
extract LSIs and cost from execution plan
- effect: given the execution plan output by SQL optimizer, related indexes in this plan should be extracted as local selected indexes. Besides, best plan's
costshould be returned to the top layer of index advisor that invokes TiDB's SQL optimizer. - constraints: no
- implementation: maybe rewriting the function
compiler.Compileis a simpler way
- effect: given the execution plan output by SQL optimizer, related indexes in this plan should be extracted as local selected indexes. Besides, best plan's
**Implement top layer logic of index advisor**
Add a new SQL grammar for index advisor:
INDEX ADVISE
[LOCAL]
INFILE 'file_name'
[MAX_MINUTES number]
[MAX_IDXNUM
[PER_TABLE number]
[PER_DB number]
]
[LINES
[STARTING BY 'string']
[TERMINATED BY 'string']
]Options in bracket [] is optional, while others are compulsory. The output of this grammar look like this:
| Table | Recommended index | Num of hit queries | Reduced_cost |
|---|---|---|---|
| employee | age | 6 | 100 |
| employee | position | 2 | 20 |
| department | department_id | 3 | 60 |
Open issues (if applicable)
Design 2019 11 14 Tidb Builtin Diagnostics Zh CN (`docs/design/2019-11-14-tidb-builtin-diagnostics-zh_CN.md`)
RFC: TiDB 内置 SQL 诊断
Summary
目前 TiDB 获取诊断信息主要依赖外部工具(perf/iosnoop/iotop/vmstat/sar/...)、监控系统(Prometheus/Grafana)、日志文件、HTTP API 和 TiDB 提供的系统表。分散的工具链和繁杂的获取方式导致 TiDB 的集群的使用门槛高、运维难度大、不能提前发现问题以及遇到问题不能及时排查、诊断和恢复集群等。
本提案提出一种新的方法,在 TiDB 中内置获取诊断信息的功能,并将诊断信息使用系统表的形式对外暴露,使用户可以使用 SQL 的方式进行查询。
Motivation
本提案主要解决 TiDB 在获取诊断信息过程中的以下问题:
- 工具链分散,需要在不同工具之间来回切换,且部分 Linux 发行版未内置相应工具或内置工具的版本不一致。
- 信息获取方式不一致,比如有 SQL、HTTP、导出监控、登录各个节点查看日志等。
- TiDB 集群组件较多,对不同组件的监控进行对比和关联低效且繁琐。
- TiDB 没有集中日志管理组件,没有高效的手段对整个集群的日志进行过滤、检索、分析、聚合。
- 系统表只包含当前节点信息,不能体现整个集群的状态,如:SLOW_QUERY, PROCESSLIST, STATEMENTS_SUMMARY。
在通过提供多维度集群级别系统表和集群诊断规则框架之后,提高全集群信息查询、状态获取、日志检索、一键巡检、故障诊断几个使用场景中的效率,并为后续异常预警功能提供基础数据。
Detailed Design
系统整体概览
本提案的实现分为四层:
- L1: 最底层在各个节点实现信息采集模块,包括 TiDB/TiKV/PD 监控信息、硬件信息、内核中记录的网络 IO、磁盘 IO 信息、CPU 使用率、内存使用率等。
- L2: 第二层通过调用底层信息采集模块并通过对外服务接口(HTTP API/gRPC Service)向上层提供数据,使 TiDB 可以获取当前节点采集到的信息。
- L3: 第三层由 TiDB 拉取各个节点的信息进行聚合和汇总,并以系统表的形式对上层提供数据。
- L4: 第四层实现诊断框架,诊断框架通过查询系统表获取整个集群的状态,并根据诊断规则得到诊断结果。
如下从信息采集到使用使用诊断规则对采集的信息进行分析的数据流向图:
+-L1--------------+ +-L3-----+
| +-------------+ | | |
| | Metrics | | | |
| +-------------+ | | |
| +-------------+ | | |
| | Disk IO | +---L2:gRPC-->+ |
| +-------------+ | | |
| +-------------+ | | TiDB |
| | Network IO | | | |
| +-------------+ | | |
| +-------------+ | | |
| | Hardware | +---L2:HTTP-->+ |
| +-------------+ | | |
| +-------------+ | | |
| | System Info | | | |
| +-------------+ | | |
+-----------------+ +---+----+
|
+---infoschema---+
|
v
+-L4---------------+---------------------+
| |
| Diagnosis Framework |
| |
| +---------+ +---------+ +---------+ |
| | rule1 | | rule2 | | rule3 | |
| +---------+ +---------+ +---------+ |
+----------------------------------------+系统信息收集
TiDB/TiKV/PD 三个组件都需要实现系统信息采集模块,其中 TiDB/PD 使用 Golang 实现并复用逻辑,TiKV 需要使用 Rust 单独实现。
节点硬件信息
各个节点需要获取的硬件信息包括:
- CPU 信息:物理核心数、逻辑核心数量、NUMA 信息、CPU 频率、CPU 供应商、L1/L2/L3 缓存大小
- 网卡信息:网卡设备名、网卡是否启用、生产厂商、型号、带宽、驱动版本、接口队列数(可选)
- 磁盘信息:磁盘名、磁盘容量、磁盘使用量、磁盘分区、挂载信息
- USB 设备列表
- 内存信息
节点系统信息
各个节点需要获取的系统信息包括:
- CPU 使用率、1/5/15 分钟负载
- 内存:Total/Free/Available/Buffers/Cached/Active/Inactive/Swap
- 磁盘 IO:
- tps: 该设备每秒的传输次数
- rrqm/s: 每秒这个设备相关的读取请求有多少被 Merge
- wrqm/s: 每秒这个设备相关的写入请求有多少被 Merge
- r/s: 每秒从设备读取的数据量
- w/s: 每秒从设备写入的数据量
- rsec/s: 每秒读取的扇区数
- wsec/s: 每秒写取的扇区数
- avgrq-sz: 平均请求扇区的大小
- avgqu-sz: 是平均请求队列的长度
- await: 每一个IO请求的处理的平均时间(单位是微秒毫秒)
- svctm: 表示平均每次设备I/O操作的服务时间(以毫秒为单位)
- %util: 在统计时间内所有处理IO时间,除以总共统计时间
- 网络 IO
- IFACE:LAN接口
- rxpck/s:每秒钟接收的数据包
- txpck/s:每秒钟发送的数据包
- rxbyt/s:每秒钟接收的字节数
- txbyt/s:每秒钟发送的字节数
- rxcmp/s:每秒钟接收的压缩数据包
- txcmp/s:每秒钟发送的压缩数据包
- rxmcst/s:每秒钟接收的多播数据包
- 常用的系统配置:sysctl -a
节点配置信息
所有节点都包含当前节点的生效配置,不需要额外的步骤既可拿到配置信息。
节点日志信息
TiDB/TiKV/PD 产生的日志都保存在各自的节点上,并且 TiDB 集群部署过程中没有部署额外的日志收集组件,所以在日志检索中有以下问题:
- 日志分布在各个节点,需要单独登陆到每一个节点使用关键字进行搜索
- 日志文件会每天 rotate,所以在单个节点也需要对多个日志文件进行搜索
- 没有简单的方式对多个节点的日志按照时间排序整合到同一个文件
本提案提供以下两种思路来解决以上问题:
- 引入第三方日志收集组件对所有节点的日志进行收集
- 优势:统一的日志管理,日志可以长时间保存,并易于检索,并且多个组件的日志可以按照时间排序归并
- 劣势:增加集群运维难度,第三方组件不容易与 TiDB 内部 SQL 集成;日志收集工具会收集全量日志,收集过程占用各个系统资源(磁盘 IO、网络 IO)
- 各个节点提供日志服务,TiDB 通过各个节点的接口将谓词下推到日志检索接口,直接对各个节点返回的日志进行归并
- 优势:不引入三方组件,谓词下推后只返回过滤后的日志,能轻易的与 TiDB SQL 进行集成,并能复用 SQL 引擎的过滤、聚合等
- 劣势:如果节点日志删除后,不能检索到对应日志
根据以上的优劣势分析,本提案使用第二种方案,即各个节点提供日志搜索接口,TiDB 将日志搜索的 SQL 中谓词下推到各个节点,日志搜索接口的语义为:搜索本地日志文件,并使用谓词进行过滤,匹配的结果返回。
start_time: 日志检索的开始时间(unix 时间戳,单位毫秒),如果没有该谓词,则默认为 0。end_time: 日志检索的开始时间(unix 时间戳,单位毫秒),如果没有该谓词,则默认为int64::MAX。pattern: 如 SELECT * FROM cluster_log WHERE pattern LIKE "%gc%" 中的 %gc% 即为过滤的关键字level: 日志等级,可以选为 DEBUG/INFO/WARN/WARNING/TRACE/CRITICAL/ERRORlimit: 返回日志的条数,如果没有指定,则限制为 64k 条,防止日质量太大占用大量网络
节点性能采样数据
当前 TiDB 集群中,发现有性能瓶颈时,需要快速定位问题。火焰图 (Flame Graph)是由 Brendan Gregg 发明的,与其他的 trace 和 profiling 方法不同的是,Flame Graph 以一个全局的视野来看待时间分布,它从底部往顶部,列出所有可能的调用栈。其他的呈现方法,一般只能列出单一的调用栈或者非层次化的时间分布。
目前 TiKV 和 TiDB 获取火焰图的方式不同,并且都需要依赖外部工具。
TiKV 获取火焰图
textperf record -F 99 -p proc_pid -g -- sleep 60 perf script > out.perf /opt/FlameGraph/stackcollapse-perf.pl out.perf > out.folded /opt/FlameGraph/flamegraph.pl out.folded > cpu.svgTiDB 获取火焰图
textcurl http://127.0.0.1:10080/debug/pprof/profile > cpu.pprof go tool pprof -svg cpu.svn cpu.pprof
目前存在的两个主要问题:
- 生产环境中不一定包含对应的外部工具(perf/flamegraph.pl/go)
- TiKV 和 TiDB 没有统一的方式
为了解决以上两个问题,本提案将获取火焰图的方法内置到 TiDB 中,统一使用 SQL 触发采样并将采样数据转换为火焰图作为查询结果显示,一方面降低对外部工具的依赖,同时也极大的提升效率。各个节点实现采样数据采集功能并提供采样接口,对上层输出指定格式的采样数据。暂定输出为 [pprof](github.com/google/pprof) 定义的 ProtoBuf 格式。
采样数据获取方式:
- TiDB/PD: 使用 Golang Runtime 内置的采样数据获取接口
- TiKV: 使用
[pprof-rs](github.com/tikv/pprof-rs)库采集采样数据
节点监控信息
监控信息主要是各个组件内部定义的监控指标。目前 TiDB/TiKV/PD 都会提供 /metrics HTTP API,然后通过部署的 Prometheus 组件定时(默认配置 15s)的拉取集群各个节点的监控指标。并且部署了 Grafana 组件用于从 Prometheus 拉取监控数据,进行可视化展示。
监控信息不同于实时获取的系统信息,监控数据是一个时序数据。包含各个节点在各个时间点的数据,对于排查问题和诊断问题有非常重要的用途,所以监控信息的保存和查询对于本提案实现 TiDB 内置 SQL 诊断非常重要。为了能够在 TiDB 内使用 SQL 查询监控数据,目前有以下备选方案:
- 使用 Prometheus client 和 PromQL 查询 Prometheus server 的数据
- 优势:有现成解决方案,只需要将 Prometheus server 的地址注册到 TiDB 即可,实现简单
- 劣势:增强了 TiDB 对 Prometheus 的依赖,为后续完全移除 Prometheus 增加了困难
- 将最近一段时间内(暂定 1 天)的监控数据保存到 PD,从 PD 中查询监控数据
- 优势:该方案不依赖 Prometheus server,为后续移除 Prometheus 组件有一定帮助
- 劣势:需要实现时序保存逻辑,并实现对应的查询引擎,实现难度和工作量大
本提案倾向于方案二,虽然实现难度更大,但是对后续的工作有帮助。为了解决实现 PromQL 和时序数据保存的实现难度大和周期长的问题,将这个功能分为三个阶段实现(第三阶段视具体情况是否实现):
- PD 中添加
remote-metrics-storage配置,暂时配置为 Prometheus Server 的地址。PD 作为 proxy,将请求转移到 Prometheus 上执行,主要有以下考量:- 后续 PD 实现查询接口实现自举,TiDB 不需要做其他改动
- 用户不使用 TiDB 部署的 Prometheus 而使用自建的监控服务,依然可以使用 SQL 查询监控信息以及诊断框架
- 将 Prometheus 时序数据保存和查询相应的模块抽离出来,并嵌入到 PD 中
- PD 内部实现自己的时序保存与查询(目前 CockroachDB 的方案)
PD 性能分析
PD 目前主要承载 TiDB 集群的调度和 TSO 服务,其中:
- TSO 获取仅对 Leader 内存中的一个原子变量进行累加
- 调度生成的 Operator 和 OperatorStep 仅保存在内存中,根据 Region 的心跳信息更新内存中的状态
由以上信息可以得出在 PD 上新增监控功能对 PD 的性能影响在绝大部分情况下可以忽略不计。
系统信息获取
由于 TiDB/TiKV/PD 组件之前已经可以通过 HTTP API 对外暴露部分系统信息,并且 PD 主要通过 HTTP API 对外提供服务,所以本提案的部分接口会复用已有逻辑,使用 HTTP API 从各个组件获取数据,比如配置信息获取。
由于 TiKV 后续计划完全移除 HTTP API,所以除了已有接口复用之外,不再额外添加新的 HTTP API,所有日志检索、硬件信息、系统信息获取统一定义 gRPC Service,各个组件实现对应的 Service 并在启动过程中注册到 gRPC Server 中。
gRPC Service 定义
// Diagnostics service for TiDB cluster components.
service Diagnostics {
// Searchs log in the target node
rpc search_log(SearchLogRequest) returns (SearchLogResponse) {};
// Retrieves server info in the target node
rpc server_info(ServerInfoRequest) returns (ServerInfoResponse) {};
}
enum LogLevel {
Debug = 0;
Info = 1;
Warn = 2;
Trace = 3;
Critical = 4;
Error = 5;
}
message SearchLogRequest {
int64 start_time = 1;
int64 end_time = 2;
LogLevel level = 3;
string pattern = 4;
int64 limit = 5;
}
message SearchLogResponse {
repeated LogMessage messages = 1;
}
message LogMessage {
int64 time = 1;
LogLevel level = 2;
string message = 3;
}
enum ServerInfoType {
All = 0;
HardwareInfo = 1;
SystemInfo = 2;
LoadInfo = 3;
}
message ServerInfoRequest {
ServerInfoType tp = 1;
}
message ServerInfoItem {
// cpu, memory, disk, network ...
string tp = 1;
// eg. network: lo1/eth0, cpu: core1/core2, disk: sda1/sda2
string name = 2;
string key = 3;
string value = 4;
}
message ServerInfoResponse {
repeated ServerInfoItem items = 1;
}可复用的 HTTP API
目前 TiDB/TiKV/PD 包含部分可复用 HTTP API,本提案暂不将对应接口迁移至 gRPC Service,迁移工作由后续其他计划完成。所有 HTTP API 需要以 JSON 格式返回数据,以下是提案中可能用到的 HTTP API 列表:
- 获取配置信息
- PD: /pd/api/v1/config
- TiDB/TiKV: /config
- 性能采样接口: TiDB/PD 包含以下所有接口,TiKV 暂时只包含 CPU 性能采样接口
- CPU: /debug/pprof/profile
- Memory: /debug/pprof/heap
- Allocs: /debug/pprof/allocs
- Mutex: /debug/pprof/mutex
- Block: /debug/pprof/block
集群信息系统表
每个 TiDB 实例均可以通过前两层提供的 HTTP API 或 gRPC Service 访问其他节点的信息,从而实现集群的 Global View。本提案中通过新建一系列相关系统表将采集到的集群信息向上层提供数据,上层包括不限于:
- 终端用户:用户直接通过 SQL 查询获取集群信息排查问题
- 运维系统:TiDB 的使用环境比较多样,客户可以通过 SQL 获取集群信息将 TiDB 集成到自己的运维系统中
- 生态工具:外部工具通过 SQL 拿到集群信息实现功能定制,比如
[sqltop](https://github.com/ngaut/sqltop)可以直接通过集群statements_summary获取整个集群的 SQL 采样信息
集群拓扑系统表
要为 TiDB 实例提供一个 Global View,首先需要为 TiDB 实例提供一个拓扑系统表,可以从拓扑系统表中获取各个节点的 HTTP API Address 和 gRPC Service Address,从而方便的构造出各个远程 API 的 Endpoint,进一步获取目标节点采集的信息。
本提案实现完成可以通过 SQL 查询以下结果:
/* Detailed source-code truncated for AI context efficiency. */监控信息系统表
由于监控指标会随着程序的迭代添加和删除监控指标,对于同一个监控指标,可能有不同的表达式获取监控不同维度的信息。鉴于以上两个需求,需要设计一个有弹性的监控系统表框架,本提案暂时才采取以下方案:将表达式映射为 metrics_schema 数据库中的系统表,表达式与系统表的关系可以通过以下方式关联:
定义在配置文件
text# tidb.toml [metrics_schema] qps = `sum(rate(tidb_server_query_total[$STEP])) by (result)` memory_usage = `process_resident_memory_bytes{job="tidb"}` goroutines = `rate(go_gc_duration_seconds_sum{job="tidb"}[$STEP])`HTTP API 注入
textcurl -XPOST http://host:port/metrics_schema?name=distsql_duration&expr=`histogram_quantile(0.999, sum(rate(tidb_distsql_handle_query_duration_seconds_bucket[$STEP])) by (le, type))`特殊 SQL 命令
textmysql> admin metrics_schema add parse_duration `histogram_quantile(0.95, sum(rate(tidb_session_parse_duration_seconds_bucket[$STEP])) by (le, sql_type))`从文件中加载
textmysql> admin metrics_schema load external_metrics.txt #external_metrics.txt execution_duration = `histogram_quantile(0.95, sum(rate(tidb_session_execute_duration_seconds_bucket[$STEP])) by (le, sql_type))` pd_client_cmd_ops = `sum(rate(pd_client_cmd_handle_cmds_duration_seconds_count{type!="tso"}[$STEP])) by (type)`
添加以上表之后就可以在 metrics_schema 库中查看对应的表:
mysql> use metrics_schema;
Database changed
mysql> show tables;
+-------------------------------------+
| Tables_in_metrics_schema |
+-------------------------------------+
| qps |
| memory_usage |
| goroutines |
| distsql_duration |
| parse_duration |
| execution_duration |
| pd_client_cmd_ops |
+-------------------------------------+
7 rows in set (0.00 sec)表达式映射到系统表时字段的确定方式主要取决与表达式执行结果的数据。以表达式 sum(rate(pd_client_cmd_handle_cmds_duration_seconds_count{type!="tso"}[1m]offset 0)) by (type) 为例,查询的结果为:
| Element | Value |
|---|---|
| {type="update_gc_safe_point"} | 0 |
| {type="wait"} | 2.910521666666667 |
| {type="get_all_stores"} | 0 |
| {type="get_prev_region"} | 0 |
| {type="get_region"} | 0 |
| {type="get_region_byid"} | 0 |
| {type="scan_regions"} | 0 |
| {type="tso_async_wait"} | 2.910521666666667 |
| {type="get_operator"} | 0 |
| {type="get_store"} | 0 |
| {type="scatter_region"} | 0 |
映射为表结构以及查询结果为:
/* Detailed source-code truncated for AI context efficiency. */对于多个 label 的 PromQL 就会有多个列的数据,可以方便的使用已有的 SQL 执行引擎对数据过滤、聚合得到期望的结果。
节点性能剖析系统表
通过各个节点的 /debug/pprof/profile 拿到对应节点性能采样数据,然后对采样数据进行聚合,最终使用 SQL 查询结果的方式向用户输出性能剖析结果。由于 SQL 查询结果不能以 svg 的格式输出,所以需要解决输出内容展示的问题。
火焰图快速定位问题的核心点是:
- 提供全局视野
- 展示全部调用路径
- 层次化展示
本提案提出的解决方案聚焦在解决核心问题的点上,而未拘泥于是图形展示形式。最终的方案为:对采样数据进行聚合,并将所有的调用路径使用树形结构逐行进行展示。
解决方案是通过以下方式契合三个核心点:
- 提供全局视野:对每一个聚合结果使用单独的一列展示在全局的使用比例,可以方便过滤排序
- 展示全部调用路径:将所有的调用路径都作为查询结果,并使用单独的列对各个调用路径的子树进行编号,可以方便的通过过滤只查看某一个子树
- 层次化展示:使用树形结构展示堆栈,使用单独的列记录栈的深度,可以方便的对不同栈的深度进行过滤
本提案需要实现以下性能剖析表:
| 表名 | 描述 |
|---|---|
| tidb_profile_cpu | TiDB CPU 火焰图 |
| tikv_profile_cpu | TiKV CPU 火焰图 |
| tidb_profile_block | TiDB 阻塞情况火焰图 |
| tidb_profile_memory | TiDB 内存对象火焰图 |
| tidb_profile_allocs | 内存分配火焰图 |
| tidb_profile_mutex | 锁的争用情况火焰图 |
| tidb_profile_goroutines | 系统中已有的 goroutines,排查 goroutine 泄漏、阻塞 |
内存表全局化
目前 slow_query/statements_summary/processlist 只包含单节点数据,本提案通过添加以下三张集群级别系统表使任何一个 TiDB 实例可以查看整个集群的信息:
| 表名 | 描述 |
|---|---|
| cluster_slow_query | 所有 TiDB 节点的 slow_query 表数据 |
| cluster_statements_summary | 所有 TiDB 节点的 statements summary 表数据 |
| cluster_processlist | 所有 TiDB 节点的 processlist 表数据 |
所有节点的配置信息
对于一个大集群,通过 HTTP API 去每一个节点获取配置的方式较为繁琐和低效,本提案提供全集群配置信息系统表,简化整个集群配置信息的获取、过滤、聚合。
如下示例是实现本提案后的预期结果:
/* Detailed source-code truncated for AI context efficiency. */节点硬件/系统/负载信息系统表
根据 gRPC Service 的协议定义,每一个 ServerInfoItem 包含信息的名字以及对应的键值对,在向用户展示时,需要添加节点的类型以及节点地址。
/* Detailed source-code truncated for AI context efficiency. */全链路日志系统表
当前日志搜索需要登陆多台机器分别进行检索,并且没有简单的办法对多个机器的检索结果按照时间全排序。本提案新建一个 cluster_log 系统表用于提供全链路日志,简化通过日志排查问题的方式以及提高效率。实现方式为:通过 gRPC Diagnosis Service 的 search_log 接口,将日志过滤的谓词下推到各个节点,并最终按照时间进行归并。
如下示例是实现本提案后的预期结果:
/* Detailed source-code truncated for AI context efficiency. */集群诊断
在当前的集群拓扑下,各个组件分散,数据源和数据格式异构,不便于通过程序化的手段进行集群诊断,所以需要人工进行问题诊断。通过前面几层提供的数据系统表,每一个 TiDB 节点都有了一个稳定的全集群 Global View,所以可以在这个基础上实现一个问题诊断框架。通过定义诊断规则能够快速发现集群的已有问题和潜在问题。
诊断规则定义:诊断规则是通过读入各个系统表的数据,并通过检测异常数据发现问题的逻辑。
诊断规则可以分为三个层次:
- 发现潜在问题:比如通过判断磁盘容量和磁盘使用量的比例发现磁盘容量不足
- 发现已有问题:比如通过查看负载情况,发现 Coprocessor 的线程池已经跑满
- 给出修复建议:比如通过分析磁盘 IO 发现延迟过高,可以给出更换磁盘的建议
本提案主要负责实现诊断框架和部分诊断规则,更多的诊断规则需要根据使用经验逐步沉淀,最终形成一个专家系统,降低使用门槛和运维难度。后续内容不详细探讨具体某条的诊断规则,主要聚焦诊断框架的实现。
诊断框架设计
诊断框架的设计需要考虑多种用户使用场景,包括不限于:
- 用户选择固定版本后,不会轻易升级 TiDB 集群版本
- 用户自定义诊断规则
- 不重启集群加载新的诊断规则
- 诊断框架需要能方便的与已有运维系统集成
- 用户可能会屏蔽部分诊断,比如用户预期是一个异构系统,那么会屏蔽异构诊断规则
- ...
需要实现一个支持规则热加载的诊断系统,目前有以下备选方案:
- Golang Plugin:使用不同的插件来定义诊断规则,并且加载到 TiDB 的进程中
- 优势:使用 Golang 开发,开发门槛低
- 劣势:版本管理容易出错,需要和宿主 TiDB 使用同样的版本编译插件
- 内嵌 Lua:在运行时或启动过程中加载 Lua 脚本,脚本从 TiDB 读取系统表数据,并根据诊断规则判断并反馈结果
- 优势:Lua 是一个完全依赖宿主的语言,语法简单,容易与宿主集成
- 劣势:依赖另一个脚本语言
- Shell Script:Shell 具备流程控制功能,所以可以用 Shell 定义诊断规则
- 优势:易于编写、加载和执行,对 TiDB 内部无侵入,只需要外部 Shell 执行对应 SQL 即可
- 劣势:需要在安装 mysql client 的机器上运行
本提案暂时采用第三种方案,使用 Shell 编写诊断规则。对 TiDB 没有侵入,同时也为后续实现更好的方案提供扩展性。
Design 2019 11 14 Tidb Builtin Diagnostics (`docs/design/2019-11-14-tidb-builtin-diagnostics.md`)
RFC: TiDB Built-in SQL Diagnostics
Summary
Currently, TiDB obtains diagnostic information mainly relying on external tools (perf/iosnoop/iotop/iostat/vmstat/sar/...), monitoring systems (Prometheus/Grafana), log files, HTTP APIs, and system tables provided by TiDB. The decentralized toolchains and cumbersome acquisition methods lead to high barriers to the use of TiDB clusters, difficulty in operation and maintenance, failure to detect problems in advance, and failure to timely investigate,diagnose, and recover clusters.
This proposal proposes a new method of acquiring diagnostic information in TiDB for exposure in system tables so that users can query diagnostic information using SQL statements.
Motivation
This proposal mainly solves the following problems in TiDB's process of obtaining diagnostic information:
- The toolchains are scattered, so TiDB needs to switch back and forth between different tools. In addition, some Linux distributions don't have corresponding built-in tools; even if they do, the versions of the tools aren't as expected.
- The information acquisition methods are inconsistent, for example, SQL, HTTP, exported monitoring, viewing logs by logging into each node, and so on.
- There are many TiDB cluster components. and the comparison and correlation of the monitoring information between different components are inefficient and cumbersome.
- TiDB does not have centralized log management components, so there are no efficient ways to filter, retrieve, analyze, and aggregate logs of the entire cluster.
- The system table only contains the information of the current node, which does not reflect the state of the entire cluster, such as: SLOW_QUERY, PROCESSLIST, STATEMENTS_SUMMARY.
The efficiency of cluster-scale information query, state acquisition, log retrieval, one-click inspection, and fault diagnosis can be improved after the multi-dimensional cluster-level system table and the cluster's diagnostic rule framework are provided. And basic data can be provided for subsequent exception alarming.
Detailed design
System overview
The implementation of this proposal is divided into four layers:
- L1: The lowest level implements the information collection module at each node, including monitoring information, hardware information, network IO recorded in the kernel, Disk IO information, CPU usage, memory usage, etc, of TiDB/TiKV/PD.
- L2: The second layer can obtain the information collected by the current node by calling the underlying information collection module and providing data to the upper layer through external service interfaces (HTTP API/gRPC Service).
- L3: In the third layer, TiDB pulls the information from each node for aggregation and summarizing, and provides the data to the upper layer in the form of the system table.
- L4: The fourth layer implements the diagnostic framework. The diagnostic framework obtains the status of the entire cluster by querying the system table and obtains the diagnostic result according to the diagnostic rules.
The following chart shows the data flow from information collection to analysis using the diagnostic rules:
+-L1--------------+ +-L3-----+
| +-------------+ | | |
| | Metrics | | | |
| +-------------+ | | |
| +-------------+ | | |
| | Disk IO | +---L2:gRPC-->+ |
| +-------------+ | | |
| +-------------+ | | TiDB |
| | Network IO | | | |
| +-------------+ | | |
| +-------------+ | | |
| | Hardware | +---L2:HTTP-->+ |
| +-------------+ | | |
| +-------------+ | | |
| | System Info | | | |
| +-------------+ | | |
+-----------------+ +---+----+
|
+---infoschema---+
|
v
+-L4---------------+---------------------+
| |
| Diagnosis Framework |
| |
| +---------+ +---------+ +---------+ |
| | rule1 | | rule2 | | rule3 | |
| +---------+ +---------+ +---------+ |
+----------------------------------------+System information collection
The system information collection module needs to be implemented for all of TiDB/TiKV/PD components. TiDB/PD uses Golang to implement with reuse of the underlying logic; TiKV needs separation implementation in Rust.
Node hardware information
The hardware information that each node needs to obtain includes:
- CPU information: physical core number, logical core number, NUMA information, CPU frequency, CPU vendor, L1/L2/L3 cache
- NIC information: NIC device name, NIC enabled status, manufacturer, model, bandwidth, driver version, number of interface queues (optional)
- Disk information: disk name, disk capacity, disk usage, disk partition, mount information
- USB device list
- Memory information
Node System Information
The hardware information that each node needs to obtain includes:
- CPU Usage, loads in 1/5/15 minutes:
- Memory: Total/Free/Available/Buffers/Cached/Active/Inactive/Swap
- Disk IO:
- tps: number of transfers per second that were issued to the device.
- rrqm/s: number of read requests merged per second that were queued to the device.
- wrqm/s: number of write requests merged per second that were queued to the device.
- r/s: number (after merges) of read requests completed per second for the device.
- r/s: number (after merges) of read requests completed per second for the device.
- r/s: number (after merges) of read requests completed per second for the device.
- r/s: number (after merges) of read requests completed per second for the device.
- r/s: number (after merges) of read requests completed per second for the device.
- w/s: number (after merges) of write requests completed per second for the device.
- rsec/s: number of sectors (kilobytes, megabytes) read from the device per second.
- wsec/s: number of sectors (kilobytes, megabytes) written to the device per second.
- await: average time (in milliseconds) for I/O requests issued to the device to be served.
- %util: percentage of elapsed time during which I/O requests were issued to the device (bandwidth utilization for the device)
- Network IO
- IFACE: name of the network interface for which statistics are reported.
- rxpck/s: total number of packets received per second.
- txpck/s: total number of packets transmitted per second.
- rxkB/s: total number of kilobytes received per second.
- txkB/s: total number of kilobytes transmitted per second.
- rxcmp/s: number of compressed packets received per second.
- txcmp/s: number of compressed packets transmitted per second.
- rxmcst/s: number of multicast packets received per second.
- System configuration:
sysctl -a
Node configuration information
All nodes contain the effective configuration for the current node, and no additional steps are required to get the configuration information.
Node log information
Currently, the logs generated by TiDB/TiKV/PD are saved on their respective nodes, and no additional log collection components are deployed during TiDB cluster deployment, so there are the following problems in log retrieval:
- Logs are distributed on each node. You need to log in to each node to search using keywords.
- Log files are rotated every day, so we need to search among multiple log files even on a single node.
- There is no easy way to combine logs of multiple nodes into a single file which sorted by the time.
This proposal provides the following two solutions to the above problems:
- Introduce a third-party log collection component to collect logs from all nodes
- Advantages: with a unified log management mechanism, logs can be saved for a long time, and are easy to retrieve; logs of multiple components can be sorted by time.
- Disadvantages: third-party components are not easy to integrate with TiDB SQL engine, which may increase the difficulty of cluster operation and maintenance; the log collection tool collects logs fully, so the collection process will take up system resources (Disk IO, Network IO).
- Each node provides a log service. TiDB pushes the predicate to the log retrieval interface through the log service of each node, and directly merges the logs returned by each node.
- Advantages: no third-party component is introduced. Only logs that have been filtered by the pushdown predicates are returned; the implementation can easily be integrated with TiDB SQL and reuse SQL engine functions such as filter and aggregation.
- Disadvantages: If the log files are deleted in some nodes, the corresponding log cannot be retrieved.
This proposal uses the second way after weighing in on the above advantages and disadvantages. That is, each node provides a log search service, and TiDB pushes the predicate in the log search SQL to each node. The semantics of the log search service is: search for local log files, and filter using predicates, and then return the matched results.
The following are the predicates that the log interface needs to process:
start_time: start time of the log retrieval (Unix timestamp, in milliseconds). If there is no such predicate, the default is 0.end_time:: end time of the log retrieval (Unix timestamp, in milliseconds). If there is no such predicate, the default isint64::MAX.pattern: filter pattern determined by the keyword. For example,SELECT * FROM cluster_logWHERE "%gc%"%gc%is the filtered keyword.level: log level; can be selected as DEBUG/INFO/WARN/WARNING/TRACE/CRITICAL/ERRORlimit: the maximum of logs items to return, preventing the log from being too large and occupying a large bandwidth of the network.. If not specified, the default limit is 64k.
Node performance sampling data
In a TiDB cluster, when performance bottlenecks occur, we usually need a way to quickly locate the problem. The Flame Graph was invented by Brendan Gregg. Unlike other trace and profiling methods, Flame Graph looks at the time distribution in a global view, listing all possible call stacks from bottom to top. Other rendering methods generally only list a single call stack or a non-hierarchical time distribution.
TiKV and TiDB currently have different ways of obtaining a flame graph and all of them rely on external tools.
TiKV retrieves the flame graph via:
textperf record -F 99 -p proc_pid -g -- sleep 60 perf script > out.perf /opt/FlameGraph/stackcollapse-perf.pl out.perf > out.folded /opt/FlameGraph/flamegraph.pl out.folded > cpu.svgTiDB retrieves the flame graph via:
textcurl http://127.0.0.1:10080/debug/pprof/profile > cpu.pprof go tool pprof -svg cpu.svn cpu.pprof
There are two main problems currently:
- The production environment may not contain the corresponding external tool (perf/flamegraph.pl/go)
- There is no unified way for TiKV and TiDB.
In order to solve the above two problems, this proposal proposes to build the flame map in TiDB in the flame map, so that TiDB and TiKV can both use SQL to trigger sampling, and the sampled data can be converted into query results in flame maps. This way we can reduce the dependency on external tools, and at the same time improve efficiency greatly. For each node, a sampling data acquisition function is implemented and the sampling interface provided, through which a specified format is output to the upper layer. The tentative output is the ProtoBuf format defined by [pprof](github.com/google/pprof).
Sampling data acquisition method:
- TiDB/PD: Use the sample data acquisition interface built in Golang runtime
- TiKV: Collect sample data using the
[pprof-rs](github.com/tikv/pprof-rs)library
Node monitoring information
Monitoring information mainly includes monitoring metrics defined internally by each component. At present, TiDB/TiKV/PD provides the /metrics HTTP API, through which the deployed Prometheus component pulls the monitoring metrics of each node of the cluster in a timing manner (15s interval by default). And the Grafana component is deployed to pull the monitoring data from Prometheus for visualization.
The monitoring information is different from the system information acquired in real time. The monitoring data is time-series data which contains the data of each node at each time point. It is very useful for troubleshooting and diagnosing problems, so how monitoring information is saved and inquired is very important for this proposal. In order to be able to use SQL to query monitoring data in TiDB, there are currently the following options:
- Use Prometheus client and PromQL to query the data from the Prometheus server
- Advantages: there is a ready-made solution; just register the address of Prometheus server to TiDB, which is simple to implement.
- Disadvantages: TiDB will rely more on Prometheus, which increases the difficulty for subsequent removal of Prometheus.
- Save the monitoring data for the most recent period (tentative 1 day) to PD and query monitoring data from PD.
- Advantages: this solution does not depend on the Prometheus server. Easy for subsequent removal of Prometheus.
- Disadvantages: requires implementation of time-series saving logic in PD and the corresponding query engine. The workload and difficulty are high.
In this proposal, we are opt to the second solution. Although it is more difficult to implement, it will benefit the follow-up work. Considering the difficulty and long development cycle, we can implement this function in three stages (the third stage is implemented depending on the specific situation):
Add the
remote-metrics-storageconfiguration to the PD and temporarily configure it as the address of the Prometheus Server. PD acts as a proxy, and the request is transferred to Prometheus for execution. The main considerations are as follows:- PD will have its own implementation of the query interface to realize bootstrapping. No other changes needed for TiDB.
- With bootstrapping realized, users can still use SQL to query monitoring information and diagnostic frameworks without relying on the Prometheus component deployed by TiDB
Extract the modules for persisting and querying Prometheus time series data and embed it in PD.
PD internally implements its own module for persisting and query time series data (currently CockroachDB's solution)
PD performance analysis
PD mainly handles scheduling and TSO services for TiDB clusters, where:
- TSO fetching accumulates only one atomic variable in Leader memory
- The Operator and OperatorStep generated by the schedule are only stored in memory, and the state in memory is updated according to the heartbeat information of the Region.
From the above information, it can be concluded that the performance impact of the new monitoring function on the PD can be ignored in most cases.
Retrieve system information
Since the TiDB/TiKV/PD component has previously exposed some system information through the HTTP API, and the PD mainly provides external services through the HTTP API, some interfaces of this proposal reuse existing logics and use the HTTP API to obtain data from various components. For example, configuration information.
However, because TiKV plan to completely removes the HTTP API in the future, only the existing interfaces will be reused for TiKV, and no new HTTP APIs will be added. There will be a unified gRPC service defined for log retrieval, hardware information, and system information acquisition. Each component implements their own services, which are registered to the gRPC Server during startup.
gRPC service definition
// Diagnostics service for TiDB cluster components.
service Diagnostics {
// Searches log in the target node
rpc search_log(SearchLogRequest) returns (SearchLogResponse) {};
// Retrieves server info in the target node
rpc server_info(ServerInfoRequest) returns (ServerInfoResponse) {};
}
enum LogLevel {
Debug = 0;
Info = 1;
Warn = 2;
Trace = 3;
Critical = 4;
Error = 5;
}
message SearchLogRequest {
int64 start_time = 1;
int64 end_time = 2;
LogLevel level = 3;
string pattern = 4;
int64 limit = 5;
}
message SearchLogResponse {
repeated LogMessage messages = 1;
}
message LogMessage {
int64 time = 1;
LogLevel level = 2;
string message = 3;
}
enum ServerInfoType {
All = 0;
HardwareInfo = 1;
SystemInfo = 2;
LoadInfo = 3;
}
message ServerInfoRequest {
ServerInfoType tp = 1;
}
message ServerInfoItem {
// cpu, memory, disk, network ...
string tp = 1;
// eg. network: lo1/eth0, cpu: core1/core2, disk: sda1/sda2
string name = 1;
string key = 2;
string value = 3;
}
message ServerInfoResponse {
repeated ServerInfoItem items = 1;
}Reusable HTTP API
Currently, TiDB/TiKV/PD includes a partially reusable HTTP API. This proposal does not migrate the corresponding interface to the gRPC Service. The migration will be completed by other subsequent plans. All HTTP APIs need to return data in JSON format. The following is a list of HTTP APIs that may be used in this proposal:
- Retrieve configuration information
- PD: /pd/api/v1/config
- TiDB/TiKV: /config
- Performance sampling interface: TiDB and PD contain all the following interfaces, while TiKV temporarily only contains the CPU performance sampling interface
- CPU: /debug/pprof/profile
- Memory: /debug/pprof/heap
- Allocs: /debug/pprof/allocs
- Mutex: /debug/pprof/mutex
- Block: /debug/pprof/block
Cluster information system tables
Each TiDB instance can access the information of other nodes through the HTTP API or gRPC Service provided by the first two layers. This way we can implement the Global View forw the cluster. In this proposal, the collected cluster information is provided to the upper layer by creating a series of related system tables. The upper layer includes not limited to:
- End User: Users can obtain cluster information directly through SQL query to troubleshooting problem
- Operation and maintenance system: The ability to obtain cluster information through SQL will make it easier for users to integrate TiDB into their own operation and maintenance systems.
- Eco-system tools: External tools get the cluster information through SQL to realize function customization. For example,
[sqltop](https://github.com/ngaut/sqltop)can directly obtain the SQL sampling information of the entire cluster through thestatements_summarytable of the cluster.
Cluster Topology System Table
To realize Global View for the TiDB instance, we need to provide a topology system table, where we can obtain the HTTP API Address and gRPC Service Address of each node. This way the Endpoints can be easily constructed for remote APIs. The Endpoint further acquires the information collected by the target node.
The implementation of this proposal can query the following results through SQL:
/* Detailed source-code truncated for AI context efficiency. */Monitoring information system table
Monitoring metrics are added and deleted as the program is iterated. For this reason, the same monitoring metric might be obtained through different PromQL expressions to monitor information in different dimensions. Therefore, it is necessary to design a flexible monitoring system table frame. This proposal temporarily adopts the this scheme - mapping expressions to system tables in the metrics_schema database. The relationship between expressions and system tables can be mapped in the following ways:
Define in the configuration file
text# tidb.toml [metrics_schema] qps = `sum(rate(tidb_server_query_total[$INTERVAL] offset $OFFSET_TIME)) by (result)` memory_usage = `process_resident_memory_bytes{job="tidb"}` goroutines = `rate(go_gc_duration_seconds_sum{job="tidb"}[$INTERVAL] offset $OFFSET_TIME)`Inject via HTTP API
textcurl -XPOST http://host:port/metrics_schema?name=distsql_duration&expr=`histogram_quantile(0.999, sum(rate(tidb_distsql_handle_query_duration_seconds_bucket[$INTERVAL] offset $OFFSET_TIME)) by (le, type))`Use special SQL commands
textmysql> admin metrics_schema add parse_duration `histogram_quantile(0.95, sum(rate(tidb_session_parse_duration_seconds_bucket[$INTERVAL] offset $OFFSET_TIME)) by (le, sql_type))`Load from file
textmysql> admin metrics_schema load external_metrics.txt #external_metrics.txt execution_duration = `histogram_quantile(0.95, sum(rate(tidb_session_execute_duration_seconds_bucket[$INTERVAL] offset $OFFSET_TIME)) by (le, sql_type))` pd_client_cmd_ops = `sum(rate(pd_client_cmd_handle_cmds_duration_seconds_count{type!="tso"}[$INTERVAL] offset $OFFSET_TIME)) by (type)`
After passing the above mapping, you can view the following table in the metrics_schema library:
mysql> use metrics_schema;
Database changed
mysql> show tables;
+-------------------------------------+
| Tables_in_metrics_schema |
+-------------------------------------+
| qps |
| memory_usage |
| goroutines |
| distsql_duration |
| parse_duration |
| execution_duration |
| pd_client_cmd_ops |
+-------------------------------------+
7 rows in set (0.00 sec)The way the field is determined when the expression is mapped to the system table depends mainly on the result data of the expression execution. Take expression sum(rate(pd_client_cmd_handle_cmds_duration_seconds_count{type!="tso"}[1m]offset 0)) by (type) as an example, the result of the query is:
| Element | Value |
|---|---|
| {type="update_gc_safe_point"} | 0 |
| {type="wait"} | 2.910521666666667 |
| {type="get_all_stores"} | 0 |
| {type="get_prev_region"} | 0 |
| {type="get_region"} | 0 |
| {type="get_region_byid"} | 0 |
| {type="scan_regions"} | 0 |
| {type="tso_async_wait"} | 2.910521666666667 |
| {type="get_operator"} | 0 |
| {type="get_store"} | 0 |
| {type="scatter_region"} | 0 |
The following are the query results mapped to the system table schema:
/* Detailed source-code truncated for AI context efficiency. */PromQL query statements with multiple labels will be mapped to multiple columns of data, which can be easily filtered and aggregated using existing SQL execution engines.
Performance profiling system table
The corresponding node performance sampling data is obtained by /debug/pprof/profile of each node, and then aggregated performance profiling results are output to the user in the form of SQL query. Since the SQL query results cannot be output in svg format, we need to solve the problem of output display.
Our proposed solution is to aggregate the sampled data and display all the call paths on a line-by-line basis in a tree structure. This can be implemented by using flamegraph. The core ideas and the corresponding implementations are described as below:
- Provide a global view: use a separate column for each aggregate result to show the global usage scale, which can be used to facilitate filtering and sorting to
- Show all call paths: all call paths are used as query results. And use a separate column to number the subtrees of each call path, we can easily view only one subtreeby filtering
- Hierarchical display: use the tree structure to display the stack, use a separate column to record the depth of the stack, which is convenient Filtering the depth of different stacks
This proposal needs to implement the following performance profiling table:
| Table | Description |
|---|---|
| tidb_profile_cpu | TiDB CPU flame graph |
| tikv_profile_cpu | TiKV CPU flame graph |
| tidb_profile_block | Stack traces that led to blocking on synchronization primitives |
| tidb_profile_memory | A sampling of memory allocations of live objects |
| tidb_profile_allocs | A sampling of all past memory allocations |
| tidb_profile_mutex | Stack traces of holders of contended mutexes |
| tidb_profile_goroutines | Stack traces of all current goroutines |
Globalized memory system table
Current the slow_query/statements_summary/processlist memory tables only contain single-node data. This proposal allows any TiDB instance to view information about the entire cluster by adding the following three cluster-level system tables:
| Table Name | Description |
|---|---|
| cluster_slow_query | slow_query table data for all TiDB nodes |
| cluster_statements_summary | statements summary table Data for all TiDB nodes |
| cluster_processlist | processlist table data for all TiDB nodes |
Configuration information of all nodes
For a large cluster, the way to obtain configuration by each node through HTTP API is cumbersome and inefficient. This proposal provides a full cluster configuration information system table, which simplifies the acquisition, filtering, and aggregation of the entire cluster configuration information.
See the following example for some expected results of this proposal:
/* Detailed source-code truncated for AI context efficiency. */Node hardware/system/load information system tables
According to the definition of gRPC Service protocol, each ServerInfoItem contains the name of the information and the corresponding key-value pair. When presented to the user, the type of the node and the node address need to be added.
/* Detailed source-code truncated for AI context efficiency. */Full-chain log system table
To search in the current log, users need to log in to multiple machines for retrieval respectively, and there is no easy way to sort the retrieval results of multiple machines by time. This proposal creates a new cluster_log system table to provide full-link logs, thereby simplifying the way to troubleshoot problems through logs and improving efficiency. This is achieved by pushing the log-filtering predicates down to the nodes through the search_log interface of the gRPC Diagnosis Service. The filtered logs will be eventually merged by time.
The following example shows the expected results of this proposal:
/* Detailed source-code truncated for AI context efficiency. */Cluster diagnostics
In the current cluster topology, each component is dispersed. The data sources and data formats are heterogeneous. It is not convenient to perform cluster diagnosis through programmatic ways, so manual diagnosis is required. With the data system tables provided by the previous layers, each TiDB node has a stable Global View for the full cluster. Based on this, a problem diagnosis framework can be implemented. By defining diagnostic rules, we can quickly discover existing and potential problems on your cluster.
Diagnostic rule definition: Diagnostic rules are the logics for finding problems by reading data from various system tables and detecting abnormal data.
Diagnostic rules can be divided into three levels:
- Discovery of potential problems: For example, identify insufficient disk capacity by determining the ratio of disk capacity and disk usage
- Locate an existing problem: For example, by looking at the load, we can know that the thread pool of Coprocessor has reached the bottleneck
- Provide fix suggestions: For example, by analyzing the disk IO, we observe a high latency. A recommendation to replace the disk can be provided to you.
This proposal mainly focuses on implementing the diagnostic framework and some diagnostic rules. More diagnostic rules need to be gradually accumulated based on experience, with the ultimate goal of becoming an expert system that reduces lower the bar of using and operation difficulty. The following content does not detail the specific diagnostic rules, mainly focusing on the implementation of the diagnostic framework.
Diagnostic framework design
A variety of user scenarios must be considered for the diagnostic framework design , including but not limited to:
- After selecting a fixed version, users won't upgrade the TiDB cluster version easily.
- User-defined diagnostic rules
- Loading new diagnostic rule without restarting the cluster
- The diagnosis framework needs to be easily integrated with the existing operation and maintenance system.
- Users may block some diagnostics. For example, if the user expects a heterogeneous system, heterogeneous diagnostic rules will be blocked by users.
- ...
Therefore, implementing a diagnostic system that supports hot rule loading is necessary. Currently there are the following options:
- Golang Plugin: Use different plugins to define diagnostic rules and load them into the TiDB processes
- Advantages: Low development threshold in Golang
- Disadvantages: Version management is error-prone and it requires compiling plugins with the same Golang version as the host TiDB - Embedded Lua: Load Lua scripts in runtime or during startup. The script reads system table data from TiDB, evaluates and provide feedback based on diagnostic rules
- Advantages: Lua is a fully host-dependent language with simple syntaxes; easy integration with the host
- Disadvantages: Relying on another scripting language - Shell Script: Shell supports process control, so you can define diagnostic rules with Shell
- Advantages: easy to write, load and execute
- Disadvantages: need to run on the machine where the MySQL client is installed
This proposal temporarily adopts the third option to write diagnostic rules using Shell. There is no intrusion into TiDB, and it also provides scalability for subsequent implementations of better solutions.
Design 2019 11 18 Tidb With Wasm (`docs/design/2019-11-18-tidb-with-wasm.md`)
Proposal:
- Author(s): Joshua
- Last updated: November 19
- Discussion at: https://github.com/pingcap/tidb/issues/13364
Abstract
This proposal proposes a way to build a bridge between TiDB ecosystem and WebAssembly ecosystem.
Background
As WebAssembly technology matures, more and more applications can be running in browsers, so that
users no longer have to endure cumbersome downloads and installation processes, which greatly reduces
the cost of promoting these applications. Obviously users who are using TiDB for the first time are
facing these problems. Using WebAssembly technology, we can reduce the barriers to user engagement
with TiDB, and we can also expand the TiDB audience with the help of the WebAssembly community.
Proposal
This proposal proposes to compile TiDB on various runtimes of WebAssembly and build TiDB applications
in the WebAssembly ecosystem:
- TiDB can work properly in browsers such as Chrome/Firefox on PC (done)
- tour.tidb.io and play.tidb.io can be used as the TiDB playground (done)
- Support community projects such as tidb-wasm-markdown
- TiDB can work properly in browsers on phones
- TiDB can run in wasmer and can be deployed to WebAssembly Shell
Rationale
WebAssembly is an open standard that defines a portable binary code format for executable programs,
a corresponding assembly language, and an interface to interact with the hosting environment. Its
main goal is to enable applications with high performance requirements to run on web pages. Of course,
its instruction format is also designed to be able to run on other platforms.
The WebAssembly virtual machine has better performance than JavaScript because WebAssembly's binary
format file has a more compact instruction structure, similar to ELF files (the most commonly used
binary instruction format on Unix systems, which is parsed by the loader and loaded into memory for
execution). WebAssembly is compiled into memory for execution by a specific runtime. The most common
runtimes include mainstream browsers, nodejs, and a generic implementation specifically designed for
WebAssembly - Wasmer. Even someone gives the Linux kernel a feature patch to integrate the WebAssembly
runtime into the kernel so that the user-written program can easily run in kernel mode.
Currently, all mainstream browsers support WebAssembly, so you don't have to worry about its compatibility
with browsers. The support for WebAssembly on various browsers is as follows:
Running in a non-browser environment involves interacting with the host system, which can be resolved by
WASI. We know that WebAssembly is an assembly language designed for abstract virtual machines, so it requires
a system interface to manipulate the abstracted operating system, which is defined by WASI. With WASI, the
application can be compiled once, run anywhere.
Go 1.11 experimentally added the support for WebAssembly and optimized it in Go 1.12. TiDB is written in
pure Golang. In theory, it can be compiled directly into WebAssembly according to Golang's official
document, allowing TiDB to run anywhere.
Implementation
Our implementation will be divided into several stages:
- Compile TiDB code into Wasm, regardless of whether it can run normally. We should solve the following problem:
- TiDB itself or some dependent third-party libraries may not be compatible with Wasm, so the compilation will
fail. They need to be modified accordingly.
- Migrate the result of stage 1 into PC browsers and wrap the page into the TiDB playground and TiDB tour. Possible
problems are:
- Golang compatibility with the browser environment.
- Due to the browser's security policy, we can't listen to a port using TiDB's original working mode. We need
to integrate a SQL terminal to TiDB instead of connecting via MySQL. At the same time, because the browser
prohibits the application from directly accessing local files, when the user runs SQL statements related to
file operations, we need to convert the semantics to the upload/download operations in the browser. - TiDB running in a browser cannot execute SQL in batches due to restraints of the browser, but this feature is
useful for users who want to verify TiDB’s compatibility with MySQL or other SQL database. We need to support
it in the browser.
- Migrate the result of stage 1 into phone browsers. Possible problems are:
- The webkit has a limit
on executable memory, typically it's 64 MB. However, the current Wasm compilation of TiDB is 76 MB, which requires
some downsizing. - The browser in the phone has a different interaction model than that in PC, so the SQL terminal must be compatible
with both.
- Migrate the result of stage 1 into Wasmer, and publish it to WAPM, so that it can run in any
platform easily with WAPM, even can run on WebAssembly shell. To achieve this, we should
solve:
- Golang doesn’t support WASI now, so we need to use a fork branch
of Golang and recompile the toolchain. - The result of stage 1 is too large and should be shrinked.
Solution of compilation problem
In the case of the problem of stage 1, incompatibility with WASM can be divided into the following cases:
- TiDB's own code has platform-dependent code.
- TiDB has platform-dependent code in a library that is directly or indirectly imported. This dependent library is controlled by PingCAP.
- TiDB has platform-dependent code in a library that is directly imported. This dependent library is not controlled by PingCAP.
- TiDB has platform-dependent code in a library that is indirectly imported. This dependent library is not controlled by PingCAP.
For case 1, we add the Wasm implementation for TiDB directly, according to Golang's platform-related file naming rules,
the file name format is:
- *_GOOS
- *_GOARCH
- *_GOOS_GOARCH
So the only thing we need do is to add *_wasm.go, and mock an implementation based on the implementation for other platforms.
For case 2, the solution is same as case 1, because we can modify the third-party code directly.
For case 3 and case 4, we can’t modify the code directly. There are 3 solutions:
- Open issues for these repos, and ask their owners to support WebAssembly
- Advantage: we don’t need to do it ourselves, and we can keep up with upstream
- Disadvantage: some repos have been archived, and some are no longer maintained, nobody will reply our issue
- Clone these repos to pingcap org and modify their code, then switch the reference of TiDB to the new repos.
- Advantage: we can control these code, and modify them any time
- Disadvantage: if the dependency chain is long, we should clone many repos, and we will detach from upstream.
- If TiDB only uses a few functions or symbols of these repos, we can:
- Create a new package in TiDB
- In this package, implement the functions required by Wasm platforms
- In this package, re-export the third party dependencies for non-Wasm platforms
- Modify the TiDB’s reference of the library to the new package, and all code except the new package shouldn’t reference
the third-party library.
In summary, when a third-party package does not support WebAssembly, we need to look at it in different situations.
The priority can be set as follows:
- If the third-party package is active, file an issue; if the author is busy, then create a PR
- If a third-party package has been archived or is no longer maintained, there are two cases:
- We rely heavily on it, then clone it and change it ourselves.
- We only rely slightly on it, then we use solution 3 to walk around it.
Solution of PC browser
We found that some specific system functions in Golang will crash if we try to run them in browser:
As shown in the figure above, when we execute the os.stat function, the runtime found that there
was no such a function in the environment. This situation occurs because Golang does not currently
support WASI, so it mocks the host interface using the wasm_exec.js file. However, only a few system
functions are mocked in this file, and os.stat is not among them. The solution is to mount the
functions we need to the fs object on the global object before we execute Wasm. For example:
function unimplemented(callback) {
const err = new Error("not implemented");
err.code = "ENOSYS";
callback(err);
}
function unimplemented1(_1, callback) { unimplemented(callback); }
function unimplemented2(_1, _2, callback) { unimplemented(callback); }
fs.stat = unimplemented1;
fs.lstat = unimplemented1;
fs.unlink = unimplemented1;
fs.rmdir = unimplemented1;
fs.mkdir = unimplemented2;
go.run(result.instance);Another problem for browser is that TiDB requires to listen to a port to provide service normally, which
is prohibited by the browser. Therefore, we need to change the way TiDB provides services — embedding a
SQL terminal. SQL terminal in the front-end field is very common, and we can find a ready-made one. The
only problem we need to deal with is the interface between the SQL terminal and the TiDB kernel. There
is such a method in TiDB:
// Exec executes a sql statement.
func (tk *TestKit) Exec(sql string, args ...interface{}) (sqlexec.RecordSet, error) {
var err error
if tk.Se == nil {
tk.Se, err = session.CreateSession4Test(tk.store)
tk.c.Assert(err, check.IsNil)
id := atomic.AddUint64(&connectionID, 1)
tk.Se.SetConnectionID(id)
}
ctx := context.Background()
if len(args) == 0 {
var rss []sqlexec.RecordSet
rss, err = tk.Se.Execute(ctx, sql)
if err == nil && len(rss) > 0 {
return rss[0], nil
}
return nil, errors.Trace(err)
}
stmtID, _, _, err := tk.Se.PrepareStmt(sql)
if err != nil {
return nil, errors.Trace(err)
}
params := make([]types.Datum, len(args))
for i := 0; i < len(params); i++ {
params[i] = types.NewDatum(args[i])
}
rs, err := tk.Se.ExecutePreparedStmt(ctx, stmtID, params)
if err != nil {
return nil, errors.Trace(err)
}
err = tk.Se.DropPreparedStmt(stmtID)
if err != nil {
return nil, errors.Trace(err)
}
return rs, nil
}This Exec function is exactly what we need. We can modify it slightly and use it in browsers.
The last two problems are that we need to access files and support SQL operations in batches. These
two problems can be combined into one problem, because the user executes SQL in batches in the form
of files. The only way for a browser to access a file is to upload and download, so our file access
must be converted to file upload/download in the browser. The solution is: detecting the SQL statements
executed by the user, and requesting the browser to pop the upload window when the user needs to access
files. Then the user selects a file to upload, and the data of the file is submitted to TiDB for processing.
The solution to mobile browser adaptation
Since the webkit has restrictions on the executable size in mobile browsers (usually 64 MB), and our TiDB-WASM
size is about 76 MB. An exception will occur when we run it in a mobile browser:
There are two options to reduce the size of the compiled file:
- Tailor the functionality of TiDB and remove features that are not useful in the browser (such as grpc)
- Looking for a better compilation solution. We may need to find the answer from the Golang compiler.
In addition to the browser's size limit on the Wasm binary file, we also need to solve the SQL terminal
input problem on the mobile phone. At present, the SQL terminal on PC browsers has been implemented,
but it cannot be used normally on mobile browsers, which process events differently as PC does. We need to
adapt the front end for mobile phones.
Compile to WASI
To run TiDB across platforms, we need to compile TiDB to WASI. The current version of Golang does
not support WASI, so running with wasmer after compilation will result in an error:
The above picture is the Hello world program compiled by Golang.
Golang does not plan to support WASI till v1.14, but this won’t stop us from compiling TiDB to WASI because
we already have this feature in a Golang fork. We can use this version to get TiDB running in all WASI-enabled
environments before Golang 1.14.
Design 2020 01 24 Collations (`docs/design/2020-01-24-collations.md`)
Proposal: Collations in TiDB
- Author(s): Wang Cong, Kolbe Kegel
- Last updated: 2020-02-09
- Discussion at: https://github.com/pingcap/tidb/issues/14573
Abstract
For now, TiDB only supports binary collations, this proposal is aimed to provide full collations support for TiDB.
Background
Collations
The term "Collation" is defined as the process and function of determining the sorting order of strings of characters, it varies according to language and culture.
Collations are useful when comparing and sorting data. Different languages have different rules for how to order data and how to compare characters. For example, in Swedish, "ö" and "o" are in fact different letters, so they should not be equivalent in a query (SELECT ... WHERE col LIKE '%o%'); additionally, Swedish sorting rules place "ö" after "z" in the alphabet. Meanwhile, in German, "ö" is officially considered a separate letter from "o", but it can be sorted along with "o", expanded to sort along with "oe", or sort at the end of the alphabet, depending on the context (dictionary, phonebook, etc.). In French, diacritics never affect comparison or sorting. The issue becomes even more complex with Unicode and certain Unicode encodings (especially UTF-8) where the same logical character can be represented in many different ways, using a variable number of bytes. For example, "ö" in UTF-8 is represented by the byte sequence C3B6, but it can also be represented using the "combining diaeresis" as 6FCC88. These should compare equivalently when using a multibyte-aware collation. Implementing this functionality as far down as possible in the database reduces the number of rows that must be shipped around.
Current collations in MySQL
In MySQL, collation is treated as an attribute of the character set: for each character set has options for different collations(and one of them is the default collation), every collation belongs to one character set only. The effects of collation are:
- It defines a total order on all characters of a character set.
- It determines if padding is applied when comparing two strings.
- It describes comparisons of logically identical but physically different byte sequences.
Some examples of the effects of collation can be found in this part of the MySQL Manual and this webpage.
Several collation implementations are described in this part of MySQL Manual:
- Per-character table lookup for 8-bit character sets, for example:
latin1_swedish_ci. - Per-character table lookup for multibyte character sets, including some of the Unicode collations, for example:
utf8mb4_general_ci.- Full UCA implementation for some Unicode collations, for example:
utf8mb4_0900_ai_ci.
- Full UCA implementation for some Unicode collations, for example:
Current collations in TiDB
For all character sets that are supported, TiDB accepts all of their collations by syntax and stores them as a part of metadata. The real collate-related behaviors are always in binary. For example,
tidb> create table t(a varchar(20) charset utf8mb4 collate utf8mb4_general_ci key);
Query OK, 0 rows affected
tidb> show create table t;
+-------+-------------------------------------------------------------+
| Table | Create Table |
+-------+-------------------------------------------------------------+
| t | CREATE TABLE `t` ( |
| | `a` varchar(20) COLLATE utf8mb4_general_ci NOT NULL, |
| | PRIMARY KEY (`a`) |
| | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin |
+-------+-------------------------------------------------------------+
1 row in set
tidb> insert into t values ('A');
Query OK, 1 row affected
tidb> insert into t values ('a');
Query OK, 1 row affected // Should report error "Duplicate entry 'a'"In the case above, the user creates a column with a case-insensitive collation utf8mb4_general_ci. Since the 'real' collation of TiDB is always utf8mb4_bin/binary, inserting data into the primary key with "A" and "a" does not lead to an error.
What's more, the collation utf8mb4_bin in MySQL is defined with attribute PAD SPACE, that is, trailing spaces are ignored when comparison. Currently utf8mb4_bin in TiDB is actually with attribute NO PAD:
tidb> create table t1(a varchar(20) charset utf8mb4 collate utf8mb4_bin key);
Query OK, 0 rows affected
tidb> insert into t1 values ('a')
Query OK, 1 row affected
tidb> insert into t1 values ('a ');
Query OK, 1 row affected // Should report error "Duplicate entry 'a '"Changes to make
Before diving into the details, we should notice that ALL strings in MySQL(and TiDB as well) are with implicit collations, if they're not explicitly specified. So, if we aim to update the collations in TiDB, codes related to strings comparison/lookup should be checked:
- Encoding/Decoding: update codec related functions in
codec/tablecodecpackage. - SQL Runtime:
- implement
WEIGHT_STRING()expression, which returns the sorting hexadecimal value(orsortKeys) for a string. This expression will be helpful for debugging collations. - update like/regex/string comparison related functions in
expressionpackage. - update the comparisons logic in Join/Aggregation executors in
executorpackage. - update the codes in
UnionScan(the internal buffer of transaction).
- implement
- SQL Optimizer: the optimizer may need to be aligned with the encoding changes in
plannerpackage. - DDL/Schema: check if the new collation is supported according to the versions of tables/columns, the related codes are in
ddlandinfoschemapackage. - Misc
- update string comparison related functions in
utilpackage. - check if range functions defined in table partitions work with collations.
- update string comparison related functions in
Proposal
Collate Interface
There are bascially two functions needed for the collate comparison:
- Function that is used to compare two strings according to the given collation.
- Function that is used to make a memory-comparable
sortKeycorresponding to the given string.
The interface can be defined as following:
type CharsetCollation interface {
// Compare returns an integer comparing the two byte slices. The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
Compare(a, b []byte) (int, error)
// Key returns the collation key for str, the returned slice will point to an allocation in Buffer.
Key(buf *Buffer, str []byte) ([]byte, error)
}The interface is quite similar to the Go collate package.
Row Format
The encoding layout of TiDB has been described in our previous article. The row format should be changed to make it memory comparable, this is important to the index lookup. Basic principle is that all keys encoded for strings should use the sortKeys result from Key()/KeyFromString() function. However, most of the sortKeys calculations are not reversible.
- For table data, encodings stay unchanged. All strings are compared after decoding with the
Compare()function. - For table indices, we replace current
ColumnValuewithsortKeyand encode theColumnValueto the value:- For unique indices:
textKey: tablePrefix{tableID}_indexPrefixSep{indexID}_sortKey Value: rowID_indexedColumnsValue- For non-unique indices:
textKey: tablePrefix{tableID}_indexPrefixSep{indexID}_sortKeys_rowID Value: indexedColumnsValue
Pros: Value of the index can be recovered from ColumnValue in value. It is able to scan just the index in order to upgrade the on-disk storage to fix bugs in collations, because it has the sortKey and the value in the index.
Cons: The size of index value on string column with new collations is doubled(we need to write both sortKey and indexedColumnsValue, their sizes are equal for most of the collations).
Rejected Alternative
A possible alternative option was considered as following:
- For table data, encodings stay unchanged.
- For table indices, we replace current
ColumnValuewithsortKeywithout additional change:- For unique indices:
textKey: tablePrefix{tableID}_indexPrefixSep{indexID}_sortKey Value: rowID- For non-unique indices:
textKey: tablePrefix{tableID}_indexPrefixSep{indexID}_sortKeys_rowID Value: null
Pros:
The current encoding layout keeps unchanged.
Cons:
Since index value can not be recovered from sortKey, extra table lookup is needed for current index-only queries, this may lead to performance regressions and the "covering index" can not work. The extra table lookup also requires corresponding changes to the TiDB optimizer.
The reason to reject this option is, as a distributed system, the cost of potential table lookup high so that it should be avoided it as much as possible. What's more, adding a covering index is a common SQL optimization method for the DBAs: table lookup can not be avoided through covering index is counter-intuitive.
Compatibility
Compatibility with MySQL
As stated before, MySQL has various different collation implementations. For example, in MySQL 5.7, the default collation of utf8mb4 is utf8mb4_general_ci, which has two main flaws:
- It only implement the
simple mappingsof UCA. - It used a very old version of UCA.
In MySQL 8, the default collation of utf8mb4 has been changed to utf8mb4_0900_ai_ci, in which the Unicode version is upgraded to 9.0, with full UCA implementation.
Should TiDB aim to support all collation of MySQL?
- If TiDB supports the latest collations only(for example, support
utf8mb4_0900_ai_cionly and treatutf8mb4_general_cias one of its alias). This seems to be 'standard-correct' but may lead to potential compatibility issues. - If TiDB supports all the collations, all of their implementations should be analyzed carefully. That is a lot of work.
Compatibility between TiDB versions
In this proposal, both of the compatibility issues can be solved in the new version of TiDB, and with the help of the version of metadata in TiDB, we can always indicate if a collation is old(the "fake one") or new(the "real one"). However, here we propose several requirements below and careful considerations are needed to meet them as many as possible:
- For an existing TiDB cluster, its behavior remains unchanged after upgrading to newer version
- a. After upgrade, the behavior of existing tables remains unchanged.
- b. After upgrade, the behavior of newly-created tables remains unchanged.
- c. If a TiDB cluster is replicating the data to a MySQL instance through Binlog, all replications remain unchanged. - Users of MySQL who requires collations can move to TiDB without modifying their scripts/applications.
- Users of TiDB can distinguish the tables with old collation and new collations easily, if they both exist in a TiDB cluster.
- All replications/backups/recovers through TiDB tools like Binlog-related mechanism, CDC and BR should not encounter unexpected errors caused from the changes of collations in TiDB. For example,
- When using BR, if backup data from old cluster is applied to the new cluster, the new cluster should know that the data is binary collated without padding, or otherwise 'Duplicate entry' error may be reported for primary key/unique key columns.
- If we don't allow both old collations and new collations exist in a TiDB cluster(the Option 4, see below), trying to make replications/backup & recovery between old/new clusters will break this prerequisite.
Based on the requirements listed above, the following behaviors are proposed:
Only TiDB clusters that initially bootstrapped with the new TiDB version are allowed to enable the new collations. For old TiDB clusters, everything remains unchanged after the upgrade.
We can also provide a configuration entry for the users to choose between old/new collations when deploying the new clusters.
Mark old collations with syntax comment. For a upgraded TiDB cluster, add comment like "
/* AS_BINARY_COLLATION */" for the old collations; all collations with "/* AS_BINARY_COLLATION */" comment are treated as the old ones.
Pros: Requirement 1 and 2 are met, requirement 3 can be met if we allow old/new collations exist in the same cluster in the future, since old collations are marked with syntax comment.
Cons: Since existing TiDB cluster can't get new collations enabled, requirement 3 is eliminated; Requirement 4 is not met.
Rejected Alternatives
The main reason to reject those options are: new collations that are not exist in MySQL have to be added, which may be confusing to the users and potentially break the compatibility between TiDB and MySQL.
Option 1
Add a series of new collations named with the suffix "_np_bin"(meaning "NO PADDING BINARY"), for example, utf8mb4_np_bin. Such new collations don't exist in MySQL, but they're the "real ones" used by current TiDB. After upgrading to newer TiDB versions, all old collations are shown as "_np_bin", MySQL collations behave the same with MySQL.
Pros: Requirement 1.a, 2, 3 and 4 are met.
Cons: Requirement 1.b, 1.c are not met.
Option 2
Keep all collations defined in TiDB as what they were, define a series of new collations that are actually compatible with MySQL collations. For example, we can create a new tidb_utf8_mb4_general_ci that is the same as utf8mb4_general_ci in MySQL. When TiDB users want the "real" collations, they can modify their CREATE TABLE statements to use the new ones.
Pros: Requirement 1.a, 1.b and 3 are met.
Cons: Requirement 1.c, 2 and 4 are not met, the namings are also confusing: collations that are named from MySQL are different from MySQL, but the ones named different from MySQL behave the same as MySQL.
Bug-fixing
We should also expect potential bugs in implementations of collations and get prepared for fixing them in the newer version of TiDB. However, this is not trivial since the collation affects the on-storage data, so a online data reorganization is required, which is a known limitation of TiDB. For now, another proposal is planning to support reorganizing data(the "online column type change"), we can expect it to be finished in the near future. Based on that, a possible solution for collation bug-fixing can be:
- Store a new version for the collations in the metadata of the column, it can be named as "CollationVersion" just like the current ColumnInfoVersion. This version is used to tracking the on-storage data generated by the collation.
- When we want to fix the bugs, related column index can be reorganized by a TiDB-specific DDL SQL like
ALTER TABLE ... TIDB UPGRADE COLLATION. When the job is done, collation version is updated to the latest one.
Implementation
Collations for 8-bit charsets
The implementation can be simply per-character mapping, same as MySQL.
Collations for Unicode charsets
The following features of the general collation algorithm will be supported:
- Primary Weight i.e. character
- Secondary Weight i.e. accent
- Tertiary Weight i.e. case
- PAD / NOPAD
All of them are supported by text/collate package of Go, so it is possible to map Go collations to some of UCA-based collations in MySQL like utf8mb4_unicode_ci/utf8mb4_0900_ai_ci, if we ignore the differences between UCA versions: current text/collate uses UCA version 6.2.0 and it is not changeable. However, the collations in MySQL are with different UCA versions marked in the names, for example, utf8mb4_0900_ai_ci uses version 9.0.
For non-standard UCA implementations in MySQL, i.e. the utf8mb4_general_ci. The implementation depends on our choice to the Compatibility with MySQL chapter, if a 100% compatibility of utf8mb4_general_ci is chosen, we need to implement it by our hands.
Collations in TiKV
For all collations supported by TiDB, they should be supported by TiKV as well so that the coprocessors can be pushed-down. Several libraries may be helpful for the work:
The libraries above work for standard UCA only, for all other collations, implementations should be done from nothing.
Migration Plans
The plan depends on the option chosen in Compatibility chapter.
- For existing TiDB clusters with current binary collations, nothing need to be done if the users are happy with them.
- For the potential migrations from MySQL to TiDB:
- If the collations used in MySQL have been implemented by TiDB, users from MySQL do not need to care about the collations when migrating to TiDB except Compatibility Option 2, in which the those collations need to be updated to their corresponding names.
- If there are collations that are not supported by TiDB yet, users may need to change the them to the supported ones and check if no constraint is broken after the change. The check can be done following the approach mentioned in this article.
Testing Plans
Here lists possible tests that can be done:
- The unit / integration tests corresponding to the updates in Changes to make
- The unit / integration tests corresponding to the implementations
- The collations cases that ported from mysql-tests
- The copr-pushdown tests of TiDB/TiKV
Possible Future Works
We have an opportunity to do a much better job than MySQL has done.
A collation, logically, should not be a property of a character set. Since all character sets are subsets of Unicode, collations can apply to Unicode codepoints without needing to be tied to individual character sets.
Further, a collation should not need to be a property of a column, it could rather be a property of an index, so that multiple collations can be defined for individual database objects. This would permit efficient querying of data by many different means.
Related issues
- https://github.com/pingcap/tidb/issues/222
- https://github.com/pingcap/tidb/issues/1161
- https://github.com/pingcap/tidb/issues/3580
- https://github.com/pingcap/tidb/issues/4353
- https://github.com/pingcap/tidb/issues/7519
- https://github.com/pingcap/tidb/issues/10192
Design 2020 04 17 Sql Sequence (`docs/design/2020-04-17-sql-sequence.md`)
TiDB SEQUENCE GENERATOR
- Author(s): AilinKid (Lingxiang Tai)
- Last updated: 2020-04-17
- Discussion at: https://tidbcommunity.slack.com/archives/CQNKBDVM0
Summary
"Sequence Generator" (hereinafter referred to as "Sequence") is a database feature introduced in SQL 2003 Standard. It is defined as "a mechanism for generating successive exact numeric values, one at a time, which can be either internal or external objects".
Based on the definition above, the conventional auto-increment columns of MySQL/TiDB can be considered as an internal implementation of Sequence Generator. This RFC describes the design of external Sequence Generator. Unless otherwise noted, the "Sequence" described below refers to external Sequence Generator.
Motivation
Standardization: Admittedly sequence is a well-defined syntax standard in SQL 2003. Although auto-increment can be regarded as an internal sequence implementation, it hasn't supported all the external features (such as CYCLE).
Usability: A sequence can be independent of tables, shared by multiple tables and be specified with CACHE details (either specify the number of CACHE or disable CACHE), which improves usability of the product.
Business Value: Sequence is a feature widely implemented in mainstream commercial databases. Users tend to expect TiDB can syntactically support sequence to reduce migration costs who migrate their business from other databases to TiDB.
Background
The columns in TiDB with 'auto-increment' attribute will cache batch values by default in each instance to ensure better performance, which means auto-increment only guarantees the uniqueness under a multi-tidb-node cluster. This kind of cache mode is uncontrollable and implicit in auto-increment.
But in sequence, we take it open. Users can specify whether to use cache mode or not, what the cache size should be, what's the min and max of the range like and so on. This factors make sequence more flexible, controllable and easy to use.
Syntax and Semantics
Create sequence statement:
CREATE SEQUENCE [IF NOT EXISTS] sequence_name
[ INCREMENT [ BY | = ] increment ]
[ MINVALUE [=] minvalue | NO MINVALUE | NOMINVALUE ]
[ MAXVALUE [=] maxvalue | NO MAXVALUE | NOMAXVALUE ]
[ START [ WITH | = ] start ]
[ CACHE [=] cache | NOCACHE | NO CACHE ]
[ CYCLE | NOCYCLE | NO CYCLE]Show create sequence statement:
SHOW CREATE SEQUENCE sequence_nameDrop sequence statement:
DROP SEQUENCE [IF EXISTS] sequence_name_listGet the next value of sequence:
NEXT VALUE FOR sequence_name / NEXTVAL(sequence_name)Get the previous value of sequence:
LASTVAL(sequence_name)Move the current position in sequence number axis:
SETVAL(sequence_name, num)Rationale
Sequence metadata
Sequence is a table-level object, sharing the same namespace with the base table and view objects, whose meta are recorded in *model.tableInfo. But actually sequence definition do not have columns in its meta, which means the sequence value cannot be operated by DML interface. The only way to do it is by setval function, after all, the sequence value is essentially a KV pair with some constraints.
Sequence values
Each sequence value will be stored in its own range, with the key format below:
DB:<dbID> SID:<sequenceID> ——> int64Reads and writes to the sequence value (via the functions nextval, setval), will be implemented by direct calls to the KV layer's Get, Inc, and Set functions. Since sequence objects store the value at the range of its own, it will cause hotspot at sequence meta under insertion intensive cases.
Sequence Transaction
Storing sequence values in their own ranges means that insertions to tables which use sequences will always touch two ranges. However, since the sequence update takes place outside of the SQL transaction, this should not trigger the 2PC commit protocol.
Sequence computation is under the expression framework, evaluating one value at a time. The values fetched by these functions won't be rolled back when the outer SQL transaction is aborted.
Sequence Binlog
Distinguished from auto-increment's rebase functionality, columns with sequence as default won't rebase it's value automatically when the inserted value was specified explicitly. Besides, sequence can also be used directly as the inserted expression value. Thus, it's necessary to sync the sequence value down to the upstream cluster.
Sequence binlog is triggered by both nextval and setval functions when the update reaches the storage directly rather than in the cache.
Sequence binlog is not a sort of DML binlog, but mocked as a kind of DDL job by specifying the job id equal to -1 specially. Therefore, the drainer won't take it for granted that it's a real ddl job and appears in ddl history queue.
Sequence Performance
The insertion performance of sequences is comparable to the auto-increment of the same cache size (now can be specified with auto_id_cache table option) in our recent tests on IDC cluster. The default cache size of sequence is 1000, which could achieve approximately 3 thousands TPS with 64 threads under our own SysBench.
Recommended scenarios for Sequence
Users have requirements for generating sequence value shared by multiple tables.
The user business tier prefers to encapsulate the unique value, for instance, combining the unique value with the date and the user ID to form a complete ID. And users wish that the unique value is maintained by the database.
Users are sensitive to the sequence space. To save the sequence space as much as possible, the trade-off is between the performance and the amount of
CACHE, and even using theNOCACHEmode.
Compatibility
Specific compatibility can be referred by MySQL’s compatibility.
Design 2020 04 20 Brie (`docs/design/2020-04-20-brie.md`)
Proposal: Backup/Restore/Import/Export via SQL
- Author(s): kennytm
- Last updated: 2020-04-20
- Discussion at: https://github.com/pingcap/tidb/pull/15274
Abstract
Support running backup, restore, import and export (BRIE) tasks directly on TiDB via SQL.
Background
BR is a TiDB ecosystem tool providing fast, KV-level logical backup and restore in SST format.
Lightning is another tool for importing SQL and CSV data dump into TiDB, using SST as intermediate storage.
We would like to integrate these tools directly into TiDB as SQL statements because
BR and Lightning requires direct connection with TiKV and PD.
Since direct operation on TiKV bypass TiDB's authentication, these ports must be closed from public.
In highly protected systems like DBaaS, this means BR and Lightning as separate tools cannot be used at all.Supporting SQL access also improves usability, as you don't need to install new components to use these functions,
and SQL should be more familiar with database operators.
Proposal
Syntax
Introduce 4 kinds of statements for executing backup, restore, import and export:
BACKUP DATABASE * TO 's3://storage/url';
RESTORE DATABASE * FROM 's3://storage/url';
IMPORT DATABASE * FROM 'file:///data/dump/';
EXPORT DATABASE * TO 's3://storage/url';(Note: there is no plan to implement EXPORT as of TiDB 4.0.)
SCHEMA can be used as alias of DATABASE, as usual.
These can be restricted to selected databases or tables only:
BACKUP DATABASE db1, db2, db3 TO 's3://storage/url';
BACKUP TABLE db1.tbl1, db2.tbl2, db3.tbl3 TO 's3://storage/url';Use query parameters to describe about the data source. Other options can be supplied at the end of the statement.
RESTORE DATABASE *
FROM 's3://storage/url?access-key=AAAAA&secret-access-key=SSSSS&force-path-style=1&endpoint=http://10.0.1.55:8888'
RATE_LIMIT = 512 MB/SECOND;The = sign in the options can be omitted.
List of options
Data source parameters
- s3://
- endpoint=http://s3.example.com:8080
- region=us-east-1
- storage-class=STANDARD
- sse=AES256
- acl=READ
- access-key=AKIAIOSFODNN7EXAMPLE
- secret-access-key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
- provider=aws
- force-path-style=1
- use-accelerate-endpoint=0
- gcs://
- endpoint=http://gcs.example.com:8080
- storage-class=STANDARD
- predefined-acl=READER
- credentials-file=/home/tidb/gcp_creds.json
Common options
- SEND_CREDENTIALS_TO_TIKV = 1
- CONCURRENCY = 32
- CHECKSUM = 1
- RATE_LIMIT = 125 MB/SECOND
- CHECKPOINT = 1
Backup/Export options
- SNAPSHOT = 4 HOUR AGO
- SNAPSHOT = '2020-04-20 15:00:00'
- SNAPSHOT = 416110777682551
- LAST_BACKUP = '2020-04-20 15:00:00'
- LAST_BACKUP = 416110777682551
Restore/Import options
- ONLINE = 1
Import/Export CSV options
- CSV_SEPARATOR = ','
- CSV_DELIMITER = '"'
- CSV_HEADER = COLUMNS
- CSV_HEADER = 0
- CSV_NOT_NULL = 1
- CSV_NULL = '\N'
- CSV_BACKSLASH_ESCAPE = 1
- CSV_TRIM_LAST_SEPARATORS = 1
Other Import options
- ANALYZE = 1
- SKIP_SCHEMA_FILES = 1
- BACKEND = 'local'
- TIKV_IMPORTER = '127.0.0.1:8287'
- ON_DUPLICATE = 'replace'
- STRICT_FORMAT = 1
Some niche configuration (e.g. Lightning's io-concurrency) are not exposed currently.
Execution
All 4 kinds of BRIE statements are synchronous — they block the current session until completion.
Nevertheless, these queries can be canceled using the standard KILL TIDB QUERY n statement.
Additionally, because the BRIE tasks are not using transactions, they cannot be executed concurrently.
When one BRIE task is already running, another BRIE statement must not start until the existing task has completed.
Because the BRIE statements interact with TiKV directly and can read from / write to arbitrary path,
all 4 statements require SUPER privilege to execute.
If the statement is canceled or an error is encountered, it will report an error e.g.
MySQL [tpcc]> backup table tpcc.stock to 'local:///tmp/br_tpcc_30';
ERROR 8124 (HY000): Backup failed: backup meta exists, may be some backup files in the path alreadyIf the statement completed successfully, it will report one row of summary e.g.
MySQL [tpcc]> backup database tpcc to 'local:///tmp/br_tpcc_32';
+-------------------------+-----------+-----------------+---------------------+---------------------+
| Destination | Size | BackupTS | Queue Time | Execution Time |
+-------------------------+-----------+-----------------+---------------------+---------------------+
| local:///tmp/br_tpcc_32 | 248665063 | 416099531454472 | 2020-04-12 23:09:48 | 2020-04-12 23:09:48 |
+-------------------------+-----------+-----------------+---------------------+---------------------+
1 row in set (58.453 sec)Note:
The
RESTORE(BR) andIMPORT(Lightning) operations are not using transactions and are not ACID compliant.The data and index KV pairs are ingested separately, i.e. a table being restored would have in an intermediate state
where some rows are missing index, and some index doesn't have corresponding rows.
If the operation has failed or canceled, the table would be stuck in this inconsistent state.There is currently no plan to change this behavior.
Status query
The status of the queued and running tasks can be queried using the SHOW statement:
SHOW BACKUPS;
SHOW RESTORES;
SHOW IMPORTS;
SHOW EXPORTS;Example:
MySQL [(none)]> show backups;
+-------------------------+---------+-------------------+---------------------+---------------------+------------+
| Destination | State | Progress | Queue_Time | Execution_Time | Connection |
+-------------------------+---------+-------------------+---------------------+---------------------+------------+
| local:///tmp/br_tpcc_30 | Backup | 98.38709677419355 | 2020-04-12 23:09:03 | 2020-04-12 23:09:25 | 4 |
| s3://bucket/prefix | Wait | 0 | 2020-04-12 23:09:48 | 0000-00-00 00:00:00 | 9 |
+-------------------------+---------+-------------------+---------------------+---------------------+------------+The content can be filtered using LIKE and WHERE clauses, e.g.
SHOW BACKUP LIKE 'local:%'; -- same as `Destination` LIKE 'local:%'
SHOW BACKUP WHERE `State` = 'Wait';Similar to the BRIE statements, these SHOW statements also require SUPER privilege.
To protect against leakage of secret keys,
all query parameters of S3 and GCS destinations are discarded in the SHOW statements.
Rationale
Synchronous execution
We have chosen synchronous execution entirely due to usability.
Internal tests find that it is very confusing that running BACKUP returns immediately while nothing is written out,
and not knowing when the BACKUP has finished.
This is also similar to the treatment of other long-running tasks in MySQL like CREATE INDEX and ANALYZE.
In most existing RDBMS which supports BRIE via SQL, they are executed synchronously:
| Dialect | Sync? | Syntax |
|---|---|---|
| Transact-SQL | Sync | RESTORE DATABASE db1 FROM URL = 'https://example.com/backup1.bak' |
| IBM DB2 | Sync | RESTORE DATABASE db1 FROM 'db2remote://example//backup/1' |
| SAP HANA | Sync | RECOVER DATA USING FILE ('/data/backup1') CLEAR LOG |
| MemSQL (ETL) | Async | CREATE PIPELINE restore_pl AS LOAD DATA S3 'bucket/backup1' CREDENTIALS '{…}' INTO TABLE db1.tbl1; START PIPELINE restore_pl |
| CockroachDB | Sync | RESTORE DATABASE db1 FROM 's3://bucket/backup1' |
On the other hand, synchronous execution is prone to accidental cancellation due to losing connection.
Anyway, if we do want to make it asynchronous, the syntax should be changed to emphasize this aspect (similar to MemSQL's syntax).
Syntax alternatives
The current syntax inherits from an early design, but they may be tweaked, e.g.
We use
DATABASE *to indicate no filtering, but perhaps we should omit it?sqlBACKUP TO 's3://storage/url'; RESTORE FROM 's3://storage/url'; IMPORT FROM 'file:///data/dump/'; EXPORT TO 's3://storage/url';
Configuring the data source
Currently we encode all storage-related parameters into the data source URL.
There are two other alternatives:
Use options:
sqlRESTORE DATABASE * FROM 's3://storage/url' S3_ACCESS_KEY = 'AAAAA' S3_SECRET_ACCESS_KEY = 'SSSSS' S3_FORCE_PATH_STYLE = 1 S3_ENDPOINT = 'http://10.0.1.55:8888' RATE_LIMIT = 512 MB/SECOND;Use a JSON configuration:
sqlRESTORE DATABASE * FROM 's3://storage/url' CONFIG = '{"s3":{"access-key":"AAAAA", "secret-access-key":"SSSSS", "force-path-style":true, "endpoint":"http://10.0.1.55:8888"}}' RATE_LIMIT = 512 MB/SECOND;
The current BR tool's command line is close to the first option, changed from using query parameters.
This was mainly introduced to avoid accidentally leaking the secret keys.
In this integration we need to strip off the query parameter as soon as possible.
For comparison, to configure a cloud destination in other RDBMS,
| Dialect | Configuration |
|---|---|
| Transact-SQL | Automatically configured inside Azure, not supported otherwise |
| IBM DB2 | User needs to configure the db2remote:// first, before executing the BRIE statements |
| SAP HANA | Cloud storage seems not supported |
| MemSQL | Two JSON strings, one for credentials and one for non-secret settings (e.g. region, endpoint) |
| CockroachDB | URL query parameters |
Compatibility and Migration Plan
The four BRIE statements are pure additions in TiDB 4.0+, and thus compatible with older versions.
During data migration, the BACKUP and EXPORT statements from upstream should be ignored.
RESTORE and IMPORT statements cannot be properly replicated.
Both of these will execute some DDL statements via SQL (which can be replicated).
However, the data ingestion skips the SQL layer, so binlog replication fails.
Even at TiKV level, because downstream doesn't have the same SST files, CDC may not work properly.
Currently RESTORE and IMPORT only support offline execution on a fresh cluster, i.e.
the cluster is not supposed to be serving external actors, and replication should not be set up,
so this is not expected to be a problem.
However, we should take this in mind when we support true online restore.
Implementation
The BRIE statements are implemented by embedding BR and Lightning as modules into TiDB.
These modules will expose an entry point (e.g. the RunBackup function in BR) which
- accepts a configuration structure defining entirely how a task should run, and
- executes the task in the current goroutine
The entry point function will be shared by both the CLI tool and TiDB executor.
TiDB should provide every information it knows into the configuration, including:
- PD addresses
- TLS certificate and key paths
The tools should upstream logs and metrics (which should happen automatically).
On the Backup/Restore part, PRs are already submitted to implement this:
- Parser — https://github.com/pingcap/parser/pull/746
- TiDB — https://github.com/pingcap/tidb/pull/15274
The Import (Lightning) part will start after the Backup/Restore design is accepted.
There is currently no plan to implement the Export part.
Testing Plan
Since BRIE relies on proper TiKV, the built-in testing framework using mocktikv will not work.
Testing is going to be relying entirely on integration tests.
Design 2020 05 08 Standardize Error Codes And Messages (`docs/design/2020-05-08-standardize-error-codes-and-messages.md`)
Proposal: Standardize error codes and messages
- Author(s): Joshua
- Last updated: September 29
- Discussion at: https://docs.google.com/document/d/1beoa5xyuToboSx6e6J02tjLLX5SWzmqvqHuAPEk-I58/edit?usp=sharing
Abstract
This issue proposes that TiDB components maintain standard error codes and error messages according to a consistent specification.
Motivation
When certain errors occur in TiDB components, users are often unaware of the meaning of the corresponding error message, and we plan the following two initiatives to alleviate this problem
- Specification of error codes for TiDB components
- Provide a program that allows users to quickly access information corresponding to error codes
Proposal
The Metafiles
In order to let TiUP know the the errors every component may throw, the components developers should
keep a metafile in the code repository. The metafile should be a toml file which looks like:
[8005]
error = '''Write Conflict, txnStartTS is stale'''
description = '''Transactions in TiDB encounter write conflicts.'''
workaround = '''
Check whether `tidb_disable_txn_auto_retry` is set to `on`. If so, set it to `off`; if it is already `off`, increase the value of `tidb_retry_limit` until the error no longer occurs.
'''
[9005]
error = '''Region is unavailable'''
description = '''
A certain Raft Group is not available, such as the number of replicas is not enough.
This error usually occurs when the TiKV server is busy or the TiKV node is down.
'''
workaround = '''Check the status, monitoring data and log of the TiKV server.'''Benefit:
- It's easy to write.
- It handles multiple lines well.
Tradeoff:
- The markdown content can't be previewed on writing.
Except toml, we also considered json and markdown format, see rationale section.
Rationale
This section introduce two candidate formats, which is deprecated.
metafile in JSON
The json format of metafile is like:
[
{
"code": 8005,
"error": "Write Conflict, txnStartTS is stale",
"description": "Transactions in TiDB encounter write conflicts.",
"workaround": "Check whether `tidb_disable_txn_auto_retry` is set to `on`. If so, set it to `off`; if it is already `off`, increase the value of `tidb_retry_limit` until the error no longer occurs."
},
{
"code": 9005,
"error": "Region is unavailable",
"description": "A certain Raft Group is not available, such as the number of replicas is not enough.\nThis error usually occurs when the TiKV server is busy or the TiKV node is down.",
"workaround": "Check the status, monitoring data and log of the TiKV server."
}
]Benefit:
- It's easy to write (every developer knows json).
- It's easy to parse (every programming language can handle json).
Tradeoff:
- Poor readability when multiple lines are involved.
- The markdown content can't be previewed on writing.
metafile in markdown
## Code: 8005
### Error
Write Conflict, txnStartTS is stale
### Description
A certain Raft Group is not available, such as the number of replicas is not enough.
This error usually occurs when the TiKV server is busy or the TiKV node is down.
### Workaround
Check whether `tidb_disable_txn_auto_retry` is set to `on`. If so, set it to `off`; if it is already `off`, increase the value of `tidb_retry_limit` until the error no longer occurs.
## Code: 9005
### Error
Region is unavailable
### Description
A certain Raft Group is not available, such as the number of replicas is not enough.
This error usually occurs when the TiKV server is busy or the TiKV node is down.
### Workaround
Check the status, monitoring data and log of the TiKV server.Benefit:
- It's easy to write.
- It handles multiple lines well.
- The markdown content can be previewed on writing.
Tradeoff:
- It's hard to implement (see example below)
- It's not self-consistent (see example below)
Tradeoff Example:
## Code: 8005
### Error
Write Conflict, txnStartTS is stale
### Description
A certain Raft Group is not available, such as the number of replicas is not enough.
This error usually occurs when the TiKV server is busy or the TiKV node is down.
### Workaround
## Code: 9005
### Error
Region is unavailable
### Description
A certain Raft Group is not available, such as the number of replicas is not enough.
This error usually occurs when the TiKV server is busy or the TiKV node is down.
### Workaround
Check the status, monitoring data and log of the TiKV server.As the syntax above, the 9005 block is the message part of 8005 block, so we expect it's result is the same as this toml:
[8005]
error = '''Write Conflict, txnStartTS is stale'''
description = '''Transactions in TiDB encounter write conflicts.'''
workaround = '''
## Code: 9005
### Error
Region is unavailable
### Description
A certain Raft Group is not available, such as the number of replicas is not enough.
This error usually occurs when the TiKV server is busy or the TiKV node is down.
### Workaround
Check the status, monitoring data and log of the TiKV server.
'''In this case, we must define the grammar and write a parser. Writing parser increase much complexity. What's worse
is that I found no grammar that fits it.
Summary
Through the above discussion, we recommend the toml version of metafile.
In addition, the error codes should be append only in case of conflict between versions.
The Error Definition
In the discussion above, an error has at least 4 parts:
- The error code: it's the identity of an error.
- The error field: it's the error itself the user can view in TiDB system. Like
err.Error(). - The description field: the expanded detail of why this error occurred. This could be written by developer outside the code, and the more detail this field explaining the better, even some guess of the cause could be included.
- The workaround filed: how to work around this error. It's used to teach the users how to solve the error if occurring in the real environment.
Besides, we can append a optional tags field to it:
[9005]
error = ""
description = ""
workaround = ""
tags = ["tikv"]The tags is used to classify errors (e.g. the level of seriousness). At the very beginning, we can ignore it since we don't have enough errors listed. Once we have enough data, we need to classify all errors by different dimensions. Then we will make out a standard about how to classify errors.
The Error Code Range
The error code is a 3-tuple of abbreviated component name, error class and error code, joined by a colon like {Component}:{ErrorClass}:{InnerErrorCode}.
Where Component field is the abbreviated component name of the error source, wrote as upper case, component names are mapped as below:
- TiKV: KV
- PD: PD
- DM: DM
- BR: BR
- TiCDC: CDC
- Lightning: LN
- TiFlash: FLASH
- Dumpling: DP
The ErrorClass is the name of the ErrClass the error belongs to, which defined by errors.RegisterErrorClass or someway likewise. If this is unacceptable (for projects not written with golang), anything that can classify the "type" of this error (e.g., package name.) would also be good.
The InnerErrorCode is the identity of this error internally, note that this error code can be duplicated in different component or ErrorClass. Both numeric and textual code are acceptable, but it would be better to provide textual code, which should be one or two short words with PascalCase to identity the error.
The content of ErrorClass and InnerErrorCode must matches [0-9a-zA-Z]+.
Here are some examples:
- BR:Internal:FileNotFound
- KV:Region:EpochNotMatch
- KV:Region:NotLeader
- DB:BRIE:BackupFailed
When logging, the format [ErrorCode] message should be used, for example:
[2020/07/17 18:38:06.461 +08:00] [ERROR] [import.go:259] ["failed to download file"] [error="[BR:Internal:DownloadFileFailed] failed to download foo.sst : File not found"] [errVerbose="..."]For compatibility with MySQL protocol, the code transmitted through the mysql protocol should be number only, others can be a number with a prefix string.
The code of each components looks like:
TiDB: {class}:{code}
TiKV: KV:{class}:{code}
PD: PD:{class}:{code}
TiFlash: FLASH:{class}:{code}
DM: DM:{class}:{code}
BR: BR:{class}:{code}
CDC: CDC:{class}:{code}
Lightning: LN:{class}:{code}
Dumpling: DP:{class}:{code}
{class}, {code} ~= [A-Za-z0-9]+For mysql protocol compatible components, table below shows the available purely numeric codes for each component.
| MySQL error code range | TiDB Family Component |
|---|---|
| [0, 9000) | TiDB |
| [8124, 8200) | Ecosystem Productions in TiDB |
| [9000, 9010) | TiKV / PD / TiFlash |
How It Works
In every build, the pipeline should fetch all these metafiles from all repositories:
mkdir -p errors
curl https://raw.githubusercontent.com/pingcap/tidb/master/errors.toml -o errors/tidb.toml
curl https://raw.githubusercontent.com/tikv/tikv/master/errors.toml -o errors/tikv.toml
curl https://raw.githubusercontent.com/tikv/pd/master/errors.toml -o errors/pd.tomlThen there are two tasks will be execute on the errors directory:
- Build a program that embed these errors, the program is used to quickly access information corresponding to error codes.
- Build the error code document from these errors.
Design 2020 05 11 Heap Profile Record (`docs/design/2020-05-11-heap-profile-record.md`)
Heap Profile Recorder
- Author(s): Yisaer (Song Gao)
- Last updated: 2020-05-11
- Discussion at: https://github.com/pingcap/tidb/pull/16777
Abstract
"Heap Profiler Recorder" profile the flat heap usage periodically in an extra goroutine to record the global SimpleLRUCache memory usage with an similar value.
Background
Currently, we have support memory usage and disk usage tracker for Executor. In #15407, we are going to support the Global Memory Tracker.
However, it would be too much work to realize calculating the memory usage of each Implementation of Plan and it might also causing much cpu consuming. To track the memory usage of SimpleLRUCache, we are trying to search the memory usage from runtime/pprof.
Proposal
We will record the whole SimpleLRUCache memory usage in the GlobalLRUMemUsageTracker memory tracker whose parent is GlobalMemoryUsageTracker memory tracker by using an extra goroutine to record the value searched and summed from heap profile periodically.
Rationale
When an golang application started, the runtime would startProfile in default including heap usage.
And runtime.MemProfileRate controls the fraction of memory allocations that are recorded and reported in the memory profile. In default, runtime.MemProfileRate is 512 KB which is also can be configured. When the whole heap usage of SimpleLRUCache is larger than the runtime.MemProfileRate, it would be reflected in the flat value of the pprof heap profile.
To verify whether kvcache.(*SimpleLRUCache).Put would reflect the real heap usage, I use following test to ensure it:
- fulfill the
SimpleLRUCachebyset @randomString = ? with 20000 times. - profile the heap Usage of
github.com/pingcap/tidb/util/kvcache.(*SimpleLRUCache).Putand the result is 2.55 MB
Let's dig into the Put then we can find the where the heap consumed:
/* Detailed source-code truncated for AI context efficiency. */We can find that the hash (the key of cache) and the element(the value of the cache) totally consume 2.55 MB.
- we use sizeof (the result is similar, but lower, not exact) to calculate the size of each key and element is 80byte and 40byte.
- As 2.28 MB (120 byte * 20000) is similar to the 2.55MB, we can ensure that the heap profile would reflect the heap usage of
SimpleLRUCache.
Compatibility and Migration Plan
None
Design 2020 06 01 Global Kill (`docs/design/2020-06-01-global-kill.md`)
Global Kill
- Author(s): pingyu (Ping Yu)
- Last updated: 2021-05-05
- Discussion at: https://github.com/pingcap/tidb/issues/8854
Abstract
This document introduces the design of global connection id, and the global KILL <connID> based on it.
Background
Currently connection ids are local to TiDB instances, which means that a KILL x must be directed to the correct instance, and can not safely be load balanced across the cluster, as discussed here.
Proposal
To support "Global Kill", we need:
- Global connection ids, which are unique among all TiDB instances.
- Redirect
KILL xto target TiDB instance, on which the connectionxis running. - Support both 32 & 64 bits
connID. 32 bitsconnIDis used on small clusters (number of TiDB instances less than 2048), to be fully compatible with all clients including legacy 32 bits ones, while 64 bitsconnIDis used for big clusters. Bit 0 inconnIDis a markup to distinguish between these two kinds.
Rationale
1. Structure of `connID`
32 bits
31 21 20 1 0
+--------+------------------+------+
|serverID| local connID |markup|
| (11b) | (20b) | =0 |
+--------+------------------+------+64 bits
63 62 41 40 1 0
+--+---------------------+--------------------------------------+------+
| | serverID | local connID |markup|
|=0| (22b) | (40b) | =1 |
+--+---------------------+--------------------------------------+------+Determine 32 or 64 bits
The key factor is serverID (see serverID section for detail), which depends on number of TiDB instances in cluster.
- Choose 32 bits when number of TiDB instances less than 2048. Otherwise choose 64 bits.
- When 32 bits chosen, upgrade to 64 bits when: 1) Fail to acquire
serverID(because of occupied) continuously more than 3 times (which will happen when size of cluster is increasing rapidly); 2) Alllocal connIDin 32 bitsconnIDare in used (seelocal connIDsection for detail). - When 64 bits chosen, downgrade to 32 bits in a gradually manner when cluster scales down from big to small, as TiDB instances keep
serverIDuntil next restart or lost connection to PD.
2. Bit 63
Bit 63 is always ZERO, making connID in range of non-negative int64, to be more friendly to exists codes, and some languages don't have primitive type uint64.
3. Markup
markup == 0indicates that theconnIDis just 32 bits long effectively, and high 32 bits should be all zeros. Compatible with legacy 32 bits clients.markup == 1indicates that theconnIDis 64 bits long. Incompatible with legacy 32 bits clients.markup == 1while high 32 bits are zeros, indicates that 32 bits truncation happens. SeeCompatibilitysection.
4. ServerID
serverIDis selected RANDOMLY fromserverIDs pool(see next) by each TiDB instance on startup, and the uniqueness is guaranteed by PD (etcd).serverIDshould be larger or equal to 1, to ensure that high 32 bits ofconnIDis always non-zero, and make it possible to detect truncation.serverIDs poolis:- All UNUSED
serverIDswithin [1, 2047] acquired fromCLUSTER_INFOwhen 32 bitsconnIDchosen. - All
serverIDswithin [2048, 2^22-1] when 64 bitsconnIDchosen.
- All UNUSED
On failure (e.g. fail connecting to PD, or all
serverIDare unavailable when 64 bitsconnIDchosen), we block any new connection.serverIDis kept by PD with a lease (defaults to 12 hours, long enough to avoid brutally killing any long-run SQL). If TiDB is disconnected to PD longer than half of the lease (defaults to 6 hours), all connections are killed, and no new connection is accepted, to avoid running with stale/incorrectserverID. On connection to PD restored, a newserverIDis acquired before accepting new connection.On single TiDB instance without PD, a
serverIDof1is assigned.
5. Local connID
local connID is allocated by each TiDB instance on establishing connections:
For 32 bits
connID,local connIDis possible to be integer-overflow and/or used up, especially on system being busy and/or with long running SQL. So we use a lock-free queue to maintain availablelocal connID, dequeue on client connecting, and enqueue on disconnecting. Whenlocal connIDexhausted, upgrade to 64 bits.For 64 bits
connID, allocatelocal connIDby auto-increment. Besides, flip to zero if integer-overflow, and checklocal connIDexisted or not by Server.clients for correctness with trivial cost, as the conflict is very unlikely to happen (It needs more than 3 years to use up 2^40local connIDin a 1w TPS instance). At last, return "Too many connections" error if exhausted.
6. Global kill
On processing KILL x command, first extract serverID from x. Then if serverID aims to a remote TiDB instance, get the address from CLUSTER_INFO, and redirect the command to it by "Coprocessor API" provided by the remote TiDB, along with the original user authentication.
7. Summary
| 32 bits | 64 bits | |
|---|---|---|
| ServerID pool size | 2^11 | 2^22 - 2^11 |
| ServerID allocation | Random of Unused serverIDs acquired from PD within pool. Retry if unavailable. Upgrade to 64 bits while failed more than 3 times | Random of All serverIDs within pool. Retry if unavailable |
| Local connID pool size | 2^20 | 2^40 |
| Local connID allocation | Using a queue to maintain and allocate available local connID. Upgrade to 64 bits while exhausted | Auto-increment within pool. Flip to zero when overflow. Return "Too many connections" if exhausted |
Compatibility
32 bits
connIDis compatible to well-known clients.64 bits
connIDis incompatible with legacy 32 bits clients. (According to some quick tests by now, MySQL client v8.0.19 supportsKILLa connection with 64 bitsconnID, whileCTRL-Cdoes not, as it truncates theconnIDto 32 bits). A warning is set prompting that truncation happened, but user cannot see it, becauseCTRL-Cis sent by a new connection in an instant.KILL TIDBsyntax andcompatible-kill-queryconfiguration item are deprecated.
Test Design
Prerequisite
Set small_cluster_size_threshold and local_connid_pool_size to small numbers (e.g. 4) by variable hacking, for easily switch between 32 and 64 bits connID.
Scenario A. 32 bits `connID` with small cluster
- A TiDB without PD, killed by Ctrl+C, and killed by KILL.
- One TiDB with PD, killed by Ctrl+C, and killed by KILL.
- Multiple TiDB nodes, killed {local,remote} by {Ctrl-C,KILL}.
Scenario B. Upgrade from 32 to 64 bits `connID`
- Upgrade caused by cluster scaled up from small to big.
- Upgrade caused by
local connIDused up.
Scenario C. 64 bits `connID` with big cluster
- Multiple TiDB nodes, killed {local,remote} by {Ctrl-C,KILL}.
Scenario D. Downgrade from 64 to 32 bits `connID`
- Downgrade caused by cluster scaled down from big to small.
Scenario E. Fault tolerant while disconnected with PD
- Existing connections are killed after PD lost connection for long time.
- New connections are not accepted after PD lost connection for long time.
- New connections are accepted after PD lost connection for long time and then recovered.
- Connections can be killed after PD lost connection for long time and then recovered.
Design 2020 06 24 Placement Rules In Sql (`docs/design/2020-06-24-placement-rules-in-sql.md`)
Defining placement rules in SQL
- Author(s): djshow832 (Ming Zhang), morgo (Morgan Tocker)
- Last updated: 2022-01-06
- Discussion PR: https://github.com/pingcap/tidb/pull/26221
- Tracking Issue: https://github.com/pingcap/tidb/issues/18030
- Original Document (Chinese): https://docs.google.com/document/d/18Kdhi90dv33muF9k_VAIccNLeGf-DdQyUc8JlWF9Gok
Table of Contents
- Introduction
- Motivation or Background
- Detailed Design
- Implementation
- Examples
- Impacts & Risks
- Investigation & Alternatives
- Unresolved Questions
- Changelog
Introduction
TiDB currently supports placement rules, which can define the placement of data in a more flexible and more granular way. But the current usage requires configuration files to manage them, and for end-users this can be complicated.
This document proposes an approach to configure placement rules through DDL statements. Usability is improved because the TiDB server parses the statements and notifies PD to perform the change.
Motivation or Background
The scenarios of defining placement rules in SQL include:
- Place data across regions to improve access locality
- Add a TiFlash replica for a table
- Limit data within its national border to guarantee data sovereignty
- Place latest data to SSD and history data to HDD
- Place the leader of hot data to a high-performance TiKV instance
- Increase the replica count of more important data
- Separate irrelevant data into different stores to improve availability
These scenarios usually fit into one of the following categories:
- An optimization or availability use case (such as improving data access locality)
- A compliance use case (such as ensuring data resides within a geographic region)
This proposal makes some intentional decisions so that both categories of use-cases can be handled correctly. It improves upon the earlier proposal by reducing the risk of misconfiguration which can affect compliance use cases.
Detailed Design
New Syntax Overview
The new syntax is based on a PLACEMENT POLICY statement and the ability to assign a placement policy to a schema, table or partition:
CREATE PLACEMENT POLICY policyName [placementOptions];
CREATE TABLE t1 (a INT) PLACEMENT POLICY=policyName;An earlier, experimental, version of this proposal featured the ability to assign placementOptions directly to objects (tables or partitions). This is no longer supported.
A PLACEMENT POLICY allows administrators to better keep track of usage. This can be seen as similar to how complex environments will use ROLES for management instead of directly assigning privileges to users. For example:
CREATE PLACEMENT POLICY `standardplacement` PRIMARY_REGION="us-east-1" REGIONS="us-east-1,us-east-2"In this context, "PRIMARY_REGION" and "REGIONS" are syntactic sugar which map to the label region. The following labels have special reserved words (the plural is used in contexts such as followers where multiple is possible):
hostandhosts: expected to be the same physical machine or hypervisor.rackandracks: similar to host; a group of machines that are physically close together and may suffer from many of the same failures.zoneandzones: similar to an AWS zone; much larger degree of blast radius isolation from a rack, but still vulnerable to issues such as a natural disaster.regionandregions: expected to be distributed far enough apart that there is isolation from disasters.
To use additional labels not in this list, see "Advanced Placement" below.
Creating a new table with the PLACEMENT POLICY assigned:
CREATE TABLE t1 (
id INT NOT NULL PRIMARY KEY,
b VARCHAR(100)
) PLACEMENT POLICY=`standardplacement`;Adding PLACEMENT POLICY to an existing table:
CREATE TABLE t2 (
id INT NOT NULL PRIMARY KEY,
b VARCHAR(100)
);
ALTER TABLE t2 PLACEMENT POLICY=`standardplacement`;Behavior notes:
CREATEorALTERand specifying aPLACEMENT POLICYthat does not exist results in an error: placement policy 'x' is not defined (see "Skipping Policy Validation" below)- Placement policies are globally unique names. Thus, a policy named
companyplacementpolicycan apply to the dbtestas well asuserdb. The namespace does not overlap with other DB objects. - Placement Policy names are case insensitive, and follow the same rules as tables/other identifiers for length (64 chars) and special characters.
- The full placement policy can be seen with
SHOW CREATE PLACEMENT POLICY x. This is useful for shorthand usage by DBAs, and consistent with other database objects. - It is possible to update the definition of a placement policy with
ALTER PLACEMENT POLICY x LEADER_CONSTRAINTS="[+region=us-east-1]" FOLLOWER_CONSTRAINTS="{+region=us-east-1: 1,+region=us-east-2: 1}";This is modeled on the statementALTER VIEW(where the view needs to be redefined). WhenALTER PLACEMENT POLICY xis executed, all tables that use this placement policy will need to be updated in PD. - The statement
RENAME PLACEMENT POLICY x TO yrenames a placement policy. TheSHOW CREATE TABLEoutput of all databases, tables and partitions that used this placement policy should be updated to the new name.
Advanced Placement
The syntax PRIMARY_REGION="us-east-1" REGIONS="us-east-1,us-east-2" is the recommended syntax for users, but it only works for supported labels.
Consider the case where a user wants to allocate placement based on the label disk. Using constraints is required:
ALTER PLACEMENT POLICY `standardplacement` CONSTRAINTS="[+disk=ssd]";When the constraints are specified as a dictionary ({}) numeric counts for each region must be specified and FOLLOWERS=n is disallowed:
ALTER PLACEMENT POLICY `standardplacement3` LEADER_CONSTRAINTS="[+region=us-east-1]" FOLLOWER_CONSTRAINTS="{+region=us-east-1: 1,+region=us-east-2: 1,+region=us-west-1: 1}";The placement policy above has 3 followers: 1 each in the regions us-east-1, us-east-2 and us-west-1.
Behavior notes:
- Advanced placement is available in the context of
CREATE|ALTER PLACEMENT POLICY, i.e. the usage of all placement syntax is expected to be the same in all contexts. - It is possible to set
CONSTRAINTS,LEADER_CONSTRAINTS,FOLLOWER_CONSTRAINTSandLEARNER_CONSTRAINTS. Assuming that bothCONSTRAINTSandFOLLOWER_CONSTRAINTSare specified, the conditions are "AND"ed together. - See "Constraints configuration" below for a full set of rules and syntax for constraints.
Metadata commands
Besides SHOW CREATE PLACEMENT POLICY x, it should be possible to summarize all placement for a database system. This is beneficial for compliance scenarios.
information_schema.placement_policies
A new system table information_schema.placement_policies is added to view all placement policies. The table definition is as follows:
+----------------------+---------------+------+------+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+---------------+------+------+---------+-------+
| POLICY_ID | bigint(64) | NO | | NULL | |
| CATALOG_NAME | varchar(512) | NO | | NULL | |
| POLICY_NAME | varchar(64) | NO | | NULL | |
| PRIMARY_REGION | varchar(1024) | YES | | NULL | |
| REGIONS | varchar(1024) | YES | | NULL | |
| CONSTRAINTS | varchar(1024) | YES | | NULL | |
| LEADER_CONSTRAINTS | varchar(1024) | YES | | NULL | |
| FOLLOWER_CONSTRAINTS | varchar(1024) | YES | | NULL | |
| LEARNER_CONSTRAINTS | varchar(1024) | YES | | NULL | |
| SCHEDULE | varchar(20) | YES | | NULL | |
| FOLLOWERS | bigint(64) | YES | | NULL | |
| LEARNERS | bigint(64) | YES | | NULL | |
+----------------------+---------------+------+------+---------+-------+information_schema.tables and information_schema.partitions
The information_schema tables for tables and partitions should be modified to have an additional field for tidb_placement_policy_name:
{name: "TIDB_PLACEMENT_POLICY_NAME", tp: mysql.TypeVarchar, size: 64},This helps make the information match what is available in SHOW CREATE TABLE, but in a structured format.
SHOW PLACEMENT
In addition to information_schema.tables and information_schema.partitions, a summary of the placement for a schema or table can be provided with SHOW PLACEMENT. The placement column in SHOW PLACEMENT shows the canonical version of the rules for an object (table or partition) with placement policies expanded. This is helpful for returning the canonical set of rules (which can get complicated since partitions inherit placement from tables, but can also be manually specified):
SHOW PLACEMENT FOR [{DATABASE | SCHEMA} schema_name] [TABLE table_name [PARTITION partition_name]];Examples:
/* Detailed source-code truncated for AI context efficiency. */TiDB will automatically find the effective rule based on the rule priorities.
This statement outputs at most 1 line. For example, when querying a table, only the placement rule defined on the table itself is shown, and the partitions in it will not be shown.
The output of this statement contains these fields:
- Target: The object queried. It can be a database, table, partition, or index.
- For policies, it is shown as the policy name.
- For database, it is shown in the format
DATABASE database_name - For table, it is shown in the format
TABLE database_name.table_name - For partition, it is shown in the format
TABLE database_name.table_name PARTITION partition_name
- Placement: An equivalent
ALTERstatement ontargetthat defines the placement rule. - Scheduling state: The scheduling progress from the PD aspect. It is always
NULLfor policies.
For finding the current use of a placement policy, the following syntax can be used:
SHOW PLACEMENT LIKE 'POLICY standardpol%';This will match for PLACEMENT POLICY names such as standardpolicy.
The scheduling_state is one of SCHEDULED, INPROGRESS, or PENDING. PENDING means the placement rule is semantically valid, but might not be able to be scheduled based on the current topology of the cluster.
Updates to Existing Syntax
CREATE DATABASE / ALTER DATABASE
The semantics of a PLACEMENT POLICY on a database/schema should be similar to the default character set attribute. For example:
CREATE DATABASE mydb [DEFAULT] PLACEMENT POLICY=`companystandardpolicy`;
CREATE TABLE mydb.t1 (a INT);
ALTER DATABASE mydb [DEFAULT] PLACEMENT POLICY=`companynewpolicy`;
CREATE TABLE mydb.t2 (a INT);
CREATE TABLE mydb.t3 (a INT) PLACEMENT POLICY=`companystandardpolicy`;- The tables t1 and t3 are created with the policy
companystandardpolicyand the table t2 is created withcompanynewpolicy. - The
DATABASEdefault only affects tables when they are created and there is no explicit placement policy defined. - Thus, the inheritance rules only apply when tables are being created, and if the database policy changes this will not update the table values. This differs slightly for table partitions.
- The statement
SHOW CREATE DATABASEis also available, and will show the [DEFAULT] PLACEMENT POLICY in TiDB feature specific comments (/*T![placement] DEFAULT PLACEMENT POLICY x */)
SHOW CREATE TABLE
The output of SHOW CREATE TABLE should escape placement policies in TiDB feature-specific comment syntax. i.e.
use test;
CREATE TABLE t1 (a int);
SHOW CREATE TABLE t1;
-->
CREATE TABLE `t1` (
`a` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
CREATE TABLE t2 (a int) PLACEMENT POLICY='acdc';
SHOW CREATE TABLE t2;
-->
CREATE TABLE `t2` (
`a` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![placement] PLACEMENT POLICY=`acdc` */;
ALTER DATABASE test DEFAULT PLACEMENT POLICY=`acdc`;
CREATE TABLE t3 (a int);
SHOW CREATE TABLE t3;
-->
CREATE TABLE `t3` (
`a` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin /*T![placement] PLACEMENT POLICY=`acdc` */;This helps ensure the highest level of compatibility between both TiDB versions and MySQL.
Placement Rules Syntax
Constraints configuration
The constraints syntax (described as "Advanced Placement" above) allows placement to be enforced based on labels. If CONSTRAINTS are omitted, it means no label constraint is enforced, thus the replicas can be placed anywhere.
CONSTRAINTS should be a string and in one of these formats:
- List:
[{+|-}key=value,...], e.g.[+region=us-east-1,-disk=hdd] - Dictionary:
{"{+|-}key=value,...":count,...}, e.g.{"+region=us-east-1,-disk=hdd": 1, +region=us-east-2: 2}
The prefix + indicates that data can only be placed on the stores whose labels contain such labels, and - indicates that data can’t be placed on the stores whose labels contain such labels. For example, +region=us-east-1,+region=us-east-2 indicates to place data only in us-east-1 and us-east-2 regions.
The key here refers to the label name, and value is the label value. The label name should have already been defined in the store configurations. For example, assuming a store has following labels:
[server]
labels = "region=us-east-1,rack=rack0,disk=hdd"Then +region=us-east-1 matches this store while +disk=ssd doesn't.
In the dictionary format, count must be specified, which indicates a quantity which must match. When the prefix is -, the count is still meaningful.
For example, FOLLOWER_CONSTRAINTS="{+region=us-east-1: 1,-region=us-east-2: 2}" indicates to place at least 1 follower in us-east-1, 2 replicas in anywhere but us-east-2 (by definition this will be us-east-1 since there are no other regions available).
In the list format, count is not specified. The number of followers for each constraint is not limited, but the total number of instances should still conform to the definition.
For example, FOLLOWER_CONSTRAINTS="[+region=us-east-1]" FOLLOWERS=3 indicates to place 3 followers on either us-east-1.
Label constraints can be implemented by defining label_constraints field in PD placement rule configuration. + and - correspond to property op. Specifically, + is equivalent to in and - is equivalent to notIn.
For example, +region=us-east-1,-disk=hdd is equivalent to:
"label_constraints": [
{"key": "region", "op": "in", "values": ["us-east-1"]},
{"key": "disk", "op": "notIn", "values": ["hdd"]}
]Field location_labels in PD placement rule configuration is used to isolate replicas to different zones to improve availability. For now, the global configuration can be used as the default location_labels for all placement rules defined in SQL, so it's unnecessary to specify it.
Specifying role count
The roles FOLLOWERS and LEARNERS also support an optional count in list format. For example:
CREATE PLACEMENT POLICY `standardplacement1` PRIMARY_REGION="us-east-1" REGIONS="us-east-1,us-east-2" FOLLOWERS=4;
CREATE PLACEMENT POLICY `standardplacement2` LEADER_CONSTRAINTS="[+region=us-east-1]" FOLLOWER_CONSTRAINTS="[+region=us-east-2]" FOLLOWERS=4;If the constraints is specified as a dictionary (e.g. {"+region=us-east-1":1}) the count is not applicable and an error is returned:
FOLLOWER_CONSTRAINTS="{+region=us-east-1: 1,-region=us-east-2: 2}" FOLLOWERS=3; -- technically accurate, but an error
FOLLOWER_CONSTRAINTS="{+region=us-east-1: 1,-region=us-east-2: 2}" FOLLOWERS=2; -- an errorFor dictionary format, the count is inferred by the constraint. The following constraint creates 3 followers:
FOLLOWER_CONSTRAINTS="{+region=us-east-1: 1,-region=us-east-2: 2}"Explanation:
- 1 follower in
us-east-1 - 2 followers not in
us-east-2
Schedule Property
When using either the syntactic sugar or list format for placement rules, PD is free to schedule followers/leaders wherever it decides. For example:
CREATE PLACEMENT POLICY `standardplacement1` PRIMARY_REGION="us-east-1" REGIONS="us-east-1,us-east-2" FOLLOWERS=4;- Are each of the followers split equally in us-east-1 and us-east-2?
- Could the majority of followers be placed in us-east-1? That would ensure fast quorum but reduced fault tolerance.
To address the ambiguity the concept of a "schedule" is introduced, which is the name for a strategy that PD uses to determine where to place instances. For an example:
CREATE PLACEMENT POLICY `standardplacement1` PRIMARY_REGION="us-east-1" REGIONS="us-east-1,us-east-2" FOLLOWERS=4 SCHEDULE="EVEN";The following SCHEDULE options are available:
EVEN: Followers will be balanced based on the value of the "region" label. So for example ifus-east-1has 15 stores andus-east-2has 5, it doesn't matter. 2 stores will be placed in each. This is recommended for increased fault tolerance.MAJORITY_IN_PRIMARY: As many followers as required to achieve quorum will be placed in the primary region. The remaining followers will be scheduled in the remaining secondary regions.
Key range configuration
In PD placement rule implementation, the key range must be specified. Now that table_name is specified in the ALTER TABLE statement, key range can be inferred.
Typically, key format is in such a format: t{table_id}_r{pk_value}, where pk_value may be _tidb_rowid in some cases. table_id can be inferred from table_name, thus the key range is t{table_id}_ to t{table_id+1}_.
Similarly, the key range of partitions can also be inferred.
Policy Validation
When placement policies are specified, they should be validated for correctness:
- The
FOLLOWERScount should respect raft quorum expectations. The default is2(which creates raft groups of 3). If the number is odd, it could lead to split brain scenarios, so a warning should be issued. Warnings should also be issued for a count less than 2 (this might be useful for development environments, so an error is not returned) - A policy that is impossible based on the current topology (region=us-east-1 and followers=2, but there is only 1 store in us-east-1) should be a warning. This allows for some transitional topologies.
- If the constraints are specified as a dictionary, specifying the count (i.e.
FOLLOWERS=n) is prohibited.
Skipping Placement Options
It should be possible to skip placement options. This can be seen as similar to skipping foreign key checks, which is often used by logical dumpers:
SET tidb_placement_mode='IGNORE';
CREATE TABLE t3 (a int) PLACEMENT POLICY `mycompanypolicy`;If a table is imported when tidb_placement_mode='IGNORE', and the placement policy does not validate, then the same rules of fallback apply as in the case DROP PLACEMENT POLICY (where policy is still in use).
The default value for tidb_placement_mode is STRICT. The option is an enum, and in future we may add support for a WARN mode.
Survival preference
Some important data may need to store multiple copies across availability zones, so as to have high disaster recovery survivability, such as region-level survivability, SURVIVAL_PREFERENCES can provide survivability preference settings.
The following example sets a constraint that the data try to satisfy the Survival Preferences setting:
CREATE PLACEMENT POLICY multiregion
follower=4
PRIMARY_REGION="region1"
SURVIVAL_PREFERENCES="[region, zone]";For tables with this policy set, the data will first meet the survival goal of cross-region data isolation, and then ensure the survival goal of cross-zone data isolation.
Note:
SURVIVAL_PREFERENCESis equivalent toLOCATION_LABELSin PD. For more information, please refer to Replica scheduling by topology label.
Ambiguous and edge cases
The following two policies are not identical:
CREATE PLACEMENT POLICY p1 FOLLOWER_CONSTRAINTS="[+region=us-east-1,+region=us-east-2]" FOLLOWERS=2;
CREATE PLACEMENT POLICY p2 FOLLOWER_CONSTRAINTS="{+region=us-east-1: 1,-region=us-east-2: 1}";This is because p2 explicitly requires a follower count of 1 per region, whereas p1 allows for 2 in any of the above (see "Schedule Property" above for an explanation).
Additional Semantics
Partitioned Tables
The key format of a partitioned table is t{partition_id}_r{pk_value}. As partition_id is part of the key prefix, the key range of a partition is successive. The key range is t{partition_id}_ to t{partition_id+1}_.
Defining placement rules of partitions is expected to be a common use case and is useful for both reducing multi-region latency and compliance scenarios. Because there are multiple key ranges for the table, multiple rules will be generated and sent to PD.
In Geo-Partitioning, the table must be splitted into partitions, and each partition is placed in specific zones. There are some kinds of partition placement:
- Place only leaders on one zone
- Place leaders and half of the followers on one zone
It’s up to users to choose the right solution.
The semantics of partitioning are different to the default database policy. When a table is partitioned, the partitions will by default inherit the same placement policy as the table. This can be overwritten on a per-partition basis:
CREATE TABLE t1 (id INT, name VARCHAR(50), purchased DATE)
PLACEMENT POLICY='companystandardpolicy'
PARTITION BY RANGE( YEAR(purchased) ) (
PARTITION p0 VALUES LESS THAN (2000) PLACEMENT POLICY='storeonhdd',
PARTITION p1 VALUES LESS THAN (2005),
PARTITION p2 VALUES LESS THAN (2010),
PARTITION p3 VALUES LESS THAN (2015),
PARTITION p4 VALUES LESS THAN MAXVALUE PLACEMENT POLICY='storeonfastssd'
);In this example, partition p0 uses the policy storeonhdd, partition p4 uses the policy storeonfastssd and the remaining partitions use the policy companystandardpolicy. Assuming the following ALTER TABLE statement is executed, only partitions p1-p3 will be updated:
ALTER TABLE t1 PLACEMENT POLICY=`companynewpolicy`;For the syntax:
ALTER TABLE pt
EXCHANGE PARTITION p
WITH TABLE nt;
```
If `nt` has placement rules associated with it, they will be retained when it becomes a partition of table `pt`. However, if no placement rules have been specified, then the rules of the table `pt` will be used. This helps protect against the case that a partition may need to have "default" placement rules, but default does not mean what the table uses (the output of `SHOW CREATE TABLE` would appear ambiguous). When the partition `p` is converted to table `nt`, it will continue to use the rules it had as a partition (either explicitly listed for the partition or the default for the table).
This behavior is inspired by how a `CHARACTER SET` or `COLLATE` attribute applies to a column of a table, and columns will use the character set defined at the table-level by default.
#### Removing placement from a database, table or partition
Placement policy can be removed from an object via the following syntax:
```sql
ALTER DATABASE test [DEFAULT] PLACEMENT POLICY SET DEFAULT; -- standard syntax for ALTER DATABASE
ALTER DATABASE test [DEFAULT] PLACEMENT POLICY=default; -- alternative
ALTER TABLE t1 PLACEMENT POLICY=default;
ALTER TABLE t1 PARTITION partition_name PLACEMENT POLICY=default;In this case the default rules will apply to placement, and the output from SHOW CREATE TABLE t1 should show no placement information. Thus, setting PLACEMENT POLICY=default must reset the following table_options:
FOLLOWERS=nLEARNERS=nPRIMARY REGIONREGIONSSCHEDULECONSTRAINTSFOLLOWER_CONSTRAINTSLEARNER_CONSTRAINTSPLACEMENT POLICYSURVIVAL_PREFERENCE
For a more complex rule using partitions, consider the following example:
ALTER TABLE t1 PARTITION p0 PLACEMENT POLICY="acdc";
-->
CREATE TABLE t1 (id INT, name VARCHAR(50), purchased DATE)
PARTITION BY RANGE( YEAR(purchased) ) (
PARTITION p0 VALUES LESS THAN (2000) PLACEMENT POLICY="acdc",
PARTITION p1 VALUES LESS THAN (2005)
);
ALTER TABLE t1 PLACEMENT POLICY="xyz";
-->
CREATE TABLE t1 (id INT, name VARCHAR(50), purchased DATE)
PLACEMENT POLICY="xyz"
PARTITION BY RANGE( YEAR(purchased) ) (
PARTITION p0 VALUES LESS THAN (2000) PLACEMENT POLICY="acdc",
PARTITION p1 VALUES LESS THAN (2005)
);
ALTER TABLE t1 PARTITION p0 PLACEMENT POLICY=DEFAULT;
-->
CREATE TABLE t1 (id INT, name VARCHAR(50), purchased DATE)
PLACEMENT POLICY="xyz"
PARTITION BY RANGE( YEAR(purchased) ) (
PARTITION p0 VALUES LESS THAN (2000),
PARTITION p1 VALUES LESS THAN (2005)
);The behavior above is described as ALTER TABLE t1 PARTITION p0 PLACEMENT POLICY=DEFAULT resets the placement of the partition p0 to be inherited from the table t1.
Sequences
Sequence is typically used to allocate ID in INSERT statements, so the placement of sequences affects the latency of INSERT statements.
However, sequence is typically used with cache enabled, which means very few requests are sent to sequence. So defining placement rules of sequences is not supported for now.
DDL on tables
The placement policy is associated with the definition of the table (and visible in SHOW CREATE TABLE). Thus, if a table is recovered by FLASHBACK or RECOVER, it is expected that the previous rules will be restored.
Similarly, TRUNCATE [TABLE] does not change the definition of a table. It is expected that as new data is inserted, it will continue to respect placement rules.
SHOW DDL jobs
Because CREATE TABLE and ALTER TABLE are DDL, changes to placement are also considered DDL and are visible via ADMIN SHOW DDL JOBS.
The fact that the DDL procedure in TiDB is mature helps to achieve some features of defining placement rules:
- Placement rules are defined in serial as there's only one DDL owner at the same time
- DDL is capable of disaster recovery as the middle states are persistent in TiKV
- DDL is rollbackable as the middle states can transform from one to another
- Updating schema version guarantees all active transactions are based on the same version of placement rules
The actual "completion" of the DDL job as far as TiDB is concerned is that PD has been notified of the placement rules for all of the affected regions. PD will then asynchronously apply the placement rules to all of the regions, and this progress is not observable via ADMIN SHOW DDL JOBS. The progress of scheduling can be observed via SHOW PLACEMENT or by reading information_schema.placement_policies.
Privilege management
Privilege management is quite straightforward:
ALTER [DATABASE|TABLE]statement requiresAlterprivilegeCREATE TABLEstatement requiresCreateprivilegeSHOW PLACEMENTonly shows the placement rules on the objects that visible to the current userinformation_schema.placement_policiesrequiresCREATE TABLEprivilege (it doesn't reveal anything about tables, but any user who creates a table can specify a placement policy, and needs to know the possible names of policies)ADMIN SHOW DDLrequiresSuperprivilegeCREATE PLACEMENT POLICY,DROP PLACEMENT POLICYandALTER PLACEMENT POLICYrequirePLACEMENT_ADMIN(a new dynamic privilege). This is because these objects have global scope.
Implementation
Storing Placement Policies
Placement policies will be stored in the internal meta data system, similar to tables or views. The policy name must be globally unique, but the definition of the table is not described in this proposal.
Storage Consistency
PD uses placement rules to schedule data, so a replica of placement rules for tables and partitions must be persistent in PD. However, because the rules are also considered part of the table definition, the placement rules are also persisted in PD.
The rules to guarantee consistency between these two sources is as follows:
- Changes to definition (
CREATE|ALTER TABLE,CREATE|ALTER PLACEMENT POLICY,CREATE|ALTER DATABASE) will first be persisted to TiKV. - The changes will then be applied to PD (and asynchronously apply)
It is safe to automatically retry applying the rules to PD because they are all idempotent in the current design.
If PD can not be modified, then the changes to TIKV are expected to rollback and the statement returns an error. Thus, TiKV acts as an undo log.
Because placement rules can also be configured outside of placement rules in SQL, PD should be considered the source of truth.
Querying placement rules
The scenarios where TiDB queries placement rules are as follows:
- The optimizer uses placement rules to decide to route cop requests to TiKV or TiFlash. It's already implemented and the TiFlash information is written into table information, which is stored on TiKV.
- It will probably be used in locality-aware features in the future, such as follower-read. Follower-read is always used when TiDB wants to read the nearest replica to reduce multi-region latency. In some distributed databases, it’s implemented by labelling data nodes and selecting the nearest replica according to the labels.
- Local transactions need to know the binding relationship between Raft leader and region, which is also defined by placement rules.
- Once a rule is defined on a table, all the subsequent partitions added to the table should also inherit the rule. So the
ADD PARTITIONoperation should query the rules on the table. The same is true for creating tables and indices. - The
SHOW PLACEMENTstatement should output the placement rules correctly.
As placement rules will be queried in case 1, 2 and 3, low latency must be guaranteed. As discussed in section "Storing placement rules", PD is the source of truth. To lower the latency, the only way is caching the placement rules in TiDB.
Since the cache is created, there must be a way to validate it. Different from region cache, placement rules cache can only be validated each time from PD. There are some ways to work around:
- Update the schema version once a placement rule is changed, just like other DDL. PD broadcasts the latest schema version to all the TiDB instances, and then TiDB instances fetch the newest placement rules from PD. There will be a slight delay for queries before reading the latest placement rules. The side effect is that more transactions will retry since the schema version is changed.
- TiDB queries placement rules from PD periodly. The delay is controllable but not eliminable.
- Once a placement rule is changed, PD broadcasts it to all the TiDB instances. In this approach, the schema version is not involved, so transactions are not affected. The delay is not eliminable either.
All the approaches above will result in a delay. Fortunately, for case 1 and 2 above, delay is acceptable. It doesn’t matter much if the optimizer doesn’t perceive the placement rules changement immediately. The worst result is that the latency is relatively high for a short time.
For case 3, although delay is acceptable, but all TiDB instances must be always consistent on the placement rules. To achieve this goal, the schema version needs to be updated, thus transactions with old placement rules will fail when committed.
For case 4 and 5, delay is not acceptable. Once the placement rules are written successfully, subsequent DDL statements should fetch the latest placement rules to guarantee linearizability. Now that the schema version is changed and the latest placement rules are broadcast to all the TiDB instances immediately, delay is eliminable.
Once the schema version is changed, all TiDB instances recognize the object ID and fetch placement rules from PD, rather than TiKV.
To query the placement rules on a specified object, the object ID should be written to the placement rules, or it can be inferred from other fields. Now that id contains the object ID, TiDB can decode the object ID from it. See section "Building placement rules" for details.
Building placement rules
There needs a way to map the placement rules in SQL to PD placement rule configuration. Most of the fields are discussed above, so this part focuses on group_id, id, start_key and end_key.
group_id is used to identify the source of the placement rules, so group_id is tidb.
ALTER PLACEMENT POLICY and DROP PLACEMENT POLICY need to find the rules of a specified object efficiently. It can be achieved by encoding the object ID in id.
However, an object (database, table, partition) may have multiple rules for a single role. For example:
CREATE PLACEMENT POLICY p1
FOLLOWER_CONSTRAINTS="{+region=us-east-1: 2,+region=us-east-2: 1}";
CREATE TABLE t1 (a int) PLACEMENT POLICY p1;It needs 2 placement rules for follower in the PD placement rule configuration, because each rule can only specify one count. To make id unique, a unique identifier must be appended to id. DDL job ID plus an index in the job is a good choice.
Take the case above for example, assuming the table ID of t is 100, the ID of the DDL job executing this statement is 200, then id of the placement rules are 100-200-1 and 100-200-2.
The prefix of id is in such a format:
- Database: database id
- Table: table id
- Partition: partition id
- Unpartitioned index: the concatenation of table id and index id, e.g.
100_1 - Partitioned index: the concatenation of partition id and index id
To query all the placement rules for one object, PD looks for all the id with a specific prefix.
As all placement rules are mapped to PD placement rule configurations, start_key and end_key must be generated for each object. However, databases and partitioned tables have no key ranges, so the only way is to generate a key range with no actual records.
As database IDs are all globally unique, it's fine to replace table ID with database ID in the key range. For example, assuming the database ID is 100, then the string format of its key range is:
start_key:t{database_id}_end_key:t{database_id+1}_
It's same for partitioned tables.
Region label configuration
Instead of configuring key ranges, you can also configure region labels in placement rules. PD supports label rules, which indicate the key range of a database / table / partition name. TiDB pushes label rules once the schema changes, so that PD maintains the relationship between database / table /partition names and their corresponding key ranges.
This is what a label rule may look like:
{
"id": "db1/tb1",
"labels": [
{
"key": "database-name",
"value": "db1"
},
{
"key": "table-name",
"value": "db1/tb1"
}
],
"match-type": "key-range",
"match": {
"start-key": "7480000000000000ff0a00000000000000f8",
"end-key": "7480000000000000ff0b00000000000000f8"
}
}It connects the table name db1/tb1 with the key range.
Now you need to connect the label with the database / table / partition name in the placement rules.
For example:
{
"group_id": "group_id",
"id": "id",
"region_label_key": "schema/table-name",
"region_label_value": "db1/tb1",
"role": "leader",
"label_constraints": [
{"key": "region", "op": "in", "values": ["us-east-1", "us-east-2"]}
]
}Combined with the label rule, PD indirectly knows the key range of db1/tb1 is marked with the label constraint {"key": "region", "op": "in", "values": ["us-east-1", "us-east-2"]}.
Database placement
Defining placement rules of databases simplifies the procedures when there are many tables.
For example, in a typical multi-tenant scenario, each user has a private database. The dataset in one database is relatively small, and it’s rare to query across databases. In this case, a whole database can be placed in a single region to reduce multi-region latency.
For another example, multiple businesses may run on a single TiDB cluster, which can reduce the overhead of maintaining multiple clusters. The resources of multiple businesses need to be isolated to avoid the risk that one business takes too many resources and affects others.
Since key range is not successive in one database, each table in the database corresponds to at least one placement rule, so there may be many placement rules. In either case above, there may be up to millions of tables in one database, which costs lots of time to update the rules and lots of space to store the rules.
Another option is to take advantage of the region label, which is described earlier.
In the example below, it defines multiple label rules for one database. Each label rule corresponds to one table or partition.
{
"id": "db1/tb1",
"labels": [
{
"key": "database-name",
"value": "db1"
},
{
"key": "table-name",
"value": "db1/tb1"
}
],
"match-type": "key-range",
"match": {
"start-key": "7480000000000000ff0a00000000000000f8",
"end-key": "7480000000000000ff0b00000000000000f8"
}
},
{
"id": "db1/tb2",
"labels": [
{
"key": "database-name",
"value": "db1"
},
{
"key": "table-name",
"value": "db1/tb2"
}
],
"match-type": "key-range",
"match": {
"start-key": "7480000000000000ff0c00000000000000f8",
"end-key": "7480000000000000ff0d00000000000000f8"
}
}Then you need only one placement rule for the database. When you change the placement of the database, you need to update one placement rule. However, when you drop a database, you need to delete multiple label rules plus one placement rule.
Rule priorities
Tables only inherit rules from databases when they are created, and the value is saved in the meta data. Thus, the rules of priorities are simplified from an earlier version of this proposal (and are more inline with how character sets are inherited).
The only rules are that indexes and partitions inherit the rules of tables. Partitions can explicitly overwrite the placement policy, but indexes currently do not allow placement policy to be defined (this simplification was made intentionally since there is not a clear use case until global secondary indexes are introduced).
Thus the priority is:
db --> table (Copied from db on create if placement not explicitly specified for the table)
unpartitioned table --> index
partitioned table --> partition (can be overwritten) --> indexFor example:
- At the beginning, all data is placed based on the default placement rules.
- When a placement rule is added on table
t, all data ontis placed based on the rule. - When a placement rule is added on partition
p0oft, all data onp0is placed based on the rule ofp0, but other partitions stay still. - When the placement rule on
p0is removed, data onp0is placed based on the rule oft, just like other partitions.
Rules priorities are checked when a placement rule is added, altered, or dropped.
Rule priorities can be implemented by fields index and override in the PD placement rule configuration. override is alway enabled, and index stands for the priority. Rules with higher index will overwrite the rules with lower index and same key range, but rules with same index don't overwrite each other, they just accumulate.
Specifically, index is in such a format:
indexof default placement rules is 0indexof database placement rules is 1indexof table placement rules is 2indexof partition placement rules is 3indexof index placement rules is 4
In such a way, the most granular rule always works.
Examples
Optimization: Follower read in every region
This optimization is straight forward:
CREATE PLACEMENT POLICY local_stale_reads FOLLOWER_CONSTRAINTS="{+us-east-1: 1,+us-east-2: 1,+us-west-1: 1,+us-west-2: 1}";
CREATE TABLE t (a int, b int) PLACEMENT POLICY=`local_stale_reads`;Optimization: Latest data on SSD
This optimization uses labels to define the storage type:
CREATE PLACEMENT POLICY storeonfastssd CONSTRAINTS="[+disk=ssd]";
CREATE PLACEMENT POLICY storeonhdd CONSTRAINTS="[+disk=hdd]";
CREATE TABLE t1 (id INT, name VARCHAR(50), purchased DATE)
PLACEMENT POLICY='companystandardpolicy'
PARTITION BY RANGE( YEAR(purchased) ) (
PARTITION p0 VALUES LESS THAN (2000) PLACEMENT POLICY='storeonhdd',
PARTITION p1 VALUES LESS THAN (2005),
PARTITION p2 VALUES LESS THAN (2010),
PARTITION p3 VALUES LESS THAN (2015),
PARTITION p4 VALUES LESS THAN MAXVALUE PLACEMENT POLICY='storeonfastssd'
)
;Optimization: Multi-tenancy / control of shared resources
This example is similar to latest data on SSD. The customer has a large TiDB Cluster with several workloads that are running on it. They might want to reduce the blast radius of individual users impacting each-other, and potentially improve QoS.
Assuming a schema per tenant, it is easy to create a set of "resource pools". Each pool is a label, which contains a set of tikv-servers (with sufficient capacity, and nodes to provide high availability still):
CREATE PLACEMENT POLICY poola CONSTRAINTS="[+pool=poola]";
CREATE PLACEMENT POLICY poolb CONSTRAINTS="[+pool=poolb]";
CREATE PLACEMENT POLICY poolc CONSTRAINTS="[+pool=poolc]";
ALTER DATABASE workload1 PLACEMENT POLICY=`poola`;
/* for each existing table (new ones will not require this) */
ALTER TABLE workload1.t1 PLACEMENT POLICY=`poola`;
CREATE DATABASE workload2 PLACEMENT POLICY=`poolb`;
CREATE DATABASE workload3 PLACEMENT POLICY=`poolb`;
CREATE DATABASE workload4 PLACEMENT POLICY=`poolb`;
CREATE DATABASE workload5 PLACEMENT POLICY=`poolb`;
CREATE DATABASE workload6 PLACEMENT POLICY=`poolc`;Compliance: User data needs geographic split
This example has limitations based on the current implementation. Consider the following users table:
CREATE TABLE users (
id INT NOT NULL auto_increment,
username VARCHAR(64) NOT NULL,
email VARCHAR(64) NOT NULL,
dateofbirth DATE NOT NULL,
country VARCHAR(10) NOT NULL,
PRIMARY KEY (id),
UNIQUE (username)
);We may want to ensure that users that have users in the EU store their data in a specific location. On the surface this looks straight forward:
CREATE TABLE users (
id INT NOT NULL auto_increment,
username VARCHAR(64) NOT NULL,
email VARCHAR(64) NOT NULL,
dateofbirth DATE NOT NULL,
country VARCHAR(10) NOT NULL,
PRIMARY KEY (id),
UNIQUE (username)
) PARTITION BY LIST COLUMNS (country) (
PARTITION pEurope VALUES IN ('DE', 'FR', 'GB') PLACEMENT POLICY='europe',
PARTITION pOther VALUES IN ('US', 'CA', 'MX')
);However, the definition is not valid. The unique index on username can not be enforced, because there are no global indexes for partitioned tab