# Technical Documentation: pingcap/TiDB

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/pingcap/TiDB)

### Overview (README.md)

<div align="center">
<a href='https://www.pingcap.com/?utm_source=github&utm_medium=tidb'>
<img src="docs/tidb-logo.png" alt="TiDB, a distributed SQL database" height=100></img>
</a>

---

[](https://github.com/pingcap/tidb/blob/master/LICENSE)
[](https://golang.org/)

[](https://prow.tidb.net/?repo=pingcap%2Ftidb&type=postsubmit&job=merged-tidb-build)
[](https://goreportcard.com/report/github.com/pingcap/tidb)
[](https://github.com/pingcap/tidb/releases)
</div>

# 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](#key-features)
- [Quick Start](#quick-start)
- [Need Help?](#need-help)
- [Architecture](#architecture)
- [Contributing](#contributing)
- [License](#license)
- [See Also](#see-also)
- [Acknowledgments](#acknowledgments)

## Key Features

- **[Distributed Transactions](https://www.pingcap.com/blog/distributed-transactions-tidb?utm_source=github&utm_medium=tidb)**: 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](https://docs.pingcap.com/tidb/stable/scale-tidb-using-tiup?utm_source=github&utm_medium=tidb)**: 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](https://docs.pingcap.com/tidbcloud/high-availability-with-multi-az?utm_source=github&utm_medium=tidb)**: 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)](https://www.pingcap.com/blog/htap-demystified-defining-modern-data-architecture-tidb?utm_source=github&utm_medium=tidb)**: 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](https://www.pingcap.com/cloud-native?utm_source=github&utm_medium=tidb)**: TiDB can be deployed in public clouds, on-premises, or natively in Kubernetes. [TiDB Operator](https://docs.pingcap.com/tidb-in-kubernetes/stable/tidb-operator-overview/?utm_source=github&utm_medium=tidb) helps manage TiDB on Kubernetes, automating cluster operations, while [TiDB Cloud](https://tidbcloud.com/?utm_source=github&utm_medium=tidb) provides a fully-managed service for easy and economical deployment, allowing users to set up clusters with just a few clicks.

- **[MySQL Compatibility](https://docs.pingcap.com/tidb/stable/mysql-compatibility?utm_source=github&utm_medium=tidb)**: 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](https://docs.pingcap.com/tidb/stable/ecosystem-tool-user-guide?utm_source=github&utm_medium=tidb) to help easily migrate application data into TiDB.

- **[Open Source Commitment](https://www.pingcap.com/blog/open-source-is-in-our-dna-reaffirming-tidb-commitment?utm_source=github&utm_medium=tidb)**: 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

1. Start a TiDB cluster.

    - **On local playground**. To start a local test cluster, refer to the [TiDB quick start guide](https://docs.pingcap.com/tidb/stable/quick-start-with-tidb#deploy-a-local-test-cluster?utm_source=github&utm_medium=tidb).

    - **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](https://docs.pingcap.com/tidb-in-kubernetes/stable/get-started?utm_source=github&utm_medium=tidb).

    - **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](https://tidbcloud.com/free-trial?utm_source=github&utm_medium=tidb).

2. Learn about TiDB SQL: To explore the SQL capabilities of TiDB, refer to the [TiDB SQL documentation](https://docs.pingcap.com/tidb/stable/sql-statement-overview?utm_source=github&utm_medium=tidb).

3. Use a MySQL driver or an ORM to [Build an App with TiDB](https://docs.pingcap.com/tidbcloud/dev-guide-overview?utm_source=github&utm_medium=tidb).

4. Explore key features, such as [data migration](https://docs.pingcap.com/tidbcloud/tidb-cloud-migration-overview?utm_source=github&utm_medium=tidb), [changefeed](https://docs.pingcap.com/tidbcloud/changefeed-overview?utm_source=github&utm_medium=tidb), [vector search](https://docs.pingcap.com/tidbcloud/vector-search-overview?utm_source=github&utm_medium=tidb), [HTAP](https://docs.pingcap.com/tidbcloud/tidb-cloud-htap-quickstart?utm_source=github&utm_medium=tidb), [disaster recovery](https://docs.pingcap.com/tidb/stable/dr-solution-introduction?utm_source=github&utm_medium=tidb), etc.


## Need Help?

- You can connect with TiDB users, ask questions, find answers, and help others on our community platforms: [Discord](https://discord.gg/KVRZBR2DrG?utm_source=github), Slack ([English](https://slack.tidb.io/invite?team=tidb-community&channel=everyone&ref=pingcap-tidb), [Japanese](https://slack.tidb.io/invite?team=tidb-community&channel=tidb-japan&ref=github-tidb)), [Stack Overflow](https://stackoverflow.com/questions/tagged/tidb), [TiDB Chinese Forum](https://asktug.com), X [@PingCAP](https://twitter.com/PingCAP)

- For filing bugs, suggesting improvements, or requesting new features, use [Github Issues](https://github.com/pingcap/tidb/issues) or join discussions on [Github Discussions](https://github.com/orgs/pingcap/discussions).

- To troubleshoot TiDB, refer to [Troubleshooting documentation](https://docs.pingcap.com/tidb/stable/tidb-troubleshooting-map?utm_source=github&utm_medium=tidb).

## Architecture



Learn more details about TiDB architecture in our [Docs](https://docs.pingcap.com/tidb/stable/tidb-architecture?utm_source=github&utm_medium=tidb).

## 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](https://github.com/pingcap/community/blob/master/contributors/README.md#how-to-contribute) and [TiDB Development Guide](https://pingcap.github.io/tidb-dev-guide/index.html) to get started.

- If you're looking for issues to work on, try looking at the [good first issues](https://github.com/pingcap/tidb/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) or [help wanted issues](https://github.com/pingcap/tidb/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22).

- The [contribution map](https://github.com/pingcap/tidb-map/blob/master/maps/contribution-map.md#a-map-that-guides-what-and-how-contributors-can-contribute) lists everything you can contribute.

- The [community repository](https://github.com/pingcap/community) contains everything else you need.

- Don't forget to claim your contribution swag by filling in and submitting this [form](https://forms.pingcap.com/f/tidb-contribution-swag).


<a href="https://next.ossinsight.io/widgets/official/compose-recent-active-contributors?repo_id=41986369&limit=30" target="_blank" style="display: block" align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://next.ossinsight.io/widgets/official/compose-recent-active-contributors/thumbnail.png?repo_id=41986369&limit=30&image_size=auto&color_scheme=dark" width="655" height="auto">
    <img alt="Active Contributors of pingcap/tidb - Last 28 days" src="https://next.ossinsight.io/widgets/official/compose-recent-active-contributors/thumbnail.png?repo_id=41986369&limit=30&image_size=auto&color_scheme=light" width="655" height="auto">
  </picture>
</a>

## License

TiDB is under the Apache 2.0 license. See the [LICENSE](./LICENSE) file for details.

## See Also

- [TiDB Online Playground](https://play.tidbcloud.com/?utm_source=github&utm_medium=tidb_readme)
- TiDB Case Studies: [TiDB Customers](https://www.pingcap.com/customers/?utm_source=github&utm_medium=tidb), [TiDB 事例記事](https://pingcap.co.jp/case-study/?utm_source=github&utm_medium=tidb), [TiDB 中文用户案例](https://cn.pingcap.com/case/?utm_source=github&utm_medium=tidb)
- [TiDB User Documentation](https://docs.pingcap.com/tidb/stable?utm_source=github&utm_medium=tidb)
- [TiDB Design Docs](/docs/design)
- [TiDB Release Notes](https://docs.pingcap.com/tidb/dev/release-notes?utm_source=github&utm_medium=tidb)
- [TiDB Blog](https://www.pingcap.com/blog/?utm_source=github&utm_medium=tidb)
- [TiDB Roadmap](roadmap.md)

## Acknowledgments

- Thanks [cznic](https://github.com/cznic) for providing some great open source tools.
- Thanks [GolevelDB](https://github.com/syndtr/goleveldb), [BoltDB](https://github.com/boltdb/bolt), and [RocksDB](https://github.com/facebook/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 example `testing-flow.md`, `architecture-index.md`, and
  `agents-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
1. Map the task to one primary subsystem.
2. Find existing tests covering the same behavior.
3. Reuse existing fixtures/testdata before creating new shapes.
4. 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 refresh
  - `pkg/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 on `pkg/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/executor` must not import `pkg/dxf/importinto`.
- First tests: importer metadata/option tests, `pkg/dxf/importinto/taskinfo/runtime_info_test.go` and `pkg/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 `kvsource` and dump-service lifecycle/parity tests in `export`.

## Test Surfaces
- Unit tests: package-local tests under `pkg/**`.
- Integration tests:
  - inputs: `tests/integrationtest/t/`
  - expected outputs: `tests/integrationtest/r/`
- RealTiKV tests:
  - `tests/realtikvtest/`
  - use when behavior depends on real TiKV/PD interaction.

## Practical Search Workflow
1. Start from symptom:
   - SQL keyword
   - error message
   - variable name
2. Find implementation entrypoint:
   - planner/executor/expression/session/ddl/store
3. Find existing tests around the same behavior.
4. 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](https://github.com/Deardrops), [wjhuang2016](https://github.com/wjhuang2016)
- Last updated:  Mar. 12, 2020
- Discussion at: https://github.com/pingcap/tidb/issues/9246

## Abstract

MySQL supports [invisible indexes](https://dev.mysql.com/doc/refman/8.0/en/invisible-indexes.html); 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.STATISTICS` or `SHOW 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_VISIBLE` in `information_schema.statistics`
- Add a new column `VISIBLE` in `SHOW INDEX FROM table` statement
- Show invisible column information in `SHOW CREATE TABLE` statement
- Add `use_invisible_indexes` in 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](https://github.com/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 size
```
The 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 size
```
The 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 size
```
The 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
```go
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 size
 ```
The `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 size
```
Non-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 size
```
The unique index key is unchanged.

For more intuitive information, check [the docs](https://docs.google.com/document/d/1Co5iMiaxitv3okJmLYLJxZYCNChcjzswJMRr-_45Eqg/edit?usp=sharing)

### 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:
```sql
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](https://github.com/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](https://pingcap.com/blog/2017-07-11-tidbinternal2/#map) and two proposals about [full collations](https://github.com/pingcap/tidb/pull/14574) and [cluster index](https://github.com/pingcap/tidb/blob/master/docs/design/2020-05-08-cluster-index.md) for more information.)

```
Key: tablePrefix{tableID}_indexPrefixSep{indexID}_indexedColumnsValue
Value: rowID
```

Each 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: rowID
```

So, 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](https://dev.mysql.com/doc/refman/5.7/en/partitioning-limitations-partitioning-keys-unique-keys.html) 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:

```sql
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.

```sql
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_23
```

Because 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_partitionID
```

**Pros:** 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: handle
```

Or

```
Key: tableID_indexID_partitionID_ColumnValues
```

**Pros:** 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](https://github.com/pingcap/tidb/issues/18016)). we will follow this project and add global index support in new executors.

## Rationale

[Global index in Oracle](https://docs.oracle.com/database/121/VLDBG/GUID-D1E775A0-669B-4E51-8D40-858847B64BEF.htm#VLDBG1256)
[Global index in OceanBase](https://zhuanlan.zhihu.com/p/48745358)

## 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](https://github.com/pingcap/tidb/issues/18016)  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`.

```sql
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.

```sql
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`

```sql
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.

<img alt="CNF 200" src=".\imgs\scalability-formula.png" width="200pt"/>



## 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 column `a` is 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 expression`tidb_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.

```go
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.

```go

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!

```go
// 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`

```go
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.

```Go
// 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


```go
// 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 `condition` to a expression.Expression slice `dnfItems`.
  - Make a new expression.Expression slice `newAccessItems` to store new conditions after processing tidb_shard prefix.
  - Traverse every `item` in slice `dnfItems`, if it's a `LogicAnd` expression, extracts every binary expression from it to a slice `cnfItems` and calls function `addExprPrefix4CNFCond(cnfItems)`  to add tidb_shard prefix if need; if it's a `ast.EQ` or a `ast.In` expression, calls function `addExprPrefix4CNFCond([]Expression{item})` to add tidb_shard prefix if need.
  - Make a new `LogicOR` condition by `newAccessItems`, return it.



#### (adder *exprPrefixAdder) addExprPrefix4CNFCond

Call the function `ranger.AddExpr4EqAndInCondition` to process `AND` expression.

```go
// 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

```go
// 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 `cond` in  slice `conditions`, place the `cond` to a new slice `accesses` according to the index definition field order.
  - Traverse every  `cond` in slice `accesses`, if the `cond` is not a `ast.EQ` or `ast.In` expression,  do nothing and return, otherwise extract the column value from `cond` and store it to slice `columnValues`.
  - Call the function `NeedAddGcColumn4ShardIndex` to judge if necessary to add `tidb_shard` prefix for `conditions`, if not, do nothing and return; otherwise call function `AddGcColumnCond` to add  `tidb_shard` prefix for `conditions`. 



##### NeedAddGcColumn4ShardIndex

Check whether to add `tidb_shard(x) = xxx` to the access condition.

- function declaration

```go
// 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_shard` built-in function.
  - The argument of  `tidb_shard` must be a column other than expression or else, and it must be the second column of the index.



##### AddGcColumnCond

`AddGcColumnCond` is the wrapper function for `AddGcColumn4EqCond` and `AddGcColumn4InCond`. 

```go
// 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

```go
// 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 `ColumnValue` in slice `columnValues`, calculate the value of `tidb_shard` by `ColumnValue` and store it to the variable`evaluated`.
  - Make a new expression `tidb_shard(columnName) = evaluated` and store it to `accessesCond[0]`



##### AddGcColumn4InCond

 Add the `tidb_shard(x) = xxx` for `IN` condition.

- function declaration

```go
// 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 column `a` is 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](http://github.com/xiongjiwei), [Zhang Yuanjia](https://github.com/qw4990)

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Impacts & Risks](#impacts--risks)

## 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

```sql
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](https://docs.google.com/document/d/1Co5iMiaxitv3okJmLYLJxZYCNChcjzswJMRr-_45Eqg/edit) 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.
```golang
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.
```golang
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:
- <const> MEMBER OF (<expr>)
```
IndexMerge
        IndexRangeScan(<const>)
        TableRowIDScan
```

- JSON_CONTAINS(<expr>, [<c1>, <c2>, <c3>, ...])
```
IndexMerge(AND)
        IndexRangeScan(<c1>)
        IndexRangeScan(<c2>)
        IndexRangeScan(<c3>)
        ...
        TableRowIDScan
```

- JSON_OVERLAPS(<expr>, [<c1>, <c2>, <c3>, ...])
```
IndexMerge(OR)
        IndexRangeScan(<c1>)
        IndexRangeScan(<c2>)
        IndexRangeScan(<c3>)
        ...
        TableRowIDScan
```

Each `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
```sql
-- 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 xxx` cannot 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))`.
  - 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.
- The type of multi-valued index cannot be `BINARY`, `JSON`, and `YEAR`.
- 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](https://github.com/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.

```sql
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 `IndexKeyTypeOpt` add `VECTOR` index type, and `IndexTypeOpt` add `HNSW` option type, and add vector index after creating the table.

```sql
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

```sql
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 INDEX` hint.
* The vector index only obtains the top n values through similarity. The following is the syntax for using a vector index when querying.

```sql
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.

```sql
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 function` will not exist
* 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.

```go
// 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 `ActionAddVectorIndex` DDL 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 `VectorIndexInfo` to 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_INDEXED` value of the table corresponding to the added vector index on the `system.dt_local_indexes` table on TiFlash is 0\.
        * Obtain error info from indexStat to determine if there is an error during execution.
* 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 IsRollbackable` check 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.

##### **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`
* 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 IsRollbackable` check is the same as a general index.

##### **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 ddl` to display the progress of DDL operation execution
    * The display way is considered the same as the general DDL display way, and the `ROWS_STABLE_INDEXED` information of the corresponding table of the `information_schema.tiflash_indexes` table on TiFlash can be filled into the `ROW_COUNT` information of the DDL job.
* 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/index` and `admin repair table` operations do not currently consider processing of vector indexes.
* Add relevant metrics
    * Because `ActionAddVectorIndex` is 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.

### **TiFlash**

#### **Add Vector Index**

Adding an index operation mainly consists of two steps:

1. 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.
    * `syncTableSchema` handles synchronization Schema operations, and if new index information is found, it needs to be synchronized to the table.
2. 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.
    * 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.
        * Create a `VectorIndexHNSWBuilder` to 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.

#### **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 `syncTableschema` handles 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.

#### **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](https://dev.mysql.com/doc/refman/9.0/en/vector.html), 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:*

1. *Compatibility with other features, like partition table, drop column, etc.*
2. *Compatibility with other components, like BR, TiCDC, Dumpling, BR, DM, Lighting, etc.*
3. *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](https://github.com/pingcap/tidb/issues/new/choose), which is going to be converted into a tracking issue of the design implementation.

## What is the process?

1. Create a pull request with a design document based on the [template](./TEMPLATE.md) under this directory as `YYYY-MM-DD-my-feature.md`.
2. Discussion takes place, and the text is revised in response.
3. The design document is accepted or rejected when at least two committers reach consensus and no objection from the committer.
4. If accepted, [create a tracking issue](https://github.com/pingcap/tidb/issues/new/choose) 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.
5. 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()` (inside `createIndex`)
- Job type: `job.Type = model.ActionAddIndex` (inside `createIndex`)
- Reorg meta init: `pkg/ddl/reorg_util.go:initJobReorgMetaFromVariables`
- Args (v2 typed job args): `model.ModifyIndexArgs` with `OpType = model.OpAddIndex` (inside `createIndex`)

## 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` (restores `ConditionExprString` on the built `IndexInfo`)
- Expression / generated-key indexes may introduce hidden columns:
  - Build: `pkg/ddl/executor.go:checkIndexNameAndColumns`
  - Publish: `pkg/ddl/index.go:moveAndUpdateHiddenColumnsToPublic` (done when moving `StateNone` → `StateDeleteOnly`)
- Pre-split index regions (optional `PRE_SPLIT_REGIONS` index option):
  - Manual forms persist either a region count, explicit `BY` values, or `BETWEEN` bounds with a region count in each `model.IndexArgSplitOpt`.
  - `PRE_SPLIT_REGIONS AUTO` persists 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-interval` has 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`

Owner scheduling + worker:

- Reorg worker pool: `pkg/ddl/job_scheduler.go` (routes `mysql.tidb_ddl_job.reorg=1` jobs to `reorgWorkerPool`)
- 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` → `StateDeleteOnly`
- `StateDeleteOnly` → `StateWriteOnly`
- `StateWriteOnly` → `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:

1. Runs reorg/backfill until done: `pkg/ddl/index.go:doReorgWorkForCreateIndex`
2. Decides whether to run `ANALYZE` (based on job vars and job context):
   - State machine: `job.ReorgMeta.AnalyzeState` (see `pkg/ddl/index.go:onCreateIndex`)
   - Execution: `pkg/ddl/index.go:startAnalyzeAndWait`

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)

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`

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. `convertAddIdxJob2RollbackJob` call sites).

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 JOBS`
- `ADMIN SHOW DDL JOB QUERIES`
- `ADMIN 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 also `docs/design/2022-06-07-adding-index-acceleration.md`)

## Common pitfalls checklist (before you send a PR)

- Backfill progress or `BackfillState` not 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 `ReorgTypeTxnMerge` on standalone TiDB backed by unistore. The standalone transactional path rejects `TIMESTAMP` comparison predicates before publishing the index because backfill and DML can use different time zones; `IS NULL` and `IS NOT NULL` predicates 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):

1. Is it **job-based** (persist/resume/failover) or a **metadata-only fast path**?
2. Does it require **schema state transitions** (and which ones), or can it stay `public` throughout?
3. Does it require a **reorg/backfill scan** (read/write workload), and what is the checkpoint/persistence point?
4. What are the **cancel/rollback** semantics? Which step(s) are reversible, and which need delete-range GC?
5. How does it affect **schema version + schema diff** and follower schema sync?
6. What are the **system tables** / durable metadata involved (`mysql.tidb_ddl_job`, `mysql.tidb_ddl_reorg`, ...)? Which fields must be backward compatible?
7. What is the **expected online behavior** (MDL / blocking, write conflicts, phase boundaries)?
8. 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)

1. `pkg/executor/ddl.go` (`DDLExec`) receives a DDL AST node and calls into the DDL module.
2. `pkg/ddl/executor.go` converts the statement to a `model.Job` (or multiple jobs), then **submits** it via `JobSubmitter`.
3. `JobSubmitter` allocates IDs, writes the job into `mysql.tidb_ddl_job`, and notifies the owner-side scheduler.
4. Only the **DDL owner** runs `jobScheduler`, which dispatches jobs into worker pools.
5. Workers run the job **step-by-step** (meta changes + schema state transitions), update global schema version, then wait for followers to sync.
6. When done, the job is moved to history; the submitting session is unblocked and returns success/failure.

## Execution flow diagram

```mermaid
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 result
```

## Database 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 explicit
`RESTRICTED_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`, and
`br/pkg/restore/internal/prealloc_db/db.go`. Boundary coverage lives in
`TestBRIECreateTable/TrustedRestoreReadOnlyBoundary` and
`TestCreateTablesWithPlanPreservesSourceMetadata`. 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 of
`Domain.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).Next` dispatches AST → DDL module; handles transaction boundary and converts schema-outdated errors.

### DDL module (job-based execution)

- `pkg/ddl/ddl.go`: `NewDDL` wires everything; `(*ddl).Start` starts submit loop and campaigns owner.
- `pkg/ddl/executor.go`: `type Executor` (called by SQL layer); converts statements → jobs; `DoDDLJobWrapper` waits for job completion.
- `pkg/ddl/job_submitter.go`: `type JobSubmitter` batches submission, allocates IDs, inserts into job table, and notifies scheduler.
- `pkg/ddl/job_scheduler.go`: owner-only scheduler; `ownerListener.OnBecomeOwner` starts `jobScheduler` and worker pools.
- `pkg/ddl/job_worker.go`: worker logic; `transitOneJobStep` / `runOneJobStep` drive 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 Syncer` implements 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 via `ddl.NewDDL(...)`; initializes infosync + schema syncer, and orchestrates startup order.

## Reading order

1. `docs/agents/ddl/01-execution-flow.md` — end-to-end call chain and responsibilities.
2. `docs/agents/ddl/02-job-lifecycle.md` — job/version/state machines, schema sync, owner/failover.
3. `docs/agents/ddl/03-reorg-backfill.md` — reorg/backfill and distributed backfill overview.
4. `docs/agents/ddl/04-dev-checklist.md` — where-to-change, testing, and common pitfalls.
5. `docs/agents/ddl/05-file-map.md` — quick “where is this implemented?” map inside `pkg/ddl/`.
6. `docs/agents/ddl/06-add-index.md` — add-index deep dive (fast reorg, ingest, backfill-merge).
7. `docs/agents/ddl/07-modify-column.md` — modify-column deep dive (reorg types, state machine).
8. `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/` and `pkg/executor/importer/`
- Runtime bootstrap and ownership loops: `pkg/session/` and `pkg/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`.

## 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.go` and
    `pkg/dxf/importinto/subtask_executor.go`: executor + step executors.
  - `pkg/executor/import_into.go` and `pkg/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.go` and
    `pkg/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)

1. Business logic builds task metadata/logical plan and submits a DXF task.
2. Framework persists task/subtask state through `framework/storage`.
3. `Domain` starts executor-manager loop on every TiDB node.
4. Scheduler-manager loop runs only while the local node is DDL owner.
5. Scheduler extension advances steps and dispatches subtasks.
6. 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.go` explicitly forbids changing
    existing constant values).
- 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(...)`
- Keep `GetNextStep` deterministic 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.
- `RequiredSlots` is the reservation baseline, while runtime execution may use a
  lower slot count through `ExtraParams.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
  `MaxConcurrentTask` limit 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.go` and
  `pkg/dxf/framework/scheduler/scheduler.go`.
- Slot reservation / preemption decisions:
  `pkg/dxf/framework/scheduler/slots.go`,
  `pkg/dxf/framework/taskexecutor/slot.go`, and
  `pkg/dxf/framework/taskexecutor/manager.go`.
- Keyspace/scope routing (classic vs nextgen service behavior):
  `pkg/domain/domain.go`, `pkg/dxf/framework/handle/handle.go`, and
  `pkg/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/handle` first, then follow call sites in `pkg/dxf/importinto/`
    and `pkg/ddl/`.

- "How does IMPORT INTO use DXF?"
  - `pkg/dxf/importinto/` first, then `pkg/executor/import_into.go` and
    `pkg/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-check
    `docs/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.go` and related
  distributed-backfill tests under `pkg/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.go`
  - `pkg/dxf/importinto/taskinfo/runtime_info.go`
- Scheduler and step transitions:
  - `pkg/dxf/importinto/scheduler.go`
  - `pkg/dxf/framework/proto/step.go`
- Step planning and conflict-spec generation:
  - `pkg/dxf/importinto/planner.go`
- Step executors:
  - `pkg/dxf/importinto/task_executor.go`
  - `pkg/dxf/importinto/collect_conflicts.go`
  - `pkg/dxf/importinto/conflict_resolution.go`
  - `pkg/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?"
  - `generateCollectConflictsSpecs` and `generateConflictResolutionSpecs` return
    no specs when `collectConflictInfos` finds no recorded conflicts.
  - Check whether previous step metas have `RecordedConflictKVCount > 0` in:
    - `ImportStepMeta`
    - `MergeSortStepMeta`
    - `WriteIngestStepMeta`

- "Why is checksum verification skipped in post-process?"
  - In collect-conflicts, `TooManyConflictsFromIndex` is 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.

- "Where are conflicted rows persisted?"
  - Collect-conflicts writes conflict-row files under:
    `conflicted-rows/<task-id>/<subtask-id>-<uuid>`
  - The prefix is intentionally outside `<task-id>/` cleanup path, so users can
    inspect conflict rows after task cleanup.

- "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`

## Cleanup Troubleshooting

- Cleanup entrypoint is `ImportCleaner.Clean` in `clean_up.go`.
- Classic kernel behavior:
  - Attempts to switch table mode back to normal.
  - Ignores `infoschema.ErrTableNotExists` during 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.
- Nextgen metering:
  - On succeed state, cleanup tries to send metering data based on post-process
    subtask meta.
- 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 as `errGetCrossKSSessionPool`, 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.go`
- `pkg/dxf/importinto/collect_conflicts_test.go`
- `pkg/dxf/importinto/task_executor_test.go`
- `pkg/dxf/importinto/scheduler_test.go`
- `pkg/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](https://golang.org/dl/) version 1.13 or above. You can follow the instructions in the official [installation page](https://golang.org/doc/install) (check it by `go version`)

## Create a Project

```bash
mkdir colx
cd colx
go mod init colx
touch main.go
```

## Import Dependencies

First, you need to use `go get` to fetch the dependencies through git hash. The git hashes are available in [release page](https://github.com/pingcap/tidb/releases). Take `v7.5.0` as an example:

```bash
go get -v github.com/pingcap/tidb/pkg/parser@069631e
```

> **NOTE**
> 
> 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 `types` package in TiDB repo with the following command:
>
> ```bash
> go get -v github.com/pingcap/tidb/pkg/types/parser_driver@069631e
> ```
> and import it in your golang source code:
> ```go
> import _ "github.com/pingcap/tidb/pkg/types/parser_driver"
> ```

Your directory should contain the following three files:
```
.
├── go.mod
├── go.sum
└── main.go
```

Now, 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:
1. Use the [`parser.New()`](https://pkg.go.dev/github.com/pingcap/tidb/pkg/parser?tab=doc#New) function to instantiate a parser, and
2. Invoke the method [`Parse(sql, charset, collation)`](https://pkg.go.dev/github.com/pingcap/tidb/pkg/parser?tab=doc#Parser.Parse) on the parser.

```go
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:

```bash
go run main.go
```

If 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_driver` is required. It decides how to parse the basic data types in SQL.
>
>   You can use [`github.com/pingcap/tidb/pkg/parser/test_driver`](https://pkg.go.dev/github.com/pingcap/tidb/pkg/parser/test_driver) as the `parser_driver` for test. Again, if you need advanced features, please use the `parser_driver` in TiDB (run `go get -v github.com/pingcap/tidb/types/parser_driver@069631e` and 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.result` object 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 of `parser.result` object before calling `parser.Parse()` again or before using it in another goroutine, or create a new `parser` object 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`](https://pkg.go.dev/github.com/pingcap/tidb/pkg/parser/ast?tab=doc#Node) for each kind of AST node, such as `SelectStmt`, `TableName`, `ColumnName`, etc. [`ast.Node`](https://pkg.go.dev/github.com/pingcap/tidb/pkg/parser/ast?tab=doc#Node) provides a method `Accept(v Visitor) (node Node, ok bool)` to allow any struct that has implemented [`ast.Visitor`](https://pkg.go.dev/github.com/pingcap/tidb/pkg/parser/ast?tab=doc#Visitor) to traverse itself.

[`ast.Visitor`](https://pkg.go.dev/github.com/pingcap/tidb/pkg/parser/ast?tab=doc#Visitor) is defined as follows:
```go
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):

```go
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:

```go
func extract(rootNode *ast.StmtNode) []string {
	v := &colX{}
	(*rootNode).Accept(v)
	return v.colNames
}
```

And slightly modify the main function:

```go
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:

```bash
go run main.go 'select a, b from t'
```

```
[a b]
```

You can also try a different SQL statement as an input. For example:

```console
$ 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.

1. Get the current status of TiDB, including the connections, version, and `git_hash`.

    ```shell
    curl http://{TiDBIP}:10080/status
    ```

    ```shell
    $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
        }
    }
    ```

2. Get all metrics of TiDB

    ```shell
    curl http://{TiDBIP}:10080/metrics
    ```

    In Starter deployment mode, every exported metric includes a `keyspace_id` label, 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 given `keyspace_id`.

3. 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`.

    ```shell
    curl http://{TiDBIP}:10080/regions/meta
    ```

    ```shell
    $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
        }
    ]
    ```

4. Get the table/index of hot regions

    ```shell
    curl http://{TiDBIP}:10080/regions/hot
    ```

    ```shell
    $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
        }
      ]
    }
    ```

5. Get the information of a specific region by ID

    ```shell
    curl 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"
    }
    ```

6. Get regions Information from db.table

    ```shell
    curl http://{TiDBIP}:10080/tables/{db}/{table}/regions
    ```

    ```shell
    $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
            }
        ]
    }
    ```

7. Get schema Information about all db

    ```shell
    curl http://{TiDBIP}:10080/schema
    ```

    ```shell
    $curl http://127.0.0.1:10080/schema
    [
        {
            "charset": "utf8mb4",
            "collate": "utf8mb4_bin",
            "db_name": {
                "L": "test",
                "O": "test"
            },
            "id": 266,
            "state": 5
        },
        .
        .
        .
    ]
    ```

8. Get schema Information about db

    ```shell
    curl http://{TiDBIP}:10080/schema/{db}
    ```

    ```shell
    curl http://{TiDBIP}:10080/schema/{db}?id_name_only=true
    [
    {
     "id": 119,
     "name": {
      "O": "t1",
      "L": "t1"
     }
    },
    {
     "id": 125,
     "name": {
      "O": "t2",
      "L": "t2"
     }
    }
    ]
    ```

9. Get schema Information about db.table, and you can get schema info by tableID (tableID is the **unique** identifier of table in TiDB)

    ```shell
    curl http://{TiDBIP}:10080/schema/{db}/{table}

    curl http://{TiDBIP}:10080/schema?table_id={tableID}

    curl http://{TiDBIP}:10080/schema?table_ids={tableID,...}
    ```

10. Get database information, table information and tidb info schema version by tableID.

     ```shell
     curl http://{TiDBIP}:10080/db-table/{tableID}
     ```

11. Get MVCC Information of the key with a specified handle ID

     ```shell
     curl 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:*

     ```protobuf
     enum 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)/1
     ```

     *Hint: The method to convert the Hex format key returned by TiDB API into the format recognized by [tikv-ctl](https://docs.pingcap.com/tidb/stable/tikv-control).*

     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](https://docs.pingcap.com/tidb/stable/tikv-control)

      ```shell
       ./tikv-ctl --to-escaped '7480000000000008C65F728000000000000001'
       t\200\000\000\000\000\000\010\306_r\200\000\000\000\000\000\000\001
      ```

      Step 3: Encode the key to make it memcomparable in tikv with [tikv-ctl](https://docs.pingcap.com/tidb/stable/tikv-control)

      ```shell
      ./tikv-ctl --encode 't\200\000\000\000\000\000\010\306_r\200\000\000\000\000\000\000\001'
      7480000000000008FFC65F728000000000FF0000010000000000FA
      ```

      Step 4: Convert the key from hex format to escaped format again since most `tikv-ctl` commands only accept keys in escaped format while the `--encode` command 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\372
      ```

      Step 5: Add a prefix "z" to the key. Then the key can be recognized by [tikv-ctl](https://docs.pingcap.com/tidb/stable/tikv-control). For example, use the following command to scan from tikv.

      ```
/* 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:

```shell
GO_FAILPOINTS="github.com/pingcap/tidb/pkg/server/enableTestAPI=return" ./bin/tidb-server
```

### Delete row key or index key

You can use those APIs to mock dangling row or index keys case for test.

Row key:
```shell
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:
```shell
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.

```shell
curl http://{TiDBIP}:10080/variables/global
```

The response is a JSON object mapping variable names to string values. Example response excerpt:

```json
{
 "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. */
```shell
# 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:

```shell
curl http://{TiDBIP}:10080/dxf/nodes
```

Parameters: none.

Response fields:

- `host`: The TiDB execution ID in `IP:PORT` form.
- `role`: The node's configured TiDB service scope. `dxf_service` is 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:

```json
[
 {
  "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:

```shell
curl http://{TiDBIP}:10080/dxf/schedule/status
```

Parameters: none.

Example response:

```json
{
 "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:

```shell
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 are `pause_scale_in` and `resume_scale_in`.
- `ttl`: Optional for `pause_scale_in`. Uses Go duration syntax such as `10m`, `1h`, or `2h45m`. The default is `1h`. Ignored by `resume_scale_in`.

Example response for `pause_scale_in`:

```json
{
 "enabled": true,
 "ttl": 18000000000000,
 "expire_time": "2025-08-22T21:13:01.276282+08:00"
}
```

Example response for `resume_scale_in`:

```json
{
 "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:

```shell
curl "http://{TiDBIP}:10080/dxf/schedule/tune?keyspace={keyspace}"
curl -X POST "http://{TiDBIP}:10080/dxf/schedule/tune?keyspace={keyspace}&amplify_factor={number}&ttl={duration}"
```

Parameters:

- `keyspace`: Required for both `GET` and `POST`. The target keyspace whose DXF resource calculation should be read or tuned.
- `amplify_factor`: Required for `POST`. A floating-point number in the range `[1.0, 10.0]`.
- `ttl`: Optional for `POST`. Uses Go duration syntax such as `10m`, `1h`, or `2h45m`. The default is `1h`. After the TTL expires, `GET` returns the default tuning factor.

Example `GET` response:

```json
{
 "amplify_factor": 1
}
```

Example `POST` response:

```json
{
 "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:

```shell
curl http://{TiDBIP}:10080/dxf/task/active
```

Parameters: none.

Example response:

```json
{
 "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:

```shell
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 is `20`. Valid range is `[1, 200]`.
- `page_token`: Optional. Must be a positive task ID returned as `NextPageToken` by the previous page.

Example response:

```json
{
 "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:

```shell
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:

```json
{
 "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:

```shell
curl http://{TiDBIP}:10080/dxf/schedule/max_concurrent_task
```

Example response:

```json
{
 "max_concurrent_task": 16,
 "persistence": "memory_only"
}
```

Update the value:

```shell
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:

```json
{
 "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`:

```shell
curl http://{TiDBIP}:10080/dxf/schedule/task_cleanup_batch_size
```

Example response:

```json
{
 "task_cleanup_batch_size": 20,
 "persistence": "memory_only"
}
```

Update the value:

```shell
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:

```json
{
 "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:

```shell
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's `required_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:

```json
{
 "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. */
```shell
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 on `POST` only. `1` or `true` clears 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. `1` or `true` includes per-store entries in `stores`; otherwise `stores` is omitted.

The status route accepts only `GET`. The refresh route accepts only `POST`. Other methods return HTTP 405.

Example `GET` response with `detail=1`:

```json
{
  "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`:

```json
{
  "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. |

```shell
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:

```json
{
  "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 marked
`done` 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.md` first.
- [ ] 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.md` remains concise: policy-focused, not overloaded with step-by-step runbook detail.
- [ ] Detailed workflows are linked from `AGENTS.md` to `docs/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 with `close #<id>` or `ref #<id>`.
- [ ] Agent notes follow the location and update rules in `docs/agents/notes-guide.md`.
- [ ] Testing policy in `AGENTS.md` matches testing runbook guidance under `docs/agents/` (no contradiction).

### 4) Testing and Validation Consistency

- [ ] `Task -> Validation Matrix` still defines minimal required test surfaces by change scope.
- [ ] `Testing Policy` remains policy-level and points to command playbooks under `docs/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.md` and docs under `docs/agents/` remain valid.
- [ ] Shell snippets are copy-paste safe (especially quoted patterns containing backticks).
- [ ] Any `make <target>` mention in docs is verified against `Makefile`.
- [ ] Related examples stay parameter-consistent across snippets.

## Fast Verification Commands

Use from repository root.

```bash
# 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 <base_ref> with the PR base branch if needed.
git diff --name-status <base_ref>...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
  done
```

## Acceptance Criteria for AGENTS-related Changes

A review is complete only when all are true:

- [ ] No policy contradiction across `AGENTS.md` and the changed docs under `docs/agents/`.
- [ ] No ambiguous wording for critical rules (especially test/build and PR gates).
- [ ] No stale path references.
- [ ] `AGENTS.md` preserves 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:

1. Files reviewed.
2. Drift/contradiction findings.
3. Commands run to verify references/rules.
4. Required fixes before merge.
5. 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/...`)

```bash
pushd pkg/<package_name>
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 `-record` only 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`).

```bash
rg -n --fixed-strings -- "failpoint." pkg/<package_name>
rg -n --fixed-strings -- "testfailpoint." pkg/<package_name>
# If BUILD.bazel exists, also check failpoint dependency.
test -f pkg/<package_name>/BUILD.bazel && rg -n --fixed-strings -- "@com_github_pingcap_failpoint//:failpoint" pkg/<package_name>/BUILD.bazel
```

- Use the checks above as the default decision basis.
- If `rg` finds matches, run with failpoints enabled.
- If `rg` finds no matches, run without failpoint enable/disable and state the check evidence in the final report.
- `-tags=intest,deadlock` does not enable failpoints.

### Failpoint-enabled run

```bash
./tools/check/failpoint-go-test.sh pkg/<package_name> -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 invoke `tools/bin/failpoint-ctl` directly from parallel agent tasks in the same worktree.
- Pass additional `go test` flags after the package path, for example `./tools/check/failpoint-go-test.sh pkg/<package_name> -run <TestName> -count=1`.
- If `-tags` is omitted, the script defaults to `-tags=intest,deadlock`.
- Pass `-tags=intest,deadlock,nextgen` when a test run also needs `nextgen`.
- If running Bazel directly (for example `bazel test`), run `make bazel-failpoint-enable` first, then `make bazel-failpoint-disable` after tests.
- If using `make bazel_test`, do not run `make bazel-failpoint-enable` separately because `bazel_test` already depends on it; still run `make bazel-failpoint-disable` after tests.

## Related guidance

- Bug-fix regression policy lives in `AGENTS.md` -> `Quick Decision Matrix` (`Bug fix`).
- Include exact test commands in PR description under `Tests` when preparing a PR update.

## Integration tests (`/tests/integrationtest`)

- Test inputs are in `tests/integrationtest/t`.
- Expected results are in `tests/integrationtest/r`.

```bash
pushd tests/integrationtest
./run-tests.sh -r <TestName>
popd
```

- Review changed files in `tests/integrationtest/r` and 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`, then `TestName` is `planner/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:

```bash
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.
```bash
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=$!
```

```bash
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; done
```

```bash
go 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 `-v` by default; add it only for debugging.

```bash
[ -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"
```

```bash
# 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):

```bash
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 Matrix` and skip costly `realtikvtest`.
- Alternative RealTiKV workflows are available in `tests/realtikvtest/scripts/classic/` and `tests/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](https://github.com/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:

- `Update` is 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.
- `Update` is called for every possible aggregate state, which also introduces a lot of CPU branch predictions. For example, function `AVG` behaves different when the state is `Partial1` and `Final`, it has to make a `switch` statement to handle all the possible states.
- `GetResult` returns a `types.Datum` as the final result of a group. Currently, TiDB uses `Chunk` to store the records during the query execution. The returned `Datum` has to be converted to `Chunk` outside the aggregate framework, which introduces a lot of data conversions and object allocations.
- `AggEvaluateContext` is used to store every possible partial result and maps, which consumes more memory than what is actually needed. For example, the `COUNT` only need a `int64` field to store the row count it concerns.
- `distinctChecker` is used to de-duplicate values, and uses `[]byte` as 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 that `map`.

## 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:
- `AllocPartialResult` allocates a specific data structure to store the partial result, initializes it, converts it to `PartialResult` and returns it back. Aggregate operator implementation, for example, stream aggregate operator, should hold this allocated `PartialResult` for further operations involving the partial result such as `ResetPartialResult`, `UpdatePartialResult`, etc.
- `ResetPartialResult` resets the partial result to the original state for a specific aggregate function. It converts the input `PartialResult` to the specific data structure which stores the partial result and then resets every field to the proper original state.
- `UpdatePartialResult` updates the specific partial result for an aggregate function using the input rows which all belong to the same data group. It converts the `PartialResult` to 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.
- `AppendFinalResult2Chunk` finalizes the partial result and appends the final result directly to the input `Chunk`. Like other operations, it converts the input `PartialResult` to the specific data structure firstly, calculates the final result and appends that final result to the `Chunk` provided.
- `MergePartialResult` evaluates the final result using the input `PartialResults`. Suppose the input `PartialResults` names are `dst` and `src` respectively. It converts `dst` and `src` to the same data structure firstly, merges the partial results and store the result in `dst`. 

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 the `Chunk` of 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.
- `UpdatePartialResult` is 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 using `Chunk` to 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.
- `AppendFinalResult2Chunk` directly finalizes the partial result to the chunk, without converting it to `Datum` and then converting the `Datum` back into `Chunk`. This saves a lot of object allocation, reduces the overhead of golang’s gc worker, and avoids the unnecessary value conversions between `Datum` and `Chunk`.

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 `AggFunc` interface and the `Build()` function. [@zz-jason](https://github.com/zz-jason)
- Implement the `AVG` function under the new framework. [@zz-jason](https://github.com/zz-jason)
- Implement other aggregate functions under the new framework. [@XuHuaiyu](https://github.com/XuHuaiyu)
- Add more integration tests using the random query generator. [@XuHuaiyu](https://github.com/XuHuaiyu)
- Add unit tests for the new framework. [@XuHuaiyu](https://github.com/XuHuaiyu)
- Infer input parameter type for new aggregate functions when extracting a `Project` operator under the `Aggregate` operator. [@XuHuaiyu](https://github.com/XuHuaiyu)
- Use the new framework in the hash aggregate operator. [@XuHuaiyu](https://github.com/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](https://github.com/bb7133), [@zz-jason](https://github.com/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:

1. Find the `column = constant` expression 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.

2. Find the `column A = column B` expression (which happens in `join` statements mostly) and propagate expressions like `column op constant` (as well as `constant 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:

1. 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 |

2. Infer `NotNULL` filters 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.

3. 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)   |

4. 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](https://dev.mysql.com/doc/internals/en/optimizer-constant-propagation.html) 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 `propagateConstantSolver` to support wider types of operators from column equality.

 * For proposal #2, `propagateConstantSolver` is also an applicable way to add `NotNULL` filter(`not(isnull())`), but should examine whether the column has the `NotNULL` constraint already.

 * For proposal #3, the [ranger](https://github.com/pingcap/tidb/blob/6fb1a637fbfd41b2004048d8cb995de6442085e2/util/ranger/ranger.go#L14) may be useful to help us collect and fold comparison constraints

 * For proposal #4, current rule [PredicatePushDown](https://github.com/pingcap/tidb/blob/b3d4ed79b978efadf2974f78db8eeb711509e545/plan/rule_predicate_push_down.go#L1) 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](https://github.com/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](https://pingcap.com/docs/op-guide/history-read/) 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_time` to a sufficient value.

## Compatibility

It's a new command and will not lead to compatibility issues.

## Implementation

1. `ADMIN RESTORE TABLE table_id` will enqueue a new DDL job to TiDB general DDL queue.
2. 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 `ErrTableExists` error.
3. 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 the `mysql.gc_delete_range` table. 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.
4. Use the previous table meta information of the table_id to insert the meta data into the schema meta data, like what `Meta.CreateTable` does. And set the table information state to `model.StatePublic`, then the restoration will be finished after the schema is synced by all the TiDB instances.
5. If the command is canceled or rollbacked, and the delete-range record is already removed, we need to insert it into `mysql.gc_delete_range` again, like what `Drop Table` does in `worker.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](https://github.com/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 logical `Join`
  operator can be implemented to `HashJoin`/`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 Group
```

After 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:

1. Exploring all the equivalent group expressions of each group.
2. Exploring all the potential groups.

The group and group expression can be defined as:

```go
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.

```go
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:

```go
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:

```go
// 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:

```go
type Pattern struct {
	operand  int
	children []*Pattern
}
```

The `ExprIter` should be created with a `GroupExpr` and the `Pattern` of a rule:

```go
func NewExprIter(g *GroupExpr, p *Pattern) *ExprIter
```

With the help of the above components, the pseudo code of the function
`findMoreEquiv` is:

```go
// 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:

```go
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:

```go
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:

```go
// 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:

```go
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:

```go
// 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

1. Adding a session variable named `tidb_enable_volcano_planner` to 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.

2. Implementing the framework of the new planner, including the conceptions
   described above: `Group`/`GroupExpr`/`ExprIter`/`Pattern`, the interfaces
   like `transformation`/`implementation`/`enforcing`, and the functions like
   `exploreGroup`/`findMoreEquiv`/`implGroup`/`implGroupExpr`.

3. Adding some simple transformation/implementation/enforcing rules and tests to
   make the new planner framework basically available.

4. Adopting the "Adaptor" conception to rewrite the operator push-down logical
   for different storages.

5. 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](https://github.com/winoros)
- 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:

```go
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 `b1` and `c1`'s left boundary is the same. But the right boundary is different. So we can split `c1` into two buckets. The first one's boundary is totally the same with `b1`. 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:

<img alt="original histogram" src="./imgs/histogram-1.jpeg" width="500pt"/>

Step 1:

<img alt="Step 1" src="./imgs/histogram-2.jpeg" width="500pt"/>

Step 2:

<div style="text-align: center">
<img alt="Step 2" src="./imgs/histogram-3.png" width="150pt"/>
</div>

The calculation inside the bucket can be calculated as this formula <img alt="$selectivity=joinKeySelectivity*RowCount(t1)*RowCount(t2)$" src="imgs/histogram-formula-1.png?invert_in_darkmode" align="middle" width="476.19356895pt" height="24.657534pt"/>

Where <img alt="$joinKeySelectivity = \frac{1}{NDV(t1.key)}*\frac{1}{NDV(t2.key)}*ndvAfterJoin$" src="imgs/histogram-formula-2.png?invert_in_darkmode" align="middle" width="466.6166208pt" height="27.7756545pt"/>.

The `ndvAfterJoin` can be <img alt="$min(NDV(t1.key), NDV(t2.key))$" src="imgs/histogram-formula-3.png?invert_in_darkmode" align="middle" width="248.4423216pt" height="24.657534pt"/> 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](https://github.com/pingcap/tidb/pull/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](https://github.com/pingcap/tidb/pull/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](www.github.com/zhexuany)
- 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](https://github.com/pingcap/tidb/pull/6823), 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](http://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html)

    * std offset
    * std offset dst [offset], start[/time], end[/time]
    * :characters

The 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](https://golang.org/pkg/time/#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.](https://web.archive.org/web/20180417031602/http://www.inf.uni-konstanz.de/dbis/teaching/ws0203/main-memory-dbms/download/CCA.pdf) 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`. 

1. Partition algorithm

We can use the **parallel radix cluster** algorithm raised by [Balkesen et al.](https://15721.courses.cs.cmu.edu/spring2016/papers/balkesen-icde2013.pdf) 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. 

1. 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)*.

1. Others

   3.1 We can define the partition as type chunk.List, thus `HashJoinExec` should maintain an attribute **partitions []*chunk.List**.

   3.2 For outer relation, `partition phase` and `probe phase` will 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

1. Investigate the third-party libraries for fetching the L2 cache size and calculate the number of radix bits before `build phase`. @XuHuaiyu
2. Partition the inner relation parallelly. @XuHuaiyu
3. Build hash table parallelly. @XuHuaiyu
4. 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](https://github.com/zimulala) (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.


<font size=1 face="黑体"><center>Figure 1: Structure flow chart</center></font>
#### 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
1. The MySQL Client sends a DDL operation request to the TiDB server.
2. 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.
3. 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.
4. 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.
5. 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:
1. 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.
2. 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.



<font size=1 face="黑体"><center>Figure 2: Owner detailed flow chart</center></font>
## 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](https://github.com/pingcap/docs/blob/master/mysql-compatibility.md#ddl).

---

### Design 2018 10 19 Table Partition (`docs/design/2018-10-19-table-partition.md`)

# Proposal: Table Partition

- Author(s):     [tiancaiamao](https://github.com/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](https://dev.mysql.com/doc/refman/8.0/en/partitioning.html) 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:

1. New TiDB runs on the old cluster data
2. Old TiDB runs on the new cluster data
3. 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 t 
```

is 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 `explain` result is not friendly to user
* The `UnionAll` operator can't keep order, so if some operator need ordered result such as `IndexReader`, an extra `Sort` operator is needed

If [partition selection](https://dev.mysql.com/doc/refman/5.7/en/partitioning-selection.html) 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 table
```

### Limitations

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](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](https://github.com/winoros)
- 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](https://github.com/winoros/DP-CCP/tree/master). DP-CPP is introduced in [this paper](https://dl.acm.org/citation.cfm?id=1164207).

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](https://github.com/winoros/DP-CCP/blob/dp-sub/dpsub.cpp):

```
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:

1. Enlarge its edges by constant propagation. i.e. If we have `t1.a=t2.a and  t2.a=t3.a`, we should get `t1.a=t3.a`.
2. Number join node from 0 to n. Construct a hash map `pair<int, int> to join key filters`.
3. Do the core dp algo.
4. Get the final result.
5. Note that we can ignore the `OtherCondition` in TiDB since we cannot calculate the selectivity of it. It won’t influence the join reorder’s estimation.

[PR#8025](https://github.com/pingcap/tidb/pull/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](https://pdfs.semanticscholar.org/b24a/e7a6a57c083e441d7c96cb6d71472c6e0c9b.pdf).

- There’s also one way called [transformation based join reorder](http://www.vldb.org/pvldb/vol7/p1243-shanbhag.pdf). 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](https://github.com/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:

1. Reduce the total memory consumption during the execution phase.
2. 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:

1. 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.

2. 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.

3. 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

1. Implement the column pool firstly.
2. Remove the complicated, error-prone resource recycling strategy for each
   operator.
3. 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:
```sql
CREATE OR replace VIEW popularbooks 
AS 
  SELECT isbn, 
         title, 
         author, 
         publishdate 
  FROM   books 
  WHERE  ispopular = 1 
```  

Once 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:  
```sql
SELECT Author, Title FROM PopularBooks ORDER BY Author
```

In 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 VIEW`
* `SELECT FROM VIEW`
* `DROP VIEW`
* `SHOW 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](https://dev.mysql.com/doc/refman/5.7/en/view-algorithms.html)  
    The view SQL `AlGORITHM` characteristic. The value should be one of `UNDEFINED`, `MERGE` OR `TEMPTABLE`. If no `ALGORITHM` clause is present, `UNDEFINED` is the default algorithm.
    Currently, we will only implement the `MERGE` algorithm.
* [Definer](https://dev.mysql.com/doc/refman/5.7/en/create-view.html)  
    The account of the user who created the view, in `'user_name'@'host_name'` format.
* [Security](https://dev.mysql.com/doc/refman/5.7/en/create-view.html)  
    The view SQL `SECURITY` characteristic. The value is one of `DEFINER` or `INVOKER`.
* [CheckOption](https://dev.mysql.com/doc/refman/5.7/en/view-check-option.html)  
    The `WITH CHECK OPTION` clause can be given to an updatable view to prevent inserts to rows for which the `WHERE` clause in the select_statement is not true. It also prevents updates to rows for which the `WHERE` clause 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 a `WITH CHECK OPTION` clause for an updatable view, the `LOCAL` and `CASCADED` keywords determine the scope of check testing when the view is defined in terms of another view. When neither keyword is given, the default is `CASCADED`.
* SelectStmt  
    This string is the origin `SELECT` SQL statement.
* Cols  
    This `model.CIStr` array stores view's column alias names.
* TableInfo.Columns  
    `TableInfo.Columns` only stores view's column origin names.
 
## Rationale
1. Create VIEW  
   This proposal only supports the following grammar to create view:
   ```sql
    CREATE
        [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]
    ```
    1. Parse the create view statement and build a logical plan for select clause part. If any grammar error occurs, return errors to parser.   
    2. Examine view definer's privileges. Definer should own both `CREATE_VIEW_PRIV` privilege and base table's `SELECT` privilege. We will reuse `CREATE_PRIV` privilege when implement `CREATE VIEW` feature and will support `CREATE_VIEW_PRIV` check later.  
    3. Examine create view statement. If the `ViewFieldList` clause 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 to `TableInfo.Columns`.
2. DROP VIEW  
  Implement `DROP VIEW` grammar, and delete the existing view tableinfo object. This function should reuse `DROP TABLE` code logic.
3. SELECT FROM VIEW  
    In function `func (b *PlanBuilder) buildDataSource(tn *ast.TableName) (LogicalPlan, error)`, if `tn *ast.TableName` is a view, then we build a select `LogicalPlan` from view's `SelectStmt` string. But this solution meets a problem, and here is the example:  
    ```sql
       create table t(a int,b int);
       create view v like select * from t;
       select * from t;
    ```
    Once we query from view `v`, database will rewrite view's `SelectStmt` from `select * from t` into **`select a as a,b as b from t`**.
    But, if we alter the schema of t like this:
    ```sql
       drop table t;
       create table t(c int,d int);
    ```
    Executing `select * from v` now is equivalent to **`select 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 a `Projection` at the top of original select's `LogicalPlan`, just like we rewrite view's `SelectStmt` from `select * from t` into **`select 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.  
4. Show table status  
  Modify `SHOW TABLE STATUS` function to support show view status, and we use this command to check if `CREATE VIEW` and `DROP VIEW` operation is successful. To reuse `SHOW TABLE STATUS` code 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](https://github.com/lamxTyler)
- 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:

```sql
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](https://github.com/leoppro)
- 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:

```go
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: 

```go
// RestoreCtx is Restore context to hold flags and writer
type RestoreCtx struct {
	Flags RestoreFlags
	In    io.Writer
}

const DefaultRestoreFlags = RestoreStringSingleQuotes | RestoreKeyWordUppercase | RestoreNameBackQuotes
```

## Rationale

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](https://github.com/pingcap/tidb/issues/8532).

### Example

I implemented the `Restore` function of [ast.CreateDatabasesStmt](https://github.com/pingcap/parser/blob/ce5a9247faef2b6876054935a0b0ed3771edf86d/ast/ddl.go#L67) 
and [ast.DropDatabaseStmt](https://github.com/pingcap/parser/blob/ce5a9247faef2b6876054935a0b0ed3771edf86d/ast/ddl.go#L130) for examples.

```go
// 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
}
```

```go
// 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](https://github.com/pingcap/parser/pull/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](https://github.com/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.toml` like example one.
- Implement the `validate`, `init`, `destroy` methods, which are needed for all plugins.
- Implement the kind special method to implement the plugin logic.
- Use `cmd/pluginpkg` to build plugin binary, and put the plugin binary into the plugin deployment folder.
- Start TiDB with the `-plugin-dir` and `-plugin-load` parameters.
- Run `show plugin` to 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=plugin` in the `main` package to make plugin `.so`.
- Use `plugin.Open` to `dlopen` the plugin's `.so`.
- Use `plugin.Lookup` to `dlsym` to 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](https://github.com/golang/go/blob/3b137dd2df19c261a007b8a620a2182cd679d700/src/cmd/go/internal/work/gc.go#L389)(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 in `show 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-tables` configuration.
- `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 a `NotifyEvent` method to implement the `notifyEvent` extension 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.
- `pluginpath` will 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.GetByKind` or `plugin.Get` to find matched plugins.
- Call `plugin.Declare[Kind]Manifest` to 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](https://github.com/golang/go/blob/50bd1c4d4eb4fac8ddeb5f063c099daccfb71b26/src/runtime/plugin.go#L52)), 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-dir` as the start argument to specify the folder containing plugins, e.g. '-plugin-dir=/data/deploy/tidb/plugin'.
- Add `-plugin-load` as 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 `Manifest` to 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](https://github.com/lamxTyler)
- 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 `SQL` USING `HINTED 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](https://github.com/lamxTyler)
- 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:

```sql
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

- [The Skyline Operator](https://www.cse.ust.hk/~dimitris/PAPERS/SIGMOD03-Skyline.pdf)

---

### 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 / PhysicalIndexMergeReader` 
- `IndexMergeLookUpReader / 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)
	TableScan
```

For 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:

<img alt="CNF 200" src="./imgs/cnf200m2.png" width="500pt"/>

**Note:** `SELECTIVITY`is 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)
	TableScan
```

To 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:

<img alt="DNF 200" src="./imgs/dnf200.png" width="500pt"/>


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 `IndexMergeType` indicates 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.

<img alt="Execution Model" src="./imgs/execution_model.png" width="500pt"/>

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

 <img alt="IndexMergeIntersection" src="./imgs/and.jpeg" width="500pt"/>

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` = 1

	IO Cost = (totalRowCount + mergedRowCount) * scanFactor
	
	Network Cost = (totalRowCount + mergedRowCount) * networkFactor
	
	Cpu Memory Cost = totalRowCount * cpuFactor + totalRowCount * memoryFactor
	
- `IndexMergeType` = 2

	IO Cost = (totalRowCount) * scanFactor
	
	Network Cost = totalRowCount * networkFactor
	
	Cpu Memory Cost = totalRowCount * cpuFactor + totalRowCount * memoryFactor
	
- `IndexMergeType` = 3

	IO 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

1. Implement planner operators
1. Enhance `explain` to display the plan
3. Implement executor operators
4. Testing

---

### Design 2019 11 05 Index Advisor (`docs/design/2019-11-05-index-advisor.md`)

# Proposal: Support automatic index recommendation

- Author(s): [Zou Huan](https://github.com/zouhuan1215) 
- 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:

1. **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.

2. **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 as `LSIs` (Local Selected Index) and denote the corresponding cost as `virtual_cost`. Calculate `reduced_cost = original_cost - virtual_cost`. 
   - Respectively add up `LSIs' reduced_cost` of each query in the workload. Denote the *sum* as `LSIs'` final scores.
   - Get the score list of `LSIs` descending with their corresponding score. 

3. **Evaluate index set**: 
   - Pick the top `n` indexes as the initial `recommended index set`. Denote the remaining unselected index set as `remaining index set`.
   - Execute the following *Swap and Re-evaluate* algorithm. 

```golang
// 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 = 1
```
where index on column *c* has already existed. 

- **Step1**: recommend indexes for single query. For each query, compile it and get the `original_cost` output by SQL optimizer. Then add all possible hypothetic indexes *a, b, d* to the schema, compile the same query again. After the compiling, `LSIs` can be extracted from output execution plan as well as the `virtual_cost`. Denote `reduced_cost` as *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 `LSIs` and `reduced_cost` of 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 set` is `{a, b}`, the `remaining index set` is `{c,d}` 
  - Add recommended index set `{a, b}` to the schema and at the same time mute existed index `c`
  - 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 update `min_cost` to *18*. Then try swapping 1 element between `{c, b}` and `{a, d}` and execute the re-evaluate process. 

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

### <span id="compatibility">**Support from TiDB SQL optimizer** </span>

1. **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

2. **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

3. **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 `cost` should be returned to the top layer of index advisor that invokes TiDB's SQL optimizer.
   - **constraints**: no
   - **implementation**: maybe rewriting the function `compiler.Compile` is a simpler way

### **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/ERROR
- `limit`: 返回日志的条数，如果没有指定，则限制为 64k 条，防止日质量太大占用大量网络

#### 节点性能采样数据

当前 TiDB 集群中，发现有性能瓶颈时，需要快速定位问题。火焰图 （Flame Graph）是由 Brendan Gregg 发明的，与其他的 trace 和 profiling 方法不同的是，Flame Graph 以一个全局的视野来看待时间分布，它从底部往顶部，列出所有可能的调用栈。其他的呈现方法，一般只能列出单一的调用栈或者非层次化的时间分布。

目前 TiKV 和 TiDB 获取火焰图的方式不同，并且都需要依赖外部工具。

- TiKV 获取火焰图

    ```
    perf 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.svg
    ```

- TiDB 获取火焰图

    ```
    curl 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 和时序数据保存的实现难度大和周期长的问题，将这个功能分为三个阶段实现（第三阶段视具体情况是否实现）：

1. PD 中添加 `remote-metrics-storage` 配置，暂时配置为 Prometheus Server 的地址。PD 作为 proxy，将请求转移到 Prometheus 上执行，主要有以下考量：
    - 后续 PD 实现查询接口实现自举，TiDB 不需要做其他改动
    - 用户不使用 TiDB 部署的 Prometheus 而使用自建的监控服务，依然可以使用 SQL 查询监控信息以及诊断框架
2. 将 Prometheus 时序数据保存和查询相应的模块抽离出来，并嵌入到 PD 中
3. PD 内部实现自己的时序保存与查询（目前 CockroachDB 的方案）

##### PD 性能分析

PD 目前主要承载 TiDB 集群的调度和 TSO 服务，其中：

1. TSO 获取仅对 Leader 内存中的一个原子变量进行累加
2. 调度生成的 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 定义

```proto
// 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` 数据库中的系统表，表达式与系统表的关系可以通过以下方式关联：

- 定义在配置文件

    ```
    # 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 注入

    ```
    curl -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 命令

    ```
    mysql> admin metrics_schema add parse_duration `histogram_quantile(0.95, sum(rate(tidb_session_parse_duration_seconds_bucket[$STEP])) by (le, sql_type))`
    ```

- 从文件中加载

    ```
    mysql> 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 is `int64::MAX`.
- `pattern`: filter pattern determined by the keyword. For example, `SELECT * FROM cluster_log` WHERE "%gc%" `%gc%` is the filtered keyword.
- `level`: log level; can be selected as DEBUG/INFO/WARN/WARNING/TRACE/CRITICAL/ERROR
- `limit`: 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:

    ```
    perf 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.svg
    ```

- TiDB retrieves the flame graph via:

    ```
    curl 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):

1. Add the `remote-metrics-storage` configuration 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

2. Extract the modules for persisting and querying Prometheus time series data and embed it in PD.
3. 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:

1. TSO fetching accumulates only one atomic variable in Leader memory
2. 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

```proto
// 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 the `statements_summary` table 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

    ```
    # 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

    ```
    curl -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

    ```
    mysql> 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

    ```
    mysql> 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](https://github.com/imiskolee/tidb-wasm-markdown)
- TiDB can work properly in browsers on phones
- TiDB can run in wasmer and can be deployed to [WebAssembly Shell](https://webassembly.sh/)

## 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](https://github.com/golang/go/wiki/WebAssembly#getting-started), allowing TiDB to run anywhere.

## Implementation

Our implementation will be divided into several stages:
1. 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.
2. 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.
3. Migrate the result of stage 1 into phone browsers. Possible problems are:
  - The webkit has a [limit](https://trac.webkit.org/browser/webkit/branches/safari-604.1-branch/Source/JavaScriptCore/jit/ExecutableAllocator.cpp#L90) 
    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.
4. Migrate the result of stage 1 into Wasmer, and publish it to [WAPM](https://wapm.io/), so that it can run in any 
  platform easily with WAPM, even can run on [WebAssembly shell](https://webassembly.sh/). To achieve this, we should 
  solve:
  - Golang doesn’t support WASI now, so we need to use a [fork branch](https://github.com/neelance/go/tree/wasi) 
    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:

1. TiDB's own code has platform-dependent code.
2. TiDB has platform-dependent code in a library that is directly or indirectly imported. This dependent library is controlled by PingCAP.
3. TiDB has platform-dependent code in a library that is directly imported. This dependent library is not controlled by PingCAP.
4. 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](https://golang.org/pkg/go/build/), 
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:

```js
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:

```go
// 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](http://github.com/bb7133), [Kolbe Kegel](http://github.com/kolbe)
- 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](https://dev.mysql.com/doc/refman/8.0/en/charset-collation-effect.html) of the MySQL Manual and [this webpage](https://web.archive.org/web/20171030065123/http://demo.icu-project.org/icu-bin/locexp?_=en_US&x=col).

Several collation implementations are described in [this part](https://dev.mysql.com/doc/refman/8.0/en/charset-collation-implementations.html) 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`.

### 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`/`tablecodec` package.
  - SQL Runtime:
	  + implement `WEIGHT_STRING()` expression, which returns the sorting hexadecimal value(or `sortKeys`) for a string. This expression will be helpful for debugging collations.
      + update like/regex/string comparison related functions in `expression` package.
	  + update the comparisons logic in Join/Aggregation executors in `executor` package.
	  + update the codes in `UnionScan`(the internal buffer of transaction).
  - SQL Optimizer: the optimizer may need to be aligned with the encoding changes in `planner` package.
  - DDL/Schema: check if the new collation is supported according to the versions of tables/columns, the related codes are in `ddl` and `infoschema` package.
  - Misc
      + update string comparison related functions in `util` package.
      + check if range functions defined in table partitions work with collations.

## 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 `sortKey` corresponding 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](https://godoc.org/golang.org/x/text/collate).

### Row Format

The encoding layout of TiDB has been described in our [previous article](https://docs.pingcap.com/tidb/stable/tidb-computing). 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 `ColumnValue` with `sortKey` and encode the `ColumnValue` to the value:
    - For unique indices:
	```
      Key: tablePrefix{tableID}_indexPrefixSep{indexID}_sortKey
      Value: rowID_indexedColumnsValue
	```
    - For non-unique indices:
	```
      Key: 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 `ColumnValue` with `sortKey` without additional change:
    - For unique indices:
	```
      Key: tablePrefix{tableID}_indexPrefixSep{indexID}_sortKey
      Value: rowID
	```
    - For non-unique indices:
    ```
      Key: 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 mappings` of 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_ci` only and treat `utf8mb4_general_ci` as 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:

  1. 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.
  2. Users of MySQL who requires collations can move to TiDB without modifying their scripts/applications.
  3. Users of TiDB can distinguish the tables with old collation and new collations easily, if they both exist in a TiDB cluster.
  4. 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:

1. 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.

2. We can also provide a configuration entry for the users to choose between old/new collations when deploying the new clusters.

3. 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](https://github.com/pingcap/parser/blob/b27aebeca4ba3fd938900fb57c0ea45c55d3753a/model/model.go#L66). 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](#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:

  * [Rust unicode_collation](https://docs.rs/unicode-collation/0.0.1/unicode_collation)
  * [Rust servo/rust-icu](https://github.com/servo/rust-icu)
  * [C++ std::collate](https://en.cppreference.com/w/cpp/locale/collate)
  * [C/C++ ICU4C](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c)

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](#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](https://mysqlserverteam.com/mysql-8-0-collations-migrating-from-older-collations).

## Testing Plans

Here lists possible tests that can be done:

  * The unit / integration tests corresponding to the updates in [Changes to make](#changes-to-make)
  * The unit / integration tests corresponding to the [implementations](#implementation)
  * 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](https://github.com/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_name
```

Drop sequence statement:

```
DROP SEQUENCE [IF EXISTS] sequence_name_list
```

Get 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> ——> int64 
```

Reads 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 the `NOCACHE` mode.

## Compatibility

Specific compatibility can be referred by [MySQL’s compatibility](https://pingcap.com/docs/stable/reference/mysql-compatibility/).

---

### Design 2020 04 20 Brie (`docs/design/2020-04-20-brie.md`)

# Proposal: Backup/Restore/Import/Export via SQL

- Author(s):     [kennytm](https://github.com/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.

[BR]: https://github.com/pingcap/br/
[SST]: https://github.com/facebook/rocksdb/wiki/Creating-and-Ingesting-SST-files
[Lightning]: https://github.com/pingcap/tidb-lightning

## Proposal

### Syntax

Introduce 4 kinds of statements for executing backup, restore, import and export:

```sql
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:

```sql
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.

```sql
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

<details><summary>Data source parameters</summary>

* 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

</details>

<details><summary>Common options</summary>

* SEND_CREDENTIALS_TO_TIKV = 1
* CONCURRENCY = 32
* CHECKSUM = 1
* RATE_LIMIT = 125 MB/SECOND
* CHECKPOINT = 1

</details>

<details><summary>Backup/Export options</summary>

* SNAPSHOT = 4 HOUR AGO
* SNAPSHOT = '2020-04-20 15:00:00'
* SNAPSHOT = 416110777682551
* LAST_BACKUP = '2020-04-20 15:00:00'
* LAST_BACKUP = 416110777682551

</details>

<details><summary>Restore/Import options</summary>

* ONLINE = 1

</details>

<details><summary>Import/Export CSV options</summary>

* 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

</details>

<details><summary>Other Import options</summary>

* ANALYZE = 1
* SKIP_SCHEMA_FILES = 1
* BACKEND = 'local'
* TIKV_IMPORTER = '127.0.0.1:8287'
* ON_DUPLICATE = 'replace'
* STRICT_FORMAT = 1

</details>

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 already
```

If 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) and `IMPORT` (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:

```sql
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.
```sql
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](https://docs.microsoft.com/en-us/sql/t-sql/statements/restore-statements-transact-sql?view=sql-server-ver15) | Sync | `RESTORE DATABASE db1 FROM URL = 'https://example.com/backup1.bak'` |
| [IBM DB2](https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.admin.cmd.doc/doc/r0001976.html) | Sync | `RESTORE DATABASE db1 FROM 'db2remote://example//backup/1'` |
| [SAP HANA](https://help.sap.com/viewer/4fe29514fd584807ac9f2a04f6754767/2.0.04/en-US/93637a07e3b544398aa02de1541b903c.html) | Sync | `RECOVER DATA USING FILE ('/data/backup1') CLEAR LOG` |
| [MemSQL](https://docs.memsql.com/v7.0/reference/sql-reference/pipelines-commands/create-pipeline/) (ETL) | Async | `CREATE PIPELINE restore_pl AS LOAD DATA S3 'bucket/backup1' CREDENTIALS '{…}' INTO TABLE db1.tbl1; START PIPELINE restore_pl` |
| [CockroachDB](https://www.cockroachlabs.com/docs/stable/restore.html) | 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?

    ```sql
    BACKUP 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:

1. Use options:

    ```sql
    RESTORE 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;
    ```

2. Use a JSON configuration:

    ```sql
    RESTORE 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).

[the `RunBackup` function]: https://github.com/pingcap/br/blob/f5c37f36457b582710634f31fc2b9a1fb66254c6/pkg/task/backup.go#L94

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:

```toml
[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:

```json
[
    {
        "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

```md
## 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:

```md
## 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:

```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:
```toml
[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`](https://github.com/pingcap/errors/blob/f9054262e67a3704a936a6ea216e73287486490d/terror/terror.go#L41) 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:

```bash
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.toml
```

Then 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](https://pingcap.com/docs/stable/reference/error-codes/) 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](https://github.com/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](https://github.com/pingcap/tidb/issues/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](https://github.com/golang/go/blob/48a90d639d578d2b33fdc1903f03e028b4d40fa9/src/cmd/oldlink/internal/ld/main.go#L155) 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:

1. fulfill the `SimpleLRUCache` by `set @randomString = ? with 20000 times`.
2. profile the heap Usage of `github.com/pingcap/tidb/util/kvcache.(*SimpleLRUCache).Put` and 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.

3. we use [sizeof](https://github.com/templarbit/sizeof) (the result is similar, but lower, not exact) to calculate the size of each key and element is 80byte and 40byte.
4. 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](https://github.com/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](https://github.com/pingcap/tidb/issues/8854).

## Proposal

To support "Global Kill", we need:
1. Global connection ids, which are unique among all TiDB instances.
2. Redirect `KILL x` to target TiDB instance, on which the connection `x` is running.
3. Support both 32 & 64 bits `connID`. 32 bits `connID` is 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 bits `connID` is used for big clusters. Bit 0 in `connID` is 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) All `local connID` in 32 bits `connID` are in used (see `local connID` section 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 `serverID` until 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 == 0` indicates that the `connID` is just 32 bits long effectively, and high 32 bits should be all zeros. Compatible with legacy 32 bits clients.
-  `markup == 1` indicates that the `connID` is 64 bits long. Incompatible with legacy 32 bits clients.
-  `markup == 1` while __high 32 bits are zeros__, indicates that 32 bits truncation happens. See `Compatibility` section.

#### 4. ServerID
- `serverID` is selected RANDOMLY from `serverIDs pool`_(see next)_ by each TiDB instance on startup, and the uniqueness is guaranteed by PD (etcd). `serverID` should be larger or equal to 1, to ensure that high 32 bits of `connID` is always non-zero, and make it possible to detect truncation.

- `serverIDs pool` is:
  - All __UNUSED__ `serverIDs` within [1, 2047] acquired from [`CLUSTER_INFO`](https://docs.pingcap.com/tidb/stable/information-schema-cluster-info#cluster_info) when 32 bits `connID` chosen.
  - All `serverIDs` within [2048, 2^22-1] when 64 bits `connID` chosen.

- On failure (e.g. fail connecting to PD, or all `serverID` are unavailable when 64 bits `connID` chosen), we block any new connection.
- `serverID` is 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/incorrect `serverID`. On connection to PD restored, a new `serverID` is acquired before accepting new connection.
- On single TiDB instance without PD, a `serverID` of `1` is assigned.

#### 5. Local connID
`local connID` is allocated by each TiDB instance on establishing connections:

- For 32 bits `connID`, `local connID` is 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 available `local connID`, dequeue on client connecting, and enqueue on disconnecting. When `local connID` exhausted, upgrade to 64 bits.

- For 64 bits `connID`, allocate `local connID` by __auto-increment__. Besides, flip to zero if integer-overflow, and check `local connID` existed or not by [Server.clients](https://github.com/pingcap/tidb/blob/7e1533392030514440d27ba98001c374cdf8808f/server/server.go#L122) for correctness with trivial cost, as the conflict is very unlikely to happen (It needs more than 3 years to use up 2^40 `local connID` in 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`](https://docs.pingcap.com/tidb/stable/information-schema-cluster-info#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 `connID` is compatible to well-known clients.

- 64 bits `connID` is __incompatible__ with legacy 32 bits clients. (According to some quick tests by now, MySQL client v8.0.19 supports `KILL` a connection with 64 bits `connID`, while `CTRL-C` does not, as it truncates the `connID` to 32 bits). A warning is set prompting that truncation happened, but user cannot see it, because `CTRL-C` is sent by a new connection in an instant.

- [`KILL TIDB`](https://docs.pingcap.com/tidb/v4.0/sql-statement-kill) syntax and [`compatible-kill-query`](https://docs.pingcap.com/tidb/v4.0/tidb-configuration-file#compatible-kill-query) configuration 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
1. A TiDB without PD, killed by Ctrl+C, and killed by KILL.
2. One TiDB with PD, killed by Ctrl+C, and killed by KILL.
3. Multiple TiDB nodes, killed {local,remote} by {Ctrl-C,KILL}.

### Scenario B. Upgrade from 32 to 64 bits `connID`
1. Upgrade caused by cluster scaled up from small to big.
2. Upgrade caused by `local connID` used up.

### Scenario C. 64 bits `connID` with big cluster
1. Multiple TiDB nodes, killed {local,remote} by {Ctrl-C,KILL}.

### Scenario D. Downgrade from 64 to 32 bits `connID`
1. Downgrade caused by cluster scaled down from big to small.

### Scenario E. Fault tolerant while disconnected with PD
1. Existing connections are killed after PD lost connection for long time.
2. New connections are not accepted after PD lost connection for long time.
3. New connections are accepted after PD lost connection for long time and then recovered.
4. 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](https://github.com/djshow832) (Ming Zhang), [morgo](https://github.com/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](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
    * [New Syntax Overview](#new-syntax-overview)
    * [Updates to Existing Syntax](#updates-to-existing-syntax)
    * [Placement Rules Syntax](#placement-rules-syntax)
    * [Additional Semantics](#additional-semantics)
    * [Privilege management](#privilege-management)
* [Implementation](#implementation)
    * [Storing Placement Policies](#storing-placement-policies)
    * [Storage Consistency](#storage-consistency)
    * [Querying Placement Rules](#querying-placement-rules)
    * [Building placement rules](#building-placement-rules)
    * [Rule priorities](#rule-priorities)
* [Examples](#examples)
    * [Optimization: Follower read in every region](#optimization-follower-read-in-every-region)
    * [Optimization: Latest data on SSD](#optimization-latest-data-on-ssd)
    * [Optimization: Multi-tenancy / control of shared resources](#optimization-multi-tenancy--control-of-shared-resources)
    * [Compliance: User data needs geographic split](#compliance-user-data-needs-geographic-split)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
    * [Known Limitations](#known-limitations)
* [Unresolved Questions](#unresolved-questions)
    * [Compliance Requirements](#compliance-requirements)
    * [Behaviors](#behaviors)
* [Changelog](#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:

1. An optimization or availability use case (such as improving data access locality)
2. 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:

```sql
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:

```sql
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):
- `host` and `hosts`: expected to be the same physical machine or hypervisor.
- `rack` and `racks`: similar to host; a group of machines that are physically close together and may suffer from many of the same failures.
- `zone` and `zones`: 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.
- `region` and `regions`: 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:

```sql
CREATE TABLE t1 (
	id INT NOT NULL PRIMARY KEY,
	b VARCHAR(100)
) PLACEMENT POLICY=`standardplacement`;
```

Adding `PLACEMENT POLICY` to an existing table:

```sql
CREATE TABLE t2 (
	id INT NOT NULL PRIMARY KEY,
	b VARCHAR(100)
);
ALTER TABLE t2 PLACEMENT POLICY=`standardplacement`;
```

Behavior notes:

- `CREATE` or `ALTER` and specifying a `PLACEMENT POLICY` that 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 `companyplacementpolicy` can apply to the db `test` as well as `userdb`. 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 statement `ALTER VIEW` (where the view needs to be redefined). When `ALTER PLACEMENT POLICY x` is executed, all tables that use this placement policy will need to be updated in PD.
- The statement `RENAME PLACEMENT POLICY x TO y` renames a placement policy. The `SHOW CREATE TABLE` output 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:

```sql
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:

```sql
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_CONSTRAINTS` and `LEARNER_CONSTRAINTS`. Assuming that both `CONSTRAINTS` and `FOLLOWER_CONSTRAINTS` are 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:

```sql
+----------------------+---------------+------+------+---------+-------+
| 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`:

```golang
{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):

```sql
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 `ALTER` statement on `target` that defines the placement rule.
* Scheduling state: The scheduling progress from the PD aspect. It is always `NULL` for policies.

For finding the current use of a placement policy, the following syntax can be used:

```sql
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](https://dev.mysql.com/doc/refman/8.0/en/charset-database.html). For example:

```sql
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 `companystandardpolicy` and the table t2 is created with `companynewpolicy`.
* The `DATABASE` default 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 DATABASE` is 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.

```sql
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:

```sql
[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:

```sql
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:

```sql
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 error
```

For dictionary format, the count is inferred by the constraint. The following constraint creates 3 followers:

```sql
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:

```sql
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:

```sql
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 if `us-east-1` has 15 stores and `us-east-2` has 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:

1. The `FOLLOWERS` count should respect raft quorum expectations. The default is `2` (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)
2. 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.
3. 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:

```sql
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:

``` sql
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_PREFERENCES` is equivalent to `LOCATION_LABELS` in PD. For more information, please refer to [Replica scheduling by topology label](https://docs.pingcap.com/tidb/dev/schedule-replicas-by-topology-labels#schedule-replicas-by-topology-labels).

#### Ambiguous and edge cases

The following two policies are not identical:

```sql
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:

```sql
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:

```sql
ALTER TABLE t1 PLACEMENT POLICY=`companynewpolicy`;
```

For the syntax:
```sql
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=n`
- `LEARNERS=n`
- `PRIMARY REGION`
- `REGIONS`
- `SCHEDULE`
- `CONSTRAINTS`
- `FOLLOWER_CONSTRAINTS`
- `LEARNER_CONSTRAINTS`
- `PLACEMENT POLICY`
- `SURVIVAL_PREFERENCE`

For a more complex rule using partitions, consider the following example:

```sql
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 requires `Alter` privilege
* `CREATE TABLE` statement requires `Create` privilege
* `SHOW PLACEMENT` only shows the placement rules on the objects that visible to the current user
* `information_schema.placement_policies` requires `CREATE TABLE` privilege (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 DDL` requires `Super` privilege
* `CREATE PLACEMENT POLICY`, `DROP PLACEMENT POLICY` and `ALTER PLACEMENT POLICY` require `PLACEMENT_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:

1. 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.
2. 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.
3. Local transactions need to know the binding relationship between Raft leader and region, which is also defined by placement rules.
4. Once a rule is defined on a table, all the subsequent partitions added to the table should also inherit the rule. So the `ADD PARTITION` operation should query the rules on the table. The same is true for creating tables and indices.
5. The `SHOW PLACEMENT` statement 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:

```sql
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) --> index
```

For example:

1. At the beginning, all data is placed based on the default placement rules.
2. When a placement rule is added on table `t`, all data on `t` is placed based on the rule.
3. When a placement rule is added on partition `p0` of `t`, all data on `p0` is placed based on the rule of `p0`, but other partitions stay still.
4. When the placement rule on `p0` is removed, data on `p0` is placed based on the rule of `t`, 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:

* `index` of default placement rules is 0
* `index` of database placement rules is 1
* `index` of table placement rules is 2
* `index` of partition placement rules is 3
* `index` of 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:
```sql
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:

```sql
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):

```sql
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:

```sql
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:

```sql
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 tables.

In the future we will need to be able to define the index for `username` as a global index, and allow it to have different placement rules where it can be read from all regions.

This example also demonstrates that this specification only provides partition level placement (and not row-level or column level security). The workaround for the user will require splitting the table:

```sql
CREATE TABLE users (
	id INT NOT NULL auto_increment PRIMARY KEY,
	/* public details */
);

CREATE TABLE user_details (
	user_id INT NOT NULL,
	/* private columns */
	/* partition this table */
);
```

Assuming that global indexes can be added to the TiDB server, this use-case can be improved. But for correct execution the server will also require the following functionality:
- The ability to mark global indexes as invisible at run-time if the `PLACEMENT POLICY` does not permit them to be read.
- The ability to mark the clustered index as invisible. i.e. in the case that there is a global unique index on `username` it may be permitted to be read, but a read of the `username` from the clustered index might need to be disabled.

## Impacts & Risks

1. The largest risk is designing a set of SQL statements that are sufficiently flexible to handle major use cases, but not too flexible that misconfiguration is likely when the user has compliance requirements. The following design decisions have been made to mitigate this risk:
  - The DDL statement to `ALTER TABLE t1 ADD PLACEMENT` has been removed from the proposal.
  - The DDL statement `CREATE PLACEMENT POLICY` has been added (allowing common configurations to be saved).
  - Configuring placement rules for indexes is no longer supported (we can add it once global indexes are added).
  - The inheritance rules have been simplified to match character set/collation inheritance.
2. There is a risk that we do not fully understand compliance requirements (see unresolved questions), or that the substantial effort required to achieve compliance with DDL, internal SQL and DML.
3. Related to (2), there is risk that the implementation of compliance requirements has a significant burden on multiple teams, including ecosystem tools (Backup, CDC, DM). Even tools such as dumpling should ideally be able to backup placement rules in logical form.
4. The compliance use-case may depend on global secondary indexes for many scenarios (see "Compliance: User data needs geographic split"), but they are not currently supported.
4. There is some risk that a common use case can not be expressed in `CONSTRAINT` syntax, leading to complicated scenarios where users still need to express placement by using PD directly. Ideally, we can recommend users use SQL rules exclusively.
5. Many other features in TiDB are in development, some of which may influence placement rules. Clustered index affects the key format of primary index, but fortunately the prefix of key range is untouched. Global secondary index largely affects the placement rules of partitioned tables.

## Investigation & Alternatives

For investigation, we looked at the implementation of placement rules in various databases (CockroachDB, Yugabyte, OceanBase).

The idea of using a `PLACEMENT POLICY` was inspired by how OceanBase has Placement Groups, which are then applied to tables. The idea of using a Placement Group/Placement Policy can also be seen as similar to using a "tablespace" in a traditional database.

CockroachDB does not look to have something directly comparable to `PLACEMENT POLICY`, but it does have the ability to specify "replication zones" for "system ranges" such as default, meta, liveness, system, timeseries. Before dropping `ALTER TABLE t1 ADD PLACEMENT` from this proposal, it was investigated the CockroachDB does not support this syntax, presumably for simplification and minimising similar risks of misconfiguration.

### Known Limitations

- In this proposal, placement policies are global-level and not specific to a database. This simplifies the configuration, but makes it restrictive for multi-tenant scenarios where a schema-per-tenant is provided. This is because creating or modifying placement policies requires a privilege which is cluster scoped (`PLACEMENT_ADMIN`). The limitation is that "tenants" will be able to `CREATE TABLE (..) PLACEMENT POLICY=x`, but they will not be able to `CREATE PLACEMENT POLICY x` or `ALTER PLACEMENT POLICY x`
- Complex scenarios may exist where there is not a column in the current table which can be used to partition the table into different regions, but instead there is a column which is a foreign key to another table from which this information can be determined. In this scenario, the user will be required to "denormalize" the usage and move the parent_id into the child table so geo-partitioning is possible.
- The name `REGION` is ambigous, since we are using it for placement as well as to refer to a chunk of data. We could avoid region here, but the problem is it is the most used term for a geographic location of a data center. We recommend instead calling both region but in documentation refering to them as "data regions" and "placement regions".

## Unresolved Questions

### Compliance Requirements

For compliance use-cases, it is clear that data at rest should reside within a geographic region. What is not clear is which (if any) circumstances data in transit is permitted to leave. There are several known issues which will need to be resolved:

* **Backup**: The `BACKUP` SQL command (and br) accept a single location such as `s3://bucket-location/my-backup` to centralize the backup. This centralization likely violates compliance requirements (assuming there are >=2 requirements that conflict on a single cluster). Backing up segments of data individually is both an inconsistent backup, and likely to result in misconfiguration which violates compliance rules. Users have a reasonable expectation of backup integration with compliance placement rules.
* **CDC**: Similar to `BACKUP`, it should not be possible to subscribe to changes for data in a different jurisdiction.
* **DDL**: The current implementation of DDL uses a centralized DDL owner which reads data from relevant tables and performs operations such as building indexes. The _read_ operation may violate compliance rules.
* **Internal SQL**: Similar to DDL, several centralized background tasks, such as updating histograms/statistics need to be able to _read_ the data.
* **DML**: It is not yet known which restrictions need to be placed on user queries. For example, if a poorly written user-query does not clearly target the `USA` partition when reading user data, should it generate an error because the `EUROPE` partition needs to be read in order for the semantics of the query to be correct? This may cause problems in development and integration environments if the restrictions can not be distilled into environments with smaller topologies.
* **Routing**: When there is a data center for Europe, and a Data center for the USA, and the data is partitioned with requirements that DML from the USA can not read data in Europe, how is that enforced? Is it configured in such a way that the tidb-servers in the USA can not route to the tikv-servers in Europe? If this is the case, then it means the European servers can not hold non-user compliance data that the USA might need to read. If it is not the case, then there might be some sort of key management/crypto scheme to control access to sensitive data.

### Behaviors

#### Syntax for Restricted Access (Compliance Case)

Assume that if the example is logically like the "Compliance: User data needs geographic split" case:

```sql
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')
);
```

What does `SHOW CREATE PLACEMENT POLICY europe` look like?

I assume that it is something like:

```sql
CREATE PLACEMENT POLICY europe CONSTRAINTS="+region=eu-west-1" RESTRICTED;
```

This specific semantic will be the hardest to implement because of the other dependencies in the server.

## Changelog

* 20221-01-06:
  - Removed Direct placement options, and support only placement policies.
  - Renamed infoschema tables to make sense based on direct placement removal.
  - Incorporate change from `PLACEMENT_CHECKS` to `tidb_placement_mode`.

* 2021-11-29:
  - Updated limits on object length.
  - Removed built-in placement policies (not supported for now, need additional discussion due to `DEFAULT` conflicts.)

* 2021-10-29:
  - Add more description to 'scheduling_state'.

* 2021-09-13:
  - Removed support for `VOTER_CONSTRAINTS` and `VOTERS`. The motivation for this change is that dictionary syntax is ambiguous cases when both `VOTER_CONSTRAINTS` and `FOLLOWER_CONSTAINTS` are set. We can re-add this syntax if there is a clear use-case requirement in future.

* 2021-07-26:
  - Converted proposal to use the new template for technical designs.
  - Removed the syntax `ALTER TABLE t1 ADD PLACEMENT POLICY` due to ambiguity in some cases, and risk of misconfiguration for compliance cases.
  - Added `CREATE PLACEMENT POLICY` syntax.
  - Renamed `ALTER TABLE t1 ALTER PLACEMENT POLICY` to `ALTER TABLE t1 PLACEMENT` to bring syntax inline with other atomic changes, such as `ALTER TABLE t1 CHARACTER SET x`. The usage of `PLACEMENT POLICY` now refers to a placement policy defined from `CREATE PLACEMENT POLICY` (other commands like `SHOW PLACEMENT POLICY` are also updated to `SHOW PLACEMENT`).
  - Remove index as a placement option (we can add it again once global indexes for temporary tables exist, but it is not strictly required for an MVP).
  - Made implementation in `CREATE TABLE` and `SHOW CREATE TABLE` required, to support the compliance use-case.
  - Changed `ALTER TABLE ALTER PARTITION p0` to `ALTER TABLE PARTITION p0`
  - Added short-hand syntactic sugar for constraints to handle default cases.
  - Changed it so that you can no longer specify multiple constraints.
  - Use defaults for `count` of each role, and `ROLE_CONSTRAINTS` syntax.
  - Added `SCHEDULE` property
  - Removed further ambiguous cases such as count when using dictionary syntax.

---

### Design 2020 07 07 Change Column Types (`docs/design/2020-07-07-change-column-types.md`)

# Proposal: Changing column types

- Author(s):     [zimuxia](https://github.com/zimulala) (Xia Li)
- Last updated:  2020-07-07
- Discussion at: https://tidbcommunity.slack.com/archives/CMAKWBNJU

## Abstract

This proposal proposes a new feature that supports column type modification more comprehensively.

## Background

This feature mainly uses the syntax of `alter table ... change/modify column` to support the modification of column type. The specific syntax is as follows:

```sql
ALTER TABLE tbl_name
    [alter_specification]

alter_specification:
CHANGE [COLUMN] old_col_name new_col_name column_definition
        [FIRST | AFTER col_name]
| MODIFY [COLUMN] col_name column_definition
        [FIRST | AFTER col_name]
```

At present, column type modification only supports the lengthening of the same type, that is, there is no true change to the data type in the storage layer. The limitation of the new support is as follows:
* Lossy changes are not supported, such as changing from BIGINT to INTEGER, or from VARCHAR(255) to VARCHAR(10)
* Modification of the precision of DECIMAL type is not supported
* Does not support changing the UNSIGNED attribute
* Only support changing CHARACTER SET attribute from utf8 to utf8mb4

## Proposal

The column type modifications supported by this proposal will involve rewriting column data and refactoring related indexes. This operation still needs to meet the basic requirements of online DDL operation, and to meet the compatibility between previous and subsequent versions of TiDB.

To support this feature, TiDB needs to add additional related columns to the modified column. The type of the newly added column is the type you want to modify. In addition, it is necessary to add each additional related index to the index that contains this column, and update the type of the corresponding column in new indexes.

## Rationale

This proposal suggests adding additional related columns and indexes which involve the column to be modified, that is, making a copy of the columns and indexes that contain `the changed/modified column`. And if user data is written during the copying process, the corresponding data needs to be updated in real time. Assume that the type of `colA` is changed from `originalType` to `newType`, `idxA` (index with `colA`, here it is assumed that there is only one corresponding general index, the index has no relation to column generation).

### Pre-preparation

Add `ChangingCol` and `ChangingIdx` fields to the column and related index that need to be modified, which are used to associate the modified column and index information.

When performing an insert or update operation (executed in the `AddRecord` or `UpdateRecord` function) on the column whose type is to be modified, the column and index to be backed up are written or updated according to the `newType` type.

### Process

1. Update the metadata information, including creating a corresponding column for `changingcolA` and `changingIdxA` for idxA, and add them to the end of the column array or index array in `TableInfo`. The state of `changingColA` and `changingIdxA` can be changed similar to add index operation, especially in `StateWriteReorganization` state, such as initializing reorganization information.
2. In the reorganization processing stage, row data and index data need to be processed in batches, which is similar to the `add index` operation during initial implementation. Get the batch processing range, and then use the `newType` to construct the `changingColA` and `changingIdxA` information for the insert operation (this operation requires the corresponding row and index column to be locked). If data-truncated are encountered and errors at this stage, it is necessary to report the errors and roll back to exit.
3. The next phase of change requires 3 status changes:
    * Lock this table and cannot write to it.
    * Drop `colA` and `idxA`, change the status of `changingColA` and `changingIdxA` to public, and change their names, offsets, etc.
    * Unlock this table.

### Note

This operation itself is an `alter table tableName modify/change column …` statement, which includes changing the column type, changing the column attribute from null to not null, changing the column offset, etc. Considering the atomicity, some operations need to be changed together.

In addition, due to the complexity of this feature, considering that the friendly review needs to be divided into multiple PRs, a switch can be added to deal with the problem of multiple PRs.

### Rolling back

This requires changing the state of `colA` and `idxA` to `StatePublic`, and then dropping `changingColA` and `changingIdxA`. Of course, if you modify the flag and other attributes, you need to roll back.

## Compatibility

### Compatibility issues with MySQL

* Considering the complexity of supporting clustered-index and currently TiDB does not fully support clustered-index, so temporarily this feature does not support type modification for columns with the primary key.
* In addition, we temporarily do not support column type change on three features of partition table, generated column, and expression index in the first stage of implementation.

### Compatibility issues with TiDB

The DDL statement itself already has a corresponding type (ActionModifyColumn). If you need to improve this operation, you will encounter compatibility issues when performing rolling upgrades. This problem is handled by adding a global variable `tidb_enable_change_column_type`. When this value is true, the `modify/change column` statement is allowed to perform more types of column type changes (features supported by this proposal).

* For new clusters, set this variable to true during bootstrap.
* For clusters requiring rolling upgrade, the default value is false, and users need to explicitly set this variable to true.

### Compatible issues with other components

This feature needs to be synchronized with components such as Tools, TiFlash, and BR.

## Implementation

In addition to considering the update of the corresponding column type and data, and the update of the data in the index column involved, the implementation of column type modification also needs to consider the following characteristics.

### Generate columns

When the modified type relates to generated columns (either stored or virtual), the implementation has the following characteristics:

* The generated column type related to this column is unchanged.
* When performing an insert operation, the column value of the modified type will be affected by the generated column expression with this column. 
* The value of the relevant generated column changes with the value of the column of the modified type.

### Expression index

When columns of the modified type have a related expression index, the implementation has the following characteristics:

* The Type, DBType and Max_length of the related expression index may be modified.
* When performing an insert operation, the value of the column of the modified type will be affected by the expression in the expression index of this column.

## Open issues (if applicable)

https://github.com/pingcap/tidb/issues/17526

---

### Design 2020 09 12 Utf8mb4 Pinyin Order (`docs/design/2020-09-12-utf8mb4-pinyin-order.md`)

# Proposal: support `pinyin` order for `utf8mb4` charset

- Author(s):     [xiongjiwei](https://github.com/xiongjiwei)
- Last updated:  2020-11-06
- Discussion at: https://github.com/pingcap/tidb/issues/19747

## Abstract
This proposal proposes a new feature that supports `pinyin` order for chinese character.

## Background
It's unable now to order by a column based on its pinyin order. For example:

```sql
create table t(
	a varchar(100)
)
charset = 'utf8mb4' collate = 'utf8mb4_zh_0900_as_cs';

# insert some data:
insert into t values ("中文"), ("啊中文");

# a query requires to order by column a in its pinyin order:
select * from t order by a;
+-----------+
| a         |
+-----------+
| 啊中文    |
| 中文      |
+-----------+
2 rows in set (0.00 sec)
```

## Proposal

`pinyin` order for Chinese character supported by this proposal will add a new collation named `utf8mb4_zh_pinyin_tidb_as_cs` which is support all Unicode and sort Chinese characters correctly according to the PINYIN collation in zh.xml file of [CLDR24](http://unicode.org/Public/cldr/24/core.zip), and only support those Chinese characters with `pinyin` in zh.xml currently, we support neither those CJK characters whose category defined in Unicode are Symbol with the same shape as Chinese characters nor the PINYIN characters. In `utf8mb4_zh_pinyin_tidb_as_cs`, `utf8mb4` means charset utf8mb4, `zh` means Chinese language, `pinyin` means it has pinyin order, `tidb` means a special(tidb) version, and `as_cs` means it is accent-sensitive and case-sensitive.

### Advantages

It's a lot of work if we implement `utf8mb4_zh_0900_as_cs`. The implementation of MySQL looks complicated with weight reorders, magic numbers, and some tricks. Implementing `utf8mb4_zh_pinyin_tidb_as_cs` is much easier. It supports all Chinese characters and sorts Chinese characters in pinyin order. It is good enough.

### Disadvantages

It is not compatible with MySQL. MySQL does not have a collation named `utf8mb4_zh_pinyin_tidb_as_cs`.

## Rationale

### How to implement

#### Compare and Key

- For any Chinese character, which has non-zero seq NO. defined in zh.xml according to its gb18030 code, the final weight shall be 0xFFA00000+(seq No.)
- For any non-Chinese gb18030 character 2 bytes C, the final weight shall be C itself.
- For any non-Chinese gb18030 character 4 bytes C, the final weight shall be 0xFF000000+diff(C)(we get diff by Algorithm).

### Parser

Choose collation ID `2048` for `utf8mb4_zh_pinyin_tidb_as_cs` and add it into parser.

> MySQL supports two-byte collation IDs. The range of IDs from 1024 to 2047 is reserved for user-defined collations. [see also](https://dev.mysql.com/doc/refman/8.0/en/adding-collation-choosing-id.html)

### Compatibility with current collations

`utf8mb4_zh_pinyin_tidb_as_cs` has same priority with `utf8mb4_unicode_ci` and `utf8mb4_general_ci`, which means these three collations incompatible with each other.

### Alternative
MySQL has a lot of language specific collations, for `pinyin` order, MySQL uses collation `utf8mb4_zh_0900_as_cs`.

## Compatibility and Migration Plan

### Compatibility issues with MySQL

There is no `utf8mb4_zh_pinyin_tidb_as_cs` collation in MySQL. We can comment `utf8mb4_zh_pinyin_tidb_as_cs` when users need to replicate their data from TiDB to MySQL.

## Open issues (if applicable)

https://github.com/pingcap/tidb/issues/19747

https://github.com/pingcap/tidb/issues/10192

---

### Design 2020 09 30 Index Usage Information (`docs/design/2020-09-30-index-usage-information.md`)

# Proposal:

- Author(s):     [rebelice](https://github.com/rebelice)
- Last updated:  Sep. 30, 2020
- Discussion at: N/A

## Abstract

This document describes the design of recording index usage information.

## Background

There may be unused indexes in the database. In addition, modifying database tables, indexes, and query statements may cause some indexes to not be used in the future. Users may want to clear these long-unused indexes to relieve storage and performance pressure.

Related issues:

- https://github.com/pingcap/tidb/issues/14998
- https://github.com/pingcap/tidb/issues/14607
- https://github.com/pingcap/tidb/issues/17508
- https://asktug.com/t/topic/34614/12

## Proposal

### SCHEMA_INDEX_USAGE

Design system tables to record index usage information. The system table is designed as follows:

1. The system table is located in `mysql` database and is named `SCHEMA_INDEX_USAGE`.
2. Columns of `SCHEMA_INDEX_USAGE`:

| Column name  | Data type | Description |
|--------------|-----------|-------------|
| TABLE_ID     | bigint    | ID of the table or view on which the index is defined.|
| INDEX_ID     | bigint    | ID of the index.|
| QUERY_COUNT  | longlong  | Number of the SQL using this index.|
| ROWS_SELECTED| longlong  | Number of rows read from the index. We can check the average fetched rows count of each query of the index through `ROWS_READ` / `QUERY_COUNT`.|
| LAST_USED_AT | timestamp | The last time of the SQL using this index.|


3. Typical usage: `select * from mysql.SCHEMA_INDEX_USAGE`.

#### Table creation: 

```sql
create table SCHEMA_INDEX_USAGE (
	TABLE_ID bigint(21),
	INDEX_ID bigint(21),
	QUERY_COUNT BIGINT,
	ROUWS_SELECTED BIGINT,
	LAST_USED_AT timestamp,
	PRIMARY KEY (SCHEMA_NAME, TABLE_NAME, INDEX_NAME)
);
```

According to the [TiDB Doc](https://docs.pingcap.com/zh/tidb/stable/information-schema-tidb-indexes#tidb_indexes), `INDEX_ID` should be `bigint(21)`. Similarly, [this doc](https://docs.pingcap.com/zh/tidb/stable/information-schema-tables#tables) tells us that `TABLE_ID` should be `bigint(21)`.

#### Table update: 

```sql
insert into mysql.SCHEMA_INDEX_USAGE values (schemaA, tableA, indexA, count, row, used_at) 
on duplicate key update query_count=query_count+count, rows_selected=rows_selected+row, last_used_at=greatest(last_used_at, used_at)
```

#### Update method:

Statistics update is divided into statistics and persistence of index usage information. Index usage information is counted by the exec-info collector. And persistence is periodically writing data to system tables. We add a global variable `index-usage-sync-lease` to control the persistence cycle. It is set to 1 minute by default. In addition, add a global SQL variable to control whether to turn on this feature.

### SCHEMA_UNUSED_INDEXES

Due to MySQL compatibility, add the system table `SCHEMA_UNUSED_INDEXES`.

1. Create a view `SCHEMA_UNUSED_INDEXES` on table `SCHEMA_INDEX_USAGE`.
2. Columns of it:

| Column name   | Data type | Description           |
| -----------   | --------- | --------------------- |
| object_schema | varchar   | The schema name.      |
| object_name   | varchar   | The table name.       |
| index_name    | varchar   | The unused index name.|

#### View creation:

```sql
create view information_schema.schema_unused_indexes 
as select i.table_schema as table_schema, i.table_name as table_name, i.index_name as index_name 
from mysql.tidb_indexes as i left join mysql.schema_index_usage as u 
on i.table_schema=u.table_schema and i.table_name=u.table_name and i.index_name=u.index_name
where u.query_count=0 or u.query_count is null;
```

### INFORMATION_SCHEMA.SCHEMA_INDEX_USAGE

We use `TABLE_ID` and `INDEX_ID` as ID `mysql.SCHEMA_INDEX_USAGE`. Because of `TABLE_ID` and `INDEX_ID` is not user-friendly, we need a more user-friendly view.
Columns of it:

| Column name  | Data type | Description |
|--------------|-----------|-------------|
| TABLE_SCHEMA | varchar   | Name of the database on which the table or view is defined.|
| TABLE_NAME   | varchar   | Name of the table or view on which the index is defined.|
| INDEX_NAME   | varchar   | Name of the index.|
| QUERY_COUNT  | longlong  | Number of the SQL using this index.|
| ROWS_SELECTED| longlong  | Number of rows read from the index. We can check the average fetched rows count of each query of the index through `ROWS_READ` / `QUERY_COUNT`.|
| LAST_USED_AT | timestamp | The last time of the SQL using this index.|

#### View creation:

```sql
create view information_schema.schema_index_usage
as select idx.table_schema as table_schema, idx.table_name as table_name, idx.key_name as index_name, stats.query_count as query_count, stats.rows_selected as rows_selected
from mysql.schema_index_usage as stats, information_schema.tidb_indexes as idx, information_schema.tables as tables
where tables.table_name = idx.table_schema
	AND tables.table_name = idx.table_name
	AND tables.tidb_table_id = stats.table_id
	AND idx.index_id = stats.index_id
```

### FLUSH SCHEMA_INDEX_USAGE

#### User story

Users may have just completed a deployment which changes query patterns such that they expect there will be unused indexes. They can potentially look at the `LAST_USED_AT` column, but sometimes flushing is more desired.

Similar usage: `FLUSH INDEX_STATISTICS` from https://www.percona.com/doc/percona-server/LATEST/diagnostics/user_stats.html.

SQL Syntax: `FLUSH SCHEMA_INDEX_USAGE`
Users can use this to initialize SCHEMA_INDEX_USAGE as
```sql
delete from mysql.schema_index_usage;
```
And it needs a [RELOAD privilege](https://dev.mysql.com/doc/refman/5.7/en/privileges-provided.html#priv_reload) check.

### Privilege

Read privilege: Reading SCHEMA_INDEX_USAGE and SCHEMA_UNUSED_INDEXES need permission. A user can see only the rows in the tables that correspond to tables for which the user has the proper access privileges, such as information_schema.tables.
Write privilege: These tables are read-only. You can use FLUSH SCHEMA_INDEX_USAGE command to reinitialize tables, which requires the RELOAD privilege.

## Rationale

### MySQL

- Doc: The [schema_unused_indexes](https://dev.mysql.com/doc/refman/5.7/en/sys-schema-unused-indexes.html) view shows indexes for which there are no events, which indicates that they are not being used. By default, rows are sorted by schema and table.
- User interface
	- SQL:  `select * from schema_unused_indexes;`
	- Columns of schema_unused_indexes
		- object_schema (The schema name)
		- object_name (The table name)
		- index_name (The unused index name)
- The data for this view comes from the [table_io_waits_summary_by_index_usage](https://dev.mysql.com/doc/refman/5.7/en/table-waits-summary-tables.html#performance-schema-table-io-waits-summary-by-table-table). The table contains the following columns
	- object_typje, object_schema, object_name, index_name
	- In addition, there are columns related to statistical information with different granularities, such as: statistical information of all read operations, statistical information of write operations, or statistical information of all operations.

### SQL-Server

- Doc: [sys.dm_db_index_usage_stats](https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-index-usage-stats-transact-sql?view=sql-server-ver15) returns counts of different types of index operations and the time each type of operation was last performed.
- User interface
	- SQL: `select * from sys.dm_db_index_usage_stats;`
	- Columns of sys.dm_db_index_usage_stats
		- database_id
		- object_id
		- index_id
		- The number and final execution time of different types of index operations, including seek, scan, lookup, update. Each operation distinguishes user operations and system operations
	- Whenever the index is used, the information in the table will be updated.

### Oracle

- Doc: [V$OBJECT_USAGE](https://docs.oracle.com/cd/B28359_01/server.111/b28320/dynviews_2077.htm#REFRN30162) displays statistics about index usage gathered from the database.
- User interface
	- SQL: `select * from v$object_usage;`
	- Columns of v$object_usage
		- index_name
		- table_name
		- monitoring
		- used
		- start_monitoring
		- end_monitoring
- Oracle can set whether to monitor an index.

## Compatibility and Migration Plan

MySQL supports `SCHEMA_UNUSED_INDEXES`. We are considering compatibility and also support this view.

## Implementation

My implementation plan is in [issues/19209](https://github.com/pingcap/tidb/issues/19209)

## Testing Plan

The test method is similar to general statistics.

## Open issues (if applicable)

---

### Design 2021 03 01 Pipelined Window Functions (`docs/design/2021-03-01-pipelined-window-functions.md`)

# Proposal: Pipeline Window Function Execution

- Author(s): [ichn-hu](https://github.com/ichn-hu)
- Discussion at: https://github.com/pingcap/tidb/pull/23028
- Tracking issue: https://github.com/pingcap/tidb/pull/23022

## Note

* Row number is often shortened to RN, and RNF for RN function
* Window function is often shortened to WF

## Abstract

This document proposes to support executing window functions in a pipelined manner.

## Background

The current WF implementation materialized a whole partition before processing it, and if a partition is too large, it will cause TiDB OOM. One particular example is seen in [issue/18444](https://github.com/pingcap/tidb/issues/18444) where the whole table is processed as a single partition in order to get a row number for the paging scenario, while the alternative solution using user variable could significantly decrease the memory usage.

As the cause is clear, we aim to pipeline the calculation of some of the window function, which means the window function executor will return data as soon as possible before the whole partition is consumed. After this design is implemented, the evaluation of RN WF will not cause the whole partition to be materialized, instead, it can be processed in a pipelined manner in the whole executor pipeline, that’s why we call it pipelining.

### Review of current implementation

The current window function implementation is like this (with a focus on processing RN):

1. Data is sorted by partition key and order by key when feeding to window function.
2. vecGroupChecker is used to split data by the partition key.
3. Data is accumulated in groupRows until a whole partition is read from child executor.
4. Then e.consumeGroupRows will be called, which in turn uses windowProcessor to process the rows.
5. There are current 3 processor types that implement the windowProcessor interface:
   1. aggWindowProcessor, dealt with partition without frame constraint, i.e. the function will be called upon the whole partition, e.g. sum over whole partition, then every row gets the same result on the window function, it is indeed confusing that RN is implemented on aggWindowProcessor, latter we’ll show that it is more natural to be expressed in rowFrameWindowProcessor.
   2. rowFrameWindowProcessor, dealt with partition with ROWS frame constraint, i.e. a fixed length bounding window sliding over rows, each step produced a new value given the rows within the window. Note the window can have unbounded preceding and following.
   3. rangeFrameWindowProcessor, with RANGES frame constraint, i.e. the window is defined by value range, so it can vary (a lot) from row to row.
6. For RN, it only uses `aggWindowProcessor`, as [the MySQL document](https://dev.mysql.com/doc/refman/8.0/en/window-functions-frames.html) pointed out.

> Standard SQL specifies that window functions that operate on the entire partition should have no frame clause. MySQL permits a frame clause for such functions but ignores it. These functions use the entire partition even if a frame is specified:  

* CUME_DIST()
* DENSE_RANK()
* LAG()
* LEAD()
* NTILE()
* PERCENT_RANK()
* RANK()
* ROW_NUMBER()

7. In aggWindowProcessor, three functions are implemented:
   1. consumeGroupRows: call agg function’s UpdatePartialResult on all rows within a partition
   2. appendResult2Chunk: call agg function’s AppendFinalResult2Chunk and write result to the result chunk, this function is called repetitively until every row is processed in a partition
   3. resetPartialResult: call agg function’s ResetPartialResult
8. Accordingly, the RN agg function does nothing on UpdatePartialResult, increases the RN counter and append to result on AppendFinalResult2Chunk and resets the counter on ResetPartialResult

## Proposal

After carefully examining the source code, we provide the following solution, which is based on unifying windowProcessor, and then pipeline it, so that RN function as well as many other WF currently using sliding windows can be pipelined.

### Unify windowProcessor

* For rowFrameWindowProcessor and rangeFrameWindowProcessor does nothing in consumeGroupRows  
  * And they will call Slide if the WF has implemented slide (i.e. Slide, AppendFinalResult2Chunk), or it will recalculate the result on the whole frame using the traditional aggFunc calculation strategy (i.e. UpdatePartialResult and then AppendFinalResult2Chunk and ResetPartialResult for each row)
* The Slide implementation is by nature pipelinable.  
  * **The two sides of the sliding window only moves monotonically**.
  * However, the current implementation requires the number of rows in the whole partition to be known (or it can’t be pipelined) if the end is unbounded.
* For aggWindowProcessor:
  * RN can definitely be pipelined, and it can be implemented in a sliding way (the window is the current row itself)
  * Aggregation over the whole partition can’t be pipelined, and it can only be processed after the whole partition is ready.

However, we could see it as the sliding window is the whole partition for each row

### How to unify?

We need to modify the executor build to support this:

* For row number: the sliding window is of length 1, it slides with current row, **i.e. is a rowFrame start at currentRow and end at currentRow**
* For other agg functions on the whole partition: the sliding window is the whole partition, invariant for each row, **i.e. is a rowFrame start at unbounded preceding and end at unbounded following**

### Pipelining

* assume the total number of rows in a partition is N, which we do not know in advance since the data is pipelined  
  * UpdatePartialResult: append partial rows to the aggregation function, needs to append N rows eventually
  * Slide (perhaps this function is better implemented on windowProcessor): must be called before calling AppendFinalResult2Chunk, it returns success or fail if the current rows consumed by UpdatePartialResult is not enough to slide for next row, it will also return an estimated number of rows so that it can be called (useful for unbounded following, we can use -1 to denote that it needs the whole partition, 0 means success immediately, and n if we could know the number of rows needed (for rowFrame) or 1 for rangeFrame since we need to examine row by row
  * AppendFinalResult2Chunk: append result for one row, can be called N times, and can only be called after a successful slide
  * FinishUpdate: called upon the whole partition has been appended, this is to notify the SlidingWindowAggFunc that the whole partition is consumed, so that for those function that needs the whole partition, it is now time to return success on slide
* We want the movement of the sliding window to be the driver for data fetching on the children executor, so the dataflow logic needs to be modified  
  * Next() will call windowProcessor’s Slide function to drive it
  * Slide function will fetch data from child, and use vecGroupCheck to split it
  * Then the data is processed at maximum effort using  
    * UpdatePartialResult
    * Slide or do nothing if it is not SlidingWindowAggFunc
    * If Slide returns success or the whole partition is processed  
      * Obtain the result using AppendFinalResult2Chunk
  * Result is then feed back to Next, and returned once the chunk is full  
    * There could be a background goroutine pulling data

## Rationale

This feature will decrease memory consumption for executing window function.

## Compatibility

Pipelining won't cause any compatibility issue.

## Implementation

All implemented by [PR23022](https://github.com/pingcap/tidb/pull/23022).

* [x] Create PipelinedWindowExec based on current implementation and modify the windowProcessor interface.
* [x] Change data flow, make Next() pulling data from windowProcessor, and windowProcessor calls fetchChild and process data at maximum effort.
* [x] Modify Slide semantic and add FinishUpdate function on SlidingWindowAggFunc interface, and modify correspondingly on each window function.
* [x] Done pipelining for SlidingWindowAggFunc, add test to make sure it is correct.
* [x] Modify RN to be SlidingWindowAggFunc, and add planner support.
* [x] Add test for RN.
* [x] Benchmark, make sure it has constant memory consumption and no execution time regression.

---

### Design 2021 03 09 Dynamic Privileges (`docs/design/2021-03-09-dynamic-privileges.md`)

# Proposal:

- Author(s):     [morgo](https://github.com/morgo)
- Last updated:  June 16, 2021
- Discussion at: N/A

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Test Design](#test-design)
    * [Functional Tests](#functional-tests)
    * [Scenario Tests](#scenario-tests)
    * [Compatibility Tests](#compatibility-tests)
    * [Benchmark Tests](#benchmark-tests)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
* [Unresolved Questions](#unresolved-questions)

## Introduction

This document was created to discuss the design of Dynamic Privileges. It is intended to be implemented in combination with Security Enhanced Mode, but there no interdependencies between the two features.

## Motivation or Background

MySQL 8.0 introduced the concept of “dynamic privileges” (see [WL#8131](https://dev.mysql.com/worklog/task/?id=8131)). The intention behind this functionality is that plugins can create new named privileges to suit their purposes, such as “Firewall Admin” or “Audit Admin” instead of requiring the `SUPER` privilege, which becomes overloaded and too coarse.

Dynamic privileges are **not to be confused with** SQL Roles (RBAC). They work together just fine. Consider the following testcase which demonstrates the features working together:

```
/* Detailed source-code truncated for AI context efficiency. */
```

Dynamic privileges are different from static privileges in the following ways:

* The name of the privilege is “DYNAMIC”. A plugin registers it, and the server has no prior knowledge of its existence.
* Privileges can only be global scoped.
* Privileges are stored in the table `mysql.global_grants` and not `mysql.user`.
* The `GRANT OPTION` is stored for each dynamic privilege (versus for the user as a whole).

We have the same requirement for fine grained privileges in TiDB, so it makes sense to adopt a similar implementation of dynamic privileges. This document describes both the implementation of the framework for dynamic privileges and an initial set of dynamic privileges that are required to be implemented.

## Detailed Design

Implementing Dynamic Privileges requires the following work to be completed.

### Persistence

For TiDB, we can use the same table structure as MySQL:

```sql
CREATE TABLE `global_grants` (
  `USER` char(32) NOT NULL DEFAULT '',
  `HOST` char(255) NOT NULL DEFAULT '',
  `PRIV` char(32) NOT NULL DEFAULT '',
  `WITH_GRANT_OPTION` enum('N','Y') NOT NULL DEFAULT 'N',
  PRIMARY KEY (`USER`,`HOST`,`PRIV`)
);
```

There is an existing table called “global_priv” which initially looked like it provided similar functionality, except:
* The priv is expected to be a JSON encoded string
* There is no column named `WITH_GRANT_OPTION`.

I looked at repurposing this table (which stores TLS options), but because the `PRIV` value is the data and not the key, it gets messy. I instead plan to use the same schema as MySQL.

This table will persist dynamic privileges. Similar to MySQL, the cache is read into memory and cached (privilege/privileges/cache.go). Dynamic privileges will be cached in the same way as existing privileges.

### Privilege Checking API

Checking for existence of a Dynamic privilege needs a different function from normal privilege checks. I.e.

```
// RequestVerification(activeRole []*auth.RoleIdentity, db, table,
// column string, priv mysql.PrivilegeType) bool
if pm.RequestVerification(activeRoles, "", "", "", mysql.ProcessPriv) {
	// has processPrivilege
}
```

This is not suitable because:
* The privilege `mysql.ProcessPriv` must be predefined (i.e. it's not dynamic).
* The 3 empty string values (schema, table, column) are never applicable to dynamic privileges.
* Dynamic privileges are grantable individually. There may be scenarios where code wants to check if a user has both a dynamic privilege and the ability to grant it (such as in the output of `SHOW GRANTS`).

I propose the following:

```
// RequestDynamicVerification(activeRole []*auth.RoleIdentity, priv string, grantable bool) bool
if pm.RequestDynamicVerification(activeRoles, "BACKUP_ADMIN", false) {
	// has backup admin privilege
}
```

### Plugin API

There will need to be a way for plugins to register new dynamic privileges via their OnInit method. I propose the following:

```
import (
	"github.com/pingcap/tidb/privilege/privileges"
)

err = privileges.RegisterDynamicPrivilege("AUDIT_ADMIN")
if err != nil {
	return err
}
```

### Metadata Commands

#### SHOW GRANTS

The output of `SHOW GRANTS` needs to be modified to show each of the dynamic privileges applicable to a user, following static privileges. I.e.
```
mysql [localhost:8023] {root} (test) > show grants for 'u1';
+---------------------------------------------------------+
| Grants for u1@%                                         |
+---------------------------------------------------------+
| GRANT USAGE ON *.* TO `u1`@`%`                          |
| GRANT BINLOG_ADMIN ON *.* TO `u1`@`%`                   |
| GRANT BACKUP_ADMIN ON *.* TO `u1`@`%` WITH GRANT OPTION |
+---------------------------------------------------------+
3 rows in set (0.00 sec)
```
#### Information_schema

The table `user_privileges` should show a hybrid of both static and dynamic privileges:

```
mysql [localhost:8023] {root} (information_schema) > mysql [localhost:8023] {root} where grantee = "'u1'@'%'"
    -> ;
+----------+---------------+----------------+--------------+
| GRANTEE  | TABLE_CATALOG | PRIVILEGE_TYPE | IS_GRANTABLE |
+----------+---------------+----------------+--------------+
| 'u1'@'%' | def           | USAGE          | NO           |
| 'u1'@'%' | def           | BINLOG_ADMIN   | NO           |
| 'u1'@'%' | def           | BACKUP_ADMIN   | YES          |
+----------+---------------+----------------+--------------+
3 rows in set (0.00 sec)
```

#### SHOW CREATE USER

No change

#### CREATE USER

No change

#### GRANT / REVOKE

Needs to support the syntax of a privilege being either a static privilege, or a dynamic privilege. Dynamic privileges only support `*.*`

```
mysql [localhost:8023] {root} (information_schema) > grant select on *.* to 'u1';
Query OK, 0 rows affected (0.00 sec)

mysql [localhost:8023] {root} (information_schema) > grant binlog_admin on test.* to 'u1';
ERROR 3619 (HY000): Illegal privilege level specified for BINLOG_ADMIN
mysql [localhost:8023] {root} (information_schema) > grant binlog_admin on *.* to 'u1';
Query OK, 0 rows affected (0.01 sec)
````

`GRANT ALL` will also GRANT each of the `DYNAMIC` privileges that are registered with the server at the time the command is executed:

```
/* Detailed source-code truncated for AI context efficiency. */
```

Currently TiDB does not expand `GRANT ALL` when the value is read back from `SHOW GRANTS`. It is possible to maintain this current behavior difference.

#### Alter User

No change

### Initial Set of Dynamic Privileges

#### Borrowed from MySQL

| Privilege Name | Description | Notes |
| --------------- | --------------- | --------------- |
| `BACKUP_ADMIN` | Enables BR backups and restores, as well as lightning restores. | Currently this required `SUPER`. It will now require `BACKUP_ADMIN` or `SUPER`. |
| `SYSTEM_VARIABLES_ADMIN` | Allows changing any GLOBAL system variable. | Currently this required `SUPER`. It will now require `SYSTEM_VARIABLES_ADMIN` or `SUPER`. |
| `ROLE_ADMIN` | Allows granting and revoking roles. | Won’t allow revoking on restricted_users (see below). |
| `CONNECTION_ADMIN` | Allows killing connections. | Like `PROCESS` static privilege, but slightly more restrictive (no show processlist). |
| `SYSTEM_USER` | The user can't be altered or dropped by only the `CREATE USER` privilege. | Helps prevent security escalations. |

#### TiDB Extensions

| Privilege Name | Description | Notes |
| --------------- | --------------- | --------------- |
| `RESTORE_ADMIN` | Restoring should require more permissions than backup because it is a higher risk operation. | It is inspired by MySQL's BACKUP_ADMIN/CLONE_ADMIN but not applicable to MySQL due to no online restore. |
| `RESTRICTED_VARIABLES_ADMIN` | Allows changing a restricted `GLOBAL` system variable. | Currently in SEM all high risk variables are unloaded. TBD, it might be required in future that they are only visible/settable to those with this privilege and not SUPER. |
| `RESTRICTED_STATUS_ADMIN` | Allows observing restricted status variables. | i.e. `SHOW GLOBAL STATUS` by default hides some statistics when `SEM` is enabled. |
| `RESTRICTED_CONNECTION_ADMIN` | Killing connections that belong to your own user is always permitted. Killing connections that belong to other users requires `CONNECTION_ADMIN` or `SUPER`; but there is an exception for `RESTRICTED_USER_ADMIN` users. To kill these connections also requires `RESTRICTED_CONNECTION_ADMIN`. This affects `KILL`, `KILL TIDB` commands. | It is intended for the CloudAdmin user in DBaaS. |
| `RESTRICTED_USER_ADMIN` | A special privilege to say that their access can’t be changed by `SUPER` users. Statements `DROP USER`, `SET PASSWORD`, `ALTER USER`, `REVOKE` are all limited. | It is intended for the CloudAdmin user in DbaaS. |
| `RESTRICTED_TABLES_ADMIN` | A special privilege which means that the SEM hidden table semantic doesn’t apply. | It is intended for the CloudAdmin user in DbaaS. | 

### Parser Changes

The parser already supports `DYNAMIC` privileges. This can be confirmed by the following patch to TiDB, where they are sent as the static type of `ExtendedPriv`:

```
diff --git a/planner/core/planbuilder.go b/planner/core/planbuilder.go
index 90d5b9e82..d1644ee83 100644
--- a/planner/core/planbuilder.go
+++ b/planner/core/planbuilder.go
@@ -2298,6 +2298,11 @@ func collectVisitInfoFromGrantStmt(sctx sessionctx.Context, vi []visitInfo, stmt
 
        var allPrivs []mysql.PrivilegeType
        for _, item := range stmt.Privs {
+
+               if item.Priv == mysql.ExtendedPriv {
+                       fmt.Printf("### Attempting to set DYNAMIC privilege: %s\n", item.Name)
+               }
+
                if item.Priv == mysql.AllPriv {
                        switch stmt.Level.Level {
                        case ast.GrantLevelGlobal:
```

This results in the following written to the log file:
```
mysql> grant acdc on *.* to u1;
ERROR 8121 (HY000): privilege check fail

### Attempting to set DYNAMIC privilege: acdc
```

It might be possible that changes are still required if `ExtendedPriv` is not supported in all contexts (REVOKE, etc).

Note that creating a role with the same name as a DYNAMIC privilege is supported. A `GRANT` statement can be attributed to ROLES when it omits the ON *.* syntax. Thus:

```
GRANT BINLOG_ADMIN TO u1; // grants the role binlog_admin
GRANT BINLOG_ADMIN ON *.* TO u1; // grants the dynamic privilege binlog_admin
```

This same nuance applies to MySQL.

### Documentation Plan

The statement reference pages for each of the affected metadata commands will need to be updated to describe dynamic privileges.

There will also need to be documentation specific to `DYNAMIC` privileges to describe how it works, and the purpose of fine-grained access control.

## Test Design

Testing dynamic privileges is a little bit complex because of the various ways privileges can be inherited by users:

* Direct `GRANT` to the user
* Granting to a role that the user inherits.

### Functional Tests

Unit tests will be added to cover the semantics around role/dynamic privilege precedence, including logical restoring in a different order.

Unit tests will also cover each of the "initial set of Dynamic privileges". Tests will include both directly assigning the privileges and assigning via a ROLE (RBAC).

Integration testing needs to test with global kill enabled/disabled.

### Scenario Tests

The use-cases required by the DBaaS team should be validated when combined with `security-enhanced-mode`. They are:

| Account Name | root | cloudAdmin |
| --------------- | --------------- | --------------- |
| Backup & Restore to cloud | Y | Y |
| File privilege | N | N |
| Read or set variables | Y | Y | 
| set restricted variables(some of them even can not be read) | N | Y |
| Read or set restricted system tables | N | Y | 
| DROP USER cloudAdmin | N | Hard to N(unless some hardcoded) |
| REVOKE cloudAdmin | N | Hard to N(unless some hardcoded) |
| Show processlist, Access to threads belong to other users | Y | Y |
| Change password if the password of SUPER user is forgotten | N | Y |
| Kill connections belong to cloudAdmin | N | Y |
| SHUTDOWN / RESTART | N | Y (graceful shutdown on k8s for tidb-server) |

Scenario testing will be required for:
* all the dynamic privileges
* several user-defined dynamic privileges

### Compatibility Tests

The introduction of `DYNAMIC` privileges is not expected to introduce any compatibility issues, because backwards compatibility is ensured. However, plugins should migrate to registering their own dynamic privileges and not rely on the use of `SUPER`. This is considered an enhancement, and not included in-scope for the initial introduction of dynamic privileges (which introduces the framework for plugins to use).

## Impact & Risks

In its initial release, dynamic privilege usage will be controlled by an experimental feature flag (`tidb_enable_dynamic_privileges`), which is modifyable on a GLOBAL or SESSION basis. The implementation will be via restricting `GRANT` and `REVOKE` statements from creating dynamic privileges (it is too invasive to conditionally modify the ast visitor functionaliy).

For backwards compatibility, the MySQL-compatible dynamic privileges will also permit `SUPER`. This helps prevent upgrade issues, such a when TiDB was bootstrapped `GRANT ALL ON *.*` would not have granted all the dynamic privileges. There might be some impact on Upgrade/Downgrade story if eventually the `BACKUP_ADMIN` privilege is used instead of `SUPER`, but for the initial release I am planning to allow either.

## Investigation & Alternatives

An alternative could be to support fine-grained access in a TiDB specific way. Because the MySQL functionality overlaps nicely, it doesn’t really make sense not to follow.
The initial implementation of dynamic privileges only implements a subset of MySQL’s [dynamic privileges](https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html) (see table 6.3). Given that these are supposed to be “dynamic”, I don’t think this is a problem.

## Unresolved Questions

### Adding new dynamic privileges to a lower privileged user

In the case that `cloudAdmin` does not have `SUPER`, but requires additional fine grained privileges granted at a later date, there are several potential solutions:

1. Write a `session/bootstrap.go` task to "split" an existing `DYNAMIC` privilege into two. i.e. users with privilege `XYZ` now have `XYZ` and `ZYX`.
2. Allow the privilege `SELECT, INSERT, UPDATE ON mysql.*` to `cloudAdmin` + `RELOAD` on `*.*`. This will allow `cloudAdmin` to insert `ZYX` into the `global_grant` table, and then run `FLUSH PRIVILEGES` to reload the privilege cache.
3. Add an API for plugins that register new dynamic privileges, such that on first installation they can say `ZYX` is also satisfied by `XYZ` (triggering an internal copy of privileges).
4. Support a feature similar to MySQL's [`--init-file`](https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_init_file) which executes with unrestricted privileges.
5. Make the privilegemanager completely pluggable (it is currently an interface, and extending it to plugins is not a difficult stretch). Make cloudAdmin privileges embedded into the cloud-specific privilege manager, and not dependent on the internal system tables.

The current recommended method is (1), since the method (2) does not effectively restrict the credentials of `cloudAdmin`. (3) is a workaround for the fact that `visitInfo` does not support OR conditions for privileges. (4) and (5) have merit, but require development outside the scope of this current proposal.

---

### Design 2021 03 09 Security Enhanced Mode (`docs/design/2021-03-09-security-enhanced-mode.md`)

# Proposal:

- Author(s):     [morgo](https://github.com/morgo)
- Last updated:  May 04, 2021
- Discussion at: N/A

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Test Design](#test-design)
    * [Functional Tests](#functional-tests)
    * [Scenario Tests](#scenario-tests)
    * [Compatibility Tests](#compatibility-tests)
    * [Benchmark Tests](#benchmark-tests)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
* [Unresolved Questions](#unresolved-questions)

## Introduction

This document was created to discuss the design of Security Enhanced Mode. It comes from the DBaaS requirement that `SUPER` users must not be able to perform certain actions that could compromise the system.

### Terminology

* **Configuration Option**: The name of a variable as set in a configuration file.
* **System Variable** (aka sysvar): The name of a variable that is set in a running TiDB server using the MySQL protocol.
* **Super**: The primary MySQL "admin" privilege, which is intended to be superseded by MySQL’s "dynamic" (fine-grained) privileges starting from MySQL 8.0.

## Motivation or Background

Currently the MySQL `SUPER` privilege encapsulates a very large set of system capabilities. It does not follow the best practices of allocating _fine grained access_ to users based only on their system-access requirements.

This is particularly problematic in a DBaaS scenario such as TiDB Cloud where the `SUPER` privilege has elements that are required by both end users (TiDB Cloud Customers) and system operations (PingCAP SREs).

The design of Security Enhanced Mode (SEM) takes the approach of:

1. Restricting `SUPER` to a set of capabilities that are safe for end users.
2. Implementation of dynamic privileges ([issue #22439](https://github.com/pingcap/tidb/issues/22439)).

This approach was requested by product management based on the broad "in the wild" association of `SUPER` as "the MySQL admin privilege". Thus, proposals to create a new lesser-`SUPER` privilege have already been discussed and rejected.

The design and name of "Security Enhanced" is inspired by prior art with SELinux and AppArmor.

## Detailed Design

A boolean option called `EnableEnhancedSecurity` (default `FALSE`) will be added as a TiDB configuration option.  The following subheadings describe the behavior when `EnableEnhancedSecurity` is set to `TRUE`.

### System Variables

The following system variables will be hidden unless the user has the `RESTRICTED_VARIABLES_ADMIN` privilege:

* variable.TiDBDDLSlowOprThreshold,
* variable.TiDBAllowRemoveAutoInc,
* variable.TiDBCheckMb4ValueInUTF8,
* variable.TiDBConfig,
* variable.TiDBEnableSlowLog,
* variable.TiDBEnableTelemetry,
* variable.TiDBExpensiveQueryTimeThreshold,
* variable.TiDBForcePriority,
* variable.TiDBGeneralLog,
* variable.TiDBMetricSchemaRangeDuration,
* variable.TiDBMetricSchemaStep,
* variable.TiDBOptWriteRowID,
* variable.TiDBPProfSQLCPU,
* variable.TiDBRecordPlanInSlowLog,
* variable.TiDBRowFormatVersion,
* variable.TiDBSlowQueryFile,
* variable.TiDBSlowLogThreshold,
* variable.TiDBEnableCollectExecutionInfo,
* variable.TiDBMemoryUsageAlarmRatio,
* variable.TiDBRedactLog

The following system variables will be reset to defaults:

* variable.Hostname

### Status Variables

The following status variables will be hidden unless the user has the `RESTRICTED_STATUS_ADMIN` privilege:

* tidb_gc_leader_desc

### Information Schema Tables

The following tables will be hidden unless the user has the `RESTRICTED_TABLES_ADMIN` privilege:

* cluster_config
* cluster_hardware
* cluster_load
* cluster_log
* cluster_systeminfo
* inspection_result
* inspection_rules
* inspection_summary
* metrics_summary
* metrics_summary_by_label
* metrics_tables
* tidb_hot_regions

The following tables will be modified to hide columns unless the user has the `RESTRICTED_TABLES_ADMIN` privilege:

* tikv_store_status
    * The address, capacity, available, start_ts and uptime columns will return NULL.
* Tidb_servers_info
    * The “IP” column will return NULL.
* cluster_* tables
    * The “instance” column will show the server ID instead of the server IP address.

### Performance Schema Tables

The following tables will be hidden unless the user has the `RESTRICTED_TABLES_ADMIN` privilege:

 * pd_profile_allocs
 * pd_profile_block
 * pd_profile_cpu
 * pd_profile_goroutines
 * pd_profile_memory
 * pd_profile_mutex
 * tidb_profile_allocs
 * tidb_profile_block
 * tidb_profile_cpu
 * tidb_profile_goroutines
 * tidb_profile_memory
 * tidb_profile_mutex
 * tikv_profile_cpu

### System (mysql) Tables

The following tables will be hidden unless the user has the `RESTRICTED_TABLES_ADMIN` privilege:

* expr_pushdown_blacklist
* gc_delete_range
* gc_delete_range_done
* opt_rule_blacklist
* tidb
* global_variables

The remaining system tables will be limited to read-only operations and can not create new tables.

### Metrics Schema

All tables will be hidden, including the schema itself unless the user has the `RESTRICTED_TABLES_ADMIN` privilege.

### Commands

* `SHOW CONFIG` is changed to require the `CONFIG` privilege (with or without SEM enabled).
* `SET CONFIG` is disabled by the `CONFIG` Privilege (no change necessary)
* The `BACKUP` and `RESTORE` commands prevent local backups and restores.
* The statement `SELECT .. INTO OUTFILE` is disabled (this is the only current usage of the `FILE` privilege, effectively disabling `FILE`. For compatibility `GRANT` and `REVOKE` of `FILE` will not be affected.)

### Restricted Dynamic Privileges

TiDB currently permits the `SUPER` privilege as a substitute for any dynamic privilege. This is not 100% MySQL compatible - MySQL accepts SUPER in most cases, but not in GRANT context. However, TiDB requires this extension because:

* The visitorInfo framework does not permit OR conditions
* GRANT ALL in TiDB does not actually grant each of the individual privileges (historical difference)

When SEM is enabled, `SUPER` will no longer be permitted as a substitute for any `RESTRICTED_*` privilege. The distinction that this only applies when SEM is enabled, helps continue to work around the current server limitations.

## Test Design

### Functional Tests

The integration test suite will run with `EnableEnhancedSecurity=FALSE`, but new integration tests will be written to cover specific use cases.

Unit tests will be added to cover the enabling and disabling of sysvars, and tables.

Tests will need to check that invisible tables are both non-visible and non-grantable (it should work, since visibility can be plugged into the privilege manager directly).

If the user with `SUPER` privilege grants privileges related to these tables to other users, for example, `GRANT SELECT, INSERT, UPDATE ON information_schema.cluster_config TO 'userA'@'%%';` -- it should fail.

### Scenario Tests

It is important that users can still use TiDB with all connectors when `SEM` is enabled, and that the TiDB documentation makes sense for users with `SEM` enabled.

It is not expected that any user scenarios are affected by `SEM`, but see "Impact & Risks" for additional discussion behind design decisions.

### Compatibility Tests

We will need to consider the impact on tools. When SEM is disabled, no impact is expected. When SEM is enabled, it should be possible to make recommendations to the tools team so that they can still access meta data required to operate in DBaaS environment:

* Lightning and BR will not work currently with SEM + https://github.com/pingcap/tidb/pull/21988
* In 5.0 the recommended method for BR/Lightning to get TiKV GC stats should change.
* There is one PR still pending for obtaining statistics: https://github.com/pingcap/tidb/pull/22286 

### Benchmark Tests

No performance impact is expected.

#### Documentation Plan

Documentation is critically impacted by SEM, since it should be possible for a manual page to cover the use-case of SEM both enabled and disabled.

Supporting PRs will be required to modify both documentation and functionality so that system variables and/or tables that are hidden by SEM are not required. For example: 

* https://github.com/pingcap/tidb/pull/22286
* https://github.com/pingcap/tidb/pull/21988
* https://github.com/pingcap/docs/pull/4552

* A further change to move the `new_collation_enabled` variable from mysql.tidb to a status variable has been identified, as it appears on several manual pages. No PR has been created yet.

## Impacts & Risks

The impact of `SEM` only applies in the case that it is enabled, which it is only intended to be on DBaaS (although users of on-premises installations of TiDB may also consider enabling it).

The intention behind SEM is to reduce the impact on end users, who can continue to use `SUPER` as the defacto "admin" privilege (versus alternatives such as mentioned below). The larger impact will be on System Operators, who will need fine grained privileges to replace the `SUPER` privilege.

The largest risk with `SEM` enabled is application/MySQL compatibility. There are a number of SEM behaviors which have been discussed, with the following outcomes:

| Suggestion | Observed Risk | Outcome |
| --------------- | --------------- | --------------- |
| Is it possible to make a system variable non-readable by a non privileged user? | MySQL does not have a semantic where a sysvar would ever be non readable. Non-settable however is fine.| Variables will either be invisible or visible. Never non-readable, although non-writeable is possible (example: sql_log_bin). |
| Is it possible to hide columns in information schema? | Users may depend on ordinality of information_schema table column order. This is particularly likely with tables with useful columns at the start. | Columns will appear with NULL values when they must be hidden.|
| Is it possible to hide sysvars such as hostname? | For MySQL-specific sysvars, there is an increased likelihood applications will read them, and result in an error if they are not present. | For a specific case like hostname, it is a requirement to return a placeholder value such as ‘localhost’, rather than hide the variable. |

Users will also be able to observe if the system they are using has enhanced security mode enabled via the system variable, `tidb_enable_enhanced_security` (read-only).

## Investigation & Alternatives

The alternative to SEM is to implement fine-grained privileges for end users. This idea has been discussed and rejected. See "Motivation or Background" for context.

Amazon RDS also uses the approach of not granting `SUPER` to users, and instead offering a set of custom stored procedures to support use-cases that would usually require `SUPER`. This idea has been rejected.

### Unresolved Questions

None

---

### Design 2021 03 30 Small Table Caching (`docs/design/2021-03-30-small-table-caching.md`)

# Proposal: Caching a table in memory

- Author(@tiancaiamao)
- Discussion PR: https://github.com/pingcap/tidb/pull/23673
- Tracking Issue: https://github.com/pingcap/tidb/issues/25293

## Introduction

For a small, frequently visited, and rarely changed table, caching the whole table in memory in the TiDB server can improve performance.

## Motivation or Background

For tables that are too small, they are located in just one region, that region would become a hotspot, and such hotspots would cause a performance bottleneck. By directly caching the small table data in the TiDB layer, such hotspot issues can be solved.

We are caching tables for some scenarios already, in a way we're not realized. For example, our handling of global variables. To prevent row-at-a-time loading of each system variable from TiKV, we needed to implement the [sysvar cache](https://github.com/pingcap/tidb/pull/24359). This helps reduce `show variables like ..` latency, but the data set is small and the problem is very generic. It also doesn't help in cases where system variables read from `mysql.tidb` instead, which does not have a cache. The data of privilege related tables are also cached.

It can also be used to improve the performance of join. The cached table could be used as the inner table, cutting down the network cost of loading data to TiDB. An example is the TPC-C test, there is an ITEM table. It stores the information of all the goods sold by the sales company, including the name and price of the goods. During the execution of the "order creation" transaction, the data in this table is used to determine the price of the order. Such a table is also a typical scenario that can be optimized.

Last but not least, this feature is a voice from our customers. They meet the hotspot region problem, but they think it's too risky to enable follower read or coprocessor cache which may affect the whole cluster (according to their business model, they provide storage service to their customers, and the cluster is shared, they try to avoid a single change affecting the entire users).

## Detailed Design

If the update operation is not supported at all, the use case would be too limited. So even if we trade writing ability for reading performance, we should at least support updating.

### Key algorithm

There is a conceptual "read-write" lock to implement the caching operation.

Before caching the data, the table needs to hold a "read lock", so that the data will not be modified afterward. This "read lock" is a record providing some meta-information. All modifications must check the lock meta-information first. If the record is in the read-locked state, modifications are forbidden.

The "read" lock needs to maintain a lease for a while, and the lease should be renewed continuously. The underlying data will be safe as long as the read lock lease hold.

When performing a modification, the meta-information should be checked first. If there is a "read" lock, the "read" lock needs to be upgraded to a "write intend" lock. This step prevents the read lock from renewing the lease. After the lease expires, the meta status is change to "write" lock, write operation can be performed afterward. And after the write operation finishes, the "write" lock should be cleared, so that the subsequent "read" lock can be added and the data can be cached again.

The "write" lock also needs a TTL(time to live) to handle abnormal situations. For example, if the TiDB server crashes after the write lock succeeds, TTL gives us a hint of how to clean the orphan write lock.

Put all things together, we have this interface:

```
type StateRemote interface {
    Load()
    LockForRead()
    LockForWrite()
    RenewLease()
    WriteAndUnlock()
}
```

### Management of lock meta information

What’s the granularity of the lock? One option is to implement the meta lock at the key-value level. The advantage is that the granularity is finer and the updating performance is better. If we cache the key-value record, modifying one key would not affect the cache of the other keys. The disadvantage is that this will invade the current transaction layer implementation, and make our transaction more complex. Considering the current implementation of the transaction is very complex already, it is not wise to do so.

The other option is to implement the meta lock at the table level. Each table corresponds to one meta lock record. As long as any key of the table is modified, the table cache becomes invalid. Assuming that we only deal with small tables, and this table is updated infrequently, this option should be acceptable.

For updating operation, the `StateRemote` interface needs to be implemented. The following part of this section describes the management of lock meta information, where it should be stored, and how it is used.

Such a table could be used to store the meta-information:

```
CREATE TABLE mysql.table_cache_meta (
   tid int primary key,
   lock_type enum('NONE','READ','INTEND','WRITE'),
   lease uint64,
   oldReadLease uint64,
);
```

This table contains the `tid`, `lock_type` and `lease` information.

- `tid` records the ID of the table being cached
- `lock_type` decides whether the current state is read locked or write locked etc
- `lease` is used for the read locks lease renewal, and also for cleanup the write locks
- `oldReadLease` is necessary when the `lock_type` is 'INTEND', it stores the old read lease

LockForRead() corresponds to this operation:

```
update table_cache_meta set lock ='READ', lease = %? where  tid = %? and lock !='WRITE'
```

RenewLease() corresponds to this operation:

```
update table_cache_meta set lease = %? where tid = %? and lock ='READ'
```

LockForWrite() corresponds to this operation:

```
update table_cache_meta set lock ='INTEND' and oldLease = %? and lease = %?' where tid = %?
sleep() // wait read lease gone
update table_cache_meta set lock ='WRITE' and lease = %?' where tid = %?
```

### Caching and writing process

The way to store the in-memory cached of the table data is the same with the [temporary table](2021-04-20-temporary-table.md).
In short, the KV data of the table is loaded from TiKV, and is stored in a MemBuffer. To read that data, an extra UnionScan executor is used.


A `CachedTable` struct will be introduced. It inherits and overloads the `Table` interface. `loadSchema` will periodically load the table information on schema change. For a cached table, the `CachedTable` will be reconstructed.

`CachedTable` implements the `Table` interface, and overloads the `AddRecord` method. When `AddRecord` is called, the lock meta information needs to be checked first. This operation needs to acquire the "write" lock, that is to say, make the `lock_type` field of the meta table to 'WRITE'. After confirming that the lease time of the previous 'READ' lock has expired, the operation can be executed.

The read operation flow diagram:




The write operation flow diagram:




### How to enable this feature

The syntax of OceanBase's replicated table is to add the `DUPLICATE_SCOPE` option after the CREATE TABLE statement.

I propose to use "ALTER TABLE t [CACHE|NOCACHE]" for the syntax. This is a switch that can be turned on or off. A user can decide to use it by themself. The write performance will become very bad after caching.

"ALTER TABLE t CACHE" is a DDL operation. Assuming that all the TiDB instances know that a table is not cached, there is no correctness problem; Assuming that all tidb instances make a consensus that a table is cached, the correctness is guaranteed by the locking algorithm mentioned before. However, during the DDL operation, if some TiDB instances think that the cache is enabled, while some other instances think that the cache is not enabled, there would be a correctness issue. 

To address that problem, an intermediate `Switching` state is introduced, the schema change process is similar to the LOCK TABLE statement's implementation:

> Disabled => Switching => Enabled

- In the Disabled state, all TiDB instances know that there is no cache for the table, it can be read and written normally.
- In the Enabled state, all TiDB instances know that the table is cached, and the "lock" meta information should be checked before reading and writing.
- In the switching state, all read operation goes to the original table; and write operation needs to check the "write lock" first.

The cluster may have Disabled and Switching, or Switching and Enabled on different TiDB instances at the same time, but Disabled and Enabled will not coexist at the same time.

### Compatibility

The entry of the feature is the 'ALTER TABLE' statement. If the user does not explicitly call it, there will be no impact.

Metadata management will introduce persistent data. The old version TiDB does not access or use the meta-data, so there should not be any problem when upgrading or downgrading.

It is unsafe to mix the old and new versions of TiDB when using cached tables. Rolling updates are safe, but there is a risk that if an old version of a TiDB server re-joins after a table is in cached 'Enabled' state it could modify the contents in an unsafe manner. Currently _downgrade_ is not technically supported by TiDB, but there is no technical mechanism which prevents an older versioned binary joining a newer versioned cluster. We need to solve this issue to perform meta-data upgrades, but it is currently blocked in the requirements phase, because we have not decided from which versions upgrade/downgrade will be supported.

## Investigation & Alternatives

### OceanBase's replicated table

> "In order to cope with the high and low frequency of application access and the low-frequency access to small tables that can always access the latest data, and at the same time to ensure data consistency, currently we can only choose the solution of strong consistent read access to Leader data. However, due to the high access frequency, Leader is easy to become a performance bottleneck. In order to solve the problem of "small table broadcast" demand scenario, OceanBase 2.x version combines its own architecture to provide a copy table function, copying the copy of the related small table to all the OBServers of the tenant of the table. The table says to replicate the table, these copies are called replicas. The update transaction of the replicated table guarantees that the data is synchronized to all full-function replicas and replicas when committing, ensuring that the update transaction can be read on any OBServer of the tenant after the successful commit of the update transaction. Transaction modified data." 

Refer to https://zhuanlan.zhihu.com/p/78402011

The biggest challenge of copying data to multiple machines is that the modification of data must take effect on all machines in real time, otherwise some machines read the new data and the other part reads the old data. This must be a function that does not meet the needs of users. OceanBase uses a special broadcast protocol to ensure the copy consistency of the replicated table. When the replicated table is modified, all the copies will be modified at the same time. Moreover, the modification operation will only take effect when the copies on all machines are modified successfully.

In a distributed system, another thorny problem will arise again. If a machine fails during the process of modifying the replicated table, and the replica of the replicated table on the failed machine cannot be modified, then the replicated table can no longer be modified? If this problem is not solved, the replication table will drag down the user's operation in the event of a machine failure. Ocean Base uses a lease mechanism to solve this problem. The valid copy of the replicated table on each machine will get a lease. When the replicated table is modified, the modification must be synchronized to all leased replicas. In the event of a machine failure, the lease of the replicated table copy on the failed machine becomes invalid, and the invalidated copy will not be synchronized with new modifications, so subsequent modification operations of the replicated table will not be blocked. The invalid copy will also refuse the read operation to ensure that the old data will not be read. When the invalid copy is restored, the missing data can be chased up, and the lease will be re-granted after it catches up to the latest state."
Reference https://developer.aliyun.com/article/750271

They are optimized for join's small table broadcast. The agreement was successfully made from the majority to all copies, and write performance was sacrificed in exchange for read performance and consistency. At the implementation level, if you look at it from another perspective, OB is a table-level synchronization, which is equivalent to adding a learner role to the raft layer as a copy table.

### Reference Tables of SingleStore (formerly MemSQL)

> "Reference tables are relatively small tables that do not need to be distributed and are present on every node in the cluster. Reference tables are implemented via primary-secondary replication to every node in the cluster from the master aggregator."

Reference https://docs.singlestore.com/v7.3/key-concepts-and-features/physical-schema-design/other-schema-concepts/reference-tables/

### Collocated tables of YugaByteDB

They put related tables on the same node, which facilitates operations such as joins to reduce network-level overhead. These tables can be cut to multiple tablets, but Colocated tables are deliberately not cut. It is not a concept of caching, but it is also a scenario where the broadcast of join small tables can be optimized.

> "The assumptions behind tables that are collocated is that their data need not be automatically shared and distributed across nodes"

Reference https://docs.yugabyte.com/latest/architecture/docdb-sharding/colocated-tables/
https://github.com/yugabyte/yugabyte-db/blob/master/architecture/design/ysql-colocated-tables.md

### Oracle also has a similar feature

https://logicalread.com/oracle-11g-caching-table-in-memory-mc02/#.YFvijK_7QuU

---

### Design 2021 04 18 Common Table Expression (`docs/design/2021-04-18-common-table-expression.md`)

# Proposal: Support Common Table Expression

- Author(s): [@guo-shaoge](https://github.com/guo-shaoge), [@wjhuang2016](https://github.com/wjhuang2016)
- Discussion PR: https://github.com/pingcap/tidb/pull/24147
- Tracking Issue: https://github.com/pingcap/tidb/issues/17472

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Test Design](#test-design)
    * [Functional Tests](#functional-tests)
    * [Scenario Tests](#scenario-tests)
    * [Compatibility Tests](#compatibility-tests)
    * [Benchmark Tests](#benchmark-tests)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
* [Unresolved Questions](#unresolved-questions)
* [Future Work](#future-work)

## Introduction

This proposal describes the basic implementation of Common Table Expression(CTE) using the `Materialization` method.
`Merge` is another way to implement CTE and will be supported later.

## Motivation or Background

CTE was introduced in SQL:1999. It's a temporary result set which exists within a statement. You can reference it later in the statement.
It's similar to derived tables in some way. But CTE has extra advantages over derived tables.

1. CTE can be referenced multiple times.
2. CTE is easier to read.
3. You can use CTE to do hierarchical queries.

There are two kinds of CTE:
1. non-recursive CTE.

    ```SQL
    WITH
        cte1 AS (SELECT c1 FROM t1)
        cte2 AS (SELECT c2 FROM t2)
    SELECT cte1.c1, cte2.c2 FROM cte1, cte2 WHERE cte1.c1 = cte2.c2 AND cte1.c1 = 100;
    ```
2. recursive CTE, which can be used to do hierarchical queries. Recursive CTE normally consists of the seed part and the recursive part.
   Seed part will generate the origin data, the remaining computation will be done by the recursive part.

    ```SQL
    WITH RECURSIVE cte1 AS (
        SELECT part, sub_part FROM t WHERE part = 'human'
        UNION ALL
        SELECT t.part, t.sub_part FROM t, cte1 WHERE cte1.sub_part = t.part
    )
    SELECT * FROM cte1;
    ```

## Detailed Design
### Overview
There are two ways to implement CTE:
1. Merge: just like view, CTE is expanded on where it's used.
2. Materialization: use temporary storage to store the result of CTE, and read the temporary storage when using CTE.

`Merge` is normally a better way to implement CTE, because optimizer can pushdown predicates from outer query to inner query.
But when CTE is referenced multiple times, `Materialization` will be better. And recursive CTE can only be implemented by `Materialization`.

For simplicity, this design doc only uses `Materialization` to implement both non-recursive and recursive CTE.
So there is no need to consider how to choose between these two methods, so as to reduce the chance of bugs.
And in the near future, `Merge` will be definitely supported to implement non-recursive CTE.

`RowContainer` will be used to store the materialized result.
The result will first reside in memory, and when the memory usage exceeds `tidb_mem_quota_query`, intermediate results will be spilled to disk.

For recursive CTE, the optimizer has no way to accurately know the number of iterations. So we use the seed part's cost as CTE's cost.
Also we will add a system variable `cte_max_recursion_depth` to control the max iteration number.
If the maximum iteration number is reached, an error will be returned.

A major advantage of `Materialization` is that data will only be materialized once even if there are many references to the same CTE.
So we will add a map to record all CTE's subplan, these subplans will only be optimized and executed once.

### New Data Structures
#### Logical Operator
```Go
type LogicalCTE struct {
	logicalSchemaProducer

	cte       *CTEClass
	cteAsName model.CIStr
}

type CTEClass struct {
	IsDistinct bool
	seedPartLogicalPlan      LogicalPlan
	recursivePartLogicalPlan LogicalPlan
	IDForStorage int
	LimitBeg uint64
	LimitEnd uint64
}
```

`LogicalCTE` is the logical operator for CTE. `cte` is a member of `CTEClass` type.
The content of `CTEClass` will be the same if different CTE references point to the same CTE.

The meanings of main members in CTEClass are as follows:
1. `IsDistinct`: True if UNION [DISTINCT] and false if UNION ALL.
2. `seedPartLogicalPlan`: Logical Plan of seed part.
3. `recursivePartLogicalPlan`: Logical Plan of recursive part. It will be nil if CTE is non-recursive.
4. `IDForStorage`: ID of intermediate storage.
5. `LimitBeg` and `LimitEnd`: Useful when limit is used in recursive CTE.

```Go
type LogicalCTETable struct {
    logicalSchemaProducer

    name         string
    idForStorage int
}
```
`LogicalCTETable` will read the temporary result set of CTE. `idForStorage` points to the intermediate storage.

#### Physical Operator
`PhysicalCTE` and `PhysicalCTETable` will be added corresponding to `LogicalCTE` and `LogicalCTETable`.

#### Executor

```Go
type CTEExec struct {
	exec.BaseExecutor

	seedExec      Executor
	recursiveExec Executor

	resTbl     cteutil.Storage
	iterInTbl  cteutil.Storage
	iterOutTbl cteutil.Storage

	hashTbl baseHashTable
}
```

`CTEExec` will handle the main execution. Detailed execution process will be explained later.
1. `seedExec` and `recursiveExec`: Executors of seed part and recursive part.
2. `resTbl`: The final output is stored in this storage.
3. `iterInTbl`: Input data of each iteration.
4. `iterOutTbl`: Output data of each iteration.
5. `hashTbl`: Data will be deduplicated if UNION [DISTINCT] is used.

```Go
type CTETableReaderExec struct {
	exec.BaseExecutor

	iterInTbl cteutil.Storage
	chkIdx    int
	curIter   int
}
```

`CTETableReaderExec` is used in recursive CTE. It will read `iterInTbl` and the output chunk will be processed in `CTEExec`.

#### Storage
```Go
type Storage interface {
    OpenAndRef() bool
    DerefAndClose() error
    Add(chk *chunk.Chunk) error
    GetChunk(chkdIdx int) (*chunk.Chunk, error)
    Lock()
    Unlock()
}
```

`Storage` is used to store the intermediate data of CTE. Check the `resTbl`, `iterInTbl` and `iterOutTbl` in `CTEExec`.

Since there will be multiple executors using one `Storage`, we use a ref count to record how many users currently there are.
When the last user calls Close(), the `Storage` will really be closed.

1. `OpenAndRef()`: Open this `Storage`, if already opened, add ref count by one.
2. `DerefAndClose()`: Deref and check if ref count is zero, if true, the underlying storage will be truly closed.
3. `Add()`: Add chunk into storage.
4. `GetChunk()`: Get chunk by chunk id.
5. `Lock()` and `Unlock`: `Storage` may be used concurrently. So we need to add a lock.

### Life of a CTE
#### Parsing
In parsing phase, definition of CTE will be parsed as a subtree of the outermost select stmt.

#### Logical Plan
The parsing phase will generate an AST, which will be used to generate `LogicalCTE`. This stage will complete the following steps:
1. Distinguish between seed part and recursive part of the definition of CTE. And build logical plans for them.
2. Do some validation checks.

    1. Mutual recursive(cte1 -> cte2 -> cte1) is not supported.

    2. Column number of the seed part and the recursive part must be same.
    
    3. All seed parts should follow recursive parts.

    4. recursive parts cannot include: `ORDER BY`, `Aggregate Function`, `Window Function`, `DISTINCT`.

3. Recognize the same CTE. If there are multiple references to the same CTE.

We use the following SQL to illustrate:
```SQL
WITH RECURSIVE cte1 AS (SELECT c1 FROM t1 UNION ALL SELECT c1 FROM cte1 WHERE cte1.c1 < 10) SELECT * FROM t2 JOIN cte1;
```

The logical plan of above SQL will be like:



#### Physical Plan
In this stage, the `LogicalCTE` will be converted to `PhysicalCTE`. We just convert logical plans of the seed part and the recursive part to its physical plan.
Also `LogicalCTETable` will be converted to `PhysicalCTETable`.

The Physical Plan will be like:



#### Build Executor
Three structures will be constructed:
1. `CTEExec`: Evaluate seed part and recursive part iteratively.
2. `CTETableReaderExec`: Read result of previous iteration and return result to parent operator.
3. `Storage`: This is where the materialized results are stored. `CTEExec` will write it and `CTETableReaderExec` will read it.

The executor tree will be like:



#### Execution
The following pseudo code describes the execution of `CTEExec`:

```Go
func (e *CTEExec) Next(req *Chunk) {
    // 1. The first executed CTEExec will be responsible for filling storage.
    e.storage.Lock()
    defer e.storage.Unlock()
    if !e.storage.Done() {
        // 1.1 Compute seed part and store data into e.iterInTbl.
        for {
            // 1.2 Compute recursive part iteratively and break if reaches termination conditions.
        }
        e.storage.SetDone()
    }
    // 2. Return chunk in e.resTbl.
}
```

Only the first `CTEExec` will fill the storage. Others will be waiting until the filling process is done.
So we use `Done()` to check at the beginning of execution.
If the filling process is already done, we just read the chunk from storage.

The filling of `Storage` is done by `CTEExec` and `CTETableReaderExec` together. The following figure describes the process.



1. Compute the `SeedExec`(step 1) and all output chunks will be stored into `iterInTbl`(step 2), which will be the input data of next iteration.
2. Compute the `RecursiveExec` iteratively. `iterInTbl` will be read by `CTETableReaderExec`(step 3) and its output will be processed by executors in `RecursiveExec`(step 4,5). And finally the data will be put into `iterOutTbl`(step 5).
3. At the end of each iteration, we copy all data from `iterOutTbl` to `iterInTbl` and `resTbl`(step 7). So the output of the previous iteration will be the input of the next iteration.
4. Iteration will be terminated if:

    1. No data is generated in this iteration or
    2. Iteration number reaches `@@cte_max_recursion_depth` or
    3. Execution time reaches `@@max_execution_time`.

Data in storage will be spilled to disk if memory usage reaches `@@tidb_mem_quota_query`. `MemTracker` and `RowContainer` will handle all the spilling process.

Also we use a hash table to de-duplicate data in `resTbl`. Before copying data from `iterOutTbl` to `resTbl`, we use this hash table to check if there are duplications.

We also support use LIMIT in recursive CTE. By using LIMIT, users don’t have to worry about infinite recursion.
Because if the number of output rows reaches the LIMIT requirement, the iteration will be terminated early.

## Test Design

### Functional Tests

1. Basic usage of non-recursive and recursive CTE.
2. Define a new CTE within a CTE.
3. Use CTE in subquery.
4. Use CTE in UPDATE/DELETE/INSERT statements.
5. CTE name conflicts with other table names.
6. Join CTE with other tables/CTE.
7. Use expressions with CTE.

### Scenario Tests

We should test CTE used together with other features:
1. Use CTE with PREPARE/EXECUTE/PlanCache.
2. Use CTE with a partition table.
3. Stale read.
4. Clustered index.
5. SPM/Hint/Binding.

### Compatibility Tests

None

### Benchmark Tests

A basic performance test should be given in a specific scenario.
The memory usage, disk usage and QPS should be reported.

## Impacts & Risks

CTE is a new feature and it will not affect the overall performance.
But for now we only use `Materialization` to implement non-recursive CTE.
In some scenarios, the performance may not be as good as implementations which use `Merge`.

## Investigation & Alternatives

### Choose between Merge and Materialization
Most mainstream DBMS use `Merge` and `Materialization` to implement non-recursive cte, while recursive cte can only be implemented with `Materialization`.
`Merge` is preferred when there are no side effects, such as random()/cur_timestamp() is used in subquery.
But when CTE is referenced multiple times, `Materialization` may be better.
Also users can control which method to use explicitly by using hints.

### Materialization
For `Materialization`, most DBMS use some kind of container to store materialized result,
which will be spilled to disk if the size is too large. The computation steps for recursive CTE are all similar.

But different system use different ways to try to optimize:
1. Try to postpone materialization.
3. Pushdown predicates to reduce the size of the temporary table.

## Unresolved Questions

None

## Future Work
1. Support `Merge` and related hints(merge/no_merge).
2. Optimize `Materialization`, pushdown predicates to the materialized table.
2. MPP support. `CTEExec` will be implemented in TiFlash later. But SQL used in CTE definition still can be pushed to TiFlash.

---

### Design 2021 04 20 Temporary Table (`docs/design/2021-04-20-temporary-table.md`)

# Temporary Table Design

- Authors: [Kangli Mao](http://github.com/tiancaiamao), [Ming Zhang](http://github.com/djshow832)
- Discussion PR: https://github.com/pingcap/tidb/pull/24168
- Tracking Issue: https://github.com/pingcap/tidb/issues/24169

# Introduction

A temporary table is a special table whose rows data are only temporarily available. 

TiDB will implement both local temporary tables and global temporary tables. The local temporary table is basically compatible with MySQL temporary tables. The global temporary table is a subset of the SQL standard, which supports only one table commit action.

For a local temporary table, it is visible only within the current session, and the table is dropped automatically when the session is closed.

For a global temporary table, the table schema is visible to all the sessions, but the changes into the table are only available within the current transaction, when the transaction commits, all changes to the global temporary table are discarded.

## Syntax

The syntax of creating and dropping a global temporary table:

```sql
CREATE GLOBAL TEMPORARY TABLE tbl_name (create_definition) 
[ENGINE=engine_name]
ON COMMIT DELETE ROWS;

DROP TABLE tbl_name;
```

The syntax of creating and dropping a session(local) temporary table:

```sql
CREATE TEMPORARY TABLE tbl_name (create_definition) 
[ENGINE=engine_name];

DROP [TEMPORARY] TABLE tbl_name;
```

In the following sections, session temporary tables and local temporary tables are used interchangeably.

## Visibility of table definition

There are 2 kinds of table definition visibility.

- Global: global temporary tables are visible to all sessions. These tables only need to be created once and the metadata is persistent.
- Local: local temporary tables are visible to the session that creates them. These tables must be created in the session before being used and the metadata is only kept in memory.

## Visibility of data

There are 2 kinds of data visibility:

- Session: when the table is a session temporary table, the data will be kept after a transaction commits. Subsequent transactions will see the data committed by the previous transactions.
- Transaction: when the table is defined as `ON COMMIT DELETE ROWS`, this data will be cleared automatically after a transaction commits. Subsequent transactions won’t see the data committed by the previous transactions.

## Storage engines

TiDB uses TiKV and TiFlash to store the data of normal tables. This is also true for temporary tables by default because MySQL does so. However, temporary tables sometimes are used to boost performance, so it's also reasonable to support in-memory temporary tables. There are 2 kinds of storage engines available:

- Memory or TempTable: TiDB keeps data in memory, and if the memory consumed by a temporary table exceeds a threshold, the data will be spilled to the local disk on TiDB. This is the default storage engine, which is different from MySQL.
- InnoDB: TiDB stores data on TiKV and TiFlash with more than one replica, just like normal tables. According to MySQL, this is the default storage engine, even for temporary tables.

# Motivation or Background

Temporary tables are useful in applications where a result set is to be buffered (temporarily persisted), perhaps because it is constructed by running multiple DML operations.

The purposes of temporary tables include:

- Usability. Temporary tables are typically for a temporary use. Applications don't need to frequently truncate the table.
- Performance. In-memory temporary tables are stored in memory, which boosts performance.
- Materialize middle data for queries. Some queries apply internal temporary tables for materializing middle data, such as CTE.

# Detailed Design

## Metadata

The table ID of global temporary tables must be globally unique, while the local temporary tables don't. However, logical or physical plans involve table IDs, which means the temporary table IDs must be different from the normal table IDs. To achieve this goal, it's straightforward to also allocate local temporary tables globally.

For a global temporary table, its table name should not be duplicated with a normal table. For a local temporary table, when its name conflicts with an existing table, it will take a higher priority. We can keep the temporary tables in a local schema, and overload the original one. The databases where temporary tables belong depend on the identifier in `CREATE TABLE` statements, just like normal tables.

Since the metadata of global temporary tables are persistent on TiKV, it's straightforward to execute DDL in the same procedure as normal tables. However, the metadata of local temporary tables are only kept in the memory of the current TiDB instance, so we can bypass the complex online DDL procedure. We need only to generate the metadata locally and then merge it into the information schema. Thus, users cannot see the DDL jobs of local temporary tables through `ADMIN SHOW DDL JOBS`.

Local temporary tables don’t support altering table operations because few users will do that. TiDB should report errors when users try to do that.

As all DDL statements do, any DDL on a global temporary table will cause an implicit commit. However, creating and dropping a local temporary table doesn’t cause an implicit commit, according to [the MySQL documentation](https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html).

Each temporary table belongs to its own database. Local temporary tables have a very loose relationship with databases. Dropping a database does not automatically drop any local temporary tables created within that database. The local temporary tables still stay in a virtual database with the same name.

Truncating global temporary tables also conforms to the online DDL procedure, which affects other sessions. However, it's different for local temporary tables because the metadata is kept in memory. Truncating local temporary tables just drops the current metadata and creates a new one in memory.

DDL operations, including those using `INSTANT` and `COPY` algorithms, are simple to apply on global temporary tables. For example, adding an index on a global temporary table is easy, because the table must be empty before adding the index. This benefits from implicit commit before adding the index. Local temporary tables, on the other hand, do support adding indexes, as other altering table operations.

Some options in `CREATE TABLE` statements are not suitable for temporary tables. These options include: `AUTO_RANDOM`, `SHARD_ROW_ID_BITS`, `PRE_SPLIT_REGIONS`, `PARTITION BY`, `FOREIGN KEY`. Similarly, some related DDL operations are not supported, such as `SPLIT TABLE`, `SHOW TABLE REGIONS`, `ALTER PLACEMENT POLICY`. Table partition option is useless to a temporary table in the real use cases, so it's also not supported. Errors should be reported when users declare such options in the statements.

Since some options are not suitable for temporary tables, when a user creates a temporary table from the `CREATE TABLE LIKE` statement and the source table has these options, an error should be reported.

Other options will be kept. For example, clustered indexes and secondary indexes are kept because they can improve performance.

- Altering table types is not allowed, since few users will do that:
- Altering a temporary table to a normal table or conversely.
- Altering a global temporary table to a local temporary table or conversely.
- Altering the storage engine of temporary tables.

The result of `SHOW TABLES` contains global temporary tables, but not local temporary tables. The motivation is that local temporary tables are only for temporary usage, so the user should know what he is doing. However, `SHOW CREATE TABLE` works for all temporary tables.

Similarly, system tables `TABLES` and `COLUMNS` in `information_schema` do not contain local temporary tables, but they contain global temporary tables. For global temporary tables, the value of field `TABLE_TYPE` in `information_schema.TABLES` is `GLOBAL TEMPORARY TABLE`.

`ADMIN CHECK TABLE` and `ADMIN CHECKSUM TABLE` are used to check data integrity of the table. Data of temporary tables might also be corrupted due to unexpected problems, but it's impossible to check them because they are invisible to other sessions. So TiDB doesn’t support these commands.

Creating views on a global temporary table makes sense, and the view will also be persistent on TiKV. However, it's unreasonable to persist a view that is based on a local temporary table, because the table will be discarded when the session ends.

As the metadata of global temporary tables are persistent on TiKV, the binlog of DDL should also be exported. However, this is unnecessary for local temporary tables.

## Optimizer

Statistics of temporary tables are very different from those of normal tables. The data of each temporary table is invisible to other sessions, so it's unnecessary to persist statistics on TiKV. On the other hand, even if the sizes of temporary tables are relatively small, it's also necessary to consider statistics since it may improve the query performance significantly.

Updating statistics is a little different from normal tables. We can’t rely on `AUTO ANALYZE` anymore, because the lifecycle of one session is relatively short, it's unlikely to wait for `AUTO ANALYZE`. What’s more, `AUTO ANALYZE` runs in background sessions, which means they can’t visit the temporary data.

it's also unreasonable to force users to run `ANALYZE TABLE` periodically in applications. Intuitively, there are 2 ways to maintain statistics:
Update statistics once updating the table. When users run `ANALYZE TABLE`, TiDB updates statistics in the current session, instead of in background sessions.
Instead of maintaining statistics, collecting needed statistics before each query is another option. The collection can be boosted by sampling. `ANALYZE TABLE` needs to do nothing in this way.

Both ways are also easy to implement, and it's not concrete that we really need statistics for temporary tables for now. So we only maintain row count, and just skip maintaining NDV, selectivity and others until there’s a need.

Statistics of the same global temporary table are different in different sessions using, so every session keeps a copy of statistics for each global temporary table. However, the statistics of normal tables are stored in a global cache, which can be visited concurrently. So there needs to be a way to store the statistics of global temporary tables separately.

Obviously, the cost of reading temporary tables is much lower than reading normal tables, since TiDB doesn’t need to request TiKV or consume any network resources. So the factors of such operations should be lower or 0.

SQL binding is used to bind statements with specific execution plans. Global SQL binding affects all sessions and session SQL binding affects the current session. Since local temporary tables are invisible to other sessions, global SQL binding is meaningless. TiDB should report errors when users try to use global SQL binding on local temporary tables. Creating global or session SQL binding on global temporary tables, and creating session SQL binding on local temporary tables are both allowed.

Baseline is used to capture the plans of statements that appear more than once. The appearance of statements is counted by SQL digests. Even if all sessions share the same global temporary table definitions, the data and statistics is different from one session to another. Thus baseline and SPM is useless for temporary tables. TiDB will ignore this feature for temporary tables.

Prepared plan cache is used to cache plans for prepared statements to avoid duplicate optimization. Each session has a cache and the scope of each cache is the current session. Even if the cached plan stays in the cache after the temporary table is dropped, the plan won’t take effect and will be removed by the LRU list finally. So we just leave it as it was.

## Storage

Before going further to the executor, we need to determine the storage form of temporary tables.

Basically, there are a few alternatives to store the data of in-memory temporary tables, and the most promising ones are:

- Unistore. Unistore is a module that simulates TiKV on a standalone TiDB instance.
- UnionScan. UnionScan is a module that unit's membuffer and TiKV data. Membuffer buffers the dirty data written by a transaction. Query operators read UnionScan and UnionScan will read both buffered data and persistent data. Thus, if the persistent part is always empty, then the UnionScan itself is a temporary table.

|                  | Unistore        | UnionScan |
| -------------    | :-------------: | -----:    |
| execution        | Y               | Y         |
| indexes          | Y               | Y         |
| spilling to disk | Y               | N         |
| MVCC             | Y               | N         |


TiDB uses UnionScan to store the data of temporary tables for the following reasons:

- The performance should be better. It can cut down the marshal/unmarshal cost and a lot of the coprocessor code path, which is inevitable in the Unistore as a standalone storage engine.
- The implementation is easier. As long as we don’t take the spilling to disk feature into consideration for now, the global temporary table is almost handy. And we do not bother by the tons of background goroutines of the Unistore engine when dealing with resource releasing. How to keep the atomicity is another headache if we choose the Unistore, imagine that a transaction would write to both temporary tables and normal tables at the same time.
- A lower risk of introducing bugs. Although we implement the coprocessor in the Unistore, we just use it for the testing purpose, and we also have some experimental features first implemented in the Unistore, so its behavior may slightly differ from the real TiKV, and that difference would introduce bugs.

Nothing needs to be changed for the KV encoding, the temporary table uses the same strategy as the normal table.

When the memory consumed by a temporary table exceeds a threshold, the data should be spilled to the local disk to avoid OOM. The threshold is defined by the system variable `temptable_max_ram`, which is 1G by default. Membuffer does not support disk storage for now, so we need to implement it.

A possible implementation is to use the AOF (append-only file) persistent storage, the membuffer is implemented as a red-black tree and its node is allocated from a customized allocator. That allocator manages the memory in an arena manner. A continuous block of memory becomes an arena block and an arena consists of several arena blocks. We can dump those blocks into the disk and maintain some LRU records for them. A precondition of the AOF implementation is that once a block is dumped, it is never modified. Currently, the value of a node is append-only, but the key is modified in-place, so some changes are necessary. We can keep all the red-black tree nodes in memory, while keeping part of the key-value data in the disk.

Another option is changing the red-black tree to a B+ tree, this option is more disk friendly but the change takes more effort.

When a temporary table needs to be cleared, its disk data should also be cleared. That can be done asynchronously by a background goroutine. The goroutine needs to know whether a file is in use. So TiDB needs to maintain a map which contains in-use files, each session updates the map periodically if it'still needs the file. If some files are not touched for a long time, we can treat the session as crashed and collect the disk files.

For on-disk temporary tables, it's straightforward to store them on TiKV like normal tables. Since each local temporary table has a unique table ID, the data from different sessions are separate. However, multiple sessions using the same global temporary table will share the same table ID, which means the data from multiple sessions is continuous and stored together. Sessions will affect each other in this case.

Clearing the data of on-disk temporary tables is a little different from in-memory temporary tables. When a TiDB instance is down, the storage space needs to be collected by other TiDB instances. Thus the maintenance of in-use temporary tables should be on the TiKV side.

## Executor

For normal tables, auto-increment IDs and row IDs are allocated in batches from TiKV, which significantly improves performance. However, as temporary tables are usually inserted, it may cause write hotspot on TiKV. So the best way is to allocate IDs locally on TiDB. The ID of a global temporary table is allocated separately among sessions and rebases to 0 every time a transaction ends. That means, each session needs a copy of allocators, rather than sharing the same allocators.

Besides, `last_insert_id` is also affected by inserting into temporary tables.

Since the data of in-memory temporary tables are not needed to be cached anymore, coprocessor cache and point-get cache are ignored. But they still work for on-disk temporary tables.

Follower read indicates TiDB to read the follower replicas to release the load of leaders. For in-memory temporary tables, this hint is ignored. But it'still works for on-disk temporary tables.

Users can also choose the storage engine to read by setting `tidb_isolation_read_engines`. For in-memory temporary tables, this setting will also be ignored. But it'still works for on-disk temporary tables.

Since in-memory temporary tables are not persistent on TiKV or TiFlash, writing binlog for DML is also unnecessary. This also stays true for on-disk temporary tables, because data is invisible to other sessions.

it's straightforward to support MPP on on-disk temporary tables, because the data is also synchronized to TiFlash. Most operators on in-memory temporary tables can still be processed in TiDB, such as Aggregation and TopN. These operators will not cost much memory because the sizes of in-memory temporary tables are relatively small.

However, joining normal tables with in-memory temporary tables might be a problem, because the sizes of normal tables might be huge and thus merge sort join will cause OOM, while hash join and index lookup join will be too slow. Supporting broadcast join and shuffled hash join on in-memory temporary tables is very difficult. Fortunately, MPP typically happens in OLAP applications, where writing and scanning duration is relatively short compared to computing duration. So users can choose to define on-disk temporary tables in this case.

## Transaction

Because it's rare to read historical data of a temporary table, temporary tables don’t support features that rely on MVCC, like flashback table, recover table, stale read, and historical read. Errors will be reported when users execute such statements on temporary tables.

If a transaction only writ's to temporary tables without normal tables, it does not really need a TSO for committing, because MVCC is unsupported and the data is invisible to other sessions. But for the sake of simplicity, we still fetch commit's just like normal tables.

When a transaction commits, the data in in-memory temporary tables should not be committed on TiKV. When a transaction rollbacks, operations on normal tables and temporary tables should be rollbacked together. The data in on-disk temporary tables will be committed. However, this can be omitted by global on-disk temporary tables, because the data will be cleared anyway. TiDB can iterate KV ranges to filter out the data.

Since there won’t be concurrent modifications on a same temporary table, there won’t be lock conflicts. So `FOR UPDATE` and `LOCK IN SHARE MODE` clauses will be ignored.

Transactions might retry write operations when commit fails. DML on normal tables might rely on the data on temporary tables, so DML on temporary tables should also be retried. For example:

```
INSERT INTO normal_table SELECT * FROM temp_table
UPDATE normal_table, temp_table SET … WHERE normal_table.id=temp_table.id
```

If DML on temporary tables is not retried, such statements won’t write any data.

Specially, as mentioned above, creating and dropping local temporary tables might also be in a transaction, but they needn’t be retried.

TiDB comes with an optimization when the variable `tidb_constraint_check_in_place` is disabled: checking for duplicate values in UNIQUE indexes is deferred until the transaction commits. For those cases where temporary tables skip 2PC, this optimization should be disabled.

Local transactions are special transactions that fetch TSO from the local PD. They can not access the data that is bound to the current available zone. Although temporary tables are not bound to any zones, they are invisible to other sessions, which means local transactions can still guarantee linearizability even when they access temporary tables.

Schema change on a global temporary table may happen during a transaction which writ's to the temporary table. Unlike normal tables, the transaction won’t overwrite other transactions, so it's fine to commit. Schema change on a local temporary table will never happen during a transaction which writ's to the temporary table.

## Privileges

Creating a local temporary table checks the `CREATE TEMPORARY TABLES` privilege. No access rights are checked when dropping a local temporary table, according to [the MySQL documentation](https://dev.mysql.com/doc/refman/8.0/en/drop-table.html).

All DDL on global temporary tables check the corresponding privileges like normal tables do.

Writing to a global temporary table checks the privileges like the normal table. But there is no privilege check for a local temporary table.

Privileges can not be granted to local temporary tables, because the tables are invisible to other users. Granting privileges to global temporary tables is possible.

## Ecosystem Tools

As mentioned above, DDL binlog of global temporary tables needs to be recorded, but not for local temporary tables. DML binlog is always skipped for temporary tables. DDL of global temporary tables should be supported by all data migration tools whose upstream is TiDB, such as Dumpling, TiDB-binlog, and TiCDC.

Since `information_schema.tables` lists global temporary tables, these tables will be processed by tools like Dumpling. Fortunately, querying global temporary tables in a new session just returns empty results, so nothing needs to be handled.

When backup tools read TiKV data, the data of temporary tables should never be read. However, on-disk temporary tables are stored on TiKV and TiFlash, so they need to be ignored by those tools, such as BR and TiCDC. Since these tools can see the metadata, they should also be capable of skipping tables that are not normal tables.

Telemetry is used to report the usage information of various features in TiDB. Global and local temporary tables will be reported by telemetry separately, because the scenarios of them are different.

## Internal temporary tables

In MySQL, temporary tables will be used internally as infrastructures of other features, such as CTE, derived tables, and UNION statements. These temporary tables are called [internal temporary tables](https://dev.mysql.com/doc/refman/8.0/en/internal-temporary-tables.html).

In the future, temporary tables will probably be used internally for some new features, such as CTE. So TiDB should be capable of creating a local temporary table when it's given a list of columns. Internal temporary tables might be in-memory or on-disk, depending on the optimizer. Physical plans that don’t apply MPP should use in-memory temporary tables, otherwise they will use on-disk temporary tables.

Transactions that apply internal temporary tables might be read-only, but there are some steps which write to TiKV:

- Assigning table ID for temporary tables
- Writing to on-disk temporary tables
- Writing to on-disk temporary tables is inevitable, so the best way is NOT to report errors in this case.

When executing a CTE in MPP mode, TiFlash has to write to the temporary table by itself, because the middle data is generated by TiFlash.

## Modification to the write path

The data of the temporary table is all in the membuffer of UnionScan. Writing to the temporary table is writing to the transaction cache.

The data writing path in TiDB is typically through the `table.Table` interface, rows data are converted into key-values, and then written to TiKV via 2PC. For normal transactions, the data is cached in the membuffer until the transaction commits. The temporary table should never be written to the real TiKV.

A transaction can write to both the temporary table and the normal table. Should the temporary table share the membuffer with the normal table, or use a separate one? It's better to share the membuffer so the commit/rollback operation can be atomic. The risk is that in case of a bug, the temporary table data may be written to the real table.

For global temporary tables, since the transaction commits automatically clears the temporary table, we can filter out and discard the transaction cache data from the temporary table when committing, and the implementation is relatively simple.

For local temporary tables, the temporary table data is cleared at the end of the session, so the data should survive the transaction’s commit. We can copy the key-value data belonging to the temporary table to another place and use it in the later read operation.

## Modification to the read path

In TiDB, reading is implemented by the coprocessor. Read operations should see their own writ's. TiDB uses a UnionScan operator on top of the coprocessor's executor. This operator takes the data read by the coprocessor as a snapshot, then merges it with the membuffer, and passes the result to its parent operator.

For transactional temporary tables, there is no need to do any additional changes, the current code works well.

For the local temporary table, the key-value data of the temporary table in the current transaction should be taken out. We keep a temporary table membuffer in the session variable and if it is not null, the UnionScan operator needs to combine it with the original data. So now the data hierarchy looks like this:

    TiKV snapshot => Old membuffer => current transaction’s membuffer

## Upgrade and Downgrade Compatibility

When users downgrade TiDB to an older version after they have created a global temporary table, the table should not be seen by the older version. Otherwise, they might write to the table and then upgrade TiDB, which will be a problem.

# Test Design

A brief description of how the implementation will be tested. Both the integration test and the unit test should be considered.

## 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.

- DDL
  - Create table / create table like
  - Drop table
  - Truncate table
  - Other DDL (for global)
- DML
  - Insert / replace / update / delete / load data
  - All kinds of query operators
  - Show create table / show tables
- Transaction
  - Atomicity (for local)
  - Isolation (RC / SI, linearizability)
  - Data visibility between transactions
  - Optimistic / Pessimistic transactions
- Information_schema
  - Tables
  - Columns
- Privileges

## Scenario Tests

It's used to ensure this feature works as expected in some common scenarios.

Before we implement the spilling to disk feature, we have to know the memory usage for some scenarios. For example, 100M for each temporary table, and 500-600 concurrent connections, how much memory does TiDB use.

## Compatibility Tests

| Feature                                              | Compatibility              | Temporary Table type | Reason                                                                             |
| -------------                                        | :-------------:            | :-----:              | :---:                                                                              |
| placement rules                                      | Report error: not support  |                      | Meaningless                                                                        |
| partition                                            | Report error: not support  |                      | Meaningless                                                                        |
| show table regions / split table / pre_split_regions | Report error: not support  |                      | Meaningless                                                                        |
| stale read / historical read                         | Report error: not support  |                      | Meaningless                                                                        |
| auto_random / `shard_row_id_bits`                    | Report error: not support  |                      | No need to release writing hotspots                                                |
| flashback / recover table                            | Report error: not support  |                      | Meaningless                                                                        |
| global SQL binding                                   | Report error: not support  | local                | Bindings are meaningless after session ends & Tables are different amo ng sessions |
| view                                                 | Report error: not support  | local                | Views are meaningless after session ends & Tables are different among sessions     |
| copr cache                                           | Ignore this setting        | in-memory            | No need to cache                                                                   |
| point get cache                                      | Ignore this setting        | in-memory            | No need to cache                                                                   |
| follower read                                        | Ignore this setting        | in-memory            | Data is neither on TiKV nor on TiFlash                                            |
| read engine                                          | Ignore this setting        | in-memory            | Data is neither on TiKV nor on TiFlash                                            |
| GC                                                   | Ignore this setting        |                      | No need to GC data                                                                 |
| select for update / lock in share mode               | Ignore this setting        |                      | No lock is needed                                                                  |
| broadcast join / shuffle hash join                   | Ignore this setting        |                      | Data is not on TiFlash                                                             |
| baseline / SPM                                       | Ignore this setting        |                      |                                                                                    |
| `tidb_constraint_check_in_place`                     | Ignore this setting        | in-memory & local    | Data is not committed on TiKV                                                      |
| auto analyze                                         | Ignore this setting        |                      | Background sessions can’t access private data                                     |
| global session-specific                              | Need to backfill in memory |                      |                                                                                    |
| global txn / local txn                               | Need to deal with          |                      | No limitation for read / write                                                     |
| analyze                                              | Need to deal with          | on-disk              | Update in-memory stats in the current session instead of in system sessions        |
| telemetry                                            | Need to deal with          |                      | Report the usage of temporary tables                                               |
| view                                                 | Need to test               | global               | Drop views on dropping temporary tables                                            |
| `auto_increment` / `last_insert_id`                  | Need to deal with          |                      | AutoID is allocated locally                                                        |
| add index                                            | Need to deal with          |                      | The table is always empty before adding index                                      |
| all hints                                            | Need to test               |                      |                                                                                    |
| plan cache                                           | Need to test               |                      | plan cache is session-scope                                                        |
| show fields / index / keys                           | Need to test               |                      |                                                                                    |
| SQL binding                                          | Need to test               |                      |                                                                                    |
| clustered index                                      | Need to test               |                      |                                                                                    |
| async commit / 1PC                                   | Need to test               |                      |                                                                                    |
| checksum / check table                               | Report error: not support  |                      | Meaningless                                                                        |
| collation / charset                                  | Need to test               |                      |                                                                                    |
| batch insert                                         | Need to test               |                      |                                                                                    |
| feedback                                             | Need to test               |                      |                                                                                    |
| `statements_summary` / `slow_query`                  | Need to test               |                      | SQL normalization                                                                  |
| big transaction                                      | Need to test               |                      |                                                                                    |
| memory tracker                                       | Need to test               |                      |                                                                                    |
| explain / explain analyze                            | Need to test               |                      |                                                                                    |

Compatibility with other external components, like TiDB, PD, TiKV, TiFlash, BR, TiCDC, Dumpling, TiUP, K8s, etc.

Upgrade compatibility

Downgrade compatibility

## Benchmark Tests

The following two parts need to be measured:

- measure the performance of this feature under different parameters
- measure the performance influence on the online workload

sysbench for the temporary table, comparing its performance with the normal table. It means comparing the performance of an in-memory system with a distributed system.

# Investigation & Alternatives

How do other systems solve this issue? What other designs have been considered and what is the rationale for not choosing them?

[MySQL documentation](https://dev.mysql.com/doc/refman/8.0/en/internal-temporary-tables.html) about the temporary table

[CockroachDB](https://github.com/cockroachdb/cockroach/issues/5807) just uses the normal table as the temporary table. All the temporary tables are stored in a special schema, and it is scanned and cleaned periodically. If a session is finished, the temporary tables of that session are also cleaned.

[Oracle](https://docs.oracle.com/cd/B28359_01/server.111/b28310/tables003.htm#ADMIN11633) uses global temporary tables in the old versions, and later on they also have the private temporary tables. The private temporary table in Oracle looks like MySQL, those tables are visible to the session rather than global. For global temporary tables, Oracle does not need to handle the schema change, because `alter table` is not allowed when some transactions are using the table.

# Development Plan

Stage 1（Support transactional, in-memory temporary table）

- The architecture design for global/local, session/transaction, in-memory/disk spilling (L)
- DDL（2XL)
  - Basic DDL e.g. create/drop table/add index etc
  - Show tables/show create table for global temporary table
- DML (2XL)


- Backup and recover the temporary table meta information (L)
- Sync the temporary table DDL through CDC or Binlog to the downstream
- Privilege (L)
- Compatibility with other features (2XL)
- Performance test (L)

Stage 2 （Support for session-specific temporary table)

- create/drop session temporary table (3XL)
- Duplicated table name handling
- Compatibility with MySQL 8.0 temporary table (in-memory)
- Compatibility with other features (2XL)

Stage 3

- Support spilling to disk for all kind of temporary tables (4XL)

---

### Design 2021 04 21 Unify Log Library (`docs/design/2021-04-21-unify-log-library.md`)

# Proposal:

- Author(s): [Yifan Xu](https://github.com/SabaPing)
- Last updated: May 11, 2021
- Discussion at: https://github.com/pingcap/tidb/pull/24181
- Tracking issue: https://github.com/pingcap/tidb/issues/24190

## Abstract

There are heterogeneous logging libraries in PingCAP's golang projects. These different logging libraries affect the development efficiency and even the user configuration experience.

It is necessary to unify those heterogeneous logging libraries.

## Background

Except for slow query logs, all other logs must satisfy the [unified-log-format RFC standard](https://github.com/tikv/rfcs/blob/master/text/2018-12-19-unified-log-format.md).

However, in practice, it was found that the format of logs is confusing:

- There are few logging configuration instructions in the document. We need to enrich document especially the type and the format of logs each component would emit.
- The configured logging parameters do not match the runtime logging, e.g. `tidb_stderr` is configured with text format, but the log is in json format.
- The logs of some components do not meet the [unified-log-format RFC standard](https://github.com/tikv/rfcs/blob/23d4f9aed68a295b678e8bd909ee8479e3ba0bd1/text/2018-12-19-unified-log-format.md), e.g. `tiflash_cluster_manager`.
- Duplicate logs, e.g. `pd_stderr` will emit both text and json logs with duplicate content (but with a few subtle differences in timestamps).

## Proposal

There must be something wrong with the engineering of these codes above, and they must be changed. The cost to change them is not small.

Rationale - for long-term consideration, we should maintain code quality. The speed of output can be sacrificed in time if necessary.

Implementation plan:

1. Unify log library for `pingcap/tidb` first. For dependent parts we write dummy code to satisfy.
2. Unify log library for `pingcap/br`, remove the dependency on `pingcap/tidb/util/logutil`, and clear dummy code of `pingcap/tidb`.
3. Unify log library for `tikv/pd`.

After the implementation, we have `pingcap/tidb`, `pingcap/br`, `tikv/pd` all depend directly on `pingcap/log` and do not depend on any other log libraries (including `std/log`) or each other.

## Rationale

The following rationales are organized by GitHub repositories.

### [pingcap/log](https://github.com/pingcap/log)

As a common logging library in PingCAP, it does the following things:

- Provides the standard config schema.
- Provides a factory method for creating log handlers.
- Hard code the log format according to [unified-log-format RFC standard](https://github.com/tikv/rfcs/blob/23d4f9aed68a295b678e8bd909ee8479e3ba0bd1/text/2018-12-19-unified-log-format.md).
- Encapsulates the logic of the rolling file.
- Provides global log handler and related methods for package dimension.

### TiDB

Log library dependencies:



For historical reasons, TiDB has two third-party logging libraries, `logrus` and `pingcap/log`. `pingcap/log` is a wrapper of `zap`.

Logs of TiDB can be divided into two types, slow query logs and the other logs.
As mentioned above, these two types of logs are emitted through two different logging libraries, which results in separate configurations for the two types of logs and requires writing additional configuration conversion code.

TiDB-specific logging logic is written inside `util/logutil/log.go`, e.g., logger initialization, logger configuration, and so on.

Note this file, which is one of the main culprits of circular dependencies. The following briefly describes the key logic in `util/logutil/log.go`, two init methods and four log handlers.

#### logrus

The init method of `logrus` may initialize two `logrus` handlers.

First, it is necessary to initialize the standard log handler (package level handler). `InitLogger` first initializes the standard logger according to the configuration.

Then, determine whether the configuration has enabled slow query log, and if so, create a log handler specific to slow query.

[Here is the code](https://github.com/pingcap/tidb/blob/e79fa8c6b654e5b94e9ed0a1c0f997d6564e95be/util/logutil/log.go#L261).

Regarding where these two handlers are used.

- Some historical legacy code, such as `cmd/importer/parser.go`, which uses the standard logger by `logrus`.
- Slow query log all uses the slow query log handler created by `logrus`, code in `executor/adapter.go`.

#### [pingcap/log](https://github.com/pingcap/log)

`pingcap/log` is a wrapper around zap, and as mentioned below the two terms are equivalently interchangeable.

Similar to `logrus`, the init method of zap `func InitZapLogger(cfg *LogConfig) error` may initialize two zap handlers.

- The global zap handler, the default log handler for the entire repo, through which the vast majority of logs are emitted.
- Slow query zap handler, which is only initialized and not used.

`InitZapLogger`'s logic is very similar to `logrus`' above.

#### gRPC Logger

In `main.go` there is a bunch of grpc logger initialization code, which is not in `util/logutil/log.go`.

[Here is the code](https://github.com/pingcap/tidb/blob/e79fa8c6b654e5b94e9ed0a1c0f997d6564e95be/tidb-server/main.go#L591).

The `NewLoggerV2` method creates a go native logger handler and is only used in grpc.

### PD

PD is similar to TiDB in that it also relies on `logrus` and `pingcap/log`, but with an additional layer of `capnslog` as a proxy.

Log library dependencies:



#### Logrus

The standard logger is then passed down to the etcd (via the `capnslog` proxy), grpc and draft components as the log handler for these packages.

There is only one `logrus` handler inside the entire PD codebase.

Only the etcd, grpc, and draft components use the `logrus` handler.

The initialization of `logrus` locates at `pkg/logutil/log.go`. [Here is the code](https://github.com/tikv/pd/blob/b07be86fb91aef07e8a68258ff6149256ab511f8/pkg/logutil/log.go#L260).

#### [pingcap/log](https://github.com/pingcap/log)

There is only one zap log handler inside the entire PD codebase, and its initialization is inline `cmd/pd-server/main.go`.

[Here is the code](https://github.com/tikv/pd/blob/b07be86fb91aef07e8a68258ff6149256ab511f8/cmd/pd-server/main.go#L66).

The logic is simple, create a new handler based on the configuration and replace the global handler at the `pingcap/log` package level.

Most of the logging logic in PD will use the global zap handler.

### [pingcap/br](https://github.com/pingcap/br)

TiDB depends on BR, which in turn depends on tidb's `util/logutil/log.go`, constituting a circular dependency.

Not only is it a circular dependency, it also happens to depend on the log component. This creates a considerable obstacle for the refactor.

The following code is from `pkg/lightning/log/log.go`, which calls TiDB's `InitLogger` and then `pingcap/log`'s InitLogger.

[Here is the code](https://github.com/pingcap/br/blob/b09611d526a754cee82e6d3b12edf67e4cc885ae/pkg/lightning/log/log.go#L77).

BR also relies on TiDB's slow log, which he initializes in the main function as `SlowQueryLogger`.

BR also calls TiDB's `InitLogger` twice in two places.

BR also created two different zap handlers in two places, one of which is not used.

These problem codes are not listed here.

To refactor TiDB's logging functionality, you must first change BR to remove the dependency on TiDB log, then let TiDB depend on the new version of BR, and finally refactor TiDB's logging.

## Compatibility and Migration Plan

Must ensure that refactoring is compatible with historical logging logic. 

Guaranteed by unit testing.

## Implementation

See meta issue: https://github.com/pingcap/tidb/issues/24190.

## Testing Plan

Mainly unit testing.

## Open issues (if applicable)
## Logging code for each component

---

### Design 2021 04 26 Lock View (`docs/design/2021-04-26-lock-view.md`)

# TiDB Design Documents

- Author(s): [longfangsong](https://github.com/longfangsong), [MyonKeminta](http://github.com/MyonKeminta)
- Last updated: Oct 13, 2021
- Discussion PR: N/A
- Tracking Issue: https://github.com/pingcap/tidb/issues/24199

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Test Design](#test-design)
    * [Functional Tests](#functional-tests)
    * [Scenario Tests](#scenario-tests)
    * [Compatibility Tests](#compatibility-tests)
    * [Benchmark Tests](#benchmark-tests)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
* [Unresolved Questions](#unresolved-questions)

## Introduction

This document describes the design of the feature Lock View, which provides tools to analyze problems about transaction's lock waiting, lock contentions and deadlocks.

## Motivation or Background

Currently, it's very hard to analyze lock contentions and deadlocks for transactions. One may need to enable general log, try to reproduce the problem, and try to analyze the log to find the cause, which is very difficult and inconvenient. Even if you have the log, many conflict's information contains only a `start_ts`, which won't tell you much useful information (like the SQLs in the transaction) for reproducing the problem. We also found that this way of analyzing is not feasible in some scenarios. It's highly required to provide some better approach to analyze these kinds of problems.

## Detailed Design

Several tables will be provided in `information_schema`. Some tables has both local version (fetches data on the current TiDB node) and global version (fetches data among the whole cluster), and the global version's table name has the `"CLUSTER_"` prefix.

### Table `(CLUSTER_)TIDB_TRX`

| Field      | Type       | Comment |
|------------|------------|---------|
| `TRX_ID`    | `unsigned bigint`   | The transaction ID (aka. start ts) |
| `TRX_STARTED`|`time`| Human readable start time of the transaction |
| `CURRENT_SQL_DIGEST`|`varchar(64)`| The digest of the current executing SQL statement |
| `ALL_SQL_DIGESTS` | `text` | A list of all executed SQL statements' digests |
| `STATE`| `enum('Running', 'Lock waiting', 'Committing', 'RollingBack')`| The state of the transaction |
| `WAITING_START_TIME` | `time` | The elapsed time since the start of the current lock waiting (if any) |
| `SCOPE` | `enum('Global', 'Local')` | The scope of the transaction |
| `ISOLATION_LEVEL` | `enum('REPEATABLE-READ', 'READ-COMMITTED')` | |
| `AUTOCOMMIT` | `bool` |  |
| `SESSION_ID` | `unsigned bigint` | | 
| `USER` | `varchar` | |
| `DB` | `varchar` | |
| `SET_COUNT` | `int` | Modified keys of the current transaction |
| `LOCKED_COUNT` | `int` | Locked keys of the current transaction |
| `MEM_BUFFER_KEYS` | `int` | Entries in transaction's membuffer |
| `MEM_BUFFER_BYTES` | `int` | Size occupied by the transaction's membuffer |

* Life span of rows:
    * Create on first writing or locking operation in a transaction
    * Remove after the transaction is done
* Collecting, storing and querying:
    * All these information can be collected on TiDB side. Since the amount of concurrent transactions won't be too large, and it doesn't need to be persisted, so it's ok to implement it as a memory table. For querying among the cluster, just register the table under `infoschema/cluster.go` and write the global table name with the local one.
    * As the simplest way of implementing, most information can be passed with a similar way like `ProcessInfo`, or even directly passed via the `ProcessInfo` struct.
* Permission:
    * `PROCESS` privilege is needed to access the full content of this table. For users without `PROCESS` permission, only transactions started by the current user will be shown, and others will be filtered out, which is similar to the `processlist` table.

### Table `DATA_LOCK_WAITS`

| Field      | Type       | Comment |
|------------|------------|---------|
| `KEY`      | `varchar`  | The key that's being waiting on |
| `TRX_ID`   | `unsigned bigint` | The current transaction that's waiting for the lock |
| `SQL_DIGEST` | `varchar(64)` | The digest of the SQL that's trying to acquire the lock |
| `CURRENT_HOLDING_TRX_ID` | `unsigned bigint` | The transaction that's holding the lock and blocks the current transaction |

* Life span of rows:
    * Created on a lock come into LockManager
    * Removed after a lock leave LockManager
* Collecting, storing and querying:
    * All these will be collected on TiKV LockManager, and will need a new RPC entry for TiDB to query. LockManager won't store the un-hashed key or SQL_DIGEST for now, so we need to modify it.
* The SQL Digest of the transaction that's currently holding the lock may be helpful, but it's hard to implement under the current architecture. So it won't be included in the first version of the feature.
* Permission:
    * `PROCESS` privilege is needed to access this table.

### Table `(CLUSTER_)DEADLOCKS`

| Field      | Type       | Comment |
|------------|------------|---------|
| `DEADLOCK_ID` | `int` | There needs multiple rows to represent information of a single deadlock event. This field is used to distinguish different events. |
| `OCCUR_TIME`  | `time` | The physical time when the deadlock occurs |
| `RETRYABLE` | `bool` | Is the deadlock retryable. TiDB tries to determine if the current statement is (indirectly) waiting for a lock locked by the current statement. |
| `TRY_LOCK_TRX_ID` | `unsigned bigint` | The transaction ID (start ts) of the transaction that's trying to acquire the lock |
| `CURRENT_SQL_DIGEST` | `text` | The SQL that's being blocked |
| `KEY` | `varchar` | The key that's being locked, but locked by another transaction in the deadlock event |
| `ALL_SQL_DIGESTS` | `text` | A list of the digest of SQL statements that the transaction has executed |
| `TRX_HOLDING_LOCK` | `unsigned bigint` | The transaction that's currently holding the lock. There will be another record in the table with the same `DEADLOCK_ID` for that transaction. |

* Life span of rows:
    * Create after TiDB receive a deadlock error
    * FIFO，clean the oldest after buffer is full
* Collecting, storing and querying:
    * All of these information can be collected on TiDB side. It just need to add the information to the table when receives deadlock error from TiKV. The information of other transactions involved in the deadlock circle needed to be fetched from elsewhere (the `CLUSTER_TIDB_TRX` table) when handling the deadlock error.
    * TiKV needs to report more rich information in the deadlock error for collecting.
    * There are two types of deadlock errors internally: retryable or non-retryable. The transaction will internally retry on retryable deadlocks and won't report error to the client. Therefore, the user are typically more interested in the non-retryable deadlocks. 
        * Retryable deadlock errors are by default not collected, and can be enabled with configuration.
        * Collecting `CLUSTER_TIDB_TRX` for more rich information for retryable deadlock is possible to make the performance worse. Whether it will be collected for retryable deadlock will be decided after some tests.
* Permission:
  * `PROCESS` privilege is needed to access this table.

### TABLE `(CLUSTER_)TRANSACTION_SUMMARY`

| Field      | Type       | Comment |
|------------|------------|---------|
| `DIGEST` | `varchar(16)` | Digest of a transaction, calculated with `ALL_SQL_DIGEST` |
| `ALL_SQL_DIGEST`  | `text` | A json array which contains all SQLs' digest executed in this kind of transaction |

* Life span of rows:
    * Create after first this kind of transaction ended.
    * LRU，clean the least existed(in `TRANSACTION_ID_DIGEST`, see below) after buffer is full.
* Collecting, storing and querying:
    * All of these information can be collected on TiDB side. It just need to add the information to the table when a transaction ended.
* Permission:
  * `PROCESS` privilege is needed to access this table.

### TABLE `(CLUSTER_)TRANSACTION_ID_DIGEST`

| Field      | Type       | Comment |
|------------|------------|---------|
| `DIGEST` | `varchar(16)` | Digest of a transaction, calculated with `ALL_SQL_DIGEST` |
| `TRX_ID`  | `bigint` | The transaction ID (aka. start ts) |

* Life span of rows:
    * Create after a transaction ended and it meets some certain condition (due to the memory is limited).
    * Currently, the condition is that the transaction executed too slow, which has more chance to be conflict with other transactions.
    * FIFO，clean the oldest after buffer is full.
* Collecting, storing and querying:
    * All of these information can be collected on TiDB side. It just need to add the information to the table when a transaction ended.
* Permission:
  * `PROCESS` privilege is needed to access this table.

### Protocol

To pass necessary information between TiDB and TiKV to make this feature possible, there needs some additional information carried in the protocol defined in kvproto.

deadlockpb:

```diff
  message WaitForEntry {
    ...
+   bytes key = ...;
+   bytes resource_group_tag = ...;
  }

  message DeadlockResponse {
    ...
+   repeated WaitiForEntry wait_chain = ...;
  }
```

kvrpcpb:

```diff
  message Context {
    ...
+   bytes resource_group_tag = ...;
  }

  message Deadlock {
    ...
+   repeated deadlock.WaitForEntry wait_chain = ...;
  }

+ message GetLockWaitInfoRequest {
+     Context context = 1;
+ }
+ 
+ message GetLockWaitInfoResponse {
+     errorpb.Error region_error = 1;
+     string error = 2;
+     repeated deadlock.WaitForEntry entries = 3;
+ }
```

A field `resource_group_tag` will be added to `Context`. The SQL digest (and maybe more information) will be serialized and carried in this field. This field is expected to be reused by another feature named *Top SQL* which wants to carry SQL digest and plan to most transactional requests.

A new KV RPC `GetLockWait` will be added to allow getting the lock waiting status from TiKV. This is a store-level (instead of region level) request, like `UnsafeDestroyRange`, and those Green GC related RPCs. The request can carry some filtering options to filter out those information the user don't care about. But the current memory table implementation only allow TiDB to scan the whole table and then filter it. This may need further optimization in the future.

The locking key and `resource_group_tag` that comes from the `Context` of the pessimistic lock request is added to the deadlock detect request, and the wait chain is added to the deadlock detect response.

The wait chain will be added to the `Deadlock` error which is returned by the `PessimisticLock` request, so that when deadlock happens, the full wait chain information can be passed to TiDB.

### Configurations

#### TiDB Config File `pessimistic-txn.deadlock-history-capacity`

Specifies how many recent deadlock events each TiDB node should keep.

Dynamically changeable via HTTP API.

Value: 0 to 10000

Default: 10

#### TiDB Config File `pessimistic-txn.deadlock-history-collect-retryable`

Specifies whether to collect retryable deadlock errors to the `(CLUSTER_)DEADLOCKS` table.

Dynamically changeable via HTTP API.

Value: 0 (do not collect) or 1 (collect)

Default: 0

#### TiDB Config File `transaction-summary.transaction-id-digest-capacity`

Specifies how many transaction in `transaction_id_digest` each TiDB node should keep.

Dynamically changeable via HTTP API.

Value: 0 to 100000

Default: 10000

#### TiDB Config File `transaction-summary.transaction-id-digest-min-duration`

Specifies how long a transaction should be executed to make it be recorded in `transaction_id_digest` and considered when calculating `trx_summary`.

Dynamically changeable via HTTP API.

Value: 0 to 2147483647

Unit: ms

Default: 1000

#### TiDB Config File `transaction-summary.transaction-summary-capacity`

Specifies how many transaction summary in `trx_summary` each TiDB node should keep.

Dynamically changeable via HTTP API.

Value: 0 to 5000

Default: 500

## Compatibility

This feature is not expected to be incompatible with other features. During upgrading, when there are different versions of TiDB nodes exists at the same time, it's possible that the `CLUSTER_` prefixed tables may encounter errors. However, since this feature is typically used by user manually, this shouldn't be a severe problem. So we don't need to care much about that.

## Test Design

### Functional Tests

* Querying the tables defined above gives correct result.

### Scenario Tests

* In a scenario where there's lock contention, this feature helps locating the problem.
* In a scenario where some a SQL is blocked by another transaction, this feature helps locating the problem.
* In a scenario where deadlock happens, this feature helps finding how the deadlock is formed.

### Compatibility Tests

- N/A

### Benchmark Tests

* The feature shouldn't cause any obvious performance regression (< 2%) on normal scenarios.
* Accessing these tables shouldn't increase latency of concurrent normal queries.

## Impacts & Risks

* To be investigated

## Investigation & Alternatives

* MySQL provides `data_locks` and `data_lock_waits` tables.
* Oracle provides `v$lock` view.
* CRDB provides `crdb_internal.node_transaction_statistics` that shows rich information for transactions.

## Unresolved Questions

* Since lock waiting on TiKV may timeout and retry, it's possible that in a single query to `DATA_LOCK_WAIT` table doesn't shows all (logical) lock waiting.
* Information about internal transactions may not be collected in our first version of implementation.
* Since TiDB need to query transaction information after it receives the deadlock error, the transactions' status may be changed during that time. As a result the information in `(CLUSTER_)DEADLOCKS` table can't be promised to be accurate and complete.
* Statistics about transaction conflicts is still not enough.
* Historical information of `TIDB_TRX` and `DATA_LOCK_WAITS` is not kept, which possibly makes it still difficult to investigate some kind of problems.

---

### Design 2021 06 23 Restricted Read Only (`docs/design/2021-06-23-restricted-read-only.md`)

# Technical Design Document for Restrcted Read Only

> Author: [huzhifeng@pingcap.com](mailto:huzhifeng@pingcap.com)
This document is open to the web, and it will appear as a design doc PR to the TiDB repository.

# Introduction

In this document, we introduced the `TIDB_RESTRICTED_READ_ONLY` global variable. Turning it on will make the cluster read-only eventually for all users, including users with SUPER or CONNECTION_ADMIN privilege.

# Motivation or Background

See the [original specification](https://docs.google.com/document/d/1LtmW4fIohTjPcupD9smQGQpN2B2tRSFNyH8PFbg-L2c/edit).

# **Detailed Design**

## read-only handling

Currently, TiDB supports `read_only` and `super_read_only` global variables with no actual operation. Since TIDB_RESTRICTED_READ_ONLY does not comply with the behavior of MySQL read-only and super-read-only (which will block if there is table locked or ongoing committing of a transaction), we will not build TIDB_RESTRICTED_READ_ONLY upon read-only and super-read-only. These two variables will be remained untouched.

We will create a new global variable TIDB_RESTRICTED_READ_ONLY, and turning it to on and off will only be allowed in SEM mode, and only users with RESTRICTED_VARIABLES_ADMIN will be allowed to modify this variable.

To allow replication service to write, we introduced a new dynamic privilege level called `RESTRICTED_REPLICA_WRITER_ADMIN`, user with this privilege will be ignored for read-only checks.

Upon the change of the variable on a TiDB sever, the change will be broadcasted to all other TiDB servers through PD. Normally, the other TiDB servers will receive the update immediately, however under certain circumstances (such as TiDB server lose connection to PD), the lag can be up to 30 seconds.

### How to restrict SQLs

If read-only is turned on, we will reject SQLs that might change data during planning. The rules are:

- we won't restrict internal SQLs
- we rely on an allow list to determine whether SQL is allowed to execute
    - we would allow set variables (otherwise can't unset them)
    - we would allow `analyze table`
    - we allow `show`
    - we allow create and drop SQL bindings
    - we allow prepare SQLs
    - we allow `begin` and `rollback`
    - we only allow `commit` if there is no change in the transaction, otherwise the transaction will abort
- finally, we resort to `planner/optimizer.go:IsReadOnly` for testing if the query is read-only for cases like explain, prepare and execute, etc.

## Privilege management

- add `tidb_restricted_read_only` to hidden variables, i.e., only users with `RESTRICTED_VARIABLES_ADMIN` privilege can modify it.
  - alternative: add `RESTRICTED_READ_ONLY_ADMIN` privilege, only user with this privilege can change the setting, and user with this privilege can write to the cluster without being affected by the read-only setting. However it might be redundant for introducing a new privilege level.
- add `RESTRICTED_REPLICA_WRITER_ADMIN` to allow replication writer to surpass read-only checks. Note this privilege check is required even if SEM is not enabled, i.e., SUPER user still needs to be explicitly granted this privilege to be able to write.

## Difference with MySQL read-only

MySQL has support for read-only and super-read-only, which is currently not supported in TiDB. Restricted read only shares similar functionality as them, but differs in:

* When turning on read-only or super-read-only, MySQL might [fail or block when enabling read-only under some circumstances](https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_read_only). However turning on TIDB_RESTRICTED_READ_ONLY will return success immediately. Some other TiDB servers might not yet received the update of this variable, and will remain in updatable status until eventually the change on the global variable is broadcasted to all TiDB servers in the cluster.

## Alternative

- we will implement read-only and super-read-only that complies with MySQL's, and build TIDB_RESTRICED_READ_ONLY upon them, but we only need eventual read-only for TIDB_RESTRICTED_READ_ONLY. It is more relaxed, and it should always return success.
- we support read-only and super-read-only in a similar manner as TIDB_RESTRICED_READ_ONLY, this however will make its behavior incompatible with MySQL.

---

### Design 2021 06 23 Spilled Unparallel Hashagg (`docs/design/2021-06-23-spilled-unparallel-hashagg.md`)

# Proposal: Support Spilling Unparalleled HashAgg

- Author(s): [@wshwsh12](https://github.com/wshwsh12)
- Discussion PR: https://github.com/pingcap/tidb/pull/25792
- Tracking Issue: https://github.com/pingcap/tidb/issues/25882

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Test Design](#test-design)
    * [Functional Tests](#functional-tests)
    * [Scenario Tests](#scenario-tests)
    * [Compatibility Tests](#compatibility-tests)
    * [Benchmark Tests](#benchmark-tests)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
* [Future Work](#future-work)

## Introduction

This proposal describes the implementation of Unparalleled HashAgg that can spill intermediate data when memory usage is higher than memory quota.
Spilling for paralleled HashAgg will be supported later.

## Motivation or Background

Currently, the calculation logic of the aggregate executors in the TiDB is divided into two types, parallel and unparallel. However, when SQL memory usage exceeds the memory quota, neither implementation can use external memory to control memory usage and can only kill the SQL that is executing. In order to enable SQL to execute normally in the case of insufficient memory, we introduce the spilling algorithm for the unparallel aggregate executor.

## Detailed Design

In aggregate processing, memory increases when tuples are inserted into the hash table. So we can use the following algorithm to control the memory increasing:

1. When the memory usage is higher than the mem-quota, switch the HashAgg executor to spill-mode.
2. When HashAgg is in spill-mode, keep the tuple in the hashMap no longer growing.
  a. If the processing key exists in the Map, aggregate the result.
  b. If the processing key doesn't exist in the Map, spill the data to disk.
3. After all data have been processed, output the aggregate result in the Map, clear the Map. Then read the spilling data from disk, repeat the Step1-Step3 until all data have been aggregated.

## Test Design

### Functional Tests

* Querying using aggregate functions should give correct result.

### Scenario Tests

* When the unparallel-agg exceeds the memory quota, this feature helps reduce memory usage and run the sql successfully.
* When the parallel-agg exceeds the memory quota, the SQL will be canceled before. After the agg-concurrency args are set to 1, the SQL can run successfully.
* When the ndv of the data is low, the SQL contains distinct function will be canceled before. This feature helps the SQL run successfully.
* When the ndv of the data is high, the SQL contains distinct function will be canceled before. The SQL can be canceled successfully if there is insufficient memory.

### Compatibility Tests

* N/A

### Benchmark Tests

* The feature shouldn't cause any obvious performance regression (< 2%) on non-spilling scenario.

## Impacts & Risks

* Memory will still grow without increasing the number of new tuples in HashMap for distinct aggregate function.

## Investigation & Alternatives

## Future Work
1. Support friendly spilling implementation for the distinct aggregate functions.
2. Support spilling for paralleled HashAgg.

---

### Design 2021 06 27 Restructure Tests (`docs/design/2021-06-27-restructure-tests.md`)

# Proposal: Restructure TiDB Tests

- Author(s): [tison](http://github.com/tisonkun)
- Discussion PR: https://github.com/pingcap/tidb/pull/26024
- Tracking Issue: https://github.com/pingcap/tidb/issues/26022

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Test Design](#test-design)
* [Implementation Plan](#implementation-plan)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
* [Unresolved Questions](#unresolved-questions)

## Introduction

This document describes the proposal to restructure TiDB tests, focusing on unit tests and integration tests, especially on separating `integration_test.go` as well as unifying test infrastructure.

## Motivation or Background

On the current codebase of TiDB, tests suffer from several major troubles.

1. There are many unstable tests mainly about concurrency logic, which impacts a lot of the development experience during the project.
2. The main test framework ([pingcap/check](http://github.com/pingcap/check)) is lack of maintenance. Not only the integration with modern IDE such as GoLand is terrible so that every newcomer asks how to run a unit test, but also nobody is responsible for the test framework and the development on upstream ([go-check/check](https://github.com/go-check/check)) seems to halt.
3. Logs created by passed tests are noisy and redundant, see also [discussion on TiDB Internals forum](https://internals.tidb.io/t/topic/48).
4. There are a lot of huge test files contains many cases of "integration tests" which make the tests subtle and brittle, as well as hard to be run in parallel.
    * `expression/integration_test.go` has 9801 lines.
    * `executor/executor_test.go` has 8726 lines.
    * `ddl/db_test.go` has 6930 lines.
    * `session/session_test.go` has 4825.
    * `planner/core/integration_test.go` has 3900 lines.
5. The satellite tests are disordered. Where they are? How can we fix failures reported by them or write new cases?
    * idc-jenkins-ci-tidb/common-test
    * idc-jenkins-ci-tidb/integration-common-test 
    * idc-jenkins-ci-tidb/integration-br-test
    * idc-jenkins-ci-tidb/integration-compatibility-test
    * idc-jenkins-ci-tidb/integration-copr-test
    * idc-jenkins-ci-tidb/integration-ddl-test
    * idc-jenkins-ci-tidb/mybatis-test
    * idc-jenkins-ci-tidb/sqllogic-test-1
    * idc-jenkins-ci-tidb/sqllogic-test-2
    * idc-jenkins-ci-tidb/tics-test

In this proposal, we are focus on dealing with the first four troubles, and leave the last trouble as a start of the discussion.

## Detailed Design

To overcome the first four troubles listed above, I propose to start with migrating the main test framework from [pingcap/check](http://github.com/pingcap/check) to [stretchr/testify](https://github.com/stretchr/testify).

Besides, we refer to a series of suggestions for better tests in the appendix sections so that we can spawn another tracking issue to handle the problem caused by large test files, redundant logs, and unstable tests.

As described above, the main test framework of TiDB, i.e., pingcap/check, is lack of maintenance. Not only the integration with modern IDE such as GoLand is terrible so that every newcomer asks how to run a unit test, but also nobody is responsible for the test framework. What's worse, the development on upstream (go-check/check) seems to halt.

stretchr/testify is a widely adopted test framework for Golang project. We can make a quick comparison between these projects.

| Dimension    | pingcap/check               | go-check/check               | stretchr/testify              |
| ------------ | :-------------------------- | :--------------------------- | :---------------------------- |
| stars        | 16                          | 617                          | 13.6k                         |
| contributors | 17                          | 13                           | 188                           |
| development  | little, inactive for a year | little, inactive for a while | active                        |
| integration  | poor                        | out of go testing            | go testing, GoLand, and so on |
| checkers     | poor                        | even poor than pingcap/check | fruitful                      |

There is no doubt stretchr/testify is a better adoption than pingcap/check or go-check/check. You can see also the complaint on TiDB Internals forum, named [Better way to debug single unit test in tidb](https://internals.tidb.io/t/topic/141).

Many of Golang projects previous using pingcap/check, such as [pingcap/errors](https://github.com/pingcap/errors), [pingcap/log](https://github.com/pingcap/log), and [tikv/client-go](https://github.com/tikv/client-go), migrate to stretchr/testify and gain all benefits.

## Implementation Plan

The implementation of detailed design is separated into three phases.

* **Phase 0**: Start the migration to stretchr/testify by introducing the dependency, but new tests can be still written in pingcap/check.
* **Phase 1**: Once test kits in stretchr/testify version are implemented and there are adequate migration examples, prevent new tests written in pingcap/check.
* **Phase 2**: Finalize the migration and drop the dependency to pingcap/check.

It is planned to finish the migration in two sprints or three, i.e., four months or by the end of this year.

I will moderate the proposal and call for a vote for phase 1 on the forum and reflect the result in the tracking issue. The prerequisites should include implement all test kits necessary and have copyable migration samples. We may do it packages by packages, though.

## Test Design

This proposal is basically about tests themselves. And what we design to do with tests is covered by the detailed design section.

## Impacts & Risks

### Projects depend on github.com/pingcap/tidb/util/testkit or other test utils may break

For example, [pingcap/br](http://github.com/pingcap/br), which has an unfortunate circle dependency with pingcap/tidb for historical reasons, depends on `github.com/pingcap/tidb/util/testkit` and will be broken after we reach phase 2.

However, those projects can copy and paste the missing kits when implementation comes to phase 2. Also, we can take care of these cases and help them get rid of pingcap/check later.

Comment here if other projects suffer from this issue.

* [pingcap/br](http://github.com/pingcap/br)

## Investigation & Alternatives

To be honest, go testing already provides a test framework with parallel supports, children tests supports, and logging supports.

[kubernetes](https://github.com/kubernetes/kubernetes), [coredns](https://github.com/coredns/coredns), and [etcd](https://github.com/etcd-io/etcd) all make use of go testing, and only kubenetes uses stretchr/testify for its fruitful checkers.

This proposal keeps the same preference that we stay as friendly with go testing as possible, make use of checkers provided by stretchr/testify, and generate our own test kits.

### Test Improvement Suggestions

#### Leverage test logger implemented at pingcap/log#16

This section continues from the previous discussion on the TiDB Internals forum, named [Turn off redundant logging in TiDB tests](https://internals.tidb.io/t/topic/48).

Logs created by passed tests are generally less interesting to developers. go.uber.org/zap provides a module named `zaptest` to redirect output to `testing.TB`. It only caches the output per test case, and only print the output to the console if the test failed.

[pingcap/log#16](https://github.com/pingcap/log/pull/16) brings this function to pingcap/log and we'd better make use of it to prevent redundant logs output. In detail, we will introduce a method with the signature `logutil.InitTestLogger(t zaptest.TestingT, cfg *LogConfig)` and enable in every test related to logs.

Note that the test logger only prevents logs when go test without `-v` flag. But since we keep printing logs on failure case, we can safely remove the flag.

#### Prefer determinate tests for concurrency logics

Make use of `sync.Mutex`, `sync.WaitGroup`, or other concurrent utils like latches, and get rid of "long enough" sleep, which is brittle and causes unnecessary time for tests.

#### Separate huge test files into small test units that can be run in parallel

* `expression/integration_test.go` has 9801 lines.
* `executor/executor_test.go` has 8726 lines.
* `ddl/db_test.go` has 6930 lines.
* `session/session_test.go` has 4825.
* `planner/core/integration_test.go` has 3900 lines.

We should break these test files into small test units and try to perform white-box tests instead of just testing the end-to-end behavior.

## Unresolved Questions

What parts of the design are still to be determined?

---

### Design 2021 07 07 Rule Based Index Selection (`docs/design/2021-07-07-rule-based-index-selection.md`)

# Proposal: Improve rule based index selection

- Author(s): [xuyifangreeneyes](https://github.com/xuyifangreeneyes)
- Discussion PR: https://github.com/pingcap/tidb/pull/27223
- Tracking Issue: https://github.com/pingcap/tidb/issues/26020

## Abstract

This proposal aims to improve rule based index selection including heuristics and skyline pruning, which helps avoid choosing the wrong index due to outdated statistics.

## Background

Currently, the choice of access path mainly depends on statistics. The wrong index may be chosen due to outdated or inaccurate statistics. In order to reduce the possibility of the situation, the optimizer introduces some rule based index selection mechanisms, including heuristics and skyline pruning. We try to improve rule based index selection to enhance robustness of index selection.

## Proposal

The improvement of rule based index selection consists of always-good heuristics, skyline pruning and maybe-good heuristics.

### Always-Good Heuristics

The rules of always-good heuristics are listed as following.

1. If a unique index is covered by conditions and single scan is enough, we directly choose it.
2. If a unique index is covered by conditions but it needs double scan(index scan + table scan), we push it into an array `uniqueIdxsWithDoubleScan`. After collecting all the unique indices satisfying the condition into `uniqueIdxsWithDoubleScan`, we select the one that has the smallest number of rows to read as `uniqueBest`.
3. If an index `idx1` only needs single scan, and there is a unique index `idx2` belonging to `uniqueIdxsWithDoubleScan` whose access condition is subset of `idx1`'s, we can infer that `idx1` has limited rows to read. In this way, we refine `idx2` to obtain `idx1` so we push it into an array `singleScanIdxs`. After collecting all the indices satisfying the condition into `singleScanIdxs`, we select the one that has the smallest number of rows to read as `refinedBest`.
4. If `uniqueBest` exists while `refinedBest` doesn't, we choose `uniqueBest`. If both `uniqueBest` and `refinedBest` exist, we choose the one with the smaller number of rows to read.

In the above rules, an index being covered by conditions means for each index column there is an equal condition.

The following examples show how those rules work. The primary key `a` in the first `SELECT` statement matches rule 1, so it is chosen directly. For the second `SELECT` statement, `uniqueBest` is `idx_b` and we refine `idx_b` to obtain `idx_b_c` which is `refinedBest`. We choose `idx_b_c` finally since it has the smaller number of rows to read.

```sql
CREATE TABLE t(a INT PRIMARY KEY, b INT, c INT, UNIQUE INDEX idx_b(b), UNIQUE INDEX idx_b_c(b, c));
SELECT * FROM t WHERE a = 2 OR a = 5;
SELECT b, c FROM t WHERE b = 5 AND c > 10;
```

### Skyline Pruning

TiDB has [skyline pruning](https://github.com/pingcap/tidb/blob/master/docs/design/2019-01-25-skyline-pruning.md) to prune the index which is strictly worse than another index. When comparing two indices, it considers three dimensions: single scan or double scan, the set of columns in the access condition, matching of the physical property. There are two improvements we can make for the first dimension and the third dimension respectively.

1. If both indices need double scan, the current implementation regards the two indices equal on the first dimension. However, we can check the set of columns in `AccessPath.IndexFilters` to compare the number of table-read rows. For example, though `idx_b` and `idx_b_c` have the same access condition `b > 5` and both need double scan, `idx_b_c` has the filter condition `c > 5` but `idx_b` doesn't. Hence `idx_b_c` is better than `idx_b`.
```sql
CREATE TABLE t(a INT, b INT, c INT, INDEX idx_b(b), INDEX idx_b_c(b, c));
SELECT * FROM t WHERE b > 5 and c > 5;
```
2. The current implementation doesn't correctly identify whether the index matches the physical property in some cases and we can fix them. For example, `idx_a_b_c` matches the required order `ORDER BY a, c` since `b = 4` is constant.
```
CREATE TABLE t(a INT, b INT, c INT, d INT, INDEX idx_a_b_c(a, b, c))
SELECT * FROM t WHERE b = 4 ORDER BY a, c;
```

### Maybe-Good Heuristics

```sql
CREATE TABLE t(a INT PRIMARY KEY, b INT, c INT, INDEX idx_b(b));
SELECT * FROM t WHERE b = 2 ORDER BY a LIMIT 10;
```
In the above example, the optimizer may choose `TableFullScan` which takes much more time than  `IndexRangeScan`. The cause is that it is hard to tell which is better between `TableFullScan` matching the required order and fetching the limited number of rows and `IndexRangeScan`. For the situation, TiDB has a switch `tidb_opt_prefer_range_scan`. When the switch turns on, the optimizer always prefers range scan over full scan. There are three improvements we can do on the switch.

1. The switch is session-level, which is not enough for use in real scenes. Hence we make the switch both session-level and global-level.
2. For the unsigned handle of the table, the full range is `[0, +inf]` but the current implementation doesn't regard it as full range, which needs fixing.

## Rationale

Rules such as heuristics and skyline pruning can prevent the optimizer from choosing some obviously wrong index, which are implemented in many other databases.

## Compatibility

It does not affect the compatibility.

## Implementation

Always-good heuristics have nothing to do with the physical property, so it will be implemented in `(*DataSource).DeriveStats` after filling content for each `(*DataSource).possibleAccessPaths`. Skyline pruning and prefer-range-scan are implemented in `(*DataSource).findBestTask` and we just need to make the improvements in place.

---

### Design 2021 07 29 Hidden Sysvars (`docs/design/2021-07-29-hidden-sysvars.md`)

# Proposal: Remove hidden sysvars

- Author(s): [morgo](http://github.com/morgo)

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
  * [#1 “Stable” but intended to be deprecated or advanced configuration variables](#1-stable-but-intended-to-be-deprecated-or-advanced-configuration-variables)
  * [#2 “Experimental” feature flags](#2-experimental-feature-flags)
  * [#3 “In Development” feature flags](#3-in-development-feature-flags)
  * [#4 Non-boolean Experimental Options](#4-non-boolean-experimental-options)
* [Test Design](#test-design)
* [Implementation Plan](#implementation-plan)
  * [Appendix #1 - tidb_experimental_feature_switch documentation](#appendix-1---tidb_experimental_feature_switch-documentation)
  * [Appendix #2 - Removed system variables](#appendix-2---removed-system-variables)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
* [Unresolved Questions](#unresolved-questions)

## Introduction

Currently we create hidden/undocumented settings that are only designed for internal PingCAP users. In an internal call we unanimously agreed that this is problematic for our customers.

## Motivation or Background

The proposal is to change all hidden system variables to visible. The proposed solution differs based on the category of why the variable was made invisible.

This proposal also includes expected standards for documentation.

There are currently ~20 hidden system variables:

| Name | Usage | Category |
| ------|-------|-------------|
| tidb_enable_local_txn | Local/Global Transaction | #2 Experimental |
| tidb_txn_scope | Parameters of local transaction | #4 Non-boolean Experimental |
| tidb_txn_read_ts | "" | #4 Non-boolean Experimental |
| tidb_enable_pipelined_window_function | ‘Pipelined window function’ feature | #1 Stable |
| tidb_enable_change_multi_schema | ‘Change multi schema in one statement’ feature. | #3 In Development Feature |
| tidb_enable_point_get_cache | ‘point get cache’ feature | #2 Experimental |
| tidb_enable_extended_stats | ‘extended stats’ feature | #2 Experimental |
| tidb_partition_prune_mode | Is partition prune mode dynamic or static | #2 Experimental |
| tidb_enable_async_commit | Support Async Commit PRD  | #1 Stable |
| tidb_enable_1pc | "" | #1 Stable |
| tidb_guarantee_linearizability | "" | #1 Stable |
| tidb_enable_index_merge_join | Index merge join | #2 Experimental |
| tidb_enable_global_temporary_table | Global temporary table | #1 Stable |
| tidb_enable_stable_result_mode | Make resultset sorted(deterministic order) by default | #1 Stable |
| tidb_track_aggregate_memory_usage | Track memory usage of aggregate executor | #1 Stable |
| tidb_enable_top_sql | Top SQL (Sprint3) 总设计文档  | #2 Experimental |
| tidb_top_sql_agent_address | Parameters for Top SQL | #4 Non-boolean Experimental |
| tidb_top_sql_max_time_series_count | "" | #4 Non-boolean Experimental |
| tidb_top_sql_max_meta_count | "" | #4 Non-boolean Experimental |


## Detailed Design

### #1 “Stable” but intended to be deprecated or advanced configuration variables

These variables were hidden because they are intended to be removed in a future version, and are not typically recommended to be changed.

However; the problem with this decision is that these features do impact performance and behavior characteristics significantly, and can make debugging the difference between two clusters very difficult. This is exacerbated by our choice to only enable async commit for “new clusters”, and disable it for upgrades from earlier versions.

Consider the case that one cluster is upgraded from a logical dump, and the other from an inplace upgrade. They will have different behavior characteristics; and because the variable is hidden it is very difficult for a DBA to debug this issue.

Add to this the fact that async commit is not guaranteed to be bug free: there was a recent critical issue with async commit. There could be a case where one cluster has data corruption and the investigation is made more difficult.

These variables are also in the documentation, but hidden in the server. This makes me (as a DBA) believe that they don’t apply to my version. My MySQL experience works against me, because I expect that every variable is in SHOW VARIABLES.

**Recommended Solution:**

* Change all of these variables to be visible. They impact behavior, so it should be clear to a user when comparing clusters.
* We can add functionality to better handle deprecation in the sysvar system when it is intended to be removed.


### #2 “Experimental” feature flags

These examples are all boolean feature flags, and cover features which are not of GA quality, but are of sufficient quality that we invite users to test them out (see #3 for the still in-development case).

The rationale for making them hidden was to not pollute the variable system when they are intended to be removed rather quickly as they become stable.

However, the problem is that the number of experiments in TiDB is currently out of control. It is very difficult to know which flags specifically relate to an experiment and quickly ensure for production that all experiments are disabled. Or for development environments, you may choose to have all experiments enabled.

**Recommended solution:**

* These variables should be migrated to use `tidb_experimental_feature_switch`. This is modeled on how optimizer switches work in MySQL, and better caters for options that appear/disappear quickly.
* The documentation for `tidb_experimental_feature_switch` on system-variables can include a one-line description for each of the experiments (See Appendix #1). This is less “heavy” than documenting these as separate system variables, and there is no requirement to include docs on which version an experiment appeared or disappeared.

### #3 “In Development” feature flags

These are a subcategory of “experimental” feature flags, with the difference being that the feature is still in active development, and is not ready for users to try the experiment. There may be significant known pitfalls.

Because refactoring code itself can introduce bugs, if the code for these features exists in the server, in the interest of transparency it should be disclosed to the DBA, even if it is highly recommended that the user never use this feature.

**Recommended solution:**

* These variables should be migrated to use `tidb_experimental_feature_switch`.
* The sysvar documentation for `tidb_experimental_feature_switch` will not document these unsupported flags (See Appendix #1) but instead say:
   > Your TiDB server installation may include additional experimental features not in this list. Enabling them is not recommended and could result in data loss.

### #4 Non-boolean Experimental Options

This category of variables is different from Experimental/In Development feature flags because the tidb_experimental_feature_switch only handles boolean switches.

These variables almost always depend on an experimental feature flag (which will move to `tidb_experimental_feature_switch`). If they don’t, one might need to be created.

**Recommended Solution:**

* Because the system variable system supports dynamic registration/unregistration, these variables should be removed when the experiment is disabled, and added when the experiment is not enabled. 
* In some cases these variables might have been miscategorized and are instead “Stable” but intended to be deprecated or advanced configuration variables (category #1).

### Future Handling

Internally, we need an explicit guidebook for how the variables are added and removed with the evolution of TiDB:

* When and how a new variable is added. The cons/pros of adding a variable compared with a configuration item.
* When and how a variable will be removed.

Once it is decided, it’s a good idea to publish it the design docs.

### Documentation Standards

There are currently 75 undocumented system variables (not including noop sysvars). Because several hidden variables are actually already documented, the lack of documentation is really an orthogonal problem that also needs fixing.

It is expected that all system variables will be documented, with the exception of category #3 which in the recommendation is explicitly “documented as not documented”.

## Implementation Plan

#### Appendix #1 - tidb_experimental_feature_switch documentation

##### tidb_experimental_feature_switch

* Scope: SESSION | GLOBAL
* Default value: (system dependent)
* This variable allows you to enable or disable TiDB Server features which have not reached GA maturity.
Individual values can be changed by specifying a comma separated list. For example: `SET GLOBAL tidb_experimental_feature_switch = 'alter_placement=ON,cascades_planner=ON';`
* A wildcard can be used to change the value of all experiments. For example: `SET GLOBAL tidb_experimental_feature_switch = '%=OFF'`;
* Changing this variable on a SESSION basis requires the `SESSION_VARIABLES_ADMIN` permission.
* Experiments include:

| Name   | Usage      |
|----------|-------------|
| local_txn |  Enable Local/Global transactions |
| point_get_cache | Cache TiKV Point Get requests |
| extended_stats | Create statistics on multiple columns. This is useful in the case that columns do not have strong correlation. |
| dynamic_partition_prune  | Enable the dynamic partition prune mode. |
| index_merge_join | Enable the optimization where multiple indexes can be used and merged. |
| top_sql | Enable the Top SQL feature |

> **Warning:**
> Be careful when enabling experimental features. Your TiDB server installation may include additional experimental features not listed here, and enabling them may result in data loss.
> The experimental feature switch is settable on both a SESSION and GLOBAL basis, but some experiments might only be available globally. In which case changes to the session have no effect.

#### Appendix #2 - Removed system variables

For existing experimental flags, the procedure to remove the flag once the feature is GA is problematic since here could be users that have applications that explicitly enable the feature which now break.

This proposes that we support "removed system variables" by the sysvar framework. A removed sysvar:

* Is settable via a `SET` statement
* Returns an error for `SELECT @@var` queries
* Is not visible in `SHOW VARIABLES` output

This helps accommodate one of the main use cases (phantom `SET` statements in application code) while not returning inaccurate or out of date data.

## Test Design

- Because this change "makes more functionality visible", it is unlikely to cause compatibility issues (versus removing functionality).
- The change can be handled via unit tests.

## Impacts & Risks

- The largest impact is that users will expect system variables to be documented (of which some of the hidden system variables already are.)
- Users may feel more accustomed to setting variables if they are visible, which might lead to incorrect usage, or more complex deprecation cyles. However, there is a reasonable expectation that if the documentation states a particular value is unsafe, then it should not be used.

## Investigation & Alternatives

In MySQL system variables are never hidden. If a variable is settable by `SET x=y`, then `x` will show in `SHOW VARIABLES`.

Oracle does have [hidden variables](http://www.dba-oracle.com/art_so_undoc_parms_p2.htm) for special tasks such as tuning. But there are culture differences with Oracle that make this a difficult comparision.

## Unresolved Questions

* None

---

### Design 2021 08 18 Charsets (`docs/design/2021-08-18-charsets.md`)

# Proposal: Support Charset Framework in TiDB

- Author(s): [zimuxia](https://github.com/zimulala) (Xia Li)
- Last updated: 2021-08-18
- Tracking Issue: https://github.com/pingcap/tidb/issues/26812
- Related Document: https://docs.google.com/document/d/1SC0spRoNScR8-GwUNJ9ZHAV8zmlkq99Q2PReu88FARs/edit#
- Performance Test(simple implementation): https://docs.google.com/document/d/1c6AOPpPHOTwVKFJp7n0k72Jy8KdP3oWpTkTjo3Bk2PE/edit#

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Test Design](#test-design)
    * [Functional Tests](#functional-tests)
    * [Scenario Tests](#scenario-tests)
    * [Compatibility Tests](#compatibility-tests)
    * [Benchmark Tests](#benchmark-tests)
* [Investigation & Alternatives](#investigation--alternatives)
* [Development Plan](#development-plan)

# Introduction

Currently, TiDB only supports ascii, binary, latin1, utf8, and utf8mb4 character sets. This proposal aims to add a framework for character sets to TiDB to facilitate the support of other characters. This design takes the gbk character set as an example.

# Motivation or Background

Character: Various letters and symbols are collectively referred to as characters. A character can be a Chinese character, an English letter, an Arabic numeral, a punctuation mark, a graphic symbol or a control symbol, etc.

Charset: A collection of multiple characters is called a charset. Common character set names: ASCII character set, Unicode character set, GBK character set, etc.

Character Encoding: Character encoding can be considered as a mapping rule. According to this mapping rule, a character can be mapped into other forms of data for storage and transmission in the computer. Each character set has corresponding character encoding rules, and the commonly used character set encoding rules include UTF-8 encoding, GBK encoding and so on.

MySQL supports many character sets, such as `utf8mb4`, `gbk`, `gb18030`, etc. However, currently TiDB only supports 5 character sets, and there are still some problems with related character sets ([charset: incorrect encoding for `latin1` character set](https://github.com/pingcap/tidb/issues/18955)，[extended latin character set not support](https://github.com/pingcap/tidb/issues/3888)). Now it is difficult for TiDB to add a new character set. This proposal describes the implementation of the character set framework. In many traditional industries in China, `gbk`/`gb18030` is used, so this proposal uses gbk character set support as an example.

## Functional requirements

Support gbk character set related functions:
- Supports all code points defined by the GBK 1.0 standard.
- Support conversion with other character sets.
  - Support implicit conversion according to [collation coercibility rules](https://dev.mysql.com/doc/refman/8.0/en/charset-collation-coercibility.html).
  - Supports the use of `CAST`, `CONVERT` and other functions to convert gbk characters.
- Support SQL statements, such as: `SET CHARACTER SET GBK`, `SET NAMES GBK`, `SHOW CHARSET`, etc.
- Supports the comparison between strings in the gbk character set.
- If the characters passed in are illegal, an error or warning is returned. If an illegal character is used in `CONVERT`, an error is returned. Otherwise, a warning will be returned.
- Compatible with other components, including data import, migration, and so on.

### Supported Collations

- gbk_bin: A binary collation.
- gbk_chinese_ci: The default collation, which supports Pinyin.
- gbk_utf8mb4_bin: A binary collation encoded by utf8mb4.

# Detailed Design

After receiving the non-utf-8 character set request, this solution will convert it to the utf-8 character set, and then it will be the utf-8 character set when calculating or storing in the TiDB runtime layer and the storage layer, and finally return the result of the conversion to the non-utf-8 character set.

### Encoder/Decoder

- Encapsulate read and write functions, using the Transform functions in golang.org/x/text/encoding (The version of this package used between different components is preferably the same).

### Parser

- Add parser configuration information and record the encoding of the current parser. The value of the encoding is determined by the system variable character_set_client. When invoking Restore, you can output restore SQL according to encoding.
- All ParseOneStmt/Parse usage needs to be checked
  - For SQL strings that need to be temporarily saved, you need to bring character set information. For example, BindSQL, View Select Stmt, etc.
  - For internally executed SQL statements, since they are already utf-8, they do not need to be processed. For example, the table creation statement in the perfschema package.

### Runtime
- Add a repertoire field to collationInfo to facilitate automatic character set conversion in expressions, so that many errors like "illegal mix of collations" can be avoided.
  - The corresponding types of the Repertoire attribute are as follows:

    ```go
    type Repertoire int

    const (
      // RepertoireASCII is pure ASCII and it’s Unicode range: U+0000..U+007F
      RepertoireASCII     Repertoire = 1
      // RepertoireExtended is Extended characters and it’s Unicode range: U+0080..U+FFFF
      RepertoireExtended  Repertoire = 1 << 1
      // RepertoireUnicode consists ASCII and EXTENDED, and it’s Unicode range: U+0000..U+FFFF
      RepertoireUnicode   Repertoire = ASCII | EXTENDED
    )
    ```

- Some of the built-in functions related to string computation require special processing after conversion from utf-8.
  - Reference document: https://dev.mysql.com/doc/refman/8.0/en/string-functions.html.
  - Handle the related functions in the Coprocessor.
- Process some string-related internal functions, check whether the corresponding character set needs to be processed, specific functions such as DatumsToString, strToInt.

### Optimizer

- The statistics module may need special processing functions based on charset: AvgColSizeDataInDiskByRows, GetFixedLen, BucketToString and DecodedString, etc.
- Ranger module
  - The processing of prefix len needs to consider the charset.
  - Functions such as BuildFromPatternLike and checkLikeFunc may need to consider charset.

### Collation

Add gbk_chinese_ci and gbk_bin collations. In addition, considering the performance, we can add the collation of utf8mb4 (gbk_utf8mb4_bin).
- To support gbk_chinese_ci and gbk_bin collations, it needs to turn on the `new_collations_enabled_on_first_bootstrap` switch.
  - If `new_collations_enabled_on_first_bootstrap` is off, it only supports gbk_utf8mb4_bin which does not need to be converted to gbk charset before processing.
- Implement the Collator and WildcardPattern interface functions for each collation.
  - gbk_chinese_ci and gbk_bin need to convert utf-8 to gbk encoding and then generate a sort key.
  - Implement the corresponding functions in the Coprocessor.

### DDL

Support for character sets of databases, tables and columns when creating databases, tables or adding columns, and support for changes through alter statements.

### Others

Other behaviors that need to be dealt with:
- TiKVMinVersion information may need to be modified.
- Set character set operations are supported, such as `set character set gbk`, `set names gbk` and `set character_set_client = gbk`, etc.
- Support the correct display of character sets, such as show charset/collation.
- load data: LoadDataInfo.getLine.

### Compatibility

#### Compatibility between TiDB versions

- Upgrade compatibility:
  - There may be compatibility issues when performing operations during the rolling upgrade.
  - The new version of the cluster is expected to have no compatibility issues when reading old data.
- Downgrade compatibility:
  - Downgrade is not compatible. The index key uses the table of gbk_bin/gbk_chinese_ci. The lower version of TiDB will have problems when decoding, and it needs to be transcoded before downgrading.

#### Compatibility with MySQL

- Illegal character related issue:
  - Due to the internal conversion of non-utf-8-related encoding to utf8 for processing, it is not fully compatible with MySQL in some cases in terms of illegal character processing. TiDB controls its behavior through sql_mode.

- Collation
  - Fully support `gbk_bin` and `gbk_chinese_ci` only when the config `new_collations_enabled_on_first_bootstrap` is enabled. Otherwise, it only supports gbk_utf8mb4_bin.

#### Compatibility with other components

After using this version of TiDB, and when gbk-encoded data is already stored in the database, you can only use the components corresponding to this version or greater.
- TiKV
  - Coprocessor related builtin functions need to be processed, and collation related functions need to be implemented.
- TiCDC
  - It may need to be converted to gbk character set encoding when outputting in accordance with the [TiCDC Open Protocol](https://docs.pingcap.com/zh/tidb/dev/ticdc-open-protocol).
- TiFlash
  - Related builtin functions need to be processed, and collation related functions need to be implemented.
- BR
  - BR realizes backup and recovery by directly manipulating SST files. At present, BR only rewrites the table ID and index ID in the key when restoring, and needs to decode KV. The decoder reuses the codec interface of TiDB, and only needs to update the TiDB dependency. There are no compatibility issues.
- Lightning
  - tidb-lightning is responsible for parsing SQL to become a KV pair. It implements its own parse, and special processing may be required here.
- DM
  - Currently, DM will specify utf8mb4 when connecting to TiDB, which needs to be processed here.
  - When DDL is synchronized, TiDB-parser will be used to parse the DDL statement. Currently, empty charset and collation are used. Use the charset in binlog to pass in the Parser function (it is expected to be available in the [header of the DDL event](https://dev.mysql.com/doc/internals/en/query-event.html#q-charset-database-code)):
    - If TiDB-parser supports (ascii, binary, latin1, utf8, utf8mb4, gbk), handle it directly.
    - If it is not supported, fallback to an empty charset/collation to keep the old behavior.
- Dumpling
  - Dumpling obtains the table structure and data of upstream TiDB/MySQL by executing SQL statements, so there is no compatibility problem.
- TiDB-binlog
  - TiDB to binlog is still encoded in utf8. That is, no special treatment is required.

# Test Design

## Functional Tests

Unit and integration tests to consider
- Covers the supported built-in string functions with non-utf-8 character set, including tests for conversion of different character sets.
- Copr-pushdown test of TiDB/TiKV/TiFlash.
- Related read and write tests covering different ranges of character sets and collations.
- Set or display the test of gbk character set related sentences.
Port the gbk character set and related collation tests from mysql-tests.

## Scenario Tests

Test the feasibility of using different character sets for mixed sorting.

## Compatibility Tests

### Compatibility with other features

Test the compatibility of some related features, such as SQL binding, SQL hints, clustered index, view, expression index, statements_summary, slow_query, explain analyze and other features.

### Compatibility with other external components

- Confirm that the corresponding versions of the libraries that call utf-8 and gbk transcoded by different components are consistent.
- Using different components, gbk related operations can be executed normally.

### Upgrade compatibility

- Upgrades from versions below 4.0 do not support gbk.
- Version 4.0 and above test upgrade:
  - During the rolling upgrade process, gbk operation is not supported.
  - After the upgrade, normal gbk related operations are supported.

### Downgrade compatibility

There will be incompatibility issues when downgrading tables that use gbk encoding.

## Benchmark Tests

- Test the read and write performance test of utf-8 and gbk under the same amount of data.
- Test the corresponding collation related performance test under gbk.

# Investigation & Alternatives

- MySQL's implementation of gbk can be considered as a solution that both runtime and storage use gbk. The character set used may be different between the server and the client of MySQL, between the connection and the result set, and the character set conversion is required. Different character sets in MySQL will implement character set specific interfaces to ensure the realization of character set related functions. Among them, the specific implementation reference of gbk character set: https://github.com/mysql/mysql-server/blob/8.0/strings/ctype-gbk.cc.
- CockroachDB currently does not support additional character sets.

## Rejected Alternatives

After this solution receives the gbk character set request, it will be converted to gbk encoding for processing, that is, it is the gbk character set when calculating or storing at the TiDB runtime layer and the storage layer.
The reason for the final rejection of this plan is that the issues that need to be dealt with are more complex and more uncontrollable, such as:
- Some String methods such as Datum require special handling, such as:
  - ConvertToString
  - String()
- Most of the built-in functions related to TiDB string and some string processing methods need to be processed.
  - Mainly a large number of function signatures and related calling methods need to be modified
  - stringutil package
- TiDB uses the methods of Go's own strings library (if you modify the related methods in this item, some built-in functions of TiDB do not need to be modified)：
    - strings.go
        - ToUpper, ToLower
        - HasPrefix
        - ...
    - strconv package
        - AppendQuote
        - ParseInt, ParseFloat
        - ...
    - ToGBKString

# Development Plan

The first stage (mainly realize the development of TiDB side)

- Support normal read and write operations using gbk.
- Supports setting charset to gbk or related sentences that display gbk information.
- Support string-related commonly used functions to process characters with gbk encoding.
- Support character set conversion, that is, support to use cast, convert and other functions to convert other character sets into gbk or gbk into other character sets.
- Support gbk_bin collation.

The second stage

- Realize TiKV and TiFlash related operations.
- Compatible with other components, including TiCDC, BR, Lightning, DM, Dumpling and TiDB-binlog.
- Support gbk_chinese_ci collation.

The third stage

- Basically support all string-related functions already supported by TiDB.
- Support the use of alter statement, support to modify the charset of the column.

# Add New Charset

### Encoding

Define how character encode and decode, the main work is to implement [the encoding interface](https://github.com/pingcap/tidb/blob/7fd298d916c30ed0060db3581be58b448325819e/parser/charset/encoding.go#L65-L87)

```golang
// Encoding provide encode/decode functions for a string with a specific charset.
type Encoding interface {
	// Name is the name of the encoding.
	Name() string
	// Tp is the type of the encoding.
	Tp() EncodingTp
	// Peek returns the next char.
	Peek(src []byte) []byte
	// MbLen returns multiple byte length, if the next character is single byte, return 0.
	MbLen(string) int
	// IsValid checks whether the utf-8 bytes can be convert to valid string in current encoding.
	IsValid(src []byte) bool
	// Foreach iterates the characters in in current encoding.
	Foreach(src []byte, op Op, fn func(from, to []byte, ok bool) bool)
	// Transform map the bytes in src to dest according to Op.
	// **the caller should initialize the dest if it wants to avoid memory alloc every time, or else it will always make a new one**
	// **the returned array may be the alias of `src`, edit the returned array on your own risk**
	Transform(dest *bytes.Buffer, src []byte, op Op) ([]byte, error)
	// ToUpper change a string to uppercase.
	ToUpper(src string) string
	// ToLower change a string to lowercase.
	ToLower(src string) string
}
```
### Collation

#### [New Collation](https://docs.pingcap.com/tidb/stable/character-set-and-collation#new-framework-for-collations)

TiDB have no collation with the default config, all the collation will be ignored. After tidb 4.0, the collation framework is supported and uses a config to control it. After a new charset is added into TiDB, the related collation should also be added.


For example, `gb18030` charset have 3 different collations
```sql
| gb18030_bin                | gb18030  | 249 |         | Yes      |       1 | PAD SPACE     |
| gb18030_chinese_ci         | gb18030  | 248 | Yes     | Yes      |       2 | PAD SPACE     |
| gb18030_unicode_520_ci     | gb18030  | 250 |         | Yes      |       8 | PAD SPACE     |
```

We should at least implement `gb18030_bin` and `gb18030_chinese_ci` collations.

If the collation framework is not used, the `gb18030_bin` should be the default collation, otherwise, the `gb18030_chinese_ci` should be the default collation.

Add a new collation should implement the [Collator interface](https://github.com/pingcap/tidb/blob/7fd298d916c30ed0060db3581be58b448325819e/util/collate/collate.go#L62-L71)

```golang
// Collator provides functionality for comparing strings for a given
// collation order.
type Collator interface {
	// Compare returns an integer comparing the two strings. The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
	Compare(a, b string) int
	// Key returns the collate key for str. If the collation is padding, make sure the PadLen >= len(rune[]str) in opt.
	Key(str string) []byte
	// Pattern get a collation-aware WildcardPattern.
	Pattern() WildcardPattern
}
```

Then, add the charset and related collations into the support list to make tidb recognize it.

### TikV
Many expressions have been pushed down to tikv, we should also make tikv support the [charset](https://github.com/tikv/tikv/blob/da1c069a2f9b5222ddbd32820a5a2ae1de50c78c/components/tidb_query_datatype/src/codec/collation/mod.rs#L98) and [collation](https://github.com/tikv/tikv/blob/da1c069a2f9b5222ddbd32820a5a2ae1de50c78c/components/tidb_query_datatype/src/codec/collation/mod.rs#L68).

---

### Design 2021 09 13 Parser As Submodule Of Tidb (`docs/design/2021-09-13-parser-as-submodule-of-tidb.md`)

# Proposal: Move parser back to pingcap/tidb

- Author(s): [xhebox](http://github.com/xhebox)
- Discussion: [Move parser back to pingcap/tidb](https://internals.tidb.io/t/topic/385)
- Tracking Issue: [Tracking issue for moving parser back to TiDB](https://github.com/pingcap/tidb/issues/28257)

## Table of Contents

- [Introduction](#introduction)
- [Background](#background)
- [Detailed Plan](#detailed-plan)
- [Questions](#questions)

## Introduction

This is an refined version of the draft thread [Move parser back to pingcap/tidb](https://internals.tidb.io/t/topic/385).

In short, I want to move pingcap/parser back to the pingcap/tidb repository in the form of go sub-module.

## Background

I will explain why and how to migrate the parser back to the TiDB repository.

### Why did we move parser into a separate repository?

The original PR moving out parser is [tidb#7923: Move TiDB parser to a separate repository](https://github.com/pingcap/tidb/issues/7923). When we migrated to go module 111, @tiancaiamao decided to do so, because:

> We can put the generated `parser.go` in the repository directly, rather than generate it using Makefile script. The drawback of this way is that every time `parser.y` is touched, there will be many lines change in `parser.go` . Then the TiDB repo will be inflate quickly.
>
> A better way is moving parser to a separated repo, so every time parser is changed, only go.mod need to change accordingly.

Personally, that is a weird argument for me. Indeed, pingcap/tidb does not store the diff of `parser.go` anymore, but pingcap/parser does. How is moving the inflation from one repo to another better?

Another argument is about the messy dependency. The separation does improve the case.

### What is wrong with a separate repository?

In fact, it isn't a big problem. However, the development becomes inconvenient. You could argue that we have workarounds, but why not make the development easier?

1. We always need to ensure the version of two go modules. Cherry-picking becomes troublesome since the import version must be a specific branch of pingcap/parser.
2. It is a mysql parser, but is closely related to TiDB (basically everything except ast/mysql packages). You must code TiDB logic into the "standalone mysql parser" first before your real implementation, which means at least two PRs, even for small changes.
3. Before the PR of parser merged, the PR of TiDB must use module directive to redirect a specific version of parser to fix CI.

Problems above have defeated the previous argument `only go.mod need to change accordingly`. We only separated code into two repositories, actual work did not decrease. However, our development experience does getting worse.

## Detailed Plan

Obviously, we could move back to the old good way. But it must be a go sub-module, because:

1. To keep compatibility. Parser has been imported by other tools and other users.
2. To keep the clean dependency. That is why it is separated. We don't want to make things worse again.

The detailed plan:

1. Create parser directory, a sub-module, in pingcap/tidb, which is synchronized with pingcap/parser, with `replace github.com/pingcap/parser => ./parser`.
2. Stop sending new PRs and issues to pingcap/parser, new PRs should be directly sent to pingcap/tidb. And merge recent PRs in pingcap/parser as much as possible. Changes will be synchronized from pingcap/parser to pingcap/tidb manually, of course.
3. Announce the deprecation of pingcap/parser to possible users. Clean up old PRs, reopen it in pingcap/tidb, close it, or just forget about it. As for issues, by @kennytm, we could directly transfer all issues to pingcap/tidb according to the [document](https://docs.github.com/en/issues/tracking-your-work-with-issues/transferring-an-issue-to-another-repository). As for tests, we need to migrate the verify CI tests on jenkins. Since TiDB may migrate to verify CI eventually, it is not a good idea if we migrate to things other than verify CI. Rewriting the import path is enough for migrating verify CI.
4. We can create wrapper packages for pingcap/parser, which re-exports things from `pingcap/tidb/parser`. I mean something like `import ( . github.com/pingcap/tidb/parser/xxx)`, create a dummy function will eliminate the error of `not used import`. All code of pingcap/parser will be removed in this step. This will delevery new updates without the need of migrating importing paths.
5. After another one or two dev cycles, we could archive pingcap/parser. It mainly depends on users of pingcap/parser.

There will be a tracking issue, and the whole progress is public. Step 1 or 2 will likely take one or two weeks. Internally we could do the migration for internal tools while doing step 3.

Step 4 and 5 are long-running tasks to smoothly end the support of the old parser.

## Questions

- What about projects importing parser?

Nothing needs to be done before step 5. However, one will need to migrate the import path eventually, before the final deprecation.

- What about some complex dependency chain? For example, `pkg -> forked tidb -> other pingcap/parser`.

Nothing different for the complex dependencies. Just do the migration before the deprecation. And we don't actually remove the old commits for not breaking old apps.

- What about CI and tests?

It is not a problem. pingcap/parser only has unit tests, and integration tests `make gotest` of `pingcap/tidb`. We could run integration tests of tidb, and only run unit tests.

- How about release and versioning?

Since sub-module is merely another module inside another module, we need to release it separately from the main module. That means our release team needs to tag `parser/vX.X.X`, which can be solved by a script: thanks to the identical release cycle/version between parser and tidb.

- What about the bloated parser.go file? Nobody wants it, and it increases the size of tidb repo.

We can not simply remove it. Importing pingcap/parser to build applications needs parser.go file, but go module doesn't support something like build scripts in rust or `postbuild` in nodejs to auto-generate parser.go.

One solution is to only include the file for the released version. But TiDB does not support package semver, `go get xxx/parser` won't simply give a buildable package. That will be too frustrating for users.

---

### Design 2021 09 22 Data Consistency (`docs/design/2021-09-22-data-consistency.md`)

# Proposal: Reduce Data inconsistencies

- Author(s): [Li Su](http://github.com/lysu), [Ziqian Qin](http://github.com/ekexium)
- Tracking Issue: https://github.com/pingcap/tidb/issues/26833

## Table of Contents

- [Table of Contents](#table-of-contents)

- [Introduction](#introduction)
- [Motivation or Background](#motivation-or-background)
- [Detailed Design](#detailed-design)

- [Test Design](#test-design)

    - [Regression Tests](#regression-tests)
    - [System Tests](#system-tests)
    - [Performance Tests](#performance-tests)

- [Impacts & Risks](#impacts--risks)

## Introduction

The document proposes an enhancement that reduces data inconsistency issues in TiDB. The feature also includes an
enhancement in the logging and error handling of data inconsistency issues to help diagnosis.

## Motivation or Background

TiDB occasionally encounters data index inconsistencies, i.e., row data and indices of the same record are
inconsistent (in their numbers or content). Inconsistent data indices in production environments can have a very bad
impact on users, including but not limited to

- Read errors: errors are reported when reading or writing inconsistent data
- Data error: data can be read but the result is incorrect
- Data Loss: Data written cannot be read

It is very difficult for support engineers to locate data index inconsistencies when they occur.

- Multiple possible causes of data errors
- Inconsistency phenomenon cannot easily imply its cause
- Difficulty in collecting information available for investigation on the cause

In short, the serious impact of the problem and the difficulty of troubleshooting is the main reason why we need to
invest in improvement at present.

## Detailed Design

There are two methods to reduce data corruption from happening and spreading. And we have separate system variables to
enable them.

`tidb_enable_mutation_checker`, takes value of `ON` or `OFF`.

`tidb_txn_assertion_level`, takes value of `OFF`, `FAST`, or `STRICT`. Details will be discussed later.

### Assertion

Based on the operator characteristics and the information that the operator has already checked, some assertions can be
made with regard to the data being mutated. The assertions are pushed down to TiKV and are executed before writing. DML
operators (e.g. UpdateExec, InsertExec) are encapsulated in tables to make KV modifications to memDB:

- Put KV: Add or update KV pairs
- Del KV: delete KV pair

While the data is modified, the KV pair modified to memDB is additionally set with 4 new Assertion Flags (occupying a
total of 2 bits):

- None(00): There is currently no Assertion for KV, but subsequent modifications in the transaction can overwrite this
  value [default Flag]
- Unknown(11): KV pair cannot be asserted, and subsequent modifications within the transaction cannot be overwritten
- MustExist(10): Key must exist in storage, subsequent modifications within the transaction cannot be overwritten
- MustNotExist(01): Key must not exist in the storage, subsequent modifications within the transaction cannot be
  overwritten

The flags in MemDB, like the KV data, are first set to the current stage of the statement. After that, if the statement
reports an error and the statement rolls back, the flags will be invalidated. If the statement is executed successfully
and is submitted, the flags will take effect in the transaction. The assertion information is sent to TiKV in the
prewrite stage of 2PC. TiKV performs additional checks based on the assertions before modifying data. If the assertions
fail, TiKV rejects the request.

For pessimistic transactions, prewrite requests may not read the previous value of the key. In this case, we let the
pessimistic lock requests return the existence information of the key and cache it in the client(TiDB) side. Before
committing the transaction, the client(TiDB) side will use the information to check assertions, so that doesn't have to
be the overhead of reads in TiKV. Some keys in pessimistic transactions are not pessimistically locked, so we have 2
strategies to deal with this situation: the `FAST` mode just ignores the keys, and the `STRICT` mode will read all keys
in TiKV.

### Check Mutations

The basic idea is to ensure that the transaction will not write inconsistent data when the data before the transaction
is consistent.

For possible errors in the executor: Assume that the set of row values before and after the transaction are V1 and V2
respectively, and the data indices are consistent before the transaction is executed. The condition of data consistency
after the transaction's commitment is V1-V2 = { Del_{index}.value }, V2-V1 = { Put_{index}.value }.

## Test Design

The main quality objectives of this project include correctness, effectiveness, efficiency, ease of use, and
compatibility. The test part involves two parts: ensuring correctness (including compatibility) and measuring
effectiveness.

Correctness: There will be no false positives when the data is correct

Effectiveness:

1. Reject transactions with inconsistent mutations
2. Report errors as soon as possible for existing problematic data to prevent the spread of errors

### Regression tests

Regression tests are useful to check correctness since all tests should not report data inconsistency errors.

### System tests

Specific system test cases need to be constructed. Cases should at least involve the following parts

- Encoding related
    - Collation
    - Row format
    - Charset
    - Time zone
- Table structure
    - Concurrent DDL
    - Clustered index
    - Prefix index
    - Expression index

### Performance Tests

The enhancement should have little impact on performance, including latency, throughput, memory and CPU consumption.

Standard sysbench and TPC-C tests are needed.

## Impacts & Risks

According to the performance tests, the following impacts and risks are expected:

In the `STRICT` assertion mode, pessimistic transactions results in a notable increase in the scheduler CPU usage and
the number of kvdb get and seek operations.

The mutation checker can increase the TiDB CPU usage. When the CPU becomes the bottleneck of TiDB, introducing the
enhancement may decrease the throughput by 1.5%, and increase P95 latency by 2.4%.

---

### Design 2021 09 22 Stale Read (`docs/design/2021-09-22-stale-read.md`)

# Proposal: Support Stale Read in TiDB

- Author(s): [Yisaer](https://github.com/Yisaer) (Song Gao)
- Last updated: 2021-09-22
- Tracking Issue: https://github.com/pingcap/tidb/issues/21094
- Related Document: https://docs.google.com/document/d/1dSbXbudTK-hpz0vIBsmpfuzeQhhTFJ-zDenygt8fmCk/edit?usp=sharing

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
    * [Implementation Overview](#implementation-overview)
    * [New Syntax Overview](#new-syntax-overview)
* [Compatibility](#compatibility)
    * [ForBidden Behavior](#forbidden-behavior)
    * [Statement Priority](#statement-priority)

## Introduction

This proposal aims to support Stale Read and describe what Stale Read looks like and how to keep compatibility with other queries.

## Motivation or Background

Currently, TiDB supports Follower Read to read data from follower replicas in order to increase the query throughput. TiDB also supports Snapshot Read to read old data with a given snapshot timestamp. 

However, Follower Read still requires an RPC calling between follower replica and leader replica during querying which will be the key bottleneck to scale up the read throughput when there is a hotspot reading in this range. Moreover, in cross region scenario, an extra rpc calling will also increased the latency.

For Snapshot Read, it only reads data from leader replica which might be a bottleneck, especially in hot spot cases.

Stale Read is more like the combination of Follower Read and Snapshot Read. It supports TiDB to read data from both leader replicas and follower replicas with no extra RPC calling during followers and leaders. 

It also supports read data with a given snapshot timestamp like Snapshot Read.

## Detailed Design

### Implementation Overview

Normally, TiDB will send data query requests to the storage with a given timestamp to the leader replicas. 

In Stale Read, each replica could handle the data query request because every replica maintains the resolved timestamp from the leader replica. 

This makes each store could know the smallest resolved timestamp they could handle. Thus, TiDB could send data requests with a staleness timestamp to get the data they want.

### New Syntax Overview

Here we will introduce how to use Stale Read in TiDB in 4 methods.

1. Use Stale Read by `SELECT ... FROM ... AS OF TIMESTAMP` format

```sql
SELECT * FROM t AS OF TIMESTAMP '2021-09-22 15:04:05' WHERE id = 1;
SELECT * FROM t AS OF TIMESTAMP NOW() - INTERVAL 20 SECOND WHERE id = 1;
```

You can get detailed grammar `ebnf diagram` for `SELECT ... FROM ... AS OF TIMESTAMP` in this [document](https://docs.pingcap.com/tidb/dev/sql-statement-select)

2. Use Stale Read by `START TRANSACTION READ ONLY AS OF TIMESTAMP` format

```sql
START TRANSACTION READ ONLY AS OF TIMESTAMP '2021-09-22 15:04:05';
SELECT * FROM t WHERE id = 1;
COMMIT;
```

You can get detailed grammar `ebnf diagram` for `START TRANSACTION READ ONLY AS OF TIMESTAMP` in this [document](https://docs.pingcap.com/tidb/dev/sql-statement-start-transaction)

3. Use Stale Read by `SET TRANSACTION READ ONLY AS OF TIMESTAMP` format.

```sql
SET TRANSACTION READ ONLY AS OF TIMESTAMP '2021-09-22 15:04:05';
BEGIN;
SELECT * FROM t  WHERE id = 1;
COMMIT;
// it also affects next query statement 
SET TRANSACTION READ ONLY AS OF TIMESTAMP '2021-09-22 15:04:05';
SELECT * FROM t  WHERE id = 1;
```

You can get detailed grammar `ebnf diagram` for `SET TRANSACTION READ ONLY AS OF TIMESTAMP` in this [document](https://docs.pingcap.com/tidb/dev/sql-statement-set-transaction)

4. Enable Stale Read with given max tolerant staleness in session:

```sql
// enable stale read with max tolerant 5 seconds ago in session
SET @@tidb_read_staleness='-5';
select * from t where id = 1;
```

Note that Stale Read will only affect the following query statement `SELECT`, it won't affect the interactive transaction, or updating statement like `INSERT`,`DELETE` and `UPDATE`

#### Detail of AS OF TIMESTAMP

`AS OF TIMESTAMP` provide several ways to define the staleness of `STALE READ`, you can find detail usage in this [document](https://docs.pingcap.com/tidb/dev/as-of-timestamp#syntax)

### Compatibility

This section we will talk about the compatibility between each Stale Read situations.

#### Forbidden Behavior

Stale Read by SET TRANSACTION Statement will make next interactive transaction or query with staleness timestamp. 

Thus it is not allowed that querying stale read statement after stale read by SET TRANSACTION statement like following:

```sql
mysql> set transaction read only as of timestamp now(1);
Query OK, 0 rows affected (0.00 sec)

mysql> select * from t as of timestamp now(2);
ERROR 8135 (HY000): invalid as of timestamp: can't use select as of while already set transaction as of
```

#### Statement Priority 

After enabling `tidb_read_staleness`, the following querying will use given staleness timestamp to get data from replicas.

And you can still use Stale Read with other forms with different timestamp:

```sql
SET @@tidb_read_staleness='-5';
// query data with max tolerant 5 seconds ago
select * from t where id = 1;
// query data with exact 10 seconds ago timestamp for this statement
select * from t as of timestamp now(10) where id = 1;
// query data with exact 10 seconds ago timestamp for next statement
set transaction read only as of timestamp now(10);
select * from t where id = 1;
```

---

### Design 2021 09 29 Merge Dumpling Into Tidb (`docs/design/2021-09-29-merge-dumpling-into-tidb.md`)

# Proposal: Merge Dumpling repo into TiDB

- Author(s): [okJiang](http://github.com/okJiang)
- Discussion: [Merge Dumpling repo into TiDB](https://internals.tidb.io/t/topic/434)
- Tracking Issue: [Tracking issue for merge Dumpling repo into TiDB](https://github.com/pingcap/tidb/issues/28775)

## Table of Contents

- [Introduction](#introduction)
- [Motivation](#motivation)
- [Milestones](#milestones)
   - [Milestone 1](#milestone-1)
   - [Milestone 2](#milestone-2)
   - [Milestone 3](#milestone-3)

## Introduction

[**Dumpling**](https://github.com/pingcap/dumpling) is a tool and a Go library for creating SQL dump from a MySQL-compatible database. It is intended to replace `mysqldump` and `mydumper` when targeting TiDB.

## Motivation

There are three primary reasons to merge:

1. DM suffers from dependency problem about TiDB and Dumpling. Concretely, DM depends on TiDB and Dumpling, while Dumpling depends on TiDB too. Every time DM updates Dumpling's version, TiDB's version will be updated along with Dumpling, which is unexpected.

2. Regression during a release. Dumpling releases along with TiDB even though they are in two repos. This results in conflicts are only exposed when testing failed during a release. For example, TiDB adds a new feature, which may cause a fail in Dumpling, which Dumpling isn't aware of. This issue cannot be found on their own tests, but the integration test of Dumpling and TiDB. This is very troublesome!

3. Reduce development costs. In TiDB, there is a function `export SQL` of TiDB similar with Dumpling.

After merged, we will:

1. Get rid of the DM's dependency problem;
2. Test in a monorepo and thus expose problem earlier;
3. Reduce duplicated code such as implementing `export SQL` for TiDB with Dumpling.

## Milestones

* Milestone 1: Merge **master** branch of Dumpling into TiDB repo.
* Milestone 2: Keep maintaining released branches until they are **end of maintenance**; e.g., release-4.0.
* Milestone 3: Migrate all useful content from Dumpling to TiDB repo, e.g. issues. And then **archives** Dumpling repo.

### Milestone 1

> This section refers to https://internals.tidb.io/t/topic/256.

To achieve milestone 1, we should do as follow:

1. `git checkout -b clone-dumpling && git subtree add --prefix=dumpling https://github.com/pingcap/dumpling.git master --squash`
2. `git checkout -b merge-dumpling` (we will update code in this branch)
3. Do necessary merging:
   1. merge go.mod, go.sum;
   2. update Makefile;
   3. update the import path for DM and Dumpling;
   4. merge CI scripts.
4. Create a MR from `okJiang:merge-dumpling` to `okJiang:clone-dumpling` for reviewing locally: (link if create)
5. Create true PR from `okJiang/merge-dumpling` to `pingcap:master` (link if create)
6. After reviewing, merge it to master

### Milestone 2

In this stage, we should do lots of maintenance in both repos:

* All increment activities happened in TiDB repo and give some corresponding guidance.
* Release new version (>= 5.3) from TiDB repo.
* Maintain existing active branches released for TiDB repo and Dumpling repo.

#### What increment activities should happen in TiDB repo?

* All created PRs, issues about Dumpling;
* When we want to fix an existing issue, we can create a new issue in TiDB repo with a link to original issue.

#### What guidance should we give?

* Post migrated notice on README.md like https://github.com/pingcap/br/blob/master/README.md
* When contributors create issues or PRs, we should tell them how to re-create in TiDB repo.

#### How do we release new version from TiDB repo?

* Follow TiDB's rule: https://pingcap.github.io/tidb-dev-guide/project-management/release-train-model.html

#### How do we maintain former active released branches?

> This section refers to https://internals.tidb.io/t/topic/256

If we want to cherry-pick the specific commit <COMMIT_SHA> to Dumpling repo. DO THE FOLLOWING THINGS

1. if the <COMMIT_SHA> not in <SPLIT_BRANCH>:
    1. In TiDB repo:
       1. git subtree split --prefix=dumpling -b <SPLIT_BRANCH>
       2. git checkout <SPLIT_BRANCH>
       3. git push <DUMPLING_REPO_REMOTE> <COMMIT_SHA>:refs/heads/<SPLIT_BRANCH>
2. In Dumpling repo:
   1. git fetch origin <SPLIT_BRANCH>
   2. git checkout master
   3. git checkout -b <pick_from_tidb>
   4. git cherry-pick <COMMIT_SHA>
3. Give a PR of merge <pick_from_tidb> to master.

> We will maintain release 4.0, 5.0, 5.1, 5.2 in Dumpling repo.

### Milestone 3

After all releases(<= 5.2) end of maintenance, it is time to archive Dumpling repo. But before the truly end, we should do some closing work:

* Migrate issues from Dumpling to TiDB
* ...

---

### Design 2021 09 29 Secure Bootstrap (`docs/design/2021-09-29-secure-bootstrap.md`)

# TiDB Design Documents

- Author(s): [morgo](http://github.com/morgo)
- Discussion PR: https://github.com/pingcap/tidb/pull/28482
- Tracking Issue: https://github.com/pingcap/tidb/issues/28481

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Test Design](#test-design)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
* [Unresolved Questions](#unresolved-questions)

## Introduction

Currently, TiDB will create a root user with no password and bind to `0.0.0.0/::`. This is a potential security issue if users do not have a firewall configured correctly, or if a rogue actor has local access.

This document introduces the `--intialize-secure` and `--initialize-insecure` bootstrap options. The current behavior is equivalent to `--initialize-insecure`, but the intention is to change the default to secure **once** it is determined stable.

## Motivation or Background

The motivation for this change is to improve the default security of TiDB. The current default is insecure, and requires additional steps to be taken by users to secure TiDB.

The design attempts to make the change with the least breakage possible. However, there will be some impact to usability.

## Detailed Design

The current bootstrap (to be referred to as `--initialize-insecure`) creates a root user as follows. This will remain unchanged:

```sql
CREATE USER 'root'@'%' IDENTIFIED WITH 'mysql_native_password' AS '' REQUIRE NONE PASSWORD EXPIRE DEFAULT ACCOUNT UNLOCK;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
```

The `--initialize-secure` bootstrap will instead create a user based on the OS user. For example, with an OS user of `ubuntu`:

```sql
CREATE USER 'ubuntu'@'localhost' IDENTIFIED WITH 'auth_socket' REQUIRE NONE PASSWORD EXPIRE DEFAULT ACCOUNT UNLOCK;
GRANT ALL PRIVILEGES ON *.* TO 'ubuntu'@'localhost' WITH GRANT OPTION;
```

After TiDB has bootstrapped, the user will be able to login and create additional users:

```bash
mysql -S /tmp/tidb.sock
..
mysql> CREATE USER 'root'@'%' IDENTIFIED BY 'securePassword';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
```

### Required Supporting Features

In order to add the `--initialize-secure` bootstrap option, the following supported features are required:

1. Support for Socket Authentication (`auth_socket`) [PR in Review](https://github.com/pingcap/tidb/pull/27561)
2. Stale socket files are automatically cleaned up on server start [PR Merged](https://github.com/pingcap/tidb/pull/27886)
3. TiDB listens on both TCP **and** unix socket by default [PR in Review](https://github.com/pingcap/tidb/pull/28486)
4. Auth plugin can be changed with ALTER/CREATE [PR Draft](https://github.com/pingcap/tidb/pull/28468)

## Test Design

Integration tests are required to verify the behavior of the `--initialize-secure` bootstrap option works with other components (such as TiDB Dashboard, Operator, DBaaS, TiUP).

Some components (such as DBaaS) may choose to explicitly use `--initialize-insecure` to bootstrap, and then alter the root password to a secure password. This is similar to how bootstrapping works in MySQL with various installation methods.

There are no risks on upgrade/downgrade testing, because the change will be implemented in the bootstrap process only. This change is not intended to be cherry picked to existing GA versions, as this will cause compatibility issues with TiDB Dashboard (confirmed by TiDB Dashboard team).

## Impacts & Risks

The design choice of `auth_socket` is based on our current requirement of only supporting unix-like operating systems, and not needing to support Windows. This is a reasonable choice, as we do not expect to support Windows in the future. There might be some minor added complexity if we currently do not handle cases well such as the socket file already existing.

Adding the option `--initialize-secure` itself does not add risk, but enabling it by default will add risk as it is a difference in behavior. This design tries to minimize the risk, but it is a large change. There is a risk if we don't update all the documentation and communicate the change effectively, it will become a support issue for new users.

## Investigation & Alternatives

The alternative implementation is to generate a random password with `--initialize-secure`. This is the approach that is used by MySQL. This has been discussed, and rejected.

## Unresolved Questions

- Should the `auth_socket` user on the MySQL-side be the OS-user, or `root`. It is possible to do either. We need to discuss what is the less of 2 evils:
  - Having 2 "roots" (localhost, and %).
  - Having a default user that is different for everyone, with instructions to create a root account.

---

### Design 2021 10 09 Select For Update Of Tables (`docs/design/2021-10-09-select-for-update-of-tables.md`)

# Proposal: Support `SELECT FOR UPDATE OF TABLES`

- Author(s): [jackysp](https://github.com/jackysp)
- Tracking Issue: https://github.com/pingcap/tidb/issues/28689

## Abstract

If specific tables are named in a locking clause, then only rows coming from those tables are locked.
Any other tables used in the SELECT are simply read as usual.

## Background

In a multi-table join scenario, simply using the for update clause locks all the rows read in the tables participating in the join.
The lock granularity is too coarse, and some of the tables participating in the join may not need to be subsequently updated.
In MySQL 8.0, the `of tables` option was introduced to support locking only the specified tables.

## Proposal

### Parser

The first thing is that the parser should support the `of tables` syntax.
This has not been supported before. Store the table names in `SelectLockInfo`.

### Filter Keys

This feature is achieved by storing the information in `StmtCtx`
and using the table names in StmtCtx to filter the keys that need to be locked
when reading all the keys that need to be locked.

## Compatibility

Compatibility with MySQL 8.0 has been enhanced here.
Since the `of tables` syntax was not supported before,
it does not break any compatibility.

---

### Design 2021 10 20 Table Attributes (`docs/design/2021-10-20-table-attributes.md`)

# Proposal: Table Attributes

- Author(s): [rleungx](https://github.com/rleungx)
- Tracking Issue: https://github.com/tikv/pd/issues/3839

## Background

Recently, we have encountered such a case that the scattered region of a table/partition is merged before inserting the data. We cannot prevent it from happening right now since we are not able to control the scheduling behavior at the table/partition level. However, it will sometimes lead to a serious hot spot problem. Under this circumstance, we are going to support the attributes for the table/partition so that we can handle this case. And we have designed a new mapping mechanism to establish a relationship between tables/partitions and regions which allows the user to specify the attributes to instruct the scheduling of PD. To make use of this feature to manage the table/partition level scheduling easily, we plan to introduce a new syntax in SQL.

## Proposal

### Parser

This feature needs `parser` to support the `ATTRIBUTES` keyword. And we need to introduce two new kinds of SQL syntax for both table and partition.

For the table, we can use the following SQL to add one or multiple attributes for the table `t`:

```sql
ALTER TABLE t ATTRIBUTES[=]'key=value[, key1=value1...]';
```

And reset it by using:

```sql
ALTER TABLE t ATTRIBUTES[=]DEFAULT;
```

For partition `p`, the way is almost the same as the table:

```sql
ALTER TABLE t PARTITION p ATTRIBUTES[=]'key=value[, key1=value1...]';
```

And reset it by using:

```sql
ALTER TABLE t PARTITION p ATTRIBUTES[=]DEFAULT;
```

The attributes here can be any string that doesn't contain the reserved words. 

There is no need for TiDB to know about the actual meaning of these attributes. The only thing that TiDB should do is to construct a request which contains the ID, the table/partition key range, the attributes, etc. Then synchronizing it with PD through the DDL job. All of these will be persisted in PD.



### Display Attributes

we add a new table in the `INFORMATION_SCHEMA` named `ATTRIBUTES`. If necessary, we can also support syntax like

```sql
SHOW ATTRIBUTES FOR [{DATABASE|SCHEMA} s][TABLE t][PARTITION p];
```
or 
```
SHOW CREATE TABLE t;
```

At least we should support one way to show the attributes. Here is an example:

```
/* Detailed source-code truncated for AI context efficiency. */
```

### DDL Management
Here are the concrete behaviors when doing the DDL operations with a table/partition having the attributes.

#### Drop Clause 
+ For the drop table operation, the attributes will be deleted once the GC has finished
+ For the drop schema and partition operation, the attributes will be deleted immediately

#### Truncate Clause
+ For the truncate table operation, both table range and partition range of attributes will be updated.
+ For the truncate partition operation, the partition range of attributes will be updated.

#### Recover/Flashback Clause
+ The attributes will be kept as the old values after the recover/flashback process succeed.

#### Exchange Clause
+ The attributes will be exchanged including the ID and ranges.

### Privilege Management

Privilege management is quite straightforward:

* `ALTER TABLE` statement requires `Alter` privilege
* `information_schema.attributes` only shows the attributes on the objects that visible to the current user
* `ADMIN SHOW DDL` requires `Super` privilege

### Inheritance
Consider that if we add attributes for a table, all partitions of that table will inherit the attributes by default. As for `CREATE TABLE x LIKE y`, `x` won't inherit attributes from `y`.

### Priority
We may support adding different attributes for both tables and partitions at the same time. For example, the attribute could be `merge_option=deny` on the table level but `merge_option=allow` on the partition level in the same table.
In this case, we assume that the priority of the partition is higher than the table, so the final results could be that only some partitions can be merged, but the rest cannot.

Another thing that should be noticed is that if we have already set the attributes for a partition, then setting the new attributes for the table which includes the partition will override the attributes of the partition.

### Compatibility
There is no compatibility issue.

### Implementation
In the early stage, we are going to introduce `merge_option` attribute to indicate if a table/partition can be merged. When the `merge_option` equals `deny`, PD will prevent the table or partition from being merged. Otherwise, it will be merged once it is beyond the `split-merge-interval` under the PD default settings.

---

### Design 2021 12 08 Instance Scope (`docs/design/2021-12-08-instance-scope.md`)

# TiDB Design Documents

- Author(s): [morgo](http://github.com/morgo)
- Discussion PR: https://github.com/pingcap/tidb/pull/30558
- Tracking Issue: https://github.com/pingcap/tidb/issues/30366

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Behavior Changes](#behavior-changes)
* [Documentation Changes](#documentation-changes)
* [Test Design](#test-design)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
* [Unresolved Questions](#unresolved-questions)

## Introduction

Currently, TiDB has two primary methods of configuration:

- The configuration file (in `.toml` format) ([Docs](https://docs.pingcap.com/tidb/stable/tidb-configuration-file))
- Using MySQL compatible system variables (`SET GLOBAL sysvar=x`, `SET SESSION sysvar=x`) ([Docs](https://docs.pingcap.com/tidb/stable/system-variables))

Both the **semantics** and **naming conventions** differ between these two methods:

1. Configuration file settings only apply to a single TiDB server instance. Making changes to settings managed by the configuration file requires restarting the TiDB server.
2. System variables _natively_ manage settings that have _session_ (connection) or _global_ (cluster-wide) scope. However, some _session_ scoped variables are used to allow instance configuration. This is not a feature that is natively supported, and the usage is often confusing.
3. The configuration file uses a hierarchy of sections such as `[performance]` or `[experimental]`.
4. System variables use a flat naming convention (but often use a prefix of `tidb_feature_XXX`). Thus mapping between the two is not straight forward.

This proposal introduces _native_ support for `INSTANCE` scoped variables, such that system variables offer the superset of functionality of configuration files. It does this using a much simplified implementation from earlier proposals: an individual system variable **must not** permit both `GLOBAL` and `INSTANCE` scope. Implementing this restriction is key to this proposal; since it avoids a confusing set of precedence rules which are hard to understand. For alternative proposals see "investigation and alternatives".

## Motivation or Background

The motivation for this proposal is ease of use and maintainability:

1. It's not clear if each setting should be a configuration file setting or a system variable (we usually choose system variables, but there is no clear rule). After this proposal is implemented, we can make every setting available as a system variable (even if read-only).
2. We are being asked to make additional configuration file settings dynamically configuration (via a system variable). When we do this, the naming is inconsistent. After this proposal is implemented, we can allow the `.toml` file to support an `[instance]` section where the flat named for system variables can be used. This makes it identical to how system variables are configured in MySQL.
3. The current system is hard for users. It's hard to explain the two systems, and hard to explain the differences between them. Often "INSTANCE" scoped system variables are incorrectly documented as `SESSION`, since it's not a native behavior. Explaining how `SESSION` scope is hijacked is difficult for MySQL users to understand, because usually changes in a different session should not affect your session.

## Detailed Design

### Stage 1: Initial Implementation

From a user-oriented point of view, setting an instance scoped sysvar is the same as setting a `GLOBAL` variable:

```sql
SET GLOBAL max_connections=1234;
```

Because `INSTANCE` and `GLOBAL` are mutually exclusive, the only semantic difference is that changes to `INSTANCE` scoped variables are not persisted and are not propagated to other TiDB servers.

From a sysvar framework perspective the changes required are quite minimal. A new scope is added, and validating if setting permits `GLOBAL` scope also permits `INSTANCE` scope:

```
+++ b/sessionctx/variable/sysvar.go
@@ -56,6 +56,8 @@ const (
        ScopeGlobal ScopeFlag = 1 << 0
        // ScopeSession means the system variable can only be changed in current session.
        ScopeSession ScopeFlag = 1 << 1
+       // ScopeInstance means it is similar to global but doesn't propagate to other TiDB servers.
+       ScopeInstance ScopeFlag = 1 << 2
 
        // TypeStr is the default
        TypeStr TypeFlag = 0
@@ -257,6 +259,11 @@ func (sv *SysVar) HasGlobalScope() bool {
        return sv.Scope&ScopeGlobal != 0
 }
 
+// HasInstanceScope returns true if the scope for the sysVar includes global or instance
+func (sv *SysVar) HasInstanceScope() bool {
+       return sv.Scope&ScopeInstance != 0
+}
+
 // Validate checks if system variable satisfies specific restriction.
 func (sv *SysVar) Validate(vars *SessionVars, value string, scope ScopeFlag) (string, error) {
        // Check that the scope is correct first.
@@ -313,7 +320,7 @@ func (sv *SysVar) validateScope(scope ScopeFlag) error {
        if sv.ReadOnly || sv.Scope == ScopeNone {
                return ErrIncorrectScope.FastGenByArgs(sv.Name, "read only")
        }
-       if scope == ScopeGlobal && !sv.HasGlobalScope() {
+       if scope == ScopeGlobal && !(sv.HasGlobalScope() || sv.HasInstanceScope()) {
```

The session package handles loading/saving `GLOBAL` variable values. It will need minor changes to make `INSTANCE` Scope a noop operation (since persistence is not supported, and in the initial implementation a `GetGlobal()` function will be used to retrieve the instance value:

```
/* Detailed source-code truncated for AI context efficiency. */
```

A "non-native" `INSTANCE` variable can be changed to a native one as follows:

```
+       {Scope: ScopeInstance, Name: TiDBGeneralLog, Value: BoolToOnOff(DefTiDBGeneralLog), Type: TypeBool, skipInit: true, SetGlobal: func(s *SessionVars, val string) error {
                ProcessGeneralLog.Store(TiDBOptOn(val))
                return nil
-       }, GetSession: func(s *SessionVars) (string, error) {
+       }, GetGlobal: func(s *SessionVars) (string, error) {
                return BoolToOnOff(ProcessGeneralLog.Load()), nil
        }},
```

This introduces a compatibility issue, since users who have previously configured instance scope with `SET [SESSION] tidb_general_log = x` will receive an error because the scope is wrong. This can be fixed by adding a legacy mode to the sysvar framework which allows `INSTANCE` scoped variables to be set with either `SET GLOBAL` or `SET SESSION`:

```sql
SET GLOBAL tidb_enable_legacy_instance_scope = 1;
```

We can default to `TRUE` for now, but should revisit this in the future.

### Stage 2: Mapping All Configuration File Settings to System Variables

The second stage is to map all configuration file settings to system variable names. In MySQL any configuration file setting is also available as a system variable (even if it is read only), which makes it possible to get the configuration of the cluster with `SHOW GLOBAL VARIABLES`. Once this step is complete, it should also be possible to offer an `[instance]` section of the configuration file which accepts the system variable names (and finally consistent naming between the two systems). We can then modify the example configuration files to be based on the flat `[instance]` configuration:

```
# tidb.toml
[instance]
max_connections = 1234
tidb_general_log = "/path/to/file"
```

The default will be that we map variables as read-only, so we don't need to think about the specific cases (i.e. you can't easily change the socket or port). This helps us achieve completeness first, and then we can then evaluate which ones can be made dynamic.

The mapping system should consider all current instance variable mappings such as `log.enable-slow-log` to `tidb_enable_slow_log`. The earlier instance scoped variables proposal has an [example mapping table](https://docs.google.com/document/d/1RuajYAFVsjJCwCBpIYF--9jtgxDZZcz3cbP-iVuLxJI/edit?n=2020-09-15_Design_Doc_for_Instance_Variables#) which can be used as a guideline for how to create new system variable names.

Because variables can be configured through either an "sysvar name" (under `[instance]`) or a hierarchical name, we will need to decide which is the alias versus the actual name (the actual name appears in results like `SELECT * FROM INFORMATION_SCHEMA.CLUSTER_CONFIG`). I propose for this stage the original name is still the source of truth, but in refactoring (stage 3) we switch it.

### Stage 3: Refactoring

The use of a `GetGlobal()` and `SetGlobal()` func for each instance scoped system variable is not ideal. It is possible to refactor the system variable framework so that instance scope is stored in a map, and the values are updated automatically by `SET GLOBAL` on an instance scoped variable. On startup, as the configuration file is parsed it will update the values in the map. This seems like a better approach than the current use of Setters/Getters, and because there is a prescribed way of doing it we can correctly handle the data races that are common with our current incorrect usage of calling `config.GetGlobalConfig()`.

Thus, the source of truth for instance scoped variables moves from the `config` package to another part of the server (likely `domain`). See [issue #30366](https://github.com/pingcap/tidb/issues/30366).

Because at this stage the source of truth is now no longer the `config` package, we will also need to decide how to handle features like `INFORMATION_SCHEMA.CLUSTER_CONFIG`. If it refers to the config file, it will not necessarily reflect the current configuration of the cluster. Because every instance setting will now have a system variable name (which becomes the unified name), I recommend that we deprecate `CLUSTER_CONFIG` for TiDB. We can change `CLUSTER_CONFIG` to read from the new source of truth and maintain both for some versions to support upgrades.

## Behavior Changes

There are **very few** known scenarios where a system variable is *currently both* instance and global scoped, but each of these will require behavior changes. Here is a script to detect them:

```
package main

import (
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/pingcap/tidb/sessionctx/variable"
)

func main() {
	for _, v := range variable.GetSysVars() {
		if v.HasGlobalScope() && v.HasSessionScope() && (v.GetSession != nil || v.SetSession != nil) && (v.GetGlobal != nil || v.SetGlobal != nil) {
			fmt.Printf("%s\n", v.Name)
		}
	}
}
```

**Output:**

```
tidb_store_limit
tidb_stmt_summary_internal_query
tidb_enable_stmt_summary
tidb_stmt_summary_max_sql_length
tidb_stmt_summary_max_stmt_count
tidb_capture_plan_baselines
tidb_stmt_summary_refresh_interval
tidb_stmt_summary_history_size
```

Changes can be grouped into the following:

1. `tidb_store_limit`: This has now been converted to global-only, see [issue #30515 (merged)](https://github.com/pingcap/tidb/issues/30515).
2. `tidb_stmt_summary_XXX`, `tidb_enable_stmt_summary` and `tidb_capture_plan_baselines` (features work together): The recommendation discussed with the feature maintainers is to convert to global only.

The change to `tidb_store_limit` is unlikely to affect users, since the feature was not working correctly. However, the change to statement summary and capture plan baselines is a behavior change which might affect some users.

## Documentation Changes

For the purposes of user-communication we don't need to use the terminology `INSTANCE`. We will remove more of the confusion by instead referring to the difference between these as whether it "persists to [the] cluster". This also aligns closer to the syntax that users will be using. Consider the following example changes which are easier to read (the current text also doesn't actually explain that to set an `INSTANCE` variable you must use `SET SESSION`, so it actually communicates a lot more in fewer words):

```
/* Detailed source-code truncated for AI context efficiency. */
```sql
 # These two identical statements change a session variable
@@ -26,9 +24,9 @@ SET  GLOBAL tidb_distsql_scan_concurrency = 10;
 
 > **Note:**
 >
-> Executing `SET GLOBAL` applies immediately on the TiDB server where the statement was issued. A notification is then sent to all TiDB servers to refresh their system variable cache, which will start immediately as a background operation. Because there is a risk that some TiDB servers might miss the notification, the system variable cache is also refreshed automatically every 30 seconds. This helps ensure that all servers are operating with the same configuration.
+> Several `GLOBAL` variables persist to the TiDB cluster. For variables that specify `Persists to Cluster: Yes` a notification is sent to all TiDB servers to refresh their system variable cache when the global variable is changed. Adding additional TiDB servers (or restarting existing TiDB servers) will automatically use the persisted configuration value. For variables that specify `Persists to Cluster: No` any changes only apply to the local TiDB instance that you are connected to. In order to retain any values set, you will need to specify them in your `tidb.toml` configuration file.
 >
-> TiDB differs from MySQL in that `GLOBAL` scoped variables **persist** through TiDB server restarts. Additionally, TiDB presents several MySQL variables as both readable and settable. This is required for compatibility, because it is common for both applications and connectors to read MySQL variables. For example, JDBC connectors both read and set query cache settings, despite not relying on the behavior.
+> Additionally, TiDB presents several MySQL variables as both readable and settable. This is required for compatibility, because it is common for both applications and connectors to read MySQL variables. For example, JDBC connectors both read and set query cache settings, despite not relying on the behavior.
 
 > **Note:**
 >
@@ -47,6 +45,7 @@ SET  GLOBAL tidb_distsql_scan_concurrency = 10;
 ### allow_auto_random_explicit_insert <span class="version-mark">New in v4.0.3</span>
 
 - Scope: SESSION | GLOBAL
+- Persists to cluster: Yes
 - Default value: `OFF`
 - Determines whether to allow explicitly specifying the values of the column with the `AUTO_RANDOM` attribute in the `INSERT` statement.
 
@@ -166,7 +165,8 @@ mysql> SELECT * FROM t1;
 
 ### ddl_slow_threshold
 
-- Scope: INSTANCE
+- Scope: GLOBAL
+- Persists to cluster: No
 - Default value: `300`
 - Unit: Milliseconds
 - Log DDL operations whose execution time exceeds the threshold value.
```

What this does mean is that each variable that includes `GLOBAL` or `INSTANCE` scope needs a new line added in Docs. But this can be [auto-generated](https://github.com/pingcap/docs/pull/5720) from the sysvar source code.

## Impacts & Risks

The biggest risk is that we can not agree on a reduced scope of implementation and the project extends to cover increased scope. Configuration management is a classic example of a [bikeshed problem](https://en.wikipedia.org/wiki/Law_of_triviality), and we will likely need to make some tradeoffs to get anywhere.

Many of the alternatives are difficult to implement because they break compatibility (we need to live with `GLOBAL` means cluster `GLOBAL`, and there is no `SET CLUSTER`) or they break rolling upgrade scenarios because we currently have no specific rules of the minimum version of TiDB which can be upgraded from.

## Investigation & Alternatives

- There is no equivalent functionality to reference in MySQL since it does not have the native concept of a cluster _in the context of configuration_.
- An [earlier proposal](https://docs.google.com/document/d/1RuajYAFVsjJCwCBpIYF--9jtgxDZZcz3cbP-iVuLxJI/edit) for `INSTANCE` scope, with rules for precedence (same author)
- CockroachDB has cluster level settings and node-level settings. Most settings are cluster level, and [node-level](https://www.cockroachlabs.com/docs/v21.2/cockroach-start) needs to be parsed as arguments when starting the server.

### SET INSTANCE syntax

A small behavior change (still with the restriction that `INSTANCE` and `GLOBAL` are mutually exclusive) proposes adding `SET INSTANCE` as explicit syntax to set an instance-scoped variable. This would require the following modifications to be complete:
- `SHOW INSTANCE VARIABLES` will need to return variables that have `NONE` or `INSTANCE` scope (and `SHOW VARIABLES` continues to return all variables).
- The parser will need to support `SET INSTANCE` syntax and the `@@instance.variable` syntax
- Various parser ast code will also need modifying because a boolean can no longer reflect the scope.

The advantage of this proposal is that the documentation and usage is clearer. The disadvantage is that because MySQL does not have an instance scope (global scope in MySQL is instance-like) it could create strange behaviors with compatibility sysvars which are implemented. This **only** affects `INSTANCE` variables which are *not already* `ScopeNone` (so Port, Socket, GrantTables, LogBin are not affected). The only currently known example that is affected is `max_connections`, which is currently a noop in system variables, but available in the configuration file as `max-server-connections` (it is presumed it would be [mapped](https://docs.google.com/document/d/1RuajYAFVsjJCwCBpIYF--9jtgxDZZcz3cbP-iVuLxJI/edit?n=2020-09-15_Design_Doc_for_Instance_Variables#) to `max_connections` in Stage 2).

This means that `SET GLOBAL max_connections` would need to return an error in TiDB, because the correct syntax is `SET INSTANCE max_connections`. There is a known failover use-case to execute `SET GLOBAL max_connections = 1` + `SET GLOBAL [super_]read_only = 1` to disable writes. However, this already does not work in TiDB as there is no support for `SET GLOBAL [super_]read_only=1`. Thus, removing this compatibility does not appear to be a blocking issue.

However, the IBG support team rejects this proposal based on the expectation that there will be further tool compatibility issues not yet discovered. As MySQL does not have `SET INSTANCE` scope, users will also not be used to using this syntax.

## Unresolved Questions

- None

---

### Design 2021 12 09 TiDB Log Based Incremental Backup (`docs/design/2021-12-09-TiDB-log-based-incremental-backup.md`)

# TiDB Log-based Incremental Backup

- Author(s): @kennytm
- Discussion: N/A
- Tracking Issue: [#29501](https://github.com/pingcap/tidb/issues/29501)

## Table of Contents

* [Introduction](#introduction)
* [Background](#background)
* [Goals](#goals)
    + [Non-Goals for Version 1](#non-goals-for-version-1)
* [User Scenarios / Story](#user-scenarios--story)
* [Design](#design)
    + [BR](#br)
        - [Start task](#start-task)
        - [Check task status](#check-task-status)
        - [Stop task](#stop-task)
        - [TiKV](#tikv)
    + [Stop](#stop)
    + [Pause and Resume](#pause-and-resume)
    + [Output format](#output-format)
    + [Restore](#restore)
        - [Restore backups](#restore-backups)
    + [Merge (out of scope in v1)](#merge-out-of-scope-in-v1)
        - [Merge backups](#merge-backups)
    + [Error scenarios](#error-scenarios)
        - [Scaling out](#scaling-out)
        - [Crashing](#crashing)
        - [Network partition](#network-partition)
    + [Task management](#task-management)
* [Alternatives & Rationale](#alternatives--rationale)
* [Trivia](#trivia)

## Introduction 

<img src="imgs/log-backup-architecture.jpg" style="width:6.26772in;height:4.69444in" />

This document introduces a novel solution for backing up incremental transactional data within the TiKV server.

## Background

The ability of commercial databases to handle emergencies and accidents is a basic requirement. When a disaster occurs, we must restore the database with minimal data loss and recovery time. Various factors such as exercise, recovery time, operability and operation and maintenance.

## Goals

* Support 200T TiDB cluster backup (66 TiKVs)
* Combine log-based backup and full backup to reach
    - RTO < 6h
    - RPO < 5 min
* Support Point in Time Recovery
* Log-based backup has nearly non impact on TiDB clusters.
* Support cluster/table level backup
* Support encrypt and compress data.

### Non-Goals for Version 1

* We do not support restoring into existing tables.
    - In version 1, we require a non-empty cluster or an empty table.
        * Restore requires a completely empty cluster to begin with, so that the Table IDs can match up and the StartTS/CommitTS are correct.
        * The initial "full restore" must retain the original table ID.
        * We can perform RewritePrefix/TS but it slows the process down. We do not expect normal public service until the restore is complete
    - The data may be in an inconsistent state, and the cluster is configured to "import mode".

## User Scenarios / Story

* Users want to ensure business continuity
    - when the database fails and cannot be restored within a certain period of time. The user quickly deploys a database of the same version as the production database, and restores the backup data to the database to provide external services;
* User services need to be able to restore the data at a certain point in the past to the new cluster to meet the business needs of judicial inspections or audits

## Detailed Design

### BR

A new subcommand is added to BR to control incremental backup tasks. (Provide a TiDB HTTP API as well, see the spec.)

#### Start task

```console
$ br stream start [task_name] -u 10.0.0.1:2379 -s 's3://bucket/path' [--start-ts 123456789] ...

Starting task <task_name> from ts=123456789...

Store 1: ok (next_backup_ts =222222222).
Store 2: ok (next_backup_ts =333333333).
Store 3: ok (next_backup_ts =444444444).
Store 8: ok (next_backup_ts =123456789).

Started!
```

#### Check task status

```console
$ br stream status task_name -u 10.0.0.1:2379

Checking status of <task_name>...

Store 1: error, task completed or not found.
Store 2: ok (next_backup_ts =900000000).
Store 3: ok (next_backup_ts =911111111).
Store 8: ok (next_backup_ts =922222222).
```

#### Stop task

```console
$ br stream stop task_name -u 10.0.0.1:2379

Stopping task <task_name>...

Store 1: error, task completed or not found.
Store 2: ok (next_backup_ts =987654321).
Store 3: ok (next_backup_ts =989898989).
Store 8: ok (next_backup_ts =987987987).

Stopped at --lastbackupts=987654321.

$ br stream stop task_name -u 10.0.0.1:2379

Stopping task <task_name>...

Store 1: error, task completed or not found.
Store 2: error, task completed or not found.
Store 3: error, task completed or not found.
Store 8: error, task completed or not found.

Failed to stop the task, maybe it is already stopped. Check the TiKV logs for details.
```

#### TiKV

* We will reuse the CmdObserver<E> trait. We may either embed the logic entirely inside cdc:: Delegate, or create a new StreamBackupObserver. Prefering the latter for separation of concern.
    - We probably don't need to implement RoleObserver + RegionChangeObserver. Both are used to monitor region-not-found or leader-changed errors to propagate to downstream delegates. In backup streaming we simply stop writing to the buffers.
    - If possible we may reuse the resolved_ts crate to fetch the ResolvedTS instead of making an observer our own to reduce impact.
* Support table filtering
    - We choose to enable table filtering during backup
    - The problem about table filtering is we only have a <Table ID → Table Name> map with txn in meta.go during log backup.(e.g. mDB1_Table20 -> []byte(tableInfo)), and some operations may change the map. For example, RENAME then TRUNCATE table. we may get such sequences.
       * time 1: <21, Test_A>
       * time 2: <21, Test_B>(RENAME)
       * time 3: <22, Test_B>(TRUNCATE)

    - To Solve this problem, we need TiKV to watch all meta key changes during a task.
        * BR starts a task
            * BR puts a table-filter into a task
            * BR calculates the key range from the given table-filter. and puts the key range space into PD/Etcd.
            * BR puts the task into PD/Etcd.

        * Every TiKV node watches the task and key range space in the task.
            * when the task changes key range. such as TRUNCATE. TiKV should be aware of this change and stop observing old ranges and start observing new key ranges. when the new key range starts. TiKV needs an incremental scan to get all related keys.

        * Meta Key
            * Every Task should watch the meta key range carefully. We had such meta keys for each table.
                * DB key
                * Table key
                * AutoTableID key(ignore. calculate later)
                * AutoRandom key(ignore.calculate later)
                * Sequence/Sequence cycle key(ignore for version 1)
                * Policy key (ignore for version 1)
                * DDL history key (ignore for not use)
            * BR will calculate meta key range at the beginning of the task.

        * Handle TiDB DDL
            * Create Table/Index within table-filter
                * update the task and calculate a new range.
            * Truncate Table within table-filter
                * update the task and calculate a new range.
            * Drop Table/Index
                * update the task.
            * Rename Table
                * rename table out of table-filter
                    * ignore. let restore handle this situation.
                * rename table into table-filter.
                    * ignore. since we didn’t backup this table at the beginning.

* Memory control
    - Every TiKV node flush events independently.
    - Flush to local storage directly.
       * if backup to s3, we have a separate thread push data from local storage to s3 at every 5 minutes.
    - Need a flush control when the disk is full.

<img src="imgs/log-backup-data-flow.jpg" style="width:6.26772in;height:4.69444in" />

* Rollback
    - The Rollbacks do the real delete in rocksdb according to the txn.
    - The Rollbacks only have the StartTS.
    - So we must apply rollback events at the end of one restore task. we must ensure that the prewrite happened before rollback.


### Stop

Stopping a task causes all collected events not yet flushed to be lost.

### Pause and Resume

Pausing a task will make it stop observing the TiKV changes, record the
ResolvedTS of every involved region, and immediately flush the log files
into external storage. Then it sleeps.

Resuming a task is like re-subscribing to a CDC stream, like running br
stream start «TaskName» --backupts «PrevRTS». All KVs between PrevRTS
and current CommitTS will be scanned out and logged as a single batch.

### Output format

-   There are kinds of events we can send out: "BR-like" or "CDC-like".
    -   "BR-like" generates events below the MVCC/Percolator abstraction, and is closer to BR's SST format with content like
        -   `Put(cf="default", key="zt1\_r1«StartTS»", value="encoded\_value")`
        -   `Put(cf="write", key="zt1\_r1«CommitTS»", value="P«StartTS»")`
        -   `Delete(cf="default", key="zt1\_r1«StartTS»")`
        -   `Put(cf="write", key="zt1\_r1«CommitTS»", value="D«StartTS»")`
    -   "CDC-like" is above the MVCC abstraction and is closer to CDC's format with content like
        -   `Prewrite(start\_ts=«StartTS», op=Put(key="t1\_r1", value="encoded\_value"))`
        -   `Commit(start\_ts=«StartTS», commit\_ts=«CommitTS», key="t1\_r1")`
        -   `Prewrite(start\_ts=«StartTS», op=Delete(key="t1\_r1"))`
        -   `Commit(start\_ts=«StartTS», commit\_ts=«CommitTS», key="t1\_r1")`
-   We choose the BR-like form since it is compatible with RawKV and is easier to merge into a Full Backup. But there seems to be worry that if a lock\_cf lock is exposed in the middle it will break the SI guarantee?
-   The received events are appended to local log files per task (+ fsync), sharded by prefix of the key.
    -   If the first byte of the key is "t" ("zt"), shard by the first 9 (11) bytes.
    -   Otherwise ("m"), place it into its own file.
    -   We do not distinguish by region (shall we?).
    -   Content should be encoded as a stream of protobuf messages or other efficient binary format.
-   The current ResolvedTS is attached to the set of local log files.
-   Every 5 minutes or 128 MiB of total data (whichever sooner), we move the log files into external storage atomically.
    -   May need to ensure we don't break a transaction into two files? (what if huge transactions?)
    -   Files are renamed «Storage://Prefix»/«PhysicalTableID:%02x»/«RegionIDAndMinTSOfTheLog:016x»/«StoreID».log
    -   The file should be generated for each region. If the region contains multi tables, split it by table.
    -   The metadata would be the index of those files.
    -   We may compress (producing .log.lz4) or encrypt the file (producing .log.lz4.aes256ctr) on demand (out of scope for now).
    -   Additionally we include a metadata file «Storage://Prefix»/stream-metas/«???:016x».meta recording the initial SHA-256 checksum, encryption IV, number of entries, range of ResolvedTS/StartTS/CommitTS and range of keys of every file involved.

```protobuf
enum FileType {
    Delete = 0;
    Put = 1;
}

message DataFileInfo {
    // SHA256 of the file.
    bytes sha_256 = 1;
    // Path of the file.
    string path = 2;
    int64 number_of_entries = 3;
    
    /// Below are extra information of the file, for better filtering files.
    // The min ts of the keys in the file.
    uint64 min_ts = 4;
    // The max ts of the keys in the file.
    uint64 max_ts = 5;
    // The resolved ts of the region when saving the file.
    uint64 resolved_ts = 6;
    // The region of the file.
    int64 region_id = 7;
    // The key range of the file.
    // Encoded.
    bytes start_key = 8;
    bytes end_key = 9;
    // The column family of the file.
    string cf = 10;
    // The operation type of the file.
    FileType type = 11;

    // Whether the data file contains meta keys(m prefixed keys) only.
    bool is_meta = 12;
    // The table ID of the file contains, when `is_meta` is true, would be ignored.
    int64 table_id = 13;
    
    // It may support encrypting at future.
    reserved "iv";
}
```

-   Not embedding metadata into \*.log files, so the BR controller can dispatch the restore tasks without downloading tons of files.
-   Similar to backup meta, we may split each \*.meta file into multiple levels if it becomes too large.
-   **What happens if upload still fails after several retries?**
    -   Pause the task and report an error which br stream status can see and Prometheus can receive.

### Restore

#### Restore backups

```console
$ br restore full -s 's3://bucket/snapshot-path' -u 10.0.5.1:2379

$ br stream restore -u 10.0.5.1:2379 \
   -s 's3://bucket/path' \
   [--startts 123456789] \
   [--endts 987654321] \
   [--checksum] \
   [-f 'db3.*']
```

1.  Restoring the full backup is unchanged, using the br restore command.
2.  To restore the BR-like incremental backup, the restore API has to perform the following:
    1.  Reads the last «MRTS».meta file just before --endts to obtain the region distribution of the keys.
    2.  Perform batch-split so region distribution is the same as the end state (only do this if the existing number of regions &lt;&lt; number of regions in the archive).
    3.  "Lock" the scheduler, disallow region moving/splitting/merging.
    4.  For every «MRTS».meta file (in parallel),
        1.  Translates the -f table name filter into key range filter.
        2.  For every log file (in parallel),
            1.  If a log file's MaxCommitTS ≤ --startts or MinStartTS > --endts, skip the log file.
            2.  If a log file's key range is filtered out, skip the log file.
            3.  Gets all regions intersecting with the file's key range.
            4.  Tell the ***leader*** of every region to download and apply the log file, along with:
                1.  --startts and --endts
                2.  Key range filter
                3.  SHA-256 checksum (null if --checksum=false)
    5.  Done.
3.  On the TiKV side, after receiving the restore-file command,
    1.  Download the file
    2.  If the SHA-256 checksum is provided, perform checksum comparison.
    3.  Iterate the KV pairs, keeping only those with StartTS or CommitTS between (--startts, --endts\], and key inside the given key range filter.
    4.  Append all the KV pairs into a BatchCommandsRequest.
    5.  Perform the batch commands and let Raft replicates this to all peers.
4.  Determine whether to perform restore externally on BR, or internally on TiKV.

### Merge (out of scope in v1)

#### Merge backups

```console
$ br stream merge \
   -s 's3://bucket/path/' \
   [--read-snapshot-storage 's3://bucket/snapshot-path'] \
   --write-snapshot-storage 's3://bucket/snapshot-path-new' \
   [--startts 123456789] \
   [--endts 987654321]
```

The "merge" operation performs an offline compaction. It applies the KV events on top of an existing snapshot, and produces a new set of SST files.

### Error scenarios

#### Scaling out

If BR (or TiDB API) directly sends the tasks to TiKV services (i.e.
"push-based interface"), when we add new TiKV stores they will not know
there is a backup task, causing information loss.

I think this suggests that either

-   There has to be some kind of "BR-stream-master" (like DM-master or CDC-master) which maintains the task list and push it to any new members, or
-   The task list should be stored on etcd / PD and every TiKV uses [<u>Watch</u>](https://etcd.io/docs/v3.5/tutorials/how-to-watch-keys/) to pull new tasks.

I very much prefer the stateless, pull-based approach, but afaik TiKV
has never introduced any etcdv3 dependency before (TiDB o.t.o.h. uses
etcdv3 extensively, esp in DDL sync).

(Since TiKV itself is also a KV store, we could as well use RawKV in a
non-watched keyspace to share the task list. But it seems CDC *is*
TiKV's Watch 🤔)

#### Crashing

After a TiKV store has successfully uploaded content to external
storage, it should report to the master / etcdv3 / S3 like "in task T,
in store 8, in region 432, we have backed up until TS=123456789".

In case of a crash, the new leader of region 432 should initialize
itself from this progress report, and start scanning from TS=123456789
rather than TS=0 or Now().

This also means there is a communication cost of fetching the initial
TS.

Because we need to ensure everything in the TS range 123456789..Now()
are intact, we have to extend the GC lifetime to include 123456789.
Setting a GC safepoint has a global effect, however, whereas we only
want to prevent GC from happening in this particular region. Therefore,
we'd like to instead change the [<u>gc\_worker.rs</u> <u>implementation
in
TiKV</u>](https://github.com/tikv/tikv/blob/5552758d277b0ab2761deb88c9a82525ecac8980/src/server/gc_worker/gc_worker.rs#L224).
A keyrange can indicate if it is ready to be GC'ed. If a leader has just
been elected for &lt; 5 minutes, we indicate the region as not-GC-ready.

#### Network partition

Consider split-brain, where a region's peers are split into two groups
(say <u>1</u>,2,3 / 3,4,<u>5</u>) and both sides have leader (<u>1</u>,
<u>5</u>), and both leaders do back up (inconsistent) data to S3. Raft
should be able to avoid this, the bridge node (3) being aware of both
sides should prevent any modification (Put/Delete) on one side from
taking place and thus the back up can never diverge. So this is
equivalent to a normal partition where the minority side is considered
dead (<u>1</u>,2,3 / <s>4,5</s>).

### Task management

As stated above we need a place reachable from all TiKVs to store the
task status.

**Starting task**

BR pushes these keys:

-   TaskInfo:(task\_name) → ( all info about the task )

TiKV, on initialization, scans for every KV in the keyspace TaskInfo:
to learn what backup tasks have been scheduled. After it is done, TiKV
watches the keyspace for any new tasks.

When a new task is seen by TiKV, and the task's end\_ts &gt;
current\_ts, it will do

```rust
for region in self.regions {
    if self.is_leader(region.id) {
        put!(
            "NextBackupTS:({task.name}, {self.store_id}, {region_id})",
            task.start_ts,
        );
    }
}
```

Stop the task if end\_ts &lt;= current\_ts.

**Stopping task**

Delete the TaskInfo key. Watcher should be able to do cleanup.

**Configurating, resuming and pausing task**

Update the TaskInfo key. The KV API is equivalent to starting a task.
Pausing changes the --start-ts to the last key's CommitTS, and set
"paused" to true. Resuming restores "paused" to false.

**Initialization, leader change and region split/merge**

For every new region, we assume all keys between NextBackupTS:\* to the
current TS is not yet backed up. So we initiate a full scan on the
region for CommitTS between these two numbers.

**Flushing**

For every region which this store is still a leader of, update
NextBackupTS:\* to the ResolvedTS of the region.

**Risks**

-   Still need to sort out all potential crash scenarios
-   Scanning TxnEntry after changing leaders, no matter when it happened, may reduce the cluster's performance.
-   Events such as "DeleteRange" and "IngestSST" are not handled.
-   Should we backup lockcf
-   How to deal with Rollback (esp across 5min point)
    -   may lead to dangling default cf entries if the KVDelete is not handled
    -   in some scenarios there may be a lot of rollbacks?
    -   The Rollback key will carry start ts. For each key with start ts we need to ensure the delete happened after the put.

## Alternatives & Rationale

**Scanning RaftDB**

Since all modifications must go through Raft consensus, we can capture
the changes on RaftDB instead of TiKVDB for the incremental changes. We
can even physically copy the WAL file to minimize computation. Another
advantage of scanning RaftDB is that, if we want to batch copy events
between two timestamps (e.g. after changing leader), we don't need to
scan the entire region key space, but just those entries indexed by TS.

In fact, TiCDC also considered this approach. It was eventually
abandoned, however, due to the difficulty of actually utilizing the raft
log. Given the previous failure, we will not attempt to touch the raft
log unless the TxnEntry scan proved to have a really bad effect on
performance.

-   Scan the raft log directly. The current raftstore implementation needs to be adjusted, such as raft log gc. In addition, it is also necessary to ensure that the scan is performed during the leader’s lifetime, otherwise the complete data may not be seen.

-   Also need to pay attention to region epoch check, raft log commit != apply successfully

-   To support the interpretation of raftlog, I think I need to implement most of the logic of raftstore now, especially some operations such as split/merge/conf change. Due to the existence of these operations, the original total order raft log in a region has a sloping relationship between different regions. I think it is not easy to solve. This is also the reason why cdc did not use raftlog or wal at the time.

---

### Design 2022 03 03 Rc Read Tso Optimization (`docs/design/2022-03-03-rc-read-tso-optimization.md`)

# Read-Committed Read With Timestamp Check

- Author(s): cfzjywxk
- Last updated: March. 3, 2022
- Discussion at:

## Motivation

For the `read-committed` isolation level, each read request in a single transaction will need to fetch a new `ts` to read the latest committed data.
If the workload is a read-heavy one whose read QPS is significantly higher than writes or there're few read-write conflicts, fetching ts each time will increase the query lantecy.

The new ts itself is used to ensure the most recent data will be returned, if the data version does not change frequently then it's unnecessary to fetch a new timestamp every time.
The ts fetching could be processed in an optimistic way that ts fetching happens only when a more recent data version is encoutered, this saves the cost of many unnecessary ts fetching.

## Detailed Design

Introduce another system variable `tidb_rc_read_check_ts` to enable the "lazy ts fetch" read mode. It will take effect for all the in-transaction select statements when the transaction mode is `pessimistic` and the isolation level is `read-committed`.

The execution flow is like this:

1. If the query is executed first time, do not fetch a new `for_update_ts` and just use the last valid one(`start_ts` for the first time).
2. Do build the plan and executor like before.
3. If the execution is successful, a `resultSet` will be returned.
4. The connection layer will drive the response procesure and call `Next` function using the returned `resultSet`.
5. The read executor will try to fetch data to fill in a data `chunk`. The bottommost executor could be a `pointGet`, `batchPointGet` or a coprocessor task. What's different is a `RcReadCheckTS` flag will be set on all these read requests.
6. The read executor in the storage layer will check the read results, if a more recent version does exist then a `WriteConflict` error is reported.
7. For data write record, do check if it's newer than the current `read_ts`.
8. For lock record, return `ErrKeyIsLocked` even though the `lock.ts` is greater than the `read_ts` as the `read_ts` could be a stale one.
9. If no error is returned then the query is finished. Otherwise if there's no `chunk` responsed to the client yet, retry the whole query fetching a new global ts to do the read like normal.


## Compatibility

The default behaviours of the `read-committed` isolation level will not change. One thing different is that if the user client uses `COM_STMT_FETCH` like utility to read data from `TiDB`,
there could be problem if the returned first chunk result is already used by the client but an error is reported processing next result chunk.

---

### Design 2022 03 09 Optimize Gc For Internal Transaction (`docs/design/2022-03-09-optimize-gc-for-internal-transaction.md`)

# Optimize GC Advance For Internal Transactions

- Author(s): [Michael](https://github.com/TonsnakeLin) 
- Tracking Issue: https://github.com/pingcap/tidb/issues/32725

## Introduction

This document describes the design of the feature "optimize gc advance for internal transaction", which adds the startTS(start timestamp) of all internal transactions to the gc(garbage collect) safepoint calculation process.

## Motivation or Background

TiDB advances gc safepoint every `tidb_gc_run_interval` time with the value `now - tidb_gc_life_time`. If there is a long time transaction from user client lives more than `tidb_gc_life_time`, the safepoint can't be advanced until the transaction is finished or lives over 24 hours. This mechanism ensures the continuous advancement of gc safepoint and ensures that the data active transactions need to access will not be cleared.

However, Internal transactions run in TiDB don't comply with the mechanism above. If the internal transaction lives more than `tidb_gc_life_time`, it may fail because the data it needs to access was cleared. This design aims to resolve the problem that internal transaction run failed because data is cleared by the gc mechanism.

## Detailed Design

`Design Summary` describes the main processes of safepoint calculation and what job this design did.

### Design Summary

Currently here are two kinds of internal transactions. one is run by internal session, the other is run by function `RunInNewTxn`. This design aims to take account of all internal transactions when calculate gc safepoint.

The design stores internal sessions to session manager and stores the internal transactions to `globalInnerTxnTsBox` so that it can get startTS of internal transactions when calculates gc safepoint.

#### Calculate GC SafePoint

Currently, the processes TiDB calculates safepoint is as bellow, it is implemented in `(is *InfoSyncer) ReportMinStartTS`

- Get current timestamp from PD, save it to variable `now`,	 get timestamp that is 24 hours earlier than `now`, save it to variable `startTSLowerLimit`
- Get all user client sessions, save them to slice `processlist`
- Traverse `processlist` to get startTS from every client session and compare the `startTS` with `now` to get the minimum timestamp which is after `startTSLowerLimit` , save it as minStartTS which is gc safepoint.

This design add extra processes in `(is *InfoSyncer) ReportMinStartTS` to take account of internal transactions startTS when calculates gc safepoint. The new processes TiDB calculates safepoint is as bellow.
  - Get current timestamp from PD, save it to variable `now`, get timestamp that is earlier than `now` which is specified by system variable `tidb_gc_txn_max_wait_time`, save it to variable `startTSLowerLimit`
- Get all user client sessions, save them to slice `processlist`
- Get the startTS of every internal transaction run by internal session, save it to slice `InnerSessionStartTSList`
- Get the startTS of every internal transaction run by `RunInNewTxn`, save it to map `innerTxnStartTsMap`
- Traverse `processlist` to get startTS from every client session and compare the `startTS` with `now` to get the minimum timestamp which is after `startTSLowerLimit` , save it as `minStartTS`.
- Traverse `InnerSessionStartTSList` to get startTS and compare with `minStartTS` to get the minimum timestamp which is after `startTSLowerLimit` , save it also as `minStartTS`.
- Traverse `innerTxnStartTsMap` to get startTS and compare with `minStartTS` to get the minimum timestamp which is after `startTSLowerLimit` , save it also as `minStartTS` which is gc safepoint.

#### Store And Delete Internal Sessions

TiDB gets an internal session from a session pool implemented in `(s *session) getInternalSession`, when the transaction finished,it puts the session to the pool. It stores the session to session manager when gets an internal session, delete the session from session manager when returns the session to a pool.

#### Store And Delete Internal Transactions

The internal transactions here are executed by function `RunInNewTxn`. It stores the transaction to `globalInnerTxnTsBox` at the transaction's beginning and deletes the transaction at the end.
### Data Structure Design

#### SessionManager 

TiDB manages client sessions by SessionManager interface. This design expands the SessionManager interface to manage internal sessions too.

```go
type SessionManager interface {
	// Put the internal session pointer to the map in the SessionManager
	StoreInternalSession(se interface{})
	// Delete the internal session pointer from the map in the SessionManager
	DeleteInternalSession(se interface{})
	// Get all startTS of every transactions running in the current internal sessions
	GetInternalSessionStartTSList() []uint64
}
```

#### innerTxnStartTsBox 

This design defines a global variable `globalInnerTxnTsBox` to manage internal transactions run by function `RunInNewTxn`. The map `innerTxnStartTsBox.innerTxnStartTsMap` stores all the internal transaction startTS. 

```go
var globalInnerTxnTsBox = innerTxnStartTsBox{
	innerTSLock:		sync.Mutex{},
	innerTxnStartTsMap: make(map[uint64]struct{}, 256),
}

type innerTxnStartTsBox struct {
	innerTSLock		   sync.Mutex
	innerTxnStartTsMap map[uint64]struct{}
}
```

### Functional design

#### Store And Delete Internal Sessions

TiDB gets an internal session from a session pool implemented in `(s *session) getInternalSession`, when the transaction finished,it puts the session to the pool. This design stores the internal session to session manger in the function `(s *session) getInternalSession` and deletes the internal session from session manager in the callback returned by `getInternalSession`. It calls the function `infosync.DeleteInternalSession()` to delete the internal session from session manager and calls the function `infosync.StoreInternalSession` to add the internal session to session manger.

```go
func (s *session) getInternalSession(execOption sqlexec.ExecOption) (*session, func(), error) {
	tmp, err := s.sysSessionPool().Get()
	se := tmp.(*session)
	// Put the internal session to the map of SessionManager
	infosync.StoreInternalSession(se)
	return se, func() {
		// Delete the internal session to the map of SessionManager
		infosync.DeleteInternalSession(se)
		s.sysSessionPool().Put(tmp)
	}
}
```

#### Store And Delete Internal Transactions

The internal transactions here are executed by function `RunInNewTxn`. It stores the internal transaction startTS by function  `wrapStoreInterTxnTS()` and deletes the transaction startTS by function `wrapDeleteInterTxnTS()`.

```go
// RunInNewTxn will run the f in a new transaction environment.
func RunInNewTxn(ctx context.Context, store Storage, retryable bool, f func(ctx context.Context, txn Transaction) error) error {
	defer func() {
		wrapDeleteInterTxnTS(originalTxnTS)
	}()
	for i := uint(0); i < maxRetryCnt; i++ {
		txn, err = store.Begin()
		if i == 0 {
			originalTxnTS = txn.StartTS()
			wrapStoreInterTxnTS(originalTxnTS)
		}
		err = txn.Commit(ctx)
		...
	}
}
```

#### Calculate GC Safepoint

`ReportMinStartTS` calculates the minimum startTS of ongoing transactions (except the ones that exceed the limit), and it's result is useful for calculating the safepoint, which is gc_worker's work.This design add some code in the  function `ReportMinStartTS` to consider internal transactions when calculates the minimum startTS.

```go
func (is *InfoSyncer) ReportMinStartTS(store kv.Storage) {}
```

## Compatibility

This feature does not affect compatibility.

## Unresolved Questions

Currently, It prints a log message such as "An internal transaction running by RunInNewTxn lasts more than 1 minute" when an internal transaction lasts more than 1 minute. In the future, we should print more detail messages in the log and add some monitor data showed on the grafana panel.

---

### Design 2022 03 10 Backup With Batch Create Table (`docs/design/2022-03-10-backup-with-batch-create-table.md`)

# TiDB Design Documents

- Author(s): [fengou1](http://github.com/fengou1)
- Discussion PR: https://github.com/pingcap/tidb/issues/28763
- Tracking Issue: https://github.com/pingcap/tidb/pull/27036

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Test Design](#test-design)
  * [Compatibility Tests](#compatibility-tests)
  * [Benchmark Tests](#benchmark-tests)

## Introduction

The proposal of this design is to speed up the BR restore.

## Motivation or Background

The cluster has 6 TiB data, 30k tables, and 11 TiKVs. When I use BR to backup and restore the cluster, the speed is particularly slow. After investigation, BR can only create 2 tables per second, the entire restore speed takes nearly 4h, and the execution time spent creating tables is close to 4h. It can be seen that the execution speed of ddl is the bottleneck in this scenario.

## Detailed Design

Backup and Restore for massive tables is extremely slow, the bottleneck of creating the table is to waiting for the schema version change. Each table creates ddl cause a schema version change. 60000 tables have almost 60000 times schema change, it is very cost of restoring massive table

Currently, BR uses an internal interface named CreateTableWithInfo to create table, which creating the table and wait the schema changing one-by-one, omitting the sync of the ddl job between BR and leader, the procedure of creating one table would be like this:
```go
for _, t := range tables {
  RunInTxn(func(txn) {
  m := meta.New(txn)
  schemaVesrion := m.CreateTable(t)
  m.UpdateSchema(schemaVersion)
 })
```

the new design will introduce a new batch create table api `BatchCreateTableWithInfo`
```go
for _, info := range tableInfo {
  job, err := d.createTableWithInfoJob(ctx, dbName, info, onExist, true)
  if err != nil {
  return errors.Trace(err)
  }

  // if jobs.Type == model.ActionCreateTables, it is initialized
  // if not, initialize jobs by job.XXXX
  if jobs.Type != model.ActionCreateTables {
    jobs.Type = model.ActionCreateTables
    jobs.SchemaID = job.SchemaID
    jobs.SchemaName = job.SchemaName
  }

  // append table job args
  info, ok := job.Args[0].(*model.TableInfo)
  if !ok {
    return errors.Trace(fmt.Errorf("except table info"))
  }
    args = append(args, info)
  }

  jobs.Args = append(jobs.Args, args)

  err = d.doDDLJob(ctx, jobs)

  for j := range args {
  if err = d.createTableWithInfoPost(ctx, args[j], jobs.SchemaID); err != nil {
    return errors.Trace(d.callHookOnChanged(job, err))
  }
 }
```

For ddl work, introduce a new job type `ActionCreateTables`
```go
 case model.ActionCreateTables:
 tableInfos := []*model.TableInfo{}
 err = job.DecodeArgs(&tableInfos)

 diff.AffectedOpts = make([]*model.AffectedOption, len(tableInfos))
 for i := range tableInfos {
  diff.AffectedOpts[i] = &model.AffectedOption{
  SchemaID: job.SchemaID,
  OldSchemaID: job.SchemaID,
  TableID: tableInfos[i].ID,
  OldTableID: tableInfos[i].ID,
  }
 }
```

for each job `ActionCreateTables`, only one schema change, so one schema version for one batch of creating table, it greatly improves the performance of creating tables.


The feature auto-enabled with batch size 128 to batch create the table. Users can disable the feature by specifying `--ddl-batch-size=0`. The max batch size depends on the txn message size, currently, it configures 8MB by default. 

## Test Design
UT: see PRs https://github.com/pingcap/tidb/pull/28763, https://github.com/pingcap/tics/pull/4201, https://github.com/pingcap/tidb/pull/29380

Integration test also covered among CDC, BR, TiDB, binlog, TiFlash etc.


### Compatibility Tests

- Compatibility with binlog, please refer to https://github.com/pingcap/tidb-binlog/pull/1114.
- Compatibility with CDC, a regression test made for cdc work with br test. since CDC has a whitelist for unrecognizing ddl job and pulling data from tikv directly so that we did not find regression issues.
- Compatibility with TiFlash https://github.com/pingcap/tics/pull/4201.
- Upgrade compatibility: BR + tidb without interface BatchCreateTableWithInfo, the restore falls back to old legacy way that creates table one by one.
- Downgrade compatibility: old BR + new tidb with BatchCreateTableWithInfo, the restore using legacy way to create table.

### Benchmark Tests
- 61259 tables restore takes 4 minute 50 seconds, 200+ tables/per seconds with following configuration:
TiDB x 1: 16 CPU, 32 GB
PD x 1: 16 CPU, 32 GB
TiKV x 3: 16 CPU, 32 GB

---

### Design 2022 03 16 Functional Dependency (`docs/design/2022-03-16-functional-dependency.md`)

# Functional Dependency

- Author(s): [AilinKid](https://github.com/AilinKid) (Lingxiang Tai) [winoros](https://github.com/winoros) (Yiding Cui)
- Last updated: 2022-03-16
- Motivation Issue: https://github.com/pingcap/tidb/issues/29766
- Related Document: https://pingcap.feishu.cn/docs/doccndyrRWfcGALhjcyVhOrxWYd

## Table of Contents

* [Introduction](#introduction)
* [Motivation And Background](#motivation-And-background)
* [Detail Design](#detail-design)
    * [Implementation Overview](#implementation-overview)
        * [How to store functional dependency](#how-to-store-functional-dependency)
        * [How to maintain functional dependency](#how-to-maintain-functional-dependency)
        * [How to integrate functional dependency with TiDB arch](#how-to-integrate-functional-dependency-with-tidb-arch)
    * [Operator Overview](#operator-overview)
        * [Logical Datasource](#logical-datasource)
        * [Logical Selection](#logical-selection)
        * [Logical Projection](#logical-projection)
        * [Logical Aggregation](#logical-aggregation)
        * [Logical Join](#logical-join)
* [Investigation](#investigation)
* [Unresolved Questions](#unresolved-questions)

## Introduction

Functional Dependency (abbreviated as FD below) is a traditional relation concept with a history as long as database itself. In relational database theory, a functional dependency is a constraint between two sets of attributes in a relation from a database. In other words, a functional dependency is a constraint between two attributes in a relation.

Given a relation R and sets of attributes X,Y ∈ R, X is said to functionally determine Y (written as X → Y) if and only if each X value in R is associated with precisely one Y value in R; R is then said to satisfy the functional dependency X → Y. In other words, a dependency FD: X → Y means that the values of Y are determined by the values of X. Two tuples sharing the same values of X will necessarily have the same values of Y.

## Motivation And Background

Since we have already known the dependencies between sets of attributes (columns) after the FD has been built, we can make use of this relationship to do optimization in many scenarios. Eg: in only-full-group-by mode, for non-aggregated columns in the select list, as long as it is functionally dependent on the group-by clause columns, then we can consider it legal. Otherwise, extracting the constant, equivalence, dependency relationship between columns everytime we use it is tricky and costly.

After trials and errors of only-full-group-by check, TiDB ultimately seeks to use functional dependency to solve its only-full-group-by check problem completely. Besides, functional dependency can also be applied to many other scenarios to reduce complexity, for example, distinct elimination with/without order by, selectivity for the correlated column and so on.

## Detail Design

### Implementation Overview

* How to store functional dependency
* How to maintain functional dependency
* How to integrate functional dependency with TiDB arch

#### How to store functional dependency

Generally speaking, functional dependencies essentially store the relationship between columns. According to the paper [Exploiting functional dependence in query optimization](https://cs.uwaterloo.ca/research/tr/2000/11/CS-2000-11.thesis.pdf), this relationship can be constant, equivalence, strict and lax. Except constant is a unary, all others can be regarded as binary relationships. Therefore, we can use graph theory to store functional dependencies, maintaining edge sets between point-set and point-set, and attaching equivalence, strict and lax attributes as a label on each edge. For unary constant property, we can still save it as an edge, and since constant has no starting point-set, let's regard it as a headless edge.

* equivalence: {a} == {b}
* strict FD:   {a} -> {b}
* lax FD:      {a} ~> {b}
* constant:    { } -> {b}

For computation convenience, we can optimize equivalence as {a,b} == {a,b}, so we don't have to search from both directions when confirming whether a point is in the equivalence set.

#### How to maintain functional dependency

For the open-sourced MySQL, the construction and maintenance of FD are still relatively heavy. It uses sub-queries as logical units and uses nested methods to recursively advance FD. For each logical unit, the source for where FD is derived is relatively simple, basically from three elements there: `GROUP BY` clause, `WHERE` clause and the datasource (join/table). However, according to the paper [CS-2000-11.thesis.pdf](https://cs.uwaterloo.ca/research/tr/2000/11/CS-2000-11.thesis.pdf), TiDB chooses to build FDs based on logical operators as an alternative, without the boundary restrictions of logical sub-queries.

Example:

```sql
create table t1(a int, c int)
create table t2(a int, b int)
explain select t1.a, count(t2.b), t1.c from t1 join t2 on t2.a=t1.a where t1.c=1 group by t2.a;
```

Result:

```
/* Detailed source-code truncated for AI context efficiency. */
```

Analysis:

When building the FD through these logical operators, we call `ExtractFD()` recursively from the root node of the logical plan tree. When the call down to the leaf node (actually source table for both join side), for the inner side, the FD from the datasource of base table of t2 are nil because they have no basic key constraint. While for outer side, since there is a filter on the datasource of base table t1, we got FD as {} -> {t1.c}. Because t1.c can only be constant 1 behind the filter. Up to next level, the join condition t1=t2 will build the equivalence for point-set of {t1.a, t2.a} == {t1.a, t2.a}. Finally, when arriving the root aggregate node, we will build strict FD from group-by point-set {t2.a} to select aggregate function {count(t2.b)} reasonably. Consequently, we get FD as {} -> {t1.c} & {t1.a, t2.a} == {t1.a, t2.a} & {t2.a} -> {count(t2.b)}.

Application:

For the only-full-group-by check of building phase, after getting the FD as illustrated in the last subchapter, we can easily identify from the select list that t1.a is equivalent to the group-by column t2.a, count(t2.b) is strictly functional dependent on group-by column t2.a and t.c is definitely constant after the filter is passed. So it can pass only-full-group-by check here. For more sophisticated cases with recursive sub-queries, maintenance work of this kind of FD architecture will be automatical and reasonable because we're just pulling the request from the top node of the entire logical plan tree, and all things happen naturally.

#### How to integrate functional dependency with TiDB arch

Where to put this stuff in and when should the FD collection work be done? In FD logic, the relationship between columns is not limited to base col, but also between expressions, even sub-queries. We need to be able to identify sameness between cols, expressions and even better to have a unique id to tag them. When joining different tables, there are maybe some columns with the same name from different sources, we should still utilize this unified unique id to identify and distinguish them. Obviously, the expression tree after ast rewrite has this convenient functionality, and plus we need to utilize FD functionality to check validation when building a logical plan, so eventually we can only perform FD collection while building the logical plan stage.

As illustrated above, tidb chooses the collect FD in units of logical operators. So for the first step, integrating FD collection logic for some meaningful logic operators is necessary, such as: datasource, join, apply, selection, projection and so on. For other meaningless logical operator like sort, it will not make any difference to FD collected from its child operator, so just output what it got from its child. The most important things in FD construction chain are from various join keys, join conditions, join types, selection predicates and  group-by clause. Let's break it down and take it one by one in next chapter.

### Operator Overview

* Logical Datasource
* Logical Selection
* Logical Projection
* Logical Aggregation
* Logical Join

#### Logical Datasource

The logical datasource is the place where the most basic FD is generated. The natural FD is generated from the primary key and candidate key (unique) of the table, corresponding to strict FD and lax FD respectively. Of course, the not null attribute of the column is also a very important role. Because all rows related to null value can be rejected by that not null attribute, so that the related lax FD can become strict FD yet.

#### Logical Selection

As you can see from the sql example above, logical selection from where/having clause can be used to filter data. The selected data will have the properties constrained by this predicate. Most common FDs constructed from selection are constant, not null and equivalence, corresponding to t.a=1, t.a=1 and t.a = t.b respectively. The reason why t.a=1 can generate both constant and not null relationship is that in the expression calculation, if t.a is null, then null=1 will be calculated as null, and when the result of the predicate in where is null, this row will be rejected. So after the data is pulled from this filter, t.a mustn't be null and must be 1 only. For most operators, null value rejection characteristic is with them, which means that if a parameter on the any side of an operator is null, then the final result is null (just like what t.a=1 is shown here).

#### Logical Projection

Logical projection can be described simply because it does not generate FD itself, but truncate some useless FD sets according to the projected columns. For example, providing that the FD graph has {a} -> {b} & {b} -> {c}, when only the {a,c} columns are selected in the projection, we need to maintain the closure and transitive properties of this functional dependency graph, generating the remaining {a} -> {c} functional dependencies for the rest FD graph when column b is projected out.

#### Logical Aggregation

Logical aggregation mainly builds related FDs around the columns or expressions in the group by clause. It should be noted that if there is no group by clause but agg functions, all rows should be implicitly regarded as one group. Columns or expressions from group by clause naturally functional determine these aggregate expressions. But for others, they're waited to be judged, that's what and where only-full-group-by check does.

#### Logical Join

Logical join must be the most difficult part to infer with, because the presence of join key values, the variability of join conditions, and the difference of join types will all lead to the diversity of FD inference. For inner join, the final data comes first from cartesian product of inner and outer join side, and then pull the result through the filter generated from the inner join predicate (same as what selection does in where clause). Since reducing row data does not affect the presence of FD in that join side, data after the cartesian product can retain all FDs of operators at both sides of the join. But when data pulled through filters, it is necessary to add the FD generated by the inner join conditions.

For outer join, we need to consider more, because outer join will choose the connection method based on the position of the join conditions and the presence of the join key.

* only inner side condition           --- apply inner filter after the cartesian product is made, which means no supplied-null row will be appended on the inner side if any row is preserved; or all rows are supplied-null if all rows are filtered out.
* has outer condition or join key     --- apply all of this filter as matching judgement on the process of cartesian product, which means supplied-null row will be appended on the inner side when matching is failed.

Although both cases will keep all rows from the outer side, but how to derive FDs from both sides depends on where the conditions come from, what the columns used by the conditions are, and what the attributes the conditions can provide. We can treat the former one as an inner join, but for the latter one, we can only keep the FD from the outer table of join, and inner side's FD and filter FD has many complicated rules to infer with, we are not going to expand all of this here.

## References

- [MySQL source code](https://github.com/mysql/mysql-server/blob/8.0/sql/aggregate_check.h)
- [Exploiting functional dependence in query optimization](https://cs.uwaterloo.ca/research/tr/2000/11/CS-2000-11.thesis.pdf).
- [functional dependency reduce](https://www.inf.usi.ch/faculty/soule/teaching/2014-spring/cover.pdf).
- [Canonical Cover of Functional Dependencies in DBMS](https://www.geeksforgeeks.org/canonical-cover-of-functional-dependencies-in-dbms/)

## Unresolved Questions

- None

---

### Design 2022 03 24 Get Lock (`docs/design/2022-03-24-get-lock.md`)

# Proposal: Support `GET LOCK`

- Author(s): [morgo](https://github.com/morgo)
- Tracking Issue: https://github.com/pingcap/tidb/issues/14994

## Abstract

This proposes an implementation of `GET_LOCK()` with some limitations.

## Background

MySQL supports advisory locks (aka `GET_LOCK()`) as a way of serializing access to a resource. This is commonly used by applications such as ORMs to ensure that only one process can perform DDL at a time.

Advisory locks are session scoped (not transaction) locks. Up until MySQL 5.7 acquiring any new lock would free all previously acquired locks. This was because the locking system did not support deadlock detection internally.

## Proposal

This proposes that we use an internal table (`mysql.advisory_locks`) with the `lockName` as the `PRIMARY KEY`. When a user acquires a lock with `GET_LOCK()`, we insert a row into the table as part of an internal pessimistic transaction. The internal transaction is never committed, and stays open until `RELEASE_LOCK()` is called, or the session is closed.

The `timeout` feature of `GET_LOCK()` can be supported by modifying the pessimistic lock timeout (`innodb_lock_wait_timeout`).

When `RELEASE_LOCK()` is called, the transaction is rolled back and the row is never actually inserted into the table. Thus, there are no garbage collection requirements on the internal table.

I refer to the internal pessimistic transaction as an _attached session_ since it can not be part of the user's session, as advisory locks are session scoped and not transaction scoped. The user session that executes the `GET_LOCK()` statement is the _user session_.

## Compatibility

The following known limitations exist with an implementation based on pessimistic locks and _attached sessions_:

* Deadlock detection is not supported. This limitation is because each lock needs to be acquired in a different _attached session_. This could be a major problem, since on deadlock both sessions will wait until their timeout expires. With `GET_LOCK()`, users typically set the timeout to very large values.
* It is not possible to tell if a lock is held by another session, without acquiring it. Thus, the `IS_FREE_LOCK()` function can not be implemented in pure-SQL.
* It is not possible to tell which other session holds the lock (`IS_USED_LOCK()`). This is both because of the issue of SQL support, and because the connection ID could match the ID of a different TiDB server.
* `RELEASE_LOCK()` can only return `1` (lock released) or `0` (no lock released). In MySQL it can also return `NULL` if the lock was not held by any sessions. For the same reason `IS_FREE_LOCK()` is not supported, TiDB will always return `0` in cases MySQL would have returned `NULL`.
* The timeout for acquiring locks is capped at one hour (`max-txn-ttl`). In MySQL, it is possible to set an unlimited timeout, but we will have to document this as not supported.

These compatibility issues do not appear to be a problem for the ORMs we have looked at.

## Alternative Proposals

Of the compatibility issues, not supporting deadlock detection is the most problematic.

An alternative proposal is that we could decide that "`GET_LOCK()` is compatible with MySQL 5.6 instead of MySQL 5.7+". It is difficult to say if this will affect applications, since many users were probably not aware when using MySQL 5.6 that subsequent calls to `GET_LOCK()` would release previous locks. This alternative has been discussed, and rejected.

Since we will ship `GET_LOCK()` without deadlock detection, we can document that it is possible to manually resolve the deadlock by killing one of the locked sessions. The attached sessions themselves will not show up in `SHOW PROCESSLIST`, but the _user_ sessions will show up as in "`SELECT GET_LOCK()`" state for a long time and killing the _user_ sessions will kill the attached sessions.

---

### Design 2022 03 25 Non Transactional Dml (`docs/design/2022-03-25-non-transactional-dml.md`)

# Non-transactional statements

- Author(s): [Ziqian Qin](http://github.com/ekexium)
- Tracking issue: https://github.com/pingcap/tidb/issues/33485

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
* [Test Design](#test-design)
    * [Functional Tests](#functional-tests)
    * [Scenario Tests](#scenario-tests)
    * [Compatibility Tests](#compatibility-tests)
    * [Benchmark Tests](#benchmark-tests)
* [Impacts & Risks](#impacts--risks)
* [Investigation & Alternatives](#investigation--alternatives)
* [Unresolved Questions](#unresolved-questions)

## Introduction

A new syntax that transforms a given DML into a serial execution of mutually exclusive collectively exhaustive statements. 

For example, `BATCH ON a LIMIT 1000 DELETE FROM t` can be transformed into `DELETE FROM t WHERE a BETWEEN 1 AND 1000` and `DELETE FROM t WHERE a BETWEEN 1001 AND 2000`, assuming the min and max of `a` are respectively 1 and 2000.

## Motivation or Background

Users need to do a bulk delete or update using a single statement, while currently TiDB cannot satisfy the requirement because of the performance issue, transaction size limit, and compatibility issues with tools.

A new syntax is proposed to work around the problem. A non-transactional DML contains a DML and information that are used to "split" the statement, thus it is equivalent to a sequence of DMLs are not transactional since it does not provide atomicity and probably isolation.

Different from the deprecated batch-DML, a non-transactional DML splits SQLs so every split SQL is a normal statement and does not risk data-index consistency.

## Detailed Design

### User Interface

#### Syntax
The syntax: 
- `BATCH ON <column_name> LIMIT <batch_size> <DML>` is the complete form
- `BATCH LIMIT <batch_size> <DML>` is the shorter form. The shard column will be automatically selected from a PK column if possible. But it may return an error and require the user to specify the shard column.

In the first step only `DELETE` is going to be supported, but `UPDATE` and `INSERT INTO SELECT` are also worth considering.

For performance consideration, the shard column must be indexed. 

There can be dry run syntax to show the actual SQLs that will be executed. Query plans are not returned since there is no elegant way to contain both a SQL and a plan in a result set. 
- `BATCH ON <column_name> LIMIT <batch_size> DRY RUN QUERY <DML>` outputs the `SELECT` statement that will be executed.
- `BATCH ON <column_name> LIMIT <batch_size> DRY RUN <DML>` outputs how the statement will be split. It only outputs the first and the last split statement.

#### Output

Users get feedback from SQL return values, logs and process infos.

If all split statement succeed, the non-transactional DML returns a summary: the number of split statements and a success message. 
If the non-transactional DML is aborted, e.g. by `KILL TIDB`, it returns the error of context cancellation, and output details of failed jobs in logs if there is any.

The `info` field in process info describes not only the current SQL that is executing, but also the progress of all jobs.
Logs, slow logs and statement summaries will also contain the progress in the SQL text. 
For example, a split delete statement in slow queries can be like ``/* job 11/41 */DELETE FROM `test`.`t` WHERE `id` BETWEEN xxx AND yyy;``,
where 11 and 41 are the current job ID and the number of total jobs respectively.

Each split statement logs its detail in the INFO level as well.

### Session

Different from most of the statements, the non-transactional DML is handled at the session level. 

Non-transactional statements are treated as `SimplePlan`s and we won't compile them. In `TiDBContext.ExecuteStmt`, instead of `Session.ExecuteStmt` for most types of statements, `HandleNontransactionalDML` will be called. In `HandleNontransactionalDML`, we will split the DML into multiple statements and execute them one by one using `Session.ExecuteStatement`.

### How the split works

To find the split keys, a `SELECT` is used to read the shard column specified by the user. For example, for `BATCH ON a LIMIT 1000 DELETE FROM t WHERE b < 1000`, the select statement would look like: `SELECT a FROM t WHERE b < 1000 ORDER BY ISNULL(a,0,1), a`. It assures that NULL values are put in the first places. The result set could be large, but we don't need all of them, so results are batched until the size of the batch is greater than or equal to the specified `batchSize`. The interaction of any two batches must be none, since we use `BETWEEN` clauses to split the statement. Only the first and last elements of each batch are kept, thus forming a job. A job specifies a range in the specified column.

Theoretically, jobs can be executed in parallel, but that would require multiple sessions to execute them. There are two kinds of sessions in TiDB: user sessions that must be bound to client connections in a 1-on-1 manner, and internal sessions. Both kinds of sessions are inappropriate for the split statements, so in favor of maintenance, only the current user session will be used to execute the jobs, which is serial. In this way, the main benefit of a non-transactional DML is to overcome the transaction size limit, instead of performance superiority.

Each split statement is generated by embedding the split range in the where clause of the given DML using a `BETWEEN` operator. An exception is a `NULL` boundary where the `BETWEEN` clause is replaced by a `IS NULL` or `x IS NULL OR x < a` clause.
For example, the original statement is `BATCH ON a LIMIT 1000 DELETE FROM t WHERE b < 1000`, 
a job `{start:1, end:1000}` generates a split SQL `DELETE FROM t WHERE (a BETWEEN 1 AND 1000) AND b < 1000`.

### Error handling

A non-transactional statement obviously cannot roll back, when one of the split statement fails, a system variable `tidb_nontransactional_ignore_error` controls what happens next:
- If `tidb_nontransactional_ignore_error=0`, the non-transactional DML cancels all following jobs and returns an error immediately.
- Otherwise, the non-transactional DML continues until finishing all jobs and returns the details and error messages of all failed jobs.

If the statement is aborted by the user, it should report its progress and return the errors it has collected.

There is one exception, however. If the first job failed, we abort the whole process and return the error. There are 2 reasons for this behavior:

1. If for any reason all the jobs cannot succeed, failing in the first place is the best choice. For example, privileges are missing.
2. It's equivalent to rolling back the whole statement.

### Constraints

To make the semantics of non-transactional statements simple enough and to avoid misuse, 
there are several constraints on the DML.
Take non-transactional `DELETE` for example, only the `WHERE` clause in the delete statement is supported. 
`ORDER BY` or `LIMIT` clauses are ignored and will not take effect. An error will be returned if the DML contains them.

There may be other constraints or incompatibilities. They will be demonstrated in the official documentation of the feature. 

## Test Design

### Functional Tests

- non-transactional delete can delete everything it should delete, and don't delete anything it should not
    - multiple shard column types: int, varchar(with or without new collation), timestamp, double, decimal
    - different delete statements:
        - syntax: `DELETE FROM t`, `DELETE t FROM`
        - table aliases
        - column alias
        - where clause: no `WHERE`, simple `WHERE`, complex `WHERE` that contains `SELECT`
- errors are correctly propagated
    - inject error in the first job, it should return
    - inject errors in non-initial jobs, all errors should be collected and returned, remaining jobs should finish.
    - if appropriate privilege is not granted, the statement should fail

The tests can be done in both deterministic unit tests, and randomly generated tests that use the same set of data and check the results of a simple delete and that of a non-transactional delete.

### Scenario Tests

Simulate a simple bulk delete scenario.

- There are a large amount of data that cannot be deleted using a single delete
- Users dry run and check the query plan before executing the command
- The user aborted the command and can retry the remaining part based on the information in the error (or log).
- The result should be equivalent to a single delete statement if no error has happened.

### Compatibility Tests

Theoretically the feature won't break any compatibility in peripheral tools. 
But we will perform simple tests to see if they work with non-transactional DMLs:

- BR backup and restore
- TiCDC synchronization
- tidb-binlog synchronization

### Benchmark Tests

Benchmark the delete performance compared with a single normal delete statement:
1. BATCH ON a unique index
2. BATCH ON _tidb_rowid or an int PK
3. BATCH ON a clustered index

## Impacts & Risks

If any feature that influences sort and ordering (e.g. collation) is unstable, then the split process may be wrong and the delete statement may miss some rows or delete too many rows.

## Investigation & Alternatives

CockroachDB doesn't provide a similar mechanism, instead they have an official doc teaching users how to write scripts to manually split SQLs.

An alternative solution is to improve the ability of large transactions. But tools like CDC don't support large transactions well, so it's not feasible for now.

## Unresolved Questions

The user interface, including the syntax, the error messages, and the dry run results, may be improved.

---

### Design 2022 04 15 Multi Schema Change (`docs/design/2022-04-15-multi-schema-change.md`)

# Proposal: Support Multi-Schema Change

- Author(s): [tangenta](https://github.com/tangenta)
- Tracking Issue: https://github.com/pingcap/tidb/issues/14766

## Abstract

This proposes an implementation of applying multiple schema changes in one `ALTER TABLE` statement.

## Background

Multi-Schema Change is one of MySQL's extended features to the SQL standard. It allows the users to atomically make multiple schema changes in one statement, including column and index `ADD`, `ALTER`, `DROP`, and `CHANGE`, as well as table option changes. For example:

```sql
CREATE TABLE t (a INT, c INT);
ALTER TABLE t ADD COLUMN b INT, 
 MODIFY COLUMN c CHAR(5),
 ADD INDEX idx(a),
 ADD PRIMARY KEY (c),
 COMMENT = "comments for t";
```

Currently, TiDB only supports one schema change per SQL statement and limited multi-schema changes for some rare cases.

When users attempt to migrate data from MySQL-like databases, they may expend additional effort to rewrite a multi-schema change DDL to several single-schema change DDLs. For users who rely on ORM frameworks such as [Flyway](https://flywaydb.org/) to automatically construct SQLs, rewriting SQL could be tedious and the scripts are difficult to maintain.

Above all, the lack of this capability can be a blocking issue for those who wish to use TiDB.

### Goal

- Support MySQL-compatible Multi-Schema Change that used commonly, including `ADD/DROP COLUMN`, `ADD/DROP INDEX`, `MODIFY COLUMN`, `RENAME COLUMN`, etc.

### Non-Goals

- Support TiDB-specific Multi-Schema Change like `ADD TIFLASH REPLICA`, `ADD PARTITION`, `ALTER PARTITION`, etc.
- Resolve the 'schema is changed' error when DDL and DML are executed concurrently.
- Be 100% compatible with MySQL. MySQL may reorder the execution of schema changes, which makes the behavior counter-intuitive sometimes.
- Improve the performance of DDL, although it introduces a way to improve the performance of long-running jobs(see 'Future Work' part).

## Proposal

### Data Structure

The implementation is based on the [online DDL architecture](https://github.com/pingcap/tidb/blob/e0c461a84cf4ad55c7b51c3f9db7f7b9ba51bb62/docs/design/2018-10-08-online-DDL.md). Similar to the existing [Job](https://github.com/pingcap/tidb/blob/6bd54bea8a9ec25c8d65fcf1157c5ee7a141ab0b/parser/model/ddl.go/#L262) structure, we introduce a new structure "SubJob":

- "Job": A job is generally the internal representation of one DDL statement.
- "SubJob": A sub-job is a representation of one DDL schema change. A job may contain zero(when multi-schema change is not applicable) or more sub-jobs.

```go
// Job represents a DDL action.
type Job struct {
    Type       ActionType    `json:"type"`
    State      JobState      `json:"state"`
    // ...
    MultiSchemaInfo *MultiSchemaInfo `json:"multi_schema_info"`
}

// MultiSchemaInfo contains information for multi-schema change.
type MultiSchemaInfo struct {
   // ...
   SubJobs  []SubJob `json:"sub_jobs"`
}

// SubJob represents one schema change in a multi-schema change DDL.
type SubJob struct {
   Type    ActionType      `json:"type"`
   State   JobState        `json:"state"`
   // ...
}
```

The field `ActionType` stands for the type of DDL. For example, `ADD COLUMN` is mapped to `ActionAddColumn`; `MODIFY COLUMN` is mapped to `ActionModifyColumn`.

The Multi-Schema Change DDL jobs have the type `ActionMultiSchemaChange`. In the current worker model, there is a dedicated code path (`onMultiSchemaChange()`) to run these jobs. Only Multi-Schema Change jobs can have sub-jobs.

For example, the DDL statement

```SQL
ALTER TABLE t ADD COLUMN b INT, MODIFY COLUMN a CHAR(10);
```

can be modeled as a job like

```go
job := &Job {
    Type: ActionMultiSchemaChange,
    MultiSchemaInfo: &MultiSchemaInfo {
        SubJobs: []*SubJob {
            &SubJob {
                Type: ActionAddColumn,
                Args: ...
            },
            &SubJob {
                Type: ActionModifyColumn,
                Args: ...
            },
        }
    } 
}
```

In this way, we pack multiple schema changes into one job. Like any other job, it enqueue the DDL job queue to the persistent storage and waits for an appropriate worker to pick it up and process it.

### Job/Sub-job Execution

As shown in the code above, there is a field `State` in both `Job` and `SubJob`. All the possible states and the changes are listed here:

```
           ┌-->---    Done     ->------------------┐
           |                                       |
None -> Running -> Rollingback -> RollbackDone -> Synced
           |                                       |
           └-->--- Cancelling  -> Cancelled    -->-┘
```

We can divided these states into four types:

| States          | Normal            | Abnormal                    |
|-----------------|-------------------|-----------------------------|
| **Uncompleted** | `None`, `Running` | `Rollingback`, `Cancelling` |
| **Completed**   | `Done`            | `RollbackDone`, `Cancelled` |

Since a `Job` is executed by a DDL worker, the sub-jobs are executed in a single thread. The general principal to select a sub-job is as follows:

- For the normal state, the first uncompleted sub-job is selected in ascending order, i.e., the sub-job with the smaller order number is executed first.
- For the abnormal state, the first uncompleted sub-job is selected in descending order, i.e., the sub-job with the larger order number is executed first.

When one of the sub-job becomes abnormal, the parent job and all the other sub-jobs are changed to an abnormal state.

### Schema Object State Management

To ensure atomic execution of Multi-Schema Change, we need to carefully manage the states of the changing schema objects. Let's take the above SQL as an example:

```SQL
ALTER TABLE t ADD COLUMN b INT, MODIFY COLUMN a CHAR(10);
```

If the second sub-job `MODIFY COLUMN a CHAR (10)` fails for some reason(e.g., a row has more than ten characters), the first sub-job should be able to roll back its changes (roll back the added column `b`).

This requirement means that we cannot simply publish the schema object when a sub-job is finished. Instead, it should remain in a state invisible to users, waiting for the other sub-jobs to complete, eventually publishing all at once when it is confirmed that all sub-jobs have succeeded. This method is similar to 2PC: the "commit" cannot be started until the "prewrites" are completed.

Here is the table of schema states that can occur in different DDLs. Note that the "Revertible States" means that the changes are invisible to the users.

| DDL (Schema Change)     | Revertible States                          | Non-revertible States                       |
|-------------------------|--------------------------------------------|---------------------------------------------|
| Add Column              | None, Delete-Only, Write-Only, Write-Reorg | Public                                      |
| Add Index               | None, Delete-Only, Write-Only, Write-Reorg | Public                                      |
| Drop Column             | Public                                     | Write-Only, Delete-Only, Delete-Reorg, None |
| Drop Index              | Public                                     | Write-Only, Delete-Only, Delete-Reorg, None |
| Non-reorg Modify Column | Public (before meta change)                | Public (after meta change)                  |
| Reorg Modify Column     | None, Delete-Only, Write-Only, Write-Reorg | Public                                      |

To achieve this behavior, we introduce a flag named "non-revertible" in the sub-job. This flag is set when a schema object has reached the last revertible state. A sub-job with this flag is considered temporary completed, so that the worker can select the next sub-job. When all sub-jobs are non-revertible, all associated schema objects change to the next state in one transaction. After that, the sub-jobs are executed serially to do the rest.

On the other hand, if there is an error returned by any sub-job before all of them become non-revertible, the entire job is placed in to a `Rollingback` state. For the executed sub-jobs, we set them to `Cancelling`; for the unexecuted sub-jobs, we set them to `Cancelled`.

Finally, we consider the extreme case: an error occurs while all the sub-jobs are non-revertible. There are two kinds of errors in general, the logical error(such as the violation of unique constraint, out-of-range data) and the physical error(such as unavailablity of the network, unusability of the storage). In this situation, the error is guaranteed to be a physical one: we tend to assume that it can be resolved in a trivial way, e.g., by retrying. This behavior is consistent with the current DDL implementation. Take `DROP COLUMN` as an example, once the column enters the "Write-Only" state, there is no way to abort this job.

## Compatibility

### Upgrade Compatibility

When a TiDB cluster performs a rolling upgrade, there are 2 cases:

1. DDL owner is the new version of TiDB. When users execute a Multi-Schema Change statement on an old version of TiDB, they receive an "unsupported multi-schema change" error message.
2. DDL owner is the old version of TiDB. When users execute a Multi-Schema Change statement on a new version of TiDB, they receive the "invalid ddl job type" error message.

In both cases, the Multi-Schema Change statement cannot be executed. Therefore, users should avoid executing Multi-Schema Change during a rolling upgrade.

### MySQL Compatibility

MySQL may reorder some schema changes:

```SQL
CREATE TABLE t (b INT, a INT, INDEX i(b));
ALTER TABLE t DROP COLUMN b, RENAME COLUMN a TO b, ADD INDEX i(b), DROP INDEX i; -- success!

SHOW CREATE TABLE t;
```

```console
+-------+-------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                  |
+-------+-------------------------------------------------------------------------------------------------------------------------------+
| t     | CREATE TABLE `t` (
 `b` int DEFAULT NULL,
 KEY `i` (`b`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+-------+-------------------------------------------------------------------------------------------------------------------------------+
```

MySQL's execution order is as follows:

1. `DROP INDEX i`
2. `DROP COLUMN b`
3. `RENAME a TO b`
4. `ADD INDEX i(b)`

Since this behavior is a bit counter-intuitive, we decided not to be fully compatible with MySQL.

```SQL
ALTER TABLE t DROP COLUMN b, RENAME COLUMN a TO b, ADD INDEX i(b), DROP INDEX i;
ERROR 1060 (42S21): Duplicate column name 'b'
```

TiDB validates the schema changes against a snapshot schema structure retrieved before the execution, regardless of the previous changes in the same DDL statement. This may affect some common use cases. For example, `ALTER TABLE t ADD COLUMN a, ADD INDEX i1(a);` is not supported. However, it is not difficult to support such statements: removing the specific validation is enough. 

## Future Work

In the future, this implementation can be utilized to develop other features or achieve some optimizations:

- The table-level data reorganization like `ALTER TABLE CONVERT TO CHARSET` can be implemented by splitting a job into multiple sub-jobs.

- In the scenario of adding multiple indexes, we can improve the performance by reducing the read cost: merge multiple "ADD INDEX" sub-jobs into one sub-job, and read the data once instead of multiple times.

Furthermore, to help users understand how multi-schema change works, it is a good choice to support "EXPLAIN DDL", which can display some useful information like execution order, sub-jobs, and others.

## Alternative Proposals

- The 'job group' way. Unlike the 'SubJob', we can use a job group to represent multiple schema changes. However, this exposes the internal details of the job groups to the DDL job queue, making it more difficult to maintain.

- The existing way, which is a case-by-case implementation (for example, [#15540](https://github.com/pingcap/tidb/pull/15540)). Although some cases can be supported, it is not extensible.

- Another solution is to abandon atomization and use multiple DDL jobs to accomplish the task. This is much less complex and requires little effort. However, it can lead to confusion in the visible intermediate state.

---

### Design 2022 06 07 Adding Index Acceleration (`docs/design/2022-06-07-adding-index-acceleration.md`)

# TiDB Adding Index Acceleration 
- Author(s):     [Bear.C](https://github.com/Benjamin2037)
- Last updated:  2022-07-18
## Abstract
This document introduces a new way to create index in TiDB in a more efficient way. The existing proof-of-concept benchmark shows that it gives 4+ times performance improvement compared with the current solution. The current online create index implementation will be introduced as background knowledge.

## Background
The create index in TiDB is in an online fashion, users could add one index for a table and meanwhile DML transactions on the same table could be executed concurrently, which introduces a good experience to the user. To archive that, the process of creating an index is divided into 5 states internally:

- None - the initial state
- DeleteOnly - the index schema object is visible internally for the transactions, but index record can only be deleted.
- WriteOnly - the index schema object is visible internally for the transactions, and index record can be added/removed/updated.
- WriteReorganization - the index schema object is visible internally for the transactions, and index record can be added/removed/updated and the backfill workers are scheduled in this state to make sure index record will be 'backfilled' all for existing rows.
- Public - the final state in which all work is done and the index is visible to the user.

The backfill process scans all records from the table and generates an index key/value pair for each record, then fills the index data back into TiKV to form new index data. We found that backfilling data for index is a time-consuming task and it will be longer with user table data expanding sharply.

There are some measures that have been done to enhance the performance of creating index statements. For example, 1) the parallel execution backfill tasks and 2) adjustable batch size for every backfill batch. Below figure 1 is used to show the current backfill implementation.



From figure 1, the backfill task is firstly split into serial sub tasks, each sub tasks include one batch size record. Then, multi-workers are started up to execute backfill sub tasks parallelly.
Each worker is assigned one sub task and scans the specific record from the table.
Then generate index data for this batch record and write them back into TiKV with an optimistic write transaction.

## Goals
- Archives a better performance for creating the index in TiDB.
- Reduce the impact on DML transactions for foreground traffic when creating the index
## Non-Goal
- Make backfill work distributed in TiDB instances, which could be treated as a future enhancement based on this proposal.

## Proposal
The current backfill process could be inefficient for mainly two reasons:
1. The transactions need a full two-phase commit process and be transferred into a bunch of ‘Put’ operations for the storage(TiKV), which lead to extra overhead when we are trying to build a lot of index record.
2. The index data is written to TiKV in a ‘batch write’ transaction, it may conflict with the foreground traffic transaction and have to retry.

To improve the performance of backfill process, we would like to change it by:
1. One full copy of index data that uses the start of backfill processing as a snapshot and ingest the data to TiKV.
2. Delta part of index that user changed data during first step preparation a full copy.

The Online DDL supporting the above two preparing steps could be done async way. The new solution will also take use of this important fact.


## Rationale
In detail, instead of ‘batch write’ transaction, we could adopt the current Lightning to do the backfilling work. Lightning is a tool that is able to take rows as input and generate the SST files, ingest them to the storage(TiKV) directly. The figure 2 shows the changes of the new backfiller.



1. The first step is the similar as the current way, the worker is assigned to a sub task(range of data) and scans snapshot data with a unified timestamp obtained at ‘WriteReorganization’ state.
2. Generated this batch of index data, instead of committing a transaction for batch index data. A backfilling writer that is embedded with the Lightning engine built for each worker separately, it writes these index data to its local buffer and flush to the local storage as SST files.
3. The index data is sorted when compacting multiple SST files into one, each sorted files will be ingested into TiKV by the existing interface provided.
4. TiKV will finally combine the full copy of index data that was ingested with delta index part that was updated by user DML transaction during full copy preparation period. As the index at this time is almost completed its build process, so TiKV work in this step is not much.

Since Lightning writes index data firstly into local storage instead of committing backfill transactions to TiKV. This removes conflict with user transactions and there is no transaction commit time for backfill also. The main path bottleneck of adding indexes is removed. 

In addition to performance enhancement, the new solution could further lower the impact that DDL caused on DML. This point will be outstanding in the future implementation plan.

## Uniqueness check
For a unique index / primary key, we should be able to detect if a duplicate key is generated and reports an error if so. In order to archive that, we could reuse the `DuplicateDetect` interface provided by the Lightning engine:

```golang
service ImportSST {
   ...
   // Open a write stream to generate sst files
   rpc Write(stream WriteRequest) returns (WriteResponse) {}
   rpc RawWrite(stream RawWriteRequest) returns (RawWriteResponse) {}
   ...
 
   // Collect duplicate data from TiKV.
   rpc DuplicateDetect(DuplicateDetectRequest) returns (stream DuplicateDetectResponse) {}
}
```
Duplicate key will be reported when two unique index records with the same key but different value are encountered. In this case, we could report the error and cancel this DDL job.

### Checkpoints
In the current implementation, the progress of creating an index is persisted in reorgCtx, it is updated when each batch of the index is backfilled. For the new backfiller in this proposal, we could mark the progress in a similar way when an SST file generated from a batch of indexes is ingested successfully.
      
## Temporary files
The temporarily generated SST files are stored in local storage, the path of storage and maximum disk usage size should be configurable, but it’s not a good idea to modify them at runtime. If size of temporary files closes to allowed maximum size, the largest existing files are ingested to TiKV and cleaned.

Cleanup of the temporary files should be managed for the following cases:
- When the job is done or rollbacked, they are cleaned by the backfiller worker.
- Each TiDB instance should be able to check the inactive SST files and clean them, in case ownership of the job execution changes because of TiDB instance crashed.

## Limitations and future works
Compared with the current one, the CPU and memory consumption of new backfiller is not controlled smoothly when doing the ‘sort and ingest’.

## Compatibility
As an optimization, this proposal does not lead to any semantic change so theoretically there will be no compatibility issue.

### Enable/Disable
1. Use `tidb_ddl_enable_fast_reorg` to enable and disable new solution, default value is off. 

    Example:```TiDB> set global tidb_ddl_enable_fast_reorg = on/off;```

2. Use `tidb_ddl_disk_quota` to set a threshold of local disk max usage by new backfiller, the range of this variable is from 100 GiB to 1 PiB, default value is 100 GiB.
   
    Example:```TiDB> set global tidb_ddl_disk_quota = 107374182400;```

3. Use one config parameter `fast-reorg-local-path` to specify the sort path for lightning when it used in add index reorg stage. The default value is /tmp/tidb, please change it to your own disk path for the new backfiller could work properly.

    Example:```fast-reorg-local-path = "/tmp/tidb"```

---

### Design 2022 06 22 Foreign Key (`docs/design/2022-06-22-foreign-key.md`)

# Foreign Key Design Doc

- Author(s): [crazycs520](https://github.com/crazycs520)
- Tracking Issue: https://github.com/pingcap/tidb/issues/18209

## Abstract

This proposes an implementation of supporting foreign key constraints.

## DDL Technical Design

### Table Information Changes
The table's foreign key information will be stored in `model.TableInfo`:

```go
// TableInfo provides meta data describing a DB table.
type TableInfo struct {
    ...
    ForeignKeys         []*FKInfo            `json:"fk_info"`
    // MaxFKIndexID uses to allocate foreign key ID.
    MaxForeignKeyID     int64                `json:"max_fk_id"`
    ...
}

// FKInfo provides meta data describing a foreign key constraint.
type FKInfo struct {
    ID          int64       `json:"id"`
    Name        CIStr       `json:"fk_name"`
    RefSchema   CIStr       `json:"ref_schema"`
    RefTable    CIStr       `json:"ref_table"`
    RefCols     []CIStr     `json:"ref_cols"`
    Cols        []CIStr     `json:"cols"`
    OnDelete    int         `json:"on_delete"`
    OnUpdate    int         `json:"on_update"`
    State       SchemaState `json:"state"`
    Version     int         `json:"version"`
}
```

Struct `FKInfo` uses for the child table to record the referenced parent table. Struct `FKInfo` has existed for a long time, I just added some fields.
- `Version`: uses to distinguish between old and new versions. The new version value is 1, the old version value is 0.

Why `FKInfo` record the table/schema name instead of table/schema id? Because we may don't know the table/schema id when building `FKInfo`. Here is an example:

```sql
>set @@foreign_key_checks=0;
Query OK, 0 rows affected
>create table t2 (a int key, foreign key fk(a) references t1(id));
Query OK, 0 rows affected
>create table t1 (id int key);
Query OK, 0 rows affected
>set @@foreign_key_checks=1;
Query OK, 0 rows affected
>insert into t2 values (1);
(1452, 'Cannot add or update a child row: a foreign key constraint fails (`test`.`t2`, CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`a`) REFERENCES `t1` (`id`))')
```

As you can see, table `t2` refers to table `t1`, and when creating table `t2`, table `t1` still not be created, so we can't know the id of table `t1`.

### Create Table with Foreign Key

#### Build TableInfo

When building `TableInfo`, an index for the foreign key columns is created automatically if there is no index covering the foreign key columns. Here is an example:

```sql
mysql> create table t (id int key, a int, foreign key fk(a) references t(id));
Query OK, 0 rows affected
mysql> show create table t\G
***************************[ 1. row ]***************************
Table        | t
Create Table | CREATE TABLE `t` (
  `id` int NOT NULL,
  `a` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk` (`a`),
  CONSTRAINT `t_ibfk_1` FOREIGN KEY (`a`) REFERENCES `t` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
1 row in set
```

As you can see, the index `fk` is created automatically for the foreign key.

#### Validate

Create a table with foreign key, check the following conditions when a DDL job is built and the DDL owner received a DDL job(aka Double-Check):

- whether the user has `REFERENCES` privilege to the foreign key references table.
- Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of fixed precision types such as INTEGER and DECIMAL must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.
- Supports foreign key references between one column and another within a table. (A column cannot have a foreign key reference to itself.)
- Indexes on foreign keys and referenced keys are required, because the foreign key check can be fast and do not require a table scan.
- Prefixed indexes on foreign key columns are not supported. Consequently, BLOB and TEXT columns cannot be included in a foreign key because indexes on those columns must always include a prefix length.
- Does not currently support foreign keys for the partition table. This includes both reference and child tables.
- A foreign key constraint cannot reference any virtual generated columns, but the stored generated columns are fine.

#### Handle In DDL Owner

When the DDL Owner handle create table job, the DDL owner needs to create a new table.

At the same point in time, there may be two versions of the schema in the TiDB cluster, so we can't create a new table and
update all reference tables in one schema version, since this may break foreign key constraints, such as delete reference table
without foreign key constraint check in the child table.

```sql
-- In TiDB-1 and Schema Version is 1
insert into t_has_foreign_key values (1, 1);

-- In TiDB-0 and  Schema Version is 0
delete from t_reference where id = 1; --Since doesn't know foreign key information in old version, so doesn't do foreign key constrain check.
```

So, when creating a table with foreign key, we need multi-schema version change:

1. None -> Write Only: Create table with the state is `write-only`.
2. Write Only -> Public: Update the created table state to `public`.

#### Maintain ReferredFKInfo

Why need to maintain `ReferredFKInfo` in the reference table? When executing `UPDATE`/`DELETE` in the reference table, we need the `ReferredFKInfo` of the reference table to do a foreign key check/cascade.

How to maintain `ReferredFKInfo` in the reference table? When we create table with foreign key, we didn't add `ReferredFKInfo` into the reference table, because the reference table may not have been created yet,
when `foreign_key_checks` variable value is `OFF`, the user can create a child table before the reference table.

We decided to maintain `ReferredFKInfo` while TiDB loading schema. At first, `infoSchema` will record all table's `ReferredFKInfo`:

```sql
// ReferredFKInfo provides the referred foreign key in the child table.
type ReferredFKInfo struct {
    Cols          []CIStr `json:"cols"`
    ChildSchema   CIStr   `json:"child_schema"`
    ChildTable    CIStr   `json:"child_table"`
    ChildFKName   CIStr   `json:"child_fk"`
}
```

```go
type infoSchema struct {
    // referredForeignKeyMap records all table's ReferredFKInfo.
    // referredSchemaAndTableName => child SchemaAndTableAndForeignKeyName => *model.ReferredFKInfo
    referredForeignKeyMap map[SchemaAndTableName]map[SchemaAndTableAndForeignKeyName]*model.ReferredFKInfo
}
```

Function `applyTableUpdate` uses `applyDropTable` to drop the old table, uses `applyCreateTable` to create the new table.

In the function `applyDropTable`, we will delete the table's foreign key information from `infoSchema.referredForeignKeyMap`.

In the function `applyCreateTable`, we will add the table's foreign key information into `infoSchema.referredForeignKeyMap` first,
then get the table's `ReferredFKInfo` by schema name and table name, then store the `ReferredFKInfo` into `TableInfo.ReferredForeignKeys`.

Then `applyTableUpdate` will also need to reload the old/new table's referred table information, also uses `applyDropTable` to drop the old reference table, use `applyCreateTable` to create new reference table.

That's all.

### Alter Table Add Foreign Key

Here is an example:

```sql
create table t1 (id int key,a int, index(a));
create table t2 (id int key,a int);
alter  table t2 add foreign key fk(a) references t1(id) ON DELETE CASCADE;
```

Just like create table, we should validate first, and return an error if the conditions for creating foreign keys are not met, and also need to double-check.

When building `TableInfo`, we need to auto-create an index for foreign key columns if there are no index cover foreign key columns.
And this divides the problem into two cases:
- Case-1: No need to create an index automatically, and only add the foreign key constraint.
- Case-2: Need auto-create index for foreign key

#### Case-1: Only add foreign key constrain

The DDL owner handle adds foreign key constrain step is:

1. None -> Write Only: add foreign key constraint which state is `write-only` into the table.
2. Write Only -> Write Reorg: check all rows in the table whether has related foreign key exists in the reference table, we can use the following SQL to check:

   ```sql
   select 1 from t2 where t2.a is not null and t2.a not in (select id from t1) limit 1;
   ```
   The expected result is `empty`, otherwise, an error is returned and cancels the DDL job.

3. Write Reorg -> Public: update the foreign key constraint state to `public`.

A problem is, How the DML treat the foreign key on delete/update cascade behaviour in which state is non-public?
Here is an example:

```sql
create table t1 (id int key,a int, index(a));
create table t2 (id int key,a int, index(a));
insert into t1 values (1,1);
insert into t2 values (1,1);
alter  table t2 add constraint fk_1 foreign key (a) references t1(id) ON DELETE CASCADE;
```

The schema change of foreign key `fk_1` is from `None` -> `Write-Only` -> `Write-Reorg` -> `Public`。
When the foreign key `fk_1` in `Write-Only` state, a DML request has come to be processed:

```sql
delete from t1 where id = 1;
```

Then, TiDB shouldn't do cascade delete for foreign key `fk_1` in state `Write-Only`, since the `Add Foreign Key` DDL job maybe
failed in `Write-Reorg` state and rollback the DDL job. But it is hard to rollback the cascade deleted executed before.

So, when executing DML with `non-public` foreign key, TiDB will do foreign key constraint check instead of foreign key cascade behaviour.

#### Case-2: Auto-create index for foreign key and add foreign key constrain

As TiDB support multi-schema change now, we create an `ActionMultiSchemaChange` job that contains the following 2 sub-ddl job.
- Add Index DDL job
- Add Foreign Key Constraint DDL job

When TiDB adds foreign key DDL job meet error, TiDB will rollback the `ActionMultiSchemaChange` job and the 2 sub-ddl job will also be rollback.

### Drop Table

If `foreign_key_checks` is `ON`, then drop the table which has foreign key references will be rejected.

```sql
> drop table t1;
(3730, "Cannot drop table 't1' referenced by a foreign key constraint 't2_ibfk_1' on table 't2'.")
```

### Drop Database

If `foreign_key_checks` is `ON`, then drop the database which has foreign key references by another database will be rejected.

```sql
> drop database test;
(3730, "Cannot drop table 't1' referenced by a foreign key constraint 't2_ibfk_1' on table 't2'.")
```

### Drop Index

Drop index used by the foreign key will be rejected.

```sql
> set @@foreign_key_checks=0; -- Even disable foreign_key_checks, you still can't drop the index used for foreign key constrain.
Query OK, 0 rows affected
> alter table t2 drop index fk;
(1553, "Cannot drop index 'fk': needed in a foreign key constraint")
```

### Rename Column

Rename column which has foreign keys or references should also need to update the related child/parent table info.

```sql
create table t1 (id int key,a int, index(a));
create table t2 (id int key,a int, foreign key fk(a) references t1(id) ON DELETE CASCADE);
rename table t1 to t11;
alter table t11 change column id id1 int;
show create table t2\G
***************************[ 1. row ]***************************
    Table        | t2
Create Table | CREATE TABLE `t2` (
                                     `id` int NOT NULL,
                                     `a` int DEFAULT NULL,
                                     PRIMARY KEY (`id`),
    KEY `fk` (`a`),
    CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`a`) REFERENCES `t11` (`id1`) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
```

### Truncate Table

A truncate table which has foreign keys or references should also need to update the related child/parent table info.

### Modify Column

Modify column which used by the foreign key will be rejected.

```sql
> alter table t1 change column id id1 bigint;
(3780, "Referencing column 'a' and referenced column 'id1' in foreign key constraint 't2_ibfk_1' are incompatible.")
```

MySQL modify column problem: https://www.percona.com/blog/2019/06/04/ddl-queries-foreign-key-columns-MySQL-pxc/

What if the user really needs to modify column type, such as from `INT` to `BIGINT`. Maybe we can offer a variable such as `alter-foreign-keys-method=auto`,
then when the user modifies the column type, TiDB will auto-modify the related foreign key column's type. For easy implementation and to reduce risk, maybe only support modifying column type which doesn't need to reorg table row data.

## DML Technical Design

### DML On Child Table

On Child Table Insert Or Update, need to Find FK column value that exist in the reference table:

1. Get reference table info by table name.
2. Get the related fk index of the reference table.
3. tiny optimize, check fk column value exists in reference table cache(map[string(index_key)]struct).
3. Get related row in reference.
- Construct index key and then use snapshot `Iter` and `Seek` API to scan. If the index is unique and only contain
  foreign key columns, use the snapshot `Get` API.
    - `Iter` default scan batch size is 256, need to set 2 to avoid read unnecessary data.
4. compact column value to make sure exist.
5. If relate row exist in reference table, also need to add lock in the related row.
6. put column value into reference fk column value cache.

#### Lock

Let's see an example in MySQL first:

prepare:
```sql
create table t1 (id int key,a int, b int, unique index(a, b, id));
create table t2 (id int key,a int, b int, index (a,b,id), foreign key fk(a, b) references t1(a, b));
insert into t1 values (-1, 1, 1);
```

Then, execute the following SQL in 2 sessions:

| Session 1                        | Session 2                                   |
| -------------------------------- | ------------------------------------------- |
| Begin;                           |                                             |
| insert into t2 values (1, 1, 1); |                                             |
|                                  | delete from t1;  -- Blocked by wait lock    |
| Commit                           |                                             |
|                                  | ERROR: Cannot delete or update a parent row |

So we need to add lock in the reference table when insert/update child table.

##### In Pessimistic Transaction

When TiDB add pessimistic locks, if related row exists in the reference table, also needs to add lock in the related row.

##### In Optimistic Transaction

Just like `SELECT FOR UPDATE` statement, need to use `doLockKeys` to lock the related row in the reference table.

##### Issue

TiDB currently only support `lock for update`(aka write-lock, such as `select for update`), and doesn't support `lock for share`(aka read-lock, such as `select for share`).

So far we have to add `lock for update` in the reference table when insert/update child table, then the performance will be poor. After TiDB support `lock for share`, we should use `lock for share` instead.

#### DML Load data

Load data should also do foreign key check, but report a warning instead error:

```sql
create table t1 (id int key,a int, index(a));
create table t2 (id int key,a int, foreign key fk(a) references t1(id) ON DELETE CASCADE);

test> load data local infile 'data.csv' into table t2 FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';
Query OK, 0 rows affected
test> show warnings;
+---------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Level   | Code | Message                                                                                                                                                           |
+---------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Warning | 1452 | Cannot add or update a child row: a foreign key constraint fails (`test`.`t2`, CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`a`) REFERENCES `t1` (`id`) ON DELETE CASCADE) |
| Warning | 1452 | Cannot add or update a child row: a foreign key constraint fails (`test`.`t2`, CONSTRAINT `t2_ibfk_1` FOREIGN KEY (`a`) REFERENCES `t1` (`id`) ON DELETE CASCADE) |
+---------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
```

`data.csv` is:
```
1,1
2,2
```

### DML On reference Table

On reference Table Delete Or Update:

1. modify related child table row by referential action:
- `CASCADE`: update/delete related child table row.
- `SET NULL`: set related child row's foreign key columns value to NULL.
- `RESTRICT`, `NO ACTION`: If related row exist in child table, reject update/delete the reference table.
- `SET DEFAULT`: just like `RESTRICT`.

modify related child table rows by the following step:
1. get child table info by name(in reference table info).
2. get the child table fk index's column info.
3. build update executor to update child table rows.

### Issue need to be discussed

#### Affect Row

related article: https://www.percona.com/blog/hidden-cost-of-foreign-key-constraints-in-MySQL/

Here is a MySQL example:

prepare:
```sql
create table t1 (id int key,a int, index(a));
create table t2 (id int key,a int, foreign key fk(a) references t1(id) ON DELETE CASCADE);
insert into t1 values (1, 1);
insert into t2 values (1, 1);
```

Then delete on reference table:
```sql
> delete from t1 where id=1;
Query OK, 1 row affected
```

As you can see, in the query result, the affected row is 1, but actually should be 2, since the related row in t2 is also been deleted.

This is a MySQL behaviour, We can be compatible with it.

#### DML Execution plan

Here is a MySQL example:

prepare:
```sql
create table t1 (id int key,a int, index(a));
create table t2 (id int key,a int, foreign key fk(a) references t1(id) ON DELETE CASCADE);
insert into t1 values (1, 1);
insert into t2 values (1, 1);
```

```sql
> explain delete from t1 where id = 1;
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type  | possible_keys | key     | key_len | ref   | rows | filtered | Extra       |
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------------+
| 1  | DELETE      | t1    | <null>     | range | PRIMARY       | PRIMARY | 4       | const | 1    | 100.0    | Using where |
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+------+----------+-------------+
```

From the plan, you can't see any information about the foreign key constraint which needs to delete the related row in child table `t2`.

I think this is a MySQL issue, should we make TiDB plan better, at least when we meet some slow query, we can know maybe it is caused by modify related rows in the child table.

Here is an example plan with foreign key:

```sql
> explain delete from t1 where id = 1;
+-------------------------+---------+------+---------------+-----------------------------------+
| id                      | estRows | task | access object | operator info                     |
+-------------------------+---------+------+---------------+-----------------------------------+
| Delete_2                | N/A     | root |               | N/A                               |
| ├─Point_Get_1           | 1.00    | root | table:t1      | handle:1                          |
| └─Foreign_Key_Cascade_3 | 0.00    | root | table:t2      | foreign_key:fk, on_delete:CASCADE |
+-------------------------+---------+------+---------------+-----------------------------------+
```

And the `explain analyze` will show the foreign key cascade child plan:

```
/* Detailed source-code truncated for AI context efficiency. */
```

##### CockroachDB DML Execution Plan

```sql
CREATE TABLE customers_2 (
    id INT PRIMARY KEY
);
CREATE TABLE orders_2 (
    id INT PRIMARY KEY,
    customer_id INT REFERENCES customers_2(id) ON UPDATE CASCADE ON DELETE CASCADE
);
INSERT INTO customers_2 VALUES (1), (2), (3);
INSERT INTO orders_2 VALUES (100,1), (101,2), (102,3), (103,1);
```

```sql
> explain analyze UPDATE customers_2 SET id = 23 WHERE id = 1;
                       info
--------------------------------------------------
  planning time: 494µs
  execution time: 5ms
  distribution: local
  vectorized: true
  rows read from KV: 6 (170 B)
  cumulative time spent in KV: 978µs
  maximum memory usage: 100 KiB
  network usage: 0 B (0 messages)
  regions: us-east1

  • root
  │
  ├── • update
  │   │ nodes: n1
  │   │ regions: us-east1
  │   │ actual row count: 1
  │   │ table: customers_2
  │   │ set: id
  │   │
  │   └── • buffer
  │       │ label: buffer 1
  │       │
  │       └── • render
  │           │ nodes: n1
  │           │ regions: us-east1
  │           │ actual row count: 1
  │           │ KV rows read: 1
  │           │ KV bytes read: 27 B
  │           │
  │           └── • scan
  │                 nodes: n1
  │                 regions: us-east1
  │                 actual row count: 1
  │                 KV rows read: 1
  │                 KV bytes read: 27 B
  │                 missing stats
  │                 table: customers_2@primary
  │                 spans: [/1 - /1]
  │                 locking strength: for update
  │
  └── • fk-cascade
        fk: fk_customer_id_ref_customers_2
        input: buffer 1
```

##### PostgreSQL DML Execution Plan

```sql
postgres=# explain analyze UPDATE customers_2 SET id = 20 WHERE id = 23;
                                                             QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------
 Update on customers_2  (cost=0.15..8.17 rows=1 width=10) (actual time=0.039..0.039 rows=0 loops=1)
   ->  Index Scan using customers_2_pkey on customers_2  (cost=0.15..8.17 rows=1 width=10) (actual time=0.016..0.016 rows=1 loops=1)
         Index Cond: (id = 23)
 Planning Time: 0.057 ms
 Trigger for constraint orders_2_customer_id_fkey on customers_2: time=0.045 calls=1
 Trigger for constraint orders_2_customer_id_fkey on orders_2: time=0.023 calls=2
 Execution Time: 0.129 ms
```

## Compatibility

Since the old version TiDB already support foreign key syntax, but doesn't support it, after upgrade TiDB to latest version, the foreign key created before won't take effect. Only foreign keys created in the new version actually take effect.

You can use `SHOW CREATE TABLE` to see whethere a foreign key is take effect, the old version foreign key will have a comment `/* FOREIGN KEY INVALID */` to indicate it is invalid, the new version foreign key doesn't have this comment.

```sql
> show create table t2\G
    ***************************[ 1. row ]***************************
    Table        | t2
Create Table | CREATE TABLE `t2` (
    `id` int(11) NOT NULL,
    PRIMARY KEY (`id`) /*T![clustered_index] CLUSTERED */,
    CONSTRAINT `fk` FOREIGN KEY (`id`) REFERENCES `test`.`t1` (`id`) ON DELETE CASCADE ON UPDATE CASCADE /* FOREIGN KEY INVALID */
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
```

## Impact

### Impact of data replication

#### TiCDC

When syncing table data to downstream TiDB, TiCDC should `set @@foreign_key_checks=0` in downstream TiDB.

#### DM

When doing full synchronization, DM should `set @@foreign_key_checks=0` in downstream TiDB.

When doing incremental synchronization, DM should set `foreign_key_checks` session variable according to MySQL binlog.

#### BR

When restore data into TiDB, BR should `set @@foreign_key_checks=0` in TiDB.

## Test Case

Cascade modification test case:

```sql
drop table if exists t3,t2,t1;
create table t1 (id int key,a int, index(a));
create table t2 (id int key,a int, foreign key fk(a) references t1(id) ON DELETE CASCADE);
create table t3 (id int key,a int, foreign key fk(a) references t2(id) ON DELETE CASCADE);
insert into t1 values (1,1);
insert into t2 values (2,1);
insert into t3 values (3,2);
delete from t1 where id = 1;  -- both t1, t2, t3 rows are deleted.
```

Following is a MySQL test case about `SET DEFAULT`, as you can see, MySQL actualy doesn't support `SET DEFAULT`, the behaviour is just like `RESTRICT`

```sql
MySQL>create table t1 (a int,b int, index(a,b)) ;
Query OK, 0 rows affected
Time: 0.022s
MySQL>create table t (a int, b int, foreign key fk_a(a) references test.t1(a) ON DELETE SET DEFAULT);
Query OK, 0 rows affected
Time: 0.019s
MySQL>insert into t1 values (1,1);
Query OK, 1 row affected
Time: 0.003s
MySQL>insert into t values (1,1);
Query OK, 1 row affected
Time: 0.006s
MySQL>delete from t1 where a=1;
(1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`test`.`t`, CONSTRAINT `t_ibfk_1` FOREIGN KEY (`a`) REFERENCES `t1` (`a`))')
MySQL>select version();
+-----------+
| version() |
+-----------+
| 8.0.29    |
+-----------+
```

### Self-Referencing Tables

For example, table `employee` has a column `manager_id` references to `employee.id`.

```sql
create table employee (id int key,manager_id int, foreign key fk(manager_id) references employee(id) ON DELETE CASCADE);
insert into employee values (1,1);
insert into employee values (2,1);

test> delete from employee where id=1;
Query OK, 1 row affected
test> select * from employee;
+----+---+
| id | a |
+----+---+
0 rows in set
```

A case of self-reference and cyclical dependencies:

```sql
test> create table t (id int key,a int, foreign key fk_a(a) references t(id) ON DELETE CASCADE, foreign key fk_id(id) references t(a) ON DELETE CASCADE);
Query OK, 0 rows affected
Time: 0.045s
test> insert into t values (1,1);
(1452, 'Cannot add or update a child row: a foreign key constraint fails (`test`.`t`, CONSTRAINT `t_ibfk_2` FOREIGN KEY (`id`) REFERENCES `t` (`a`) ON DELETE CASCADE)')
```

### Cyclical Dependencies

```sql
create table t1 (id int key,a int, index(a));
create table t2 (id int key,a int, foreign key fk(a) references t1(id) ON DELETE CASCADE);
insert into t1 values (1,1);
ALTER TABLE t1 ADD foreign key fk(a) references t2(id) ON DELETE CASCADE;
(1452, 'Cannot add or update a child row: a foreign key constraint fails (`test`.`#sql-298_8`, CONSTRAINT `t1_ibfk_1` FOREIGN KEY (`a`) REFERENCES `t2` (`id`) ON DELETE CASCADE)')
```

```sql
set @@foreign_key_checks=0;
create table t1 (id int key,a int, foreign key fk(a) references t2(id) ON DELETE CASCADE);
create table t2 (id int key,a int, foreign key fk(a) references t1(id) ON DELETE CASCADE);
insert into t1 values (1, 2);
insert into t2 values (2, 1);
set @@foreign_key_checks=1;   -- add test case without this.
delete from t1 where id=1;
test> select * from t2;
+----+---+
| id | a |
+----+---+
0 rows in set
Time: 0.004s
test> select * from t1;
+----+---+
| id | a |
+----+---+
0 rows in set
```

### Check order

check order should check unique/primary key constrain first:

```sql
test> create table t1 (id int key,a int, index(a));
test> create table t2 (id int key,a int, foreign key fk(a) references t1(id) ON DELETE CASCADE);
test> insert into t1 values (1, 1);
test> insert into t2 values (1, 1);
test> insert into t2 values (1, 2);
(1062, "Duplicate entry '1' for key 't2.PRIMARY'")
test> insert ignore into t2 values (1, 2);
Query OK, 0 rows affected
```

### MATCH FULL or MATCH SIMPLE

This definition is from [CRDB](https://www.cockroachlabs.com/docs/v22.1/foreign-key.html#match-composite-foreign-keys-with-match-simple-and-match-full). MySQL doesn't mention it, here is a MySQL test case:

Here is an MySQL example:

```sql
create table t1 (i int, a int,b int, index(a,b)) ;
create table t (a int, b int, foreign key fk_a(a,b) references test.t1(a,b));

test> insert into t values (null,1);
Query OK, 1 row affected
test> insert into t values (null,null);
Query OK, 1 row affected
test> insert into t values (1,null);
Query OK, 1 row affected
```

## reference

- [MySQL FOREIGN KEY Constraints Document](https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html#foreign-key-adding)
- [3 Common Foreign Key Mistakes (And How to Avoid Them)](https://www.cockroachlabs.com/blog/common-foreign-key-mistakes/)
- [Hidden Cost of Foreign Key Constraints in MySQL](https://www.percona.com/blog/hidden-cost-of-foreign-key-constraints-in-MySQL/)
- [DDL Queries on Foreign Key Columns in MySQL/PXC](https://www.percona.com/blog/2019/06/04/ddl-queries-foreign-key-columns-mysql-pxc/)

---

### Design 2022 07 03 Block Storage Snapshot Based Backup Restore (`docs/design/2022-07-03-block-storage-snapshot-based-backup-restore.md`)

# TiDB Cluster on Amazon EBS Backup & Restore


## Table of Contents

* [Introduction](#introduction)
* [Goal](#goal)
* [Limitation](#limitation)
* [Architecture Design](#architecture-design)
    * [Solution Overview](#solution-overview)
      * [Backup Worker](#backup-worker)
      * [Restore Worker](#restore-worker)
    * [Key Design](#key-design)
      * [Backup](#backup)
      * [Restore](#restore)
    * [Data Consistency](#data-consistency)
      * [Transaction consistency](#transaction-consistency)
      * [A Raft Group consistency](#a-raft-group-consistency)
      * [Multi Raft Group consistency](#multi-raft-group-consistency)
* [Feature Detail Design](#feature-detail-design)
    * [Backup workflow](#backup-workflow)
    * [Restore workflow](#restore-workflow)
  * [Impacted components](#impacted-components)
    * [Backup Worker](#backup-worker)
    * [Restore Worker](#restore-worker)
    * [TiDB Operator](#tidb-operator)
      * [Backup design](#backup-design)
      * [Restore design](#restore-design)
    * [Backup Restore](#backup-restore)
      * [BR Backup](#br-backup)
      * [BR Restore](#br-restore)
    * [TiKV](#tikv)
    * [Interface Definition](#interface-definition)
      * [restore worker - PD / TiKV](#restore-worker-pd-tikv)
      * [BR - PD](#br-pd)
      * [TiKV - PD](#tikv-pd)
      * [BR - TiKV](#br-tikv)
      * [BR - restore worker](#br-restore-worker)
* [Exception Handling](#exception-handling)
* [Backward / Forward Compatibility](#backward-forward-compatibility)
* [Security](#security)
* [Dependencies](#dependencies)
* [Technical Risk](#technical-risk)
* [Impacts & Risks](#impacts--risks)
* [Testing Note](#testing-note)
* [Design review](#design-review)



# **Introduction**

Amazon Elastic Block Store ([Amazon EBS](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html)) is an easy-to-use, scalable, high-performance block-storage service designed for Amazon Elastic Compute Cloud (Amazon EC2). It provides varied volume types that best fit the workload. The EBS volumes that are attached to an instance are exposed as storage volumes that persist independently from the life of the instance. Most importantly, you can back up the data on your Amazon EBS volumes by taking EBS snapshots.

TiDB is a distributed database providing horizontal scalability, strong consistency, and high availability. It is designed to work in the cloud to make deployment, provisioning, operations, and maintenance flexible. 

Current TiDB Backup Restore solution provides high-performance backup and restore speeds for large-scale TiDB Clusters, however, the impact to the cluster being backed up is notable for many customers and hard to reduce based on current implementation. By leveraging the Amazon EBS snapshot feature, we can provide a block-level based backup and recovery solution with transaction consistency and minimize the impact to the target TiDB cluster..


## Goal

Backup and Restore a TiDB cluster using the EBS snapshot on the AWS, it is expected to achieve:



* Minimize impact to the TiDB cluster during the backup.
    * QPS/Transaction Latency &lt; 5%
* Shorten backup and restore time.
    * Backup time &lt; 1 hours
    * Restore time &lt; 2 hours 


## Limitation



* Only AWS EBS supported, does not support EFS, local instance store etc.
* Does not support TiFlash backup & restore.
* Does not support other clouds.


# **Architecture Design**


## Solution overview





A [Custom Resource Definition](https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/) (CRD) generated based on the Backup/Restore request launched by the customer  in TiDB Operator. 

The Backup & Restore Controller detects the CRD. Then, creates a new POD to load the corresponding worker to execute the backup and restore work.



### **Backup Worker**






1. The backup started by a backup CRD where the customer submitted.
2. TiDB Operator creates/starts the Backup Worker (Job in the above figure) based on the CRD.
3. The Backup Worker gets the global resolved_ts of the TiDB cluster through PD and saves it into metadata.
4. The Backup Worker queries the topology information of the TiDB cluster and the corresponding EBS volume info of all TiKV nodes and saves them in metadata. The Backup Worker configures the PD to prohibit operations such as replica, merge, and GC etc, and waits for the completion of the ongoing replica scheduling.
5. The Backup Worker initiates an EBS snapshot to all nodes, and records the snapshot information in metadata.
6. The Backup Worker reconfigures the PD to get it back to its original state where we start backup.
7. The Backup Worker queries the status of the snapshot in each node, and waits until all snapshot states changed from pending to completed. The Backup Worker is automatically destroyed according to the configured CRD policy.

Notice: If the user wants to delete the backup (snapshots and metadata), the user can simply remove the backup CR from TiDB Operator.


### **Restore Worker**







1. The Restore started by a restore CRD which the customer submitted.
2. TiDB Operator creates/starts the Restore Worker (Job in the above figure) based on the CRD.
3. The Backup Worker retrieves the global resolved_ts and topology diagram of the TiDB cluster from S3 backup metadata.
4. The Restore Worker checks the topology of the restored TiDB Cluster, (especially the number of TiKVs, volume). If it matches the topology in the metadata, the Restore Worker restores and mounts the snapshot to the restored TiDB Cluster from S3, otherwise it reports an error and exits.
5. The Restore Worker configures the PD to prohibit operations the same as Backup Worker do. 
6. The Restore Worker uses the global resolved_ts to invoke BR Recover component for handling the data of the TiKV node into a consistent state.
7. The Restore Worker reconfigures the PD to get it back to its original state where we start backup. The TiDB cluster is online, and then The Restore Worker is automatically destroyed according to the CRD policy. The Restoration is finished.


## Key Design


### Backup

For Backup, as Backup Worker states, there are mainly 3 steps:



1. Configure the TiDB cluster.
2. Get TiDB cluster level resolved_ts.
3. Backup data by EBS snapshot.

Step 1 assume time &lt; 5 minute (included fault tolerance, e.g. retry)

Step 2 TiKV already maintains the resolved_ts component.

Step 3 snapshot depends on the customer's EBS volume type and data change. Excluding full snapshot at first time, one day data change with gp3 type may takes ~ 10 minutes in our test.


### Restore

For Restore, as Restore Worker states, there are mainly 3 steps:



1. Initialize snapshot restore and prepare restored volume.
2. Region recovery, select a leader, and align raft log.
3. Resolved data by cluster level resolved_ts.

Step 1, assume takes &lt; 30 minutes

Step 2, assume takes &lt; 10 minutes, since the snapshot taken parallelly, the unalign raft log among peers in a Region is few.

Step 3, assume takes &lt; 30 minutes, Resolved data by removing all key-values that have versions larger than resolved_ts. And also resolved data through the raft layer, not to delete from disk directly.

Note: For EBS volume fully initialized, there are extra steps suggested by [AWS](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-initialize.html). 


## Data Consistency

TiDB Cluster On AWS EBS, a key-value write workflow as follows:

TiDB->TiKV->OS->EBS





<table>
  <tr>
   <td><strong>Layer</strong>
   </td>
   <td><strong>Owned By</strong>
   </td>
   <td><strong>Description</strong>
   </td>
  </tr>
  <tr>
   <td>SQL
   </td>
   <td>TiDB
   </td>
   <td>Where the user data comes from
   </td>
  </tr>
  <tr>
   <td>Transaction
   </td>
   <td>TiDB
   </td>
   <td>Refer to the transaction driver of TiDB, which has ACID properties. 
   </td>
  </tr>
  <tr>
   <td>MVCC
   </td>
   <td>TiKV
   </td>
   <td>Multiversion Concurrency Control module in TiKV
   </td>
  </tr>
  <tr>
   <td>Raftstore
   </td>
   <td>TiKV
   </td>
   <td>An MultiRaft implementation in TiKV
   </td>
  </tr>
  <tr>
   <td>RocksDB
   </td>
   <td>TiKV
   </td>
   <td>A key-value storage stores user data
   </td>
  </tr>
  <tr>
   <td>OS
   </td>
   <td>AWS
   </td>
   <td>EC2 instance, response to local volume and format file system on volume.
   </td>
  </tr>
  <tr>
   <td>Volume
   </td>
   <td>AWS
   </td>
   <td>EBS volume, like a disk on an on-premises data center.
   </td>
  </tr>
  <tr>
   <td>EBS
   </td>
   <td>AWS
   </td>
   <td>More like an AWS storage pool, can provide a various performance disk (gp3, io2 etc) for EC2.
   </td>
  </tr>
</table>


In TiDB, The transaction layer adopts the Percolator model, which is 2 phase commit. TiDB is a distributed key-value database. TiKV uses the raft consensus algorithm to provide strong consistency. Furthermore, TiKV implements multi-raft in Raftstore and provides data consistency and scalability.

AWS EBS is the physical storage layer, and EBS volume can be backed up by EBS snapshot. In the transaction layer, after the data of the same transaction is encoded by the MVCC and processed by the raft layer, complete transaction data is written on different TiKV EBS volumes. The consistency of the snapshot on these volumes needs to be handled as follow:


#### Transaction consistency

TiKV has the Region resolved_ts component maintains timestamp (ts) within a Region. This resolved_ts ensures that the timestamp with the maximum consistency of the current Region data, any data with timestamp lower than resolved_ts has transaction layer consistency. Meanwhile, in the latest implementation, TiKV calculates the minimum resolved_ts of the current store, and reports it to PD. See [ReportMinResolvedTsRequest](https://github.com/fengou1/kvproto/blob/bd679cab506b8b8b75af2595624c3c3cd4254354/proto/pdpb.proto#L825).

In our solution, we get this resolved_ts from PD and use it as ts to resolve backup in the restore phase.

The key-value of the same transaction will be written to different Raft Groups. In the restore phase, after a Raft Group is handled to consistency, we use transaction-consistent resolved_ts to go to each TiKV to delete the data of incomplete transactions. For this step, see the detailed design of the Backup and Restore ResolvedData phase.


#### A Raft Group consistency

For each Raft Group within TiKV, we have to deal with Region metadata and Region data.



* Region metadata




In TiKV#1, a write proposal has been applied, but TiKV#2 and TiKV#3 have not been applied.

For each Raft Group, we process the meta and data of the Region through BR RegionRecover, its workflow as follows:



1. In the restore phase, put TiKV in the recovery mode, and TiKV reports all peer lists to BR.
2. For each raft group, find the peer with most reliable log in the Region, and force it to be the leader. For other peers to be silent, start the raft state machine. leader selection refer to [BR Restore](#br-restore)
3. Wait for all peers in the Region until applied index == last index, and then set the correct raft status to exit data RegionRecover recovery.
* Region data

In the previous step of RegionRecover phase, the second step is to start the raft state machine, so that the raft log of each Region non-leader node is applied to the largest log index. Region-level data consistency achieved.


#### Multi Raft Group consistency

Turn off pd scheduler. The reason is that when there are a large number of write scenarios to TiDB Cluster, the snapshot is sync. It is very likely that peer replication from one tikv volume to another, while 2 volumes has been snapshotted asynchronously. At block-level data may be lost. At the same time, replica scheduling makes the epoch version change, and there are many intermediate states that need to be processed. These states make it very complicated to deal with such problems. Currently PD supports the following methods to turn off peer replication:


```
./pd-ctl --pd=http://127.0.0.1:2379 config set merge-schedule-limit 0
./pd-ctl --pd=http://127.0.0.1:2379 config set region-schedule-limit 0
./pd-ctl --pd=http://127.0.0.1:2379 config set replica-schedule-limit 0
./pd-ctl --pd=http://127.0.0.1:2379 config set hot-region-schedule-limit 0
```


After the above schedule is limited to 0, peer addition, deletion and replication (from one TiKV to another) are prohibited. At the same time, functions such as merge and scatter across TiKV are also prohibited. For Regions that may have overlapping Ranges due to splits, after PD scheduling is resumed. please refer to the Recover function design for details, and for details about replicas, please refer to Q&A


# **Feature Detail Design**


### **Backup workflow**






After the TiDB Operator starts the Backup Worker, the backup job starts.



1. Get the cluster level consistency min_resolved_ts. 
2. Configure the PD scheduler to stop cluster peer replication. And also stop GC.
3. Take snapshots for all TiKV volumes in the cluster through aws api, save metadata information to S3. For details, refer to the definition of[ metadata information](#bookmark=id.pm5ucdf8u44s)
4. Wait for the snapshot to complete and save the cluster meta information to S3.
5. Resume scheduling of the PD cluster.
6. Exit the backup.


### **Restore workflow**





After the TiDB Operator starts the Restore Worker, it starts to restore work.

- Restore prerequisites:



* The customer already has a cluster to be restored and specified in the CRD.
* The backup data has been specified in the CRD.
1. The Restore Worker retrieves the backup metadata, which includes cluster topology information and cluster level min_resolved_ts during backup.
2. The Restore Worker gets the topology information of the present TiDB cluster through PD. (e.g: the number of TiKVs, replica). see [GetAllStoresRequest](https://github.com/fengou1/kvproto/blob/bd679cab506b8b8b75af2595624c3c3cd4254354/proto/pdpb.proto#L235).
3. The Restore Worker checks whether the topology information of the target cluster to be restored is consistent with the original cluster information. If they are identical, start the restoration, otherwise exit directly.
4. The Restore Worker stops the related scheduling of the PD, and the PD stops the scheduler.
5. The Restore Worker stops TiKV, and restores snapshot to volume according to the snapshot id in the metadata, mounts volume to TiKV.
6. The Restore Worker restores the PD with max allocated ID which caculate from region meta report by tikv.
7. Using the cluster level resolved_ts in the backup metadata, call the BR Recover to process all TiKV data into a cluster level consistent state.
8. The Restore Worker resumes the PD scheduler to bring TiDB cluster online, the restoration work is completed, and the restore worker exits.


## Impacted components

**Backup metadata definition**


```
/* Detailed source-code truncated for AI context efficiency. */
```



### Backup Worker

Backup worker has implements the following functions:

1. Obtain the configuration information of the online backup cluster, such as resolved_ts.

2. Configure cluster PD scheduling, stop replica scheduling, turn off GC during backup, and then turn on GC after backup.

3. The snapshot function of EBS/pv volumes whose TiKV running on.

Worker container contains: 1. backup-manager, 2. BR


```bash
backup full --type=aws-ebs --pd "172.16.2.1:2379" -s "s3:/bucket/backup_folder" --volumes-file=backup.json
```


Backup worker workflow





1. TiDB Operator retrieves the PD address of the target cluster and all TiKV volume information.

2. TiDB Operator provides --volumes-file=backup.json for the backup cluster, starts the backup job, and backup.toml contains:


```json
{
 "tikv" : {
   "replicas": 3,
   "stores": [
   {
     "store_id" : 1,
     "volumes" : [
       {
         "volume_id" : "vol-0e65f40961a9f6244",
         "type" : "raft-engine.dir",
         "mount_path" : "/var/lib/tikv/raft-engine"
       },
       {
         "volume_id" : "vol-0e65f40961a9f6245",
         "type" : "storage.data-dir",
         "mount_path" : "/var/lib/tikv/data-dir"
       }
     ]
   },
   {
     "store_id" : 2,
     "volumes" : [
       {
         "volume_id" : "vol-0e65f40961a9f6246",
         "type" : "raft-engine.dir",
         "mount_path" : "/var/lib/tikv/raft-engine"
       },
       {
         "volume_id" : "vol-0e65f40961a9f6247",
         "type" : "storage.data-dir",
         "mount_path" : "/var/lib/tikv/data-dir",
       }
     ]
   },
    {
     "store_id" : 3,
     "volumes" : [
       {
         "volume_id" : "vol-0e65f40961a9f6248",
         "type" : "raft-engine.dir",
         "mount_path" : "/var/lib/tikv/raft-engine"
       },
       {
         "volume_id" : "vol-0e65f40961a9f6249",
         "type" : "storage.data-dir",
         "mount_path" : "/var/lib/tikv/data-dir",
       }
     ]
   }
 ], 
 },
 "pd" : {
   "replicas" : 3
 },
 "tidb": {
   "replicas" : 3
 }, 
 "kubernetes" : {
   "pvs" : [],
   "pvcs" : [],
   "crd_tidb_cluster" : {},
   "options" : {}
 }
 "options" : {}
}
```


3. Job contains BR, BR reads the details of backup.json and starts backup. For more backup details, see BR Backup Detailed Design.


### RestoreWorker

Restore worker implements the following functions:

1. Obtain the deployment information of the recovery cluster, such as: PD, number of tikv

2. The ability to restore EBS/pv volumes from snapshot

3. Mount and start control of TiKV volume of cluster

4. Start BR for data recovery

Worker container contains: 1. backup-manager, 2. BR

Restore worker workflow:





1. backup-manager starts BR to read backup information from S3, get all snapshotIDs, set PD to the recovery mode. Examples of BR commands are as follows:


```bash
br restore full  --type=aws-ebs --prepare --pd "172.16.2.1:2379" -s "s3:///us-west-2/meta/&sk=xx..." --output=topology.json
```


BR command output as follows:


```
/* Detailed source-code truncated for AI context efficiency. */
```


2. The backup-manager mounts the relevant volume and starts TiKV.

3. The backup-manager starts the BR again until the BR completes the restoration of data consistency, sets the PD flag to enter the normal mode, and then restarts TiKV to exit. For detailed design, see BR Restore Detailed Design


```bash
br restore full --type=aws-ebs --pd "172.16.2.1:2379" -s "s3:///us-west-2/meta/&sk=xx..."
```



### TiDB Operator

**Backup design**







1. Expand the CR of [TiDB Operator](https://github.com/pingcap/tidb-operator/): [Backup](https://github.com/pingcap/tidb-operator/blob/f73a54732ac19ddbb5b59e752794898b4502cd53/docs/api-references/docs.md#backup/BackupSchedule/Restore) / [BackupSchedule](https://github.com/pingcap/tidb-operator/blob/f73a54732ac19ddbb5b59e752794898b4502cd53/docs/api-references/docs.md#backupschedule) / [Restore](https://github.com/pingcap/tidb-operator/blob/f73a54732ac19ddbb5b59e752794898b4502cd53/docs/api-references/docs.md#restore), add new snapshot types.
2. Obtain PD / TiKV / TiDB replicas from each Spec of CR-[TiDBCluster](https://github.com/pingcap/tidb-operator/blob/f73a54732ac19ddbb5b59e752794898b4502cd53/docs/api-references/docs.md#tidbcluster).
3. Based on TiKV-StatefulSet to create the Pods / PVs / PVCs for extracting each store_id and the corresponding volume information, including volume ID, configuration type and the path to mount to the container, pay attention to the specific provisioner type here, and the volume_id will be distinguished. If the volume uses [AWS-EBS-CSI-driver](https://pingcap.feishu.cn/wiki/wikcnBbTz00zcig0FlErkCMJCKf#) whose Type is CSI and Driver is [ebs.csi.aws.com](http://ebs.csi.aws.com/), it will be extracted from Source.VolumeHandle after mapping.
4. Create a Job through Backup Manager, pass in the above meta information structure, configure storage such as S3, process permissions such as iam + serviceaccount or secret, and finally call BR to execute the call [EC2-CreateSnapshot](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.CreateSnapshot) to create a snapshot, and complete the PD scheduler and GC at the same time. management to ensure volume snapshots are performed at safe points.
5. The actual volume snapshot progress is updated by the ticker to report the backup progress until the backup is completed.
6. Wait for the BR execution to complete, report the update backup completion status, and exit the job.

**Restore design**







1. Expand CR: Restore of TiDB Operator, add snapshot restore type, expand restore state machine, add volume restore completion status and data restore complete status.
2. Set the recovery mark of CR-TiDBCluster and let the TiDBCluster Controller handle it. After the PD is created and running normally, it blocks the creation of TiKV-StatefulSet and waits for the mark of successful volume recovery to be cleared.
3. When PD is running and TiKV is not running, create Job-1 through Restore Manager, configure storage such as S3, process permissions such as iam + serviceaccount or secret, and finally call BR to restore the volume snapshot, and set the PD flag to be in recovery mode.
4. Wait for the BR execution to complete, report the metadata information of the update output, set the Restore status to volume recovery complete, and exit Job-1.
5. When the volume recovery is complete, the Restore Manager resets the blocking flag of TiKV, processes the volume information according to different Provisioners, converts the settings into the corresponding PVs, and clears the metadata information used for the binding of PVs and PVCs. In the scenario, you need to rename the corresponding PVs, and submit the above tags and newly constructed PVs / PVCs resources.
6. After the TiKV member Manager is unblocked, it continues to execute the StatefulSet creation process, and then processes the submitted PVCs/PVs and other information. After TiKV starts running and interacts with the PD with the recovery mark for the first time, it enters the recovery mode to run.
7. After the Restore Manager monitors that TiKV / PD is running, and there is a recovery mark, it creates Job-2, and finally calls BR to execute the data consistency of TiKV according to its own CR-Restore configuration parameters, metadata information, and current status. Process, clear data after min_resolved_ts, also clear PD flag and resume normal operation mode.
8. Wait for the BR execution to complete, report the updated Restore status as data recovery complete, and exit Job-2.
9. After the Restore Manager clears the recovery mark and monitors the normal operation of CR-TiDBCluster and provides services, set the Restore status to recovery complete.


### Backup Restore 


#### BR Backup

1. Backup cluster basic metadata, such as resolved_ts,

2. Configure cluster scheduling, stop replica scheduling, turn off GC during backup, and turn on GC after backup

3. The snapshot function of EBS/pv volumes

Backup workflow





1. The BR is connected to the PD, and the BR stops the peer related scheduler of the PD, mainly by setting the number of PD operators to limit. Before setting, it need to read the current operator configuration information, and restore the cluster configuration immediately after the snapshot is completed. The main PD operator needs to contain:
```go
	const enableTiKVSplitRegion = "enable-tikv-split-region"
	scheduleLimitParams := []string{
		"hot-region-schedule-limit",
		"leader-schedule-limit",
		"merge-schedule-limit",
		"region-schedule-limit",
		"replica-schedule-limit",
		enableTiKVSplitRegion,
	}
```
2. Read resolved_ts and save it in the backup data.

3. Shut down the GC by start a background safepoint keeper. Continuously update the GC safepoint to stop the GC.

4. Get the ongoing peer scheduling operator operation and wait until the scheduling is complete.

56. After the Snapshot returns (EBS snapshot returns immediately), enable copy scheduling and enable GC.

6. Wait for the AWS snapshot to complete

7. Summarize all backup data information and upload to the target storage S3.


#### BR Restore

There are mainly 2 phase implementations, RegionRecover and ResolvedData.


* RegionRecover design
1. After the 1st BR is invoked by TiDB Operator, BR first put a recovery marker in pd, and all startup TiKV read the marker at very early startup, then TiKV switches to recovery mode. At the same time, TiKV starts the recovery service.
2. BR send a read region meta request to TiKV, TiKV scans the metadata of all local regions, and sends it to the BR by a stream.
3. After the BR receives the reports of all Region info (peer list) of all TiKV instances, it makes a decision based on the reported peer list. And send the recovery command to all TiKV instances for each region; close gRPC stream after sending. The BR decision as follows:
    1. for any region, select a peer as leader, peer has the max last log term as qualified leader, or
    2. if the last log term is the same, select peer has the max last log index
    3. if the last log index is the same, select peer has the max commit index
4. BR send recover region command to TiKV, TiKV assign a leader and then wait all region peer apply to last index.
5. RegionRecover completes.
* ResolvedData design
start 2 worker to delete data with ts > min_resolved_ts

1. Scan the KV DB of each TiKV through min_resolved_ts.
2. Directly delete the Lock CF data of each KV DB.
3. For each KV DB's write CF key-value, if commit_ts > resolved_ts, delete this key-value in write CF and delete this key in default CF also. 


### TiKV

Newly added recovery service/recovery mode

1. Definitions

After TiKV starts raft-engine and kv engine, when establishing pdclient, it actively reads recovery marker from pd at very beginning of the connection between TiKV and PD.

TiKV performs data recovery in recovery mode. It mainly performs raft state machine and data consistency adjustment in the recovery phase. TiKV mainly completes the recovery work in two steps in Recovery mode:

Step 1: Report metadata, and adjust local metadata.

  1. Before TiKV starts, read the cold data of the disk. Update TiKV the cluster ID while pd connected. Also, TiKV initialize a bootstrapped cluster to PD, put PD in bootstrapped status.
  2. TiKV startup, and start recovery service, BR sends read region meta to TiKV, TiKV collect all region meta and sent to BR
  3. BR make a leader list, send to TiKV.TiKV assign a leader for region, and wait leader apply to last log
  4. BR send wait apply to TiKV, TiKV wait and check all region apply to last log

Step 3: Delete data

  7. TiKV start 2 thread to resolve data, one for clean up the lock cf, another is to delete data from write cf and data cf.

In recover mode, data consistency recovery is mainly completed. 


### Interface Definition


### BR - PD
1. enable snapshot recovery marker in pd

```bash
curl "172.16.5.31:3279/pd/api/v1/admin/snapshot-recovering" -XPOST
```

2. Get cluster level consistency timestamp resolved_ts from PD directly.

More info, please refer to[ PR](https://github.com/tikv/pd/pull/4716)


```bash
curl "172.16.5.31:3279/pd/api/v1/min-resolved-ts"
```

3. set max allocate id

```bash
curl "172.16.5.31:3279/pd/api/v1/admin/base-alloc-id" -XPOST -d "10000"
```

### TiKV - PD


```go
    message IsSnapshotRecoveringRequest {
        RequestHeader header = 1;
    }

    message IsSnapshotRecoveringResponse {
        ResponseHeader header = 1;
        bool marked = 2;
    }
    rpc IsSnapshotRecovering(IsSnapshotRecoveringRequest) returns (IsSnapshotRecoveringResponse) {}
```

### BR - TiKV

During the BR backup, a admin check op interface to check if region has ongoing interface
```go
    message CheckAdminRequest {
    }

    message CheckAdminResponse {
        Error error = 1;
        metapb.Region region = 2;
        bool has_pending_admin = 3;
    }

    // CheckPendingAdminOp used for snapshot backup. before we start snapshot for a TiKV. 
    // we need stop all schedule first and make sure all in-flight schedule has finished.  
    // this rpc check all pending conf change for leader.
    rpc CheckPendingAdminOp(CheckAdminRequest) returns (stream CheckAdminResponse) {}
```

TiKV enters the recovery mode when pd is marked as Snapshot Recovery.


TiKV report region meta interface.


```go
    message RegionMeta {
        uint64 region_id = 1;
        uint64 peer_id = 2;
        uint64 last_log_term = 3;
        uint64 last_index = 4;
        uint64 commit_index = 5;
        uint64 version = 6;
        bool tombstone = 7; //reserved, it may be used in late phase for peer check
        bytes start_key = 8;
        bytes end_key = 9;
    }

    // command to store for recover region
    message RecoverRegionRequest {
        uint64 region_id = 1;
        bool as_leader = 2; // force region_id as leader
        bool tombstone = 3; // set Peer to tombstoned in late phase
    }
    // read region meta to ready region meta
    rpc ReadRegionMeta(ReadRegionMetaRequest) returns (stream RegionMeta) {}
```


BR RegionRecover command interface


```go
    // command to store for recover region
    message RecoverRegionRequest {
        uint64 region_id = 1;
        bool as_leader = 2; // force region_id as leader
        bool tombstone = 3; // set Peer to tombstoned in late phase
    }

    message RecoverRegionResponse {
        Error error = 1;
        uint64 store_id = 2;
    }

    // execute the recovery command
    rpc RecoverRegion(stream RecoverRegionRequest) returns (RecoverRegionResponse) {}
```


During the BR ResolvedData phase, delete data interface:


```go
    // resolve data by resolved_ts
    message ResolveKvDataRequest {
        uint64 resolved_ts = 1;
    }

    message ResolveKvDataResponse {
        Error error = 1;
        uint64 store_id = 2;
        uint64 resolved_key_count = 3; // reserved for summary of restore 
        // cursor of delete key.commit_ts, reserved for progress of restore
        // progress is (current_commit_ts - resolved_ts) / (backup_ts - resolved_ts) x 100%
        uint64 current_commit_ts = 4;
    }

    // execute delete data from kv db
    rpc ResolveKvData(ResolveKvDataRequest) returns (stream ResolveKvDataResponse) {}
```



### BR - restore worker

backup phase

```bash
backup full --type=aws-ebs --pd "172.16.2.1:2379" -s "s3:/bucket/backup_folder" --volumes-file=backup.json
```

volume prepare phase

```bash
br restore full --type=aws-ebs --prepare --pd "172.16.2.1:2379" -s "s3:///us-west-2/meta/&sk=xx..." --output=topology.json
```

recovery phase

During the recovery phase, TiDB Operator needs to pass two parameters --pd and --resolved_ts to BR


```bash
br restore full --type=aws-ebs --pd "172.16.2.1:2379" -s "s3:///us-west-2/meta/&sk=xx..."
```



## Exception Handling



* Backup


1. TiKV does not configure report_min_resolved_ts_interval, backup directly failed backup. 
2. Failed to stop PD scheduler, try again. If multiple retries fail within some minutes, the entire backup fails, and then stops snapshot and removes metadata. At the same time, delete snapshot already taken.
3. Snapshot takes too long or failure

    In the version, we just simply fail the entire backup. Meanwhile, the snapshot taken shall be deleted since the backup shall be a failure.

4. If the PD cannot be connected, retry is required, and the retry logic can refer to the existing logic of BR.


* Restore


1. Unable to obtain S3 data due to permissions, fail the restore.
2. The retry mechanism is introduced because the network cannot obtain S3 data. Design can refer to the existing BR and TiKV logic.
3. The Snapshot recovery volume fails, and a retry mechanism is introduced. It fails after some tries, and removes the restore volume, rolls back to the state where backup starts.
4. BR fails in RegionRecover phase and ResolvedData phase with timeout:
    1. The retry mechanism needs to consider the time cost and the success possibility of retry. If there is no possibility of success, it will fail directly.
    2. When rollback is required in failure scenarios, the rollback should consider not to destroy the original backup snapshot data. For example: if ResolvedData fails, rollback requires unmount volume, delete volume, and set TiKV to the original state.


## Backward / Forward Compatibility

Only support v6.3.0 or late


## Security & Privilege

We prefer the IAM role to backup and restore, however, we are able to use the secret key-id way to launch the backup and restore. Here we re-use the TiDB Operator logic to handle the security part.

an extra permission need for EBS backup IAM role:
```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:*",
                "s3-object-lambda:*"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:AttachVolume",
                "ec2:CreateSnapshot",
                "ec2:CreateTags",
                "ec2:CreateVolume",
                "ec2:DeleteSnapshot",
                "ec2:DeleteTags",
                "ec2:DeleteVolume",
                "ec2:DescribeInstances",
                "ec2:DescribeSnapshots",
                "ec2:DescribeTags",
                "ec2:DescribeVolumes",
                "ec2:DetachVolume"
            ],
            "Resource": "*"
        }
    ]
}
```

Notice: prefix with ec2 Action is require to do the ebs backup and restore.
## Dependencies

[AWS API](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Welcome.html)

[AWS EBS Snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html)


## Technical Risk

All block issues had been identified. However some part of design may need some spiking during the implementation phase.


# **Testing Note**



* Transaction consistency

1. using the sync-diff-inspector to do a consistency validation, [sync-diff-inspector](https://docs.pingcap.com/tidb/stable/sync-diff-inspector-overview)

2. using the tidb-snapshot with checksum to validate consistency

  1. create a tidbcluster by tidb-operator

  2. luanch a tpcc to prepare some data

  3. apply a ebs backup yaml, check Commint-Ts

  4. using the Commit-Ts to take a session level tidb snapshot
  5. do database admin checksum

* On-premise backup and restore

4. setup a enviroment with LVM disk

  1. prepare a lvm snapshot script

  2. add --skip-AWS in tidb-operator backup and restore yaml

  3. change some code in BR for --skip-AWS, run prepare scripts

**Reference**


1. [TiKV 源码分析](https://pingcap.com/zh/blog/?tag=TiKV%20%26%2328304%3B%26%2330721%3B%26%2335299%3B%26%2326512%3B)
2. [AWS EBS ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html)

---

### Design 2022 07 20 Session Manager (`docs/design/2022-07-20-session-manager.md`)

# Proposal: Session Manager

- Author(s): [djshow832](https://github.com/djshow832)
- Tracking Issue: https://github.com/pingcap/tidb/issues/35258

## Abstract

This proposes a design of a TiDB component called Session Manager. It keeps client connections alive while the TiDB server upgrades, restarts, scales in, and scales out.

## Background

Applications generally connect to TiDB through a connection pool to reduce the overhead of creating connections. Connections in the pool are kept alive, thus TiDB has to disconnect the client connections during shutdown. This causes reconnections and QPS jitters on the application side when the TiDB cluster rolling upgrades, restarts, and scales in. Thus, database administrators sometimes operate TiDB clusters when the QPS reaches the bottom, typically in the middle of the night, which is painful.

Besides, TiDB needs to be upgraded transparently in the TiDB Cloud Dev Tier once the latest version is ready. The current situation makes TiDB impossible to upgrade without affecting users.

Therefore, we propose a new TiDB component, called Session Manager. Applications or load balancers connect to the Session Manager instead of TiDB. The Session Manager keeps the session states of current connections and redirects the session to alive TiDB instances automatically when a TiDB instance is down.



### Goal

- When the TiDB cluster performs upgrades or restarts, the Session Manager redirects the backend connections from inactive TiDB instances to active instances. This is especially important on the Dev Tier because TiDB will be upgraded frequently and automatically.
- When the TiDB cluster scales out, the Session Manager is aware of the new TiDB instances and redirects some backend connections to the new instances. This is important in a serverless architecture.
- When the TiDB cluster scales in, the Session Manager waits for the ongoing transactions to be finished and redirects some backend connections to active TiDB instances.

### Non-Goals

- When a TiDB instance fails accidentally, the Session Manager redirects the backend connections from the failed TiDB instance to an active instance.
- Block list, allow list, traffic control, audit logs.

## Proposal

### Deployment

In the cloud, applications typically connect to the Network Load Balancer (NLB), which balances the traffic to the TiDB cluster. Session Manager is placed between the NLB and the TiDB cluster.

The NLB balances the traffic to the Session Manager, and the Session Manager balances the traffic to the TiDB cluster. Most of the time, Session Manager only forwards messages between the NLB and the TiDB instances.

The Session Manager also needs to be highly available. An easy way is to deploy multiple isolated Session Manager instances. However, it's painful to maintain. For example, when a user wants to modify a configuration, he needs to connect to the proxies one by one. What we need is a Session Manager cluster.



Client addresses should be recorded in slow logs, audit logs, TiDB logs, and processlist to enable users to check the source of requests. Besides, users may configure different privileges for different IPs. However, from the viewpoint of TiDB, the client address is the address of the Session Manager. Some proxies use the [Proxy Protocol](https://www.haproxy.com/blog/using-haproxy-with-the-proxy-protocol-to-better-secure-your-database/) to pass the client address to the server and TiDB also supports the Proxy Protocol. Session Manager will also use the Proxy Protocol in the handshake phase.

### TiDB Instance Discovery

Traditional proxies require users to configure the addresses of TiDB instances. When the TiDB cluster scales out, scales in, or switches to another TiDB cluster, the user needs to reconfigure it in the proxies.

A Session Manager instance is deployed independently with other TiDB components. To connect to the TiDB cluster, the PD addresses should be passed to the Session Manager before startup. PD contains an etcd server, containing all the instance addresses in the cluster. The Session Manager watches the etcd key to detect a new TiDB instance. This is just like what TiDB instances do.

The Session Manager should also do a health check on the TiDB instance to ensure it is alive, and migrate the backend connections to other TiDB instances if it is down. The health check is achieved by trying to connect the MySQL protocol port, just like other proxies.

Session Manager can do various health checks on TiDB instances:

- It can observe the CPU and memory usage of TiDB instances so that it can perform load-based balance.
- It can observe whether the latest schema is fetched on TiDB instances so that it can avoid directing client connections to the TiDB instances that cannot serve requests.

When a TiDB instance needs to be shut down gracefully due to scale-in, upgrading, or restarting, no more new connections are accepted. The health check from the Session Manager will fail and the Session Manager no longer routes new connections to the instance. However, it still waits for the ongoing queries to be finished since the instance is still alive.

When a TiDB instance quits accidentally, the ongoing queries fail immediately and the Session Manager redirects the connections.



### Authentication

When the Session Manager migrates a session, it needs to authenticate with the new TiDB server.

It's unsafe to save user passwords in the Session Manager, so we use a token-based authentication:

1. The administrator places a self-signed certificate on each TiDB server. The certificate and key paths are defined by configurations `security.session-token-signing-cert` and `security.session-token-signing-key`. The certificates on all the servers are the same so that a message encrypted by one server can be decrypted by another.
2. When the Session Manager is going to migrate a session from one TiDB instance to another, it queries the session token. The session token is composed by the username, token expiration time, and a signature. The signature is signed with the private key of the certificate.
3. The Session Manager then authenticates with the new TiDB server with a new auth-plugin. The session token acts as the password. The new server checks the username, token expiration time, and the signature. The signature should be verified by the public key.

To ensure security, TiDB needs to guarantee that:

- The certificate rotates periodically so that it minimizes the effect of leaking the certificate.
- The username in the session token must be the same with the that in the handshake packet, so one user cannot log in with the identity of another user.
- The token expiration time cannot exceed the current time and the token lifetime cannot be too long, so one user cannot forge the token by brute force, or use a valid token for a long time.
- The signature should be verified so that TiDB can make sure the data is not forged.
- Secure transport is enforced when querying the session token because the token cannot be leaked.

### Connection State Maintenance

A MySQL connection is stateful. TiDB maintains a session state for each connection, including session variables, transaction states, and prepared statements. If the Session Manager redirects the frontend query from one backend connection to another without restoring the session state in the new connection, an error may occur.

The basic workflow is as follows:

1. When the client queries from the Session Manager, the Session Manager forwards the commands to TiDB and then forwards the query result from TiDB to the client. The session states are only updated by TiDB.
2. When the Session Manager is going to migrate a session from one TiDB instance to another, it queries the session states from the original TiDB instance and saves them. Session Manager queries session states by sending `SHOW SESSION_STATES`, the result of which is in JSON type.
3. The Session Manager then connects to the new TiDB instance and replays the session states by sending `SET SESSION_STATES '{...}'`, the parameter of which is just the result of `SHOW SESSION_STATES`.

Session states include:

- Session variables. All the session variables are replayed, because the default values may be different between TiDB instances.
- Prepared statements with their IDs. The prepared statements are created in either binary or text protocol.
- Session SQL bindings.
- User-defined variables.
- The current database.
- Last insert ID, found rows, and row count for the last query, as well as last query info, last transaction info, last DDL info.
- Last sequence values.
- Last warning and error messages.

Transactions are hard to be restored, so Session Manager doesn't support restoring a transaction. Session Manager must wait until the current transaction finishes or the TiDB instance exits due to shut down timeout. To be aware of whether the session has an active transaction, Session Manager needs to track the transaction status. This can be achieved by parsing the status flag in the response packets.

Similarly, Session Manager doesn't support restoring a result set. If the client uses a cursor to read, Session Manager must wait until the data is all fetched. Session Manager can parse the request and response packets to know whether the prepared statement is using a cursor and whether all the data is fetched.

Besides, there are some other limitations:

- When the session contains local temporary tables, table locks, or advisory locks, the TiDB won't return the session states and Session Manager will report connection failure.
- For long-run queries, such as `ADD INDEX` and `LOAD DATA`, TiDB probably won't wait until they finish. In this case, the client will be disconnected.
- Session Manager needs to reconnect to the new TiDB, which introduces handshake, authentication, and session states initialization, so there will be a performance jitter during the redirection.
- The session-level plan cache on the new TiDB instance is empty, so there will be a slight performance jitter for a while after the redirection.

### Configuration

For static configurations, they are read before the startup of the Session Manager and cannot be changed online, such as the port. These configurations can be set by command line parameters.

For dynamic configurations, it's unacceptable to restart Session Manager to set them because Session Manager is supposed to be always online. The configurations can be overwritten anytime and take effect on the whole cluster. These configurations can be stored on an etcd server, which is deployed on the same machine as the Session Manager. Each Session Manager instance watches the etcd key to update the configurations in time.

Session Manager provides an HTTP API to update dynamic configurations online, just as the other components do.

### Observability

Session Manager is one of the products in the TiDB ecosystem, so it's reasonable to integrate Session Manager with Grafana and TiDB-Dashboard.

Like the other components, Session Manager also reports metrics to Prometheus. The metrics include but are not limited to:

- The CPU and memory of each Session Manager instance
- The number of successful and failed session migrations
- The latency and QPS of queries

TiDB-Dashboard should be able to fetch the logs and profiling data of each Session Manager instance.

To troubleshoot the Session Manager, Session Manager provides an HTTP API to fetch instance-scoped or global-scoped data, such as:

- The processlist on the Session Manager instance
- The available TiDB instances from the viewpoint of the Session Manager

## Compatibility

### Upgrade Compatibility

To avoid upgrading Session Manager, Session Manager is supposed to be simple and stable enough.

However, we still can never guarantee that Session Manager will be bug free, so it still needs to support rolling upgrade. Once upgrading, the client connections will definitely be disconnected.

### MySQL Compatibility

Session Manager connects to the MySQL protocol port of TiDB servers, so it should be compatible with MySQL.

## Test Plans

Session Manager is an essential component of the query path, so it's very important to ensure its stability.

We have lots of cases to test, including:

- Test various ORM and connectors with all versions. The MySQL protocol, especially the authentication part, is different among those versions.
- Test various L4 Proxies. Different proxies use different methods to check the health of Session Manager.
- Test various statements, including randomly generated statements and MySQL tests.
- Test all scenarios tests that we have, and randomly make Session Manager redirect sessions at any time.

## Alternative Proposals

Traditional SQL proxies typically maintain the session states on themselves, rather than by backend SQL servers. They parse every response packet, or even request packet, to incrementally update the session states.

This is also possible for Session Manager. MySQL supports [`CLIENT_SESSION_TRACK` capability](https://dev.mysql.com/doc/internals/en/packet-OK_Packet.html#cs-sect-packet-ok-sessioninfo), which is also used for session migration. MySQL server is able to send human-readable state information and some predefined session states in the OK packet when the session states are changed.

The most significant advantage of this method is that Session Manager can support fail over. Now that Session Manager has all the up-to-date session states, it can migrate sessions anytime, even if the TiDB instance fails accidentally.

However, there are some drawbacks of this method:

- There are only 4 predefined state types, and the type is encoded in an `int<1>`. However, TiDB has tens of state types, some of which are TiDB-specific. We cannot extend the state types because it will break forward compatibility if MySQL adds more state types in the future.
- For some changes, e.g. user-defined variables, the OK packet just notifies the client that there is a change, but doesn't tell it what the change is. We also need to extend the protocol, which is a risk.
- There are some inevitable limitations of fail over. For example, Session Manager will never know whether the statement succeeds when TiDB doesn't respond to a `COMMIT` statement or an auto-commit DML statement.
- To support fail over, Session Manager should also be capable of reconnecting to a new Server without a fresh token. That means Session Manager may need to obtain user passwords in a certain way.

## Future Work

The most attractive scenario of routing client connections is multi-tenancy.

These are some scenarios where multi-tenancy is useful:

- Separate different businesses (or workloads) to achieve resource isolation. Each business is assigned a tenant.
- Multiple users share a TiDB cluster to save cost.



In this architecture, the NLB is not aware of tenants. Each TiDB instance belongs to only one tenant to isolate resources. Thus, it's Session Manager's responsibility to route sessions to different TiDB instances.

Session Manager can distinguish tenants by the SNI servers.

---

### Design 2022 07 22 Transaction Savepoint (`docs/design/2022-07-22-transaction-savepoint.md`)

# Proposal: Session Manager

- Author(s): [crazycs520](https://github.com/crazycs520)
- Tracking Issue: https://github.com/pingcap/tidb/issues/6840

## Abstract


This proposes a design of transaction savepoint.

## Background

Some Applications need to use transaction savepoint feature. And in order to be better compatible with some ORM frameworks, such as gorm.

### Goal

- Support transaction savepoint syntax.
- Support transaction savepoint feature, and compatible with MySQL.

### Non-Goals

- Not for implementing savepoint on the entire database, but savepoint on transaction modifications.

## Proposal

### Savepoint Implementation

`SAVEPOINT` is used to set a savepoint of a specified name in the current transaction. If a savepoint with the same name already exists, 
it will be deleted and a new savepoint with the same name will be set.

`SAVEPOINT` need to record a snapshot of current transaction, when users execute `ROLLBACK TO SAVEPOINT` statement, current transaction
will roll back to the specified savepoint.

Specifically, `SAVEPOINT` needs to record the snapshot(checkpoint) of transaction `MemDB`, and the snapshot of `TransactionContext`.

The savepoint data struct is:

```go
// SavepointRecord indicates a transaction's savepoint record.
type SavepointRecord struct {
    // name is the name of the savepoint
    Name string
    // MemDBCheckpoint is the transaction's memdb checkpoint.
    MemDBCheckpoint *tikv.MemDBCheckpoint
    // TxnCtxSavepoint is the savepoint of TransactionContext
    TxnCtxSavepoint TxnCtxNeedToRestore
}

// TxnCtxNeedToRestore stores transaction variables which need to be restored when rolling back to a savepoint.
type TxnCtxNeedToRestore struct {
    // TableDeltaMap is used in the schema validator for DDL changes in one table not to block others.
    // It's also used in the statistics updating.
    // Note: for the partitioned table, it stores all the partition IDs.
    TableDeltaMap map[int64]TableDelta
    
    // pessimisticLockCache is the cache for pessimistic locked keys,
    // The value never changes during the transaction.
    pessimisticLockCache map[string][]byte
    
    // CachedTables is not nil if the transaction write on cached table.
    CachedTables map[int64]interface{}
}

// Transaction Savepoints will be stored in TransactionContext.
type TransactionContext struct {
	...
    Savepoints []SavepointRecord
}
```

The pseudocode about `SAVEPOINT` implementation is following:

```go
func executeSavepoint(savepointName string){
	// If a savepoint with the same name already exists, it will be deleted.
	deleteSavepoint(savepointName)
	memDBCheckpoint := txn.GetMemDBCheckpoint()
	txnCtxSavepoint := txnCtx.GetCurrentSavepoint()
	txnCtx.Savepoints = append(txnCtx.Savepoints, SavepointRecord
	    Name: savepointName, 
	    MemDBCheckpoint: memDBCheckpoint, 
	    TxnCtxSavepoint: txnCtxSavepoint}
    )
}
```

> **Warning**
> Savepoint is not support when TiDB binlog enabled. Since binlog is not recommended after TiDB 4.0.

### ROLLBACK TO SAVEPOINT Implementation

`ROLLBACK TO SAVEPOINT` rolls back a transaction to the savepoint of a specified name and does not terminate the transaction. 
Data changes made to the table data after the savepoint will be reverted in the rollback, and all savepoints after the savepoint are deleted.

Specifically, `ROLLBACK TO SAVEPOINT` needs to roll back following information:

- Transaction `MemDB`
- TransactionContext

The pseudocode about `ROLLBACK TO SAVEPOINT` implementation is following:

```go
func RollbackToSavepoint(savepointName string){
	for idx, sp := range TxnCtx.Savepoints {
		if savepointName == sp.Name {
            TxnCtx.RollbackToSavepoint(sp.TxnCtxSavepoint)
            txn.RollbackMemDBToCheckpoint(sp.MemDBCheckpoint)
			// Delete the later savepoint.
			TxnCtx.Savepoints = sessVars.TxnCtx.Savepoints[:idx+1]
			return nil
		}
	}
	return errSavepointNotExists
}
```

Also need to roll back the `LazyTxn.stagingHandle` information. Since `LazyTxn.stagingHandle` stores the checkpoint of 
transaction `MemDB` when start to execute the current SQL statement, so after `ROLLBACK TO SAVEPOINT` execute, 
`LazyTxn.stagingHandle` should store the roll backed `MemDB` checkpoint handle.

> **Warning**
> `ROLLBACK TO SAVEPOINT` statements won't roll back `AUTO_INCREMENT` and `SEQUENCE`, which means the assigned AUTO_INCREMENT/SEQUENCE ID won't be reclaimed.

### RELEASE SAVEPOINT Implementation

`RELEASE SAVEPOINT` statement removes the named savepoint and **all savepoints** after this savepoint from the current transaction,  
without committing or rolling back the current transaction. If the savepoint of the specified name does not exist, the following error is returned:

```
ERROR 1305 (42000): SAVEPOINT identifier does not exist
```

### MySQL Compatibility

When `ROLLBACK TO SAVEPOINT` is used to roll back a transaction to a specified savepoint, MySQL releases the locks 
held only after the specified savepoint, while in TiDB pessimistic transaction, TiDB does not immediately release the locks 
held after the specified savepoint. Instead, TiDB releases all locks when the transaction is committed or rolled back.

---

### Design 2022 08 02 Stats Lru Cache (`docs/design/2022-08-02-stats-lru-cache.md`)

# Proposal: Stats LRU Cache

- Author(s): [Yisaer](https://github.com/yisaer)
- Tracking Issue: https://github.com/pingcap/tidb/issues/34052

## Abstract

This proposes a design of how to maintain stats cache by lru according to memory usage

## Background

Previously, tidb maintained the all the indices' stats and some columns' stats which is needed during query. 
As the maintained stats grows, the total memory usage of the stats will increase and makes tidb server OOM.
Thus we use lru to maintain stats cache in order to keep memory safe.

### Goal

- Use LRU to maintain the stats cache in memory
- Keep the total memory usage of stats cache under the quota
- Support loading stats back into memory when tidb server needs it

### Non-Goals

- Considering the stats cache are in memory, we don't provide changing stats cache into LRU without restarting

## Proposal

### Stats Cache Interface

We will provide a Stats Cache Interface which is implemented by LRU Cache and Map Cache. 
If the tidb server didn't enable Stats LRU Cache, it will use Map Cache by default. Also, we will provide config and global session variable to control whether enable Stats LRU Cache and the capacity of it.

```go
// statsCacheInner is the interface to manage the statsCache, it can be implemented by map, lru cache or other structures.
type statsCacheInner interface {
	Get(int64) (*statistics.Table, bool)
	Put(int64, *statistics.Table)
	Del(int64)
	Cost() int64
	Len() int
	SetCapacity(int64)
}
```

### Stats LRU Cache Policy

For column or index stats, we maintained following data structure for stats: 

- `Histogram` 
- `TopN`
- `CMSketch`

And we will also maintain status for each column and index stats in order to indicate its stats loading status like following:

- `AllLoaded`
- `OnlyCMSEvcited`
- `OnlyHistRemained`
- `AllEvicted`

When the column or index stats load all data structures into memory, the status will be `AllLoaded`. 
When the Stats LRU Cache memory usage exceeds the quota, the LRU Cache will select one column or index stats to evict the data structures by following rules to reduce the memory usage:

- If the status is `AllLoaded`, it will discard the `CMSketch` and the status will be changed into `OnlyCMSEvcited`
- If the status is `OnlyCMSEvcited`, it will discard the `TopN` and the status will be changed into `OnlyHistRemained`
- If the status is `OnlyHistRemained`, it will discard the `Histogram` and the status will be changed into `AllEvicted`

### Sync Stats Compatibility

Previously tidb server has Sync Stats and asynchronously Loading Histograms in order to load column stats into memory during query.
As Stats LRU Cache Policy may evict index stats in memory, we also need Sync Stats and asynchronously Loading Histograms to support loading index stats according to its loading status to keep compatible.
During the query optimization, tidb server will collect the used columns and indices, if their stats are not fully loaded, tidb-server will try to load their stats back into the memory.

---

### Design 2022 08 04 Pessimistic Lazy Constraint Check (`docs/design/2022-08-04-pessimistic-lazy-constraint-check.md`)

# Proposal: Extend `tidb_constraint_check_in_place` to Support Pessimistic Transactions

* Authors: [sticnarf](https://github.com/sticnarf), [ekexium](https://github.com/ekexium)
* Tracking issue: [#36579](https://github.com/pingcap/tidb/issues/36579)

## Abstract

We propose to make lazy uniqueness check usable not only in optimistic transactions, but also in pessimistic transactions. Then, in certain use cases, we can benefit better latency and throughput from deferring the uniqueness constraint checks until the transaction commits while not decreasing the success rate.

Similar to the current `tidb_constraint_check_in_place`, this proposal only involves uniqueness constraints of the primary key and unique keys. Other constraints such as `NOT NULL` and foreign keys are not affected.

## Background

Lazy uniqueness constraint check is a feature enabled by default for optimistic transactions. It is controlled by the system variable `tidb_constraint_check_in_place`. When this variable is off, uniqueness checks are performed when prewriting the mutations:

```sql
CREATE TABLE t1 (id INT NOT NULL PRIMARY KEY);
INSERT INTO t1 VALUES (1), (2);
BEGIN OPTIMISTIC;
INSERT INTO t1 VALUES (1); -- MySQL returns an error here; TiDB returns success.
INSERT INTO t1 VALUES (2);
COMMIT; -- ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
```

However, the feature is not available for pessimistic transactions now. We developed the pessimistic transaction mode to make the behavior close to MySQL as much as possible. So, the constraint checks are always done at the time of executing the DML and pessimistic locks for the unique keys are always written meanwhile.

Obviously, it is not free. Say we have a transaction that consists of N `INSERT` statements. By deferring the constraint checks, no RPC interactions between TiDB and TiKV are needed before the transaction commits. While in a pessimistic transaction, the RPC number during the 2PC period does not change, but there are extra N `AcquirePessimisticLock` RPCs before `COMMIT`.

Many users use pessimistic transactions only for success rate and they assume their transactions cannot fail. So, if there are DMLs involving uniqueness checks (e.g. `INSERT`), it is _likely_ the users can guarantee the uniqueness checks cannot fail as well. Otherwise, they will break their own assumptions, which means the DMLs may fail due to duplicated unique key even in pessimistic transactions.

So, skipping pessimistic locks for these keys and deferring constraint checks can reduce much latency and cost for these users while not breaking their expectations about the success rate of pessimistic transactions.

## Design

This feature makes it possible to skip acquiring pessimistic locks for the keys that need uniqueness constraint checks in pessimistic transactions. We do constraint checks for these keys during prewrite.

The main affected statements include simple `INSERT` and `UPDATE` that involve primary key or unique keys. `INSERT ON DUPLICATE` and `INSERT IGNORE` are not affected because they don't raise errors for duplicated entries.

A session/global system variable `tidb_constraint_check_in_place_pessimistic` is introduced to control the behavior. The default value is `ON` and the behavior will remain unchanged. When `tidb_constraint_check_in_place_pessimistic` is `OFF`, the new behavior will take effect in pessimistic transactions.

```sql
CREATE TABLE t1 (id INT NOT NULL PRIMARY KEY);
INSERT INTO t1 VALUES (1), (2);

set tidb_constraint_check_in_place_pessimistic = off;
BEGIN PESSIMISTIC;
SELECT * FROM t1 WHERE id = 1 FOR UPDATE; -- SELECT FOR UPDATE locks key as usual.
INSERT INTO t1 VALUES (2); -- Skip acquiring the lock and return success.
COMMIT; -- ERROR 1062 (23000): Duplicate entry '2' for key 'PRIMARY'
```

#### Protocol

Although we skip locking some keys and doing constraint checks before `COMMIT`, it is still a pessimistic transaction. Except for the keys that need constraint checks, we acquire pessimistic locks for other keys as usual.

It is completely a new kind of behavior to do constraint checks during prewrite for keys that don't get locked ahead of time. We need to change the prewrite protocol to describe it.

Previously, there is a `repeated bool` field describing whether each key needs be locked first. Generally, non-unique index keys don't need to be locked and their conflict checks are skipped.

 ```protobuf
message PrewriteRequest {
    // For pessimistic transaction, some mutations don't need to be locked, for example, non-unique index key.
    repeated bool is_pessimistic_lock = 7;
}
 ```

Now, we can reuse this field to describe the keys that need constraint checks during prewrite in a pessimistic transaction:

```protobuf
message PrewriteRequest {
	enum PessimisticAction {
		// The key needn't be locked and no extra write conflict checks are needed.
		SKIP_PESSIMISTIC_CHECK = 0;
		// The key should have been locked at the time of prewrite.
		DO_PESSIMISTIC_CHECK = 1;
		// The key doesn't need a pessimistic lock. But we need to do data constraint checks.
		DO_CONSTRAINT_CHECK = 2;
	}
    // For pessimistic transaction, some mutations don't need to be locked, for example, non-unique index key.
    repeated PessimisticAction pessimistic_actions = 7;
}
```

Because `enum` is compatible with `bool` on the wire, we can seamlessly extend the  `is_pessimistic_lock` field. In a TiDB cluster, TiKV instances are upgraded before TiDB. So, we can make sure TiKV can handle it correctly when TiDB starts using the new protocol.

When `tidb_constraint_check_in_place_pessimistic` is off, all the keys that have `PresumeKeyNotExists` flags don't need to be locked when executing the DML. They will be marked with a new special flag `NeedConstraintCheckInPrewrite`. When the transaction commits, TiDB will set the actions of these keys to `DO_CONSTRAINT_CHECK`. So, TiKV will not check the existence of pessimistic locks of these keys. Instead, constraint and write conflict checks should be done for these keys.

#### Behavior of locking lazy checked keys

Consider the following scenario (from @cfzjywxk):

```sql
/* init */ CREATE TABLE t1 (id INT NOT NULL PRIMARY KEY, v int);
/* init */ INSERT INTO t1 VALUES (1, 1);

/* s1 */ set tidb_constraint_check_in_place_pessimistic = off;
/* s1 */ BEGIN PESSIMISTIC;
/* s1 */ INSERT INTO t1 VALUES (1, 2); -- Skip acquiring the lock. So the statement would succeed.
/* s1 */ SELECT * FROM t1 FOR UPDATE; -- Here the pessimistic lock on row key '1' would be acquired
```

The `INSERT` statement puts the row with `id = 1` in the transaction write buffer of TiDB without checking the constraint. The later `SELECT FOR UPDATE` will read and lock the row with `id = 1` in TiKV. If the `SELECT FOR UPDATE` succeeded, it would be difficult to decide the result set. Returning `(1, 1), (1, 2)` breaks the unique constraint, while returning `(1, 1)` or `(1, 2)` may be all strange semantically. Using the wrong result set for following operations may even cause data inconsistency.

So, we choose to do the missing constraint check and locking whenever a key that skipped constraint check before is read from the transaction buffer. In union scan or point get executors, if we involve any key in the buffer with a `NeedConstraintCheckInPrewrite` flag, we will reset the flag and add it again to the staging buffer. Later, we can acquire locks and check the constraints for these keys. In this way, the result set will not break any constraint.

This means the read-only statements like the `SELECT FOR UPDATE` above will throw a "duplicate entry" error in the case above. It may be strange that a read-only statement raises errors like this. We should make the user aware of the behavior.

### Applicable Scenarios

When talking about the success rate, we are based on the following assumption:

**The user treats duplicated entry errors returned by DMLs as fatal errors which must abort the transaction.**

A duplicated entry error only makes a single DML statement fail in a pessimistic transaction. The transaction does not abort immediately. If the user can handle the duplicated entry error in their application and continue the transaction, skipping pessimistic locks definitely changes the behavior and lowers the success rate.

While under such an assumption, the general success rate won't change with the feature enabled in most cases.

Suppose that transaction A wants to insert a new row with a unique key, or update a field with a unique key.

1. If a duplicated record exists before the DML, when to check the constraint does not change the success rate. Currently, the duplicated entry error is raised when executing the DML. With lazy constraint check, the error is raised when committing the transaction. 

2. If the duplicated record is written by transaction B between transaction A's executing the DML and committing, let's consider different cases:

   1. If both transactions acquire the lock of the unique key, which is the current behavior, transaction B will be blocked until transaction A commits. After transaction A commits, the DML of transaction B will fail due to the duplicated entry.
   2. If transaction A skips acquiring the lock while transaction B does not, transaction A will fail unless transaction B aborts. When transaction A prewrites, it will either meet the lock or the write record from transaction B. In either case, transaction A will fail to pass the constraint check.
   3. If both transaction A and B skip acquiring the lock, it's similar to the case of an optimistic transaction. The transaction that commits first will succeed.

   Therefore, although the time when the error is raised is different, only one of the transactions will fail.
   
In a special case, the success rate may drop due to the write conflict check:

```sql
/* init */ CREATE TABLE t1 (id INT NOT NULL PRIMARY KEY);
/* init */ INSERT INTO t1 VALUES (1);

/* s1 */ BEGIN PESSIMISTIC;
/* s2 */ DELETE FROM t1 WHERE id = 1;
/* s1 */ INSERT INTO t1 VALUES (1);
/* s1 */ COMMIT;
```

If we check constraints while acquiring the lock, `s1` will succeed because the row with `id = 1` has been deleted when acquiring the lock. However, if we check constraints lazily, to ensure snapshot isolation, we have to do a write conflict check like in optimistic transactions in additional to constraint checks. In the case above, write conflict check will fail because the commit TS of `s2` is bigger than the start TS of `s1`.

#### List of typical use cases

Note that the feature is only needed if part of your transaction still needs to acquire pessimistic locks. Otherwise, use the optimistic transaction mode instead.

* `INSERT` rows to a table without any unique key. TiDB does not generate duplicated implicit row ID, so normally there cannot be unique key conflicts.
* The user guarantees their application does not `INSERT` duplicate entries, such bulk data load.

### Safety

With this feature enabled, we accept slight behavior changes, but we must guarantee the general transaction properties are still preserved.

First, atomicity is not affected. Although we skip the locking phase for some of the keys, we don't skip any conflict and constraint checks that are necessary in the usual 2PC procedure. To be more secure, we can do conflict checks for the non-unique index keys just like optimistic transactions. It avoids the risk of producing duplicated write records when there are RPC retries.

The uniqueness constraints are also preserved. For all the keys with a `PresumeKeyNotExists` flag, we check the constraint either when prewriting them, or when acquiring the pessimistic locks like in the case of [Locking Lazy Checked Keys](#behavior-of-locking-lazy-checked-keys) above. So we can guarantee no duplicated entry exists after committing the transaction. In the case of "rollback to savepoint", some keys that need constraint checks may be unchanged in the end, but we will still check the constraints for them in prewrite to make sure the client does not miss any errors.

Due to the "read committed" semantics of DMLs in pessimistic transactions, the late locking could succeed even if duplicated entries exist at the time of `INSERT` because other transactions remove the duplicated entry after that. From the view of our transaction, it's equivalent to the case when other transactions remove the duplicated entry before our `INSERT`. There will be no data corruption after the transaction commits.

#### Assumptions we make

The safety of the feature depends on these assumptions which are all true in TiDB 6.2.

- TiDB does not acquire pessimistic locks for non-unique index keys.
- TiDB does not mark non-unique index keys as `PresumeKeyNotExists`.
- If a key gets marked as `PresumeKeyNotExists`, it must be in the current statement buffer.

#### Safety with multiple operations in one statement

In current TiDB(<=6.2) implementation, the locking phase of pessimistic DML (except SELECT FOR UPDATE) begins after executors. If there are multiple operations on one key in the execution phase, they may not behave like what we expect. For example in the same statement there are operations:

1. write a key without the NeedConstraintCheckInPrewrite flag. This may be a normal locking request or because of compensating a deferred lock.
2. write the same key with the NeedConstraintCheckInPrewrite flag

In the locking phase we will not acquire pessimistic lock for the key because the NeedConstraintCheckInPrewrite flag is set. This should not happen in the current TiDB implementation, but is noteworthy.

---

### Design 2022 09 19 Distributed Ddl Reorg (`docs/design/2022-09-19-distributed-ddl-reorg.md`)

# Proposal: Distributed DDL Reorg

- Author(s): [zimulala](https://github.com/zimulala), [Defined2014](https://github.com/Defined2014)
- Tracking Issue: https://github.com/pingcap/tidb/issues/41208

## Abstract

This is distributed processing of design in the DDL reorg phase. The current design is based on the main logic that only the DDL owner can handle DDL jobs. However, for jobs in the reorg phase, it is expected that all TiDBs can claim subtasks in the reorg phase based on resource usage.

## Motivation or Background

At present, TiDB already supports parallel processing of DDL jobs on the owner. However, the resources of a single TiDB are limited. Even if it supports a parallel framework, the execution speed of DDL is relatively limited, and it will compete for resources that affect the daily operations such as TiDB's TPS.

DDL Jobs can be divided into the general job and the reorg job. It can also be considered that improving DDL operation performance can be divided into improving the performance of all DDL jobs (including the time consumption of each schema state change, checking all TiDB schema state update success, etc.), and improving the performance of the reorg stage. The current time-consuming and resource-consuming stage is obviously the reorg stage.

At present, considering the problem of significantly improving DDL performance and improving TiDB resource utilization, and relatively stable design and development, we will DDL reorg stage for distributed processing.

## Current Implementation

At present, the master branch reorg stage processing logic (that is, no lighting optimization is added), takes an  added index as an example. The simple steps that the owner needs to perform in the reorg stage of the added index operation:

1. Split the entire table [startHandle: endHandle] into ranges by region.
2. Each backfill worker scans the data in the corresponding range, then checks the data and writes it to the index.
3. After all backfill workers complete step 2, check if there is still data to process:
    1. If there is continued step 2
    2. If not, complete the entire reorg phase and update the relevant meta info.



## Rationale

### Prepare

The reorg worker and backfill worker for this scenario are completely decoupled, i.e. the two roles are not related.

Backfill workers build the associated worker pool to handle subtasks ( DDL small tasks that a job splits into during the reorg phase).

### Process

The overall process of this document program is rough as follows:

1. DDL After the owner gets the reorg job, the reorg worker will handle its various state changes until the reorg stage. We split the job into multiple subtasks by data key, and then store the relevant information on the table.
2. After that, regularly check whether all subtasks are processed (this operation is similar to the original logic), and do some other management, such as cancellation.
3. All TiDB backfill workers (regardless of whether TiDB is a DDL owner) will get subtasks to handle.
    1. Get the corresponding number of backfill workers from the backfill worker pool, and let them process subtasks in parallel. This operation is similar to the original logic and can be optimized later.
    2. Each backfill worker serially gets subtasks, executes them serially until all processing is complete, and then exits.
4. After checking in step 2 that all subtasks have been processed, update the relevant meta info and proceed to the next stage. If any subtasks fail, cancel the other subtasks and finally roll back the DDL job.



## Detailed Design

### Meta Info Definition

The contents of the existing table structure may be lacking, and a new Metadata needs to be added or defined.

Add a new field to the `DDLReorgMeta` structure in the `mysql.tidb_ddl_job` table, for example:

```go
type DDLReorgMeta struct {
    ...                    // Some of the original fields
    
    IsDistReorg   bool     // Determine whether do dist-reorg
}
```

Consider that if all subtask information is added to the TiDB_ddl_reorg.reorg field, there may be a lock problem. It is added to the `mysql.tidb_background_subtask` table, the specific structure is as follows:

```sql
+---------------+------------+------+-------------+
| Field              | Type         | Null | Key  |
+---------------+------------+------+-------------+
| id                 | bigint(20)   | NO   | PK   | auto
| Namespace string   | varchar(256) | NO   | MUL  |
| Key string         | varchar(256) | NO   | MUL  | // ele_key, ele_id, ddl_job_id, sub_id
| ddl_physical_tid   | bigint(20)   | NO   |      |
| type               | int          | NO   |      | // e.g.ddl_addIndex type
| exec_id            | varchar(256) | YES  |      |
| exec_expired       | Timestamp    | YES  |      | // TSO
| state              | varchar(64)  | YES  |      |
| checkpoint         | longblob     | YES  |      |
| start_time         | bigint(20)   | YES  |      |
| state_update_time  | bigint(20)   | YES  |      |
| meta               | longblob     | YES  |      |
+---------------+------------+------+-------------+
```

Add the following to the BackfillMeta field:

```go
type BackfillMeta struct {
    CurrKey         kv.Key
    StartKey        kv.Key
    EndKey          kv.Key
    EndInclude      bool    
    ReorgTp         ReorgType
    ...
    
    *JobMeta // parent job meta
}
```

Add `mysql.tidb_background_subtask_history` table to record completed (including failure status) subtasks. The table structure is the same as tidb_background_subtask . Considering the number of subtasks, some records of the history table are deleted regularly in the later stage.

### Principle

The general process is simply divided into two parts:

1. Managing reorg jobs is divided into the following two parts. This function is done by the reorg worker on the DDL owner node.
    1. Split the reorg job and insert it into subtasks as needed.
    2. Check if the reorg job is processing complete (including status such as failure).
2. Process the subtask and update the relevant metadata. After completion, move the subtask to the history table. This function can be processed by all roles and is completed by backfill workers.

Regarding step 1.b, the current plan is to reorg worker through timer regular check, consider the completion of subtask synchronization through PD, to actively check.

### Rules

Rules for backfill workers to claim subtasks:

- The idle backfill worker on TiDB-server will be woken up by a timer to try to preempt the remaining subtasks.
- Lease mechanism, the current TiDB backfill worker does not update the exec_expired field for a long time (keep-alive process), and other TiDB backfill workers can preempt it.
- The Owner Specifies the value. At present, the reorg worker will first split the reorg into subtasks, and then use the total number of subtasks to determine whether only native execution is required or all nodes are processed.
    - The total number of split tasks is less than minDistTaskCnt, then mark them all as native, so that the node where the owner is located has priority;
    - Otherwise, all nodes preempt the task in the first two ways.

Later, it can support more flexible segmentation tasks and assign claim tasks.

Subtask claim notification method:

- Active way:
    - The Owner node notifies the backfill worker on the local machine through chan.
    - The Owner node notifies backfill workers to other nodes by changing the information registered in the PD.
- Passive mode: All nodes themselves periodically check if there are tasks to handle.

### Interface Definition

Adjust the `backfiller` and `backfillWorker` to update their interfaces and make them more explicit and generic when fetching and processing tasks.

- `backfiller` interfaces:
```go
// backfiller existing interfaces:
func BackfillDataInTxn(handleRange reorgBackfillTask) (taskCtx backfillTaskContext, errInTxn error)
func AddMetricInfo(float64)

// backfiller new interfaces:
// get batch tasks
func GetTasks() ([]*BackfillJob, error){}
// update task
func UpdateTask(bfJob *BackfillJob) error{}
func FinishTask(bfJob *BackfillJob) error{}
// get the backfill context
func GetCtx() *backfillCtx{}
func String() string{}
```

- Interfaces that need to be added or modified by `backfillWorker`.

```go
// In the current implementation, the result is passed between the reorg worker and the backfill worker using chan, and it runs tasks by calling `run`
// In the new framework, two situations need to be adapted
// 1. As before, transfer via chan and reorg workers under the same TiDB-server
// 2. Added support for transfer through system tables to reorg workers between different TiDB-servers
// Consider early compatibility. Implement the two adaptations separately, i.e., use the original `run` function for function 1 and `runTask` for function 2
func (w *backfillWorker) runTask(task *reorgBackfillTask) (result *backfillResult) {}
// updatet reorg substask exec_id and exec_lease
func (w *backfillWorker) updateLease(bfJob *BackfillJob) error{}
func (w *backfillWorker) releaseLease() {}
// return backfiller related info
func (w *backfillWorker) String() string {}
```

- Add the backfill worker pool like `WorkerPool`(later considered to be unified with the existing WorkerPool).
- In addition, the above interface will be modified in the second phase of this project to make it more general.

### Communication Mode

In the current scheme, the backfill worker obtains subtasks and the reorg worker checks whether the subtask is completed through regular inspection and processing. Here, we consider combining PD watches for communication.

### Breakpoints Resume

When the network partition or abnormal exit occurs in the TiDB where the current backfill worker is located, the corresponding subtask may not be handled by the worker. In the current scheme, it is tentatively planned to mark whether the executor owner of the current subtask is valid by lease. There are more suitable schemes that can be discussed later. The specific operation of this scheme:

1. When the backfill worker handles a subtask, it will record the current DDL_ID (may need worker_type_worker_id suffix) in the tidb_background_subtask table as the exec_id, and regularly update the exec_expired value and curr_key.
2. Non-DDL owner TiDB encountered this problem:
    1. When there is a network problem in the TiDB where the backfill worker who is processing the subtask is located, and another TiDB obtains the current subtask and finds that its exec_expired expired (for example, the exec_expired + lease value is earlier than now () ), the exec_id and exec_expired values of this subtask are updated, and the subtask is processed from curr_key.
3. DDL Owner TiDB may encounter this problem refer to the following changing owner description.

### Changing Owner

- DDL an exception may occur in the TiDB where the owner is located, resulting in the need to switch DDL owner.
    1. The reorg worker will check the reorg info to confirm that the reorg job has completed subtasks.
        1. If it is not completed, enter the stage of reorg job splitting, and then enter the process of checking the completion of the reorg job. The subsequent process will not be repeated.
        2. If completed, enter the process of checking the completion of the reorg job. The follow-up process will not be repeated. (Problem: under the new framework, no owner can continue to perform backfill phase tasks).

### Failed

When processing the reorg stage, the process with an error when backfilling is handled as follows:

1. When one of the reorg workers has an error when processing subtask, it changes the state in the tidb_background_subtask table to the failed state and exits the process of processing this subtask.
2. DDL In addition to checking whether all tasks are completed, it will also check whether   there is a subtask execution failure (currently considering an error will return ).
    1. Move unprocessed subtasks into the TiDB_background_subtask_history table.
    2. When there is no subtask to process, the error is passed to the generation logic. This will convert the DDL job to a rollback job according to the original logic.
3. All TiDB b ackfill worker in each task to take subtask, if the half of the execution found that the task does not exist (indicating that half of the reorg task failed to execute, the owner cleaned up its subtask), then exit normally .
4. Follow-up operations refer to the rollback process.

### Cancel

When the user executes admin cancel ddl job , the job is marked as canceling as in the original logic. DDL the reorg worker where the owner is located checks this field and finds that it is canceling, the next process is similar to step 3-6 of Failed.

### Clean up

Since the subtask may be segmented by each table region, it may cause the `mysql.tidb_background_subtask_history` table is particularly large, so you need to add a regular cleaning function.

### Display

#### Display of Progress

The first stage can be through subtasks inside row count to calculate the entire DDL job row count. Then the display is the same as the original logic.

Subsequent progress can be displayed more humanely, providing results such as percentages, allowing users to better understand the processing of the reorg phase.

#### Monitor

Update and add some new logs and metrics.

## Further

- Improve and optimize backfill processing subtask scheduling strategy
    - Use more flexible and reasonable subtask segmentation and preemption mechanism
    - Prevent small reorg jobs from being blocked by large reorg jobs , this function should be handled in conjunction with resource management functions
- The framework is more general, and the current form and interface are more general, but relatively simple, the future will be improved so that it can be used more with DDL reorg as slower background tasks
- Consider the design of removing DDL owner
- Remove the reorg worker layers, and each TiDB -server only keeps one DDL worker for schema synchronization and other work.

---

### Design 2022 09 22 Global Memory Control (`docs/design/2022-09-22-global-memory-control.md`)

# Proposal: Global Memory Control

* Authors: [wshwsh12](https://github.com/wshwsh12), [Xuhuaiyu](https://github.com/Xuhuaiyu)
* Tracking issue: [#37816](https://github.com/pingcap/tidb/issues/37816)

## Abstract

This proposes a design of how to control global memory of TiDB instance.

## Background

Currently, TiDB has a query-level memory control strategy `mem-quota-query`, which triggers Cancel when the memory usage of a single SQL exceeds `mem-quota-query`. However, there is currently no global memory control strategy. 

When TiDB has multiple SQLs whose memory usage does not exceed `mem-quota-query` or memory tracking inaccurate, it will lead to high memory usage or even OOM. 

Therefore, we need an observer to check whether the memory usage of the current system is normal. When there are some problems, try to control TiDB's memory no longer continue to grow, to reduce the risk of process crashes.

## Goal

- Control the TiDB execution memory within the system variable `tidb_server_memory_limit`.

## Design

New system variables:
- `tidb_server_memory_limit`: TiDB maintains the overall memory usage within `tidb_server_memory_limit`
- `tidb_server_memory_gc_trigger`: When TiDB memory usage reaches a certain percentage of `tidb_server_memory_limit`, try to take the initiative to trigger golang GC to release memory
- `tidb_server_memory_limit_sess_min_size`: The minimum memory of a session that can be killed by TiDB

We need to implement the following three functions to control the memory usage of TiDB:
1. Kill the SQL with the most memory usage in the current system, when `HeapInuse` is larger than `tidb_server_memory_limit`.
2. Take the initiative to trigger `runtime.GC()`, when `HeapInuse` is large than `tidb_server_memory_limit`*`tidb_server_memory_limit_gc_trigger`.
3. Introduce some memory tables to observe the memory status of the current system.

### Kill the SQL with the max memory usage

New variables:

1. Global variable `MemUsageTop1Tracker atomic.Pointer[Tracker]`: Indicates the Tracker with the largest memory usage.
2. The flag `NeedKill atomic.Bool` in the structure `Tracker`: Indicates whether the SQL for the current Tracker needs to be Killed.
3. `SessionID int64` in Structure Tracker: Indicates the Session ID corresponding to the current Tracker.

Implements:

#### How to get the current TiDB memory usage Top 1
When `Tracker.Consume()` calling, check the following logic. If all are satisfied, update the `MemUsageTop1Tracker`.
1. Is it a Session-level Tracker?
2. Whether the flag `NeedKill` is false, to avoid cancel the current SQL twice
3. Whether the memory usage exceeds the threshold `tidb_server_memory_limit_sess_min_size`(default 128MB, can be dynamically adjusted), can be candidate of the `MemUsageTop1Tracker` 
4. Is the memory usage of the current Tracker greater than the current `MemUsageTop1Tracker`

#### How to Cancel the current top 1 memory usage and recycle memory in time
1. Create a goroutine that calls Golang's `ReadMemStat` interface in a 100 ms cycle. (Get the memory usage of the current TiDB instance)
2. If the `heapInuse` of the current instance is greater than `tidb_server_memory_limit`, set `MemUsageTop1Tracker`'s `NeedKill` flag. (Sends a Kill signal)
3. When the SQL call to `Tracker.Consume()`, check its own `NeedKill` flag. If it is true, trigger Panic and exit. (terminates the execution of SQL)
4. Get the `SessionID` from the tracker and continuously query its status, waiting for it to complete exited. When SQL successfully exited, explicitly trigger Golang GC to release memory. (Wait for SQL exited completely and release memory)

### Take the initiative to trigger GC

The inspiration for this design comes from uber-go-gc-tuner:
1. Use the Go1.19 `SetMemoryLimit` feature to set the soft limit to `tidb_server_memory_limit` * `tidb_server_memory_limit_gc_trigger` to ensure that GC can be triggered when reaching the certain threshold.
2. After each GC, check whether this GC is caused by memory limit. If it is caused by this, temporarily set memory limit to infinite, and then set it back to the specified threshold after 1 minute. In this way, the problem of frequent GC caused by `heapInUse` being larger than the soft limit can be avoided.

### Introduce some memory tables

Introduce `performance_schema.memory_usage` and `performance_schema.memory_usage_ops_history` to display the current system memory usage and historical operations.
This can be implemented by maintaining a set of global data, and reading and outputting directly from the global data when querying.

---

### Design 2022 09 29 Reorganize Partition (`docs/design/2022-09-29-reorganize-partition.md`)

# TiDB Design Documents

- Author(s): [Mattias Jonsson](http://github.com/mjonss)
- Discussion PR: https://github.com/pingcap/tidb/issues/38535
- Tracking Issue: https://github.com/pingcap/tidb/issues/15000

## Table of Contents

* [Introduction](#introduction)
* [Motivation or Background](#motivation-or-background)
* [Detailed Design](#detailed-design)
    * [Schema change states for REORGANIZE PARTITION](#schema-change-states-for-reorganize-partition)
    * [Error Handling](#error-handling)
    * [Notes](#notes)
* [Test Design](#test-design)
    * [Benchmark Tests](#benchmark-tests)
* [Impacts & Risks](#impacts--risks)

## Introduction

Support ALTER TABLE t REORGANIZE PARTITION p1,p2 INTO (partition pNew1 values...)

## Motivation or Background

TiDB is currently lacking the support of changing the partitions of a partitioned table, it only supports adding and dropping LIST/RANGE partitions.
Supporting REORGANIZE PARTITIONs will allow RANGE partitioned tables to have a MAXVALUE partition to catch all values and split it into new ranges. Similar with LIST partitions where one can split or merge different partitions.

When this is implemented, it will also allow future PRs transforming a non-partitioned table into a partitioned table as well as remove partitioning and make a partitioned table a normal non-partitioned table, as well as COALESCE PARTITION and ADD PARTITION for HASH partitioned tables, which is different ALTER statements but can use the same implementation as REORGANIZE PARTITION

The operation should be online, and must handle multiple partitions as well as large data sets.

Possible usage scenarios:
- Full table copy
  - merging all partitions to a single table (ALTER TABLE t REMOVE PARTITIONING)
  - splitting data from many to many partitions, like change the number of HASH partitions
  - splitting a table to many partitions (ALTER TABLE t PARTITION BY ...)
- Partial table copy (not full table/all partitions)
  - split one or more partitions
  - merge two or more partitions

These different use cases can have different optimizations, but the generic form must still be solved:
- N partitions, where each partition has M indexes

First implementation should be based on the merge-txn (row-by-row batch read, update record key with new Physical Table ID, write) transactional batches and then create the indexes in batches index by index, partition by partition.
Later we can implement the ingest (lightning way) optimization, since DDL module are on the way of evolution to do reorg tasks more efficiency.

## Detailed Design

There are two parts of the design:
- Schema change states throughout the operation
- Reorganization implementation, which will be handled in the StateWriteReorganization state.

Where the schema change states will clarify which different steps that will be done in which schema state transitions.

### Schema change states for REORGANIZE PARTITION

Since this operation will:
- create new partitions
- copy data from dropped partitions to new partitions and create their indexes
- change the partition definitions
- drop existing partitions

It will use all these schema change stages:

      // StateNone means this schema element is absent and can't be used.
      StateNone SchemaState = iota
      - Check if the table structure after the ALTER is valid
      - Use the generate physical table ids to each new partition (that was generated already by the client sending the ALTER command).
      - Update the meta data with the new partitions (AddingDefinitions) and which partitions to be dropped (DroppingDefinitions), so that new transactions can double write.
      - Set placement rules
      - Set TiFlash Replicas
      - Set legacy Bundles (non-sql placement)
      - Set the state to StateDeleteOnly
      
      // StateDeleteOnly means we can only delete items for this schema element (the new  partition).
      StateDeleteOnly
      - Set the state to StateWriteOnly

      // StateWriteOnly means we can use any write operation on this schema element,
      // but outer can't read the changed data.
      StateWriteOnly
      - Set the state to StateWriteReorganization
      
      // StateWriteReorganization means we are re-organizing whole data after write only state.
      StateWriteReorganization
      - Copy the data from the partitions to be dropped (one at a time) and insert it into the new partitions. This needs a new backfillWorker implementation.
      - Recreate the indexes one by one for the new partitions (one partition at a time) (create an element for each index and reuse the addIndexWorker). (Note: this can be optimized in the futute, either with the new fast add index implementation, based on lightning. Or by either writing the index entries at the same time as the records, in the previous step, or if the partitioning columns are included in the index or handle)
      - Replace the old partitions with the new partitions in the metadata when the data copying is done
      - Set the state to StateDeleteReorganization

      // StateDeleteReorganization means we are re-organizing whole data after delete only state.
      StateDeleteReorganization - we are using this state in a slightly different way than the comment above says.
      This state is needed since we cannot directly move from StateWriteReorganization to StatePublic.
      Imagine that the StateWriteReorganization is complete and we are updating the schema version, then if a transaction seeing the new schema version is writing to the new partitions, then those changes needs to be written to the old partitions as well, so new transactions in other nodes using the older schema version can still see the changes.
      - Remove the notion of new partitions (AddingDefinitions) and which partitions to be dropped (DroppingDefinitions) and double writing will stop when it goes to StatePublic.
      - Register the range delete of the old partition data (in finishJob / deleteRange).
      - Set the state to StatePublic
      
      // StatePublic means this schema element is ok for all write and read operations.
      StatePublic
      - Table structure is now complete and the table is ready to use with its new partitioning scheme
      - Note that there is a background job for the GCWorker to do in its deleteRange function.

During the reorganization happens in the background the normal write path needs to check if there are any new partitions in the metadata and also check if the updated/deleted/inserted row would match a new partition, and if so, also do the same operation in the new partition, just like during adding index or modify column operations currently does. (To be implemented in `(*partitionedTable) AddRecord/UpdateRecord/RemoveRecord`)

Example of why an extra state between StateWriteReorganize and StatePublic is needed:

```sql
-- table:
CREATE TABLE t (a int) PARTITION BY LIST (a) (PARTITION p0 VALUES IN (1,2,3,4,5), PARTITION p1 VALUES IN (6,7,8,9,10));
-- during alter operation:
ALTER TABLE t REORGANIZE PARTITION p0 INTO (PARTITION p0a VALUES IN (1,2,3), PARTITION p0b VALUES IN (4,5));
```

Partition within parentheses `(p0a [1] p0b [0])` is hidden or to be deleted by GC/DeleteRange. Values in the brackets after the partition `p0a [2]`.

If we go directly from StateWriteReorganize to StatePublic, then clients one schema version behind will not see changes to the new partitions:

| Data (TiKV/Unistore)                    | TiDB client 1                        | TiDB client 2                                                |
| --------------------------------------- | ------------------------------------ | ------------------------------------------------------------ |
| p0 [] p1 [] StateWriteReorganize        |                                      |                                                              |
| p0 [] p1 [] (p0a [] p0b [])             |                                      |                                                              |
| (p0 []) p1 [] p0a [] p0b [] StatePublic |                                      |                                                              |
| (p0 []) p1 [] p0a [2] p0b []            | StatePublic INSERT INTO T VALUES (2) |                                                              |
| (p0 []) p1 [] p0a [2] p0b []            |                                      | StateWriteReorganize SELECT * FROM t => [] (only sees p0,p1) |


But if we add a state between StateWriteReorganize and StatePublic and double write to the old partitions during that state it works:


| Data (TiKV/Unistore)                              | TiDB client 1                                  | TiDB client 2                                                         |
| ------------------------------------------------- | ---------------------------------------------- | -------------------------------------------------------------------- |
| p0 [] p1 [] (p0a [] p0b []) StateWriteReorganize  |                                                |                                                                       |
| (p0 []) p1 [] p0a [] p0b [] StateDeleteReorganize |                                                |                                                                       |
| (p0 [2]) p1 [] p0a [2] p0b []                     | StateDeleteReorganize INSERT INTO T VALUES (2) |                                                                       |
| (p0 [2]) p1 [] p0a [2] p0b []                     |                                                | StateWriteReorganize SELECT * FROM t => [2] (only sees p0,p1)       |
| (p0 [2]) p1 [] p0a [2] p0b [] StatePublic         |                                                |                                                                       |
| (p0 [2]) p1 [] p0a [2] p0b [4]                    | StatePublic INSERT INTO T VALUES (4)           |                                                                       |
| (p0 [2]) p1 [] p0a [2] p0b [4]                    |                                                | StateDeleteReorganize SELECT * FROM t => [2,4] (sees p0a,p0b,p1) |


### Error handling

If any non-retryable error occurs, we will call onDropTablePartition and adjust the logic in that function to also handle the roll back of reorganize partition, in a similar way as it does with model.ActionAddTablePartition.

### Notes

Note that parser support already exists.
There should be no issues with upgrading, and downgrade will not be supported during the DDL.

Notes:
- statistics should be removed from the old partitions.
- statistics will not be generated for the new partitions (future optimization possible, to get statistics during the data copying?)
- the global statistics (table level) will remain the same, since the data has not changed.
- this DDL will be online, while MySQL is blocking on MDL.

## Test Design

Re-use tests from other DDLs like Modify column, but adjust them for Reorganize partition.
A separate test plan will be created and a test report will be written and signed off when the tests are completed.

### Benchmark Tests

Correctness and functionality is higher priority than performance.

## Impacts & Risks

Impacts:
- better usability of partitioned tables
- online alter in TiDB, where MySQL is blocking
- all affected data needs to be read (CPU/IO/Network load on TiDB/PD/TiKV), even multiple times in case of indexes.
- all data needs to be writted (duplicated, both row-data and indexes), including transaction logs (more disk space on TiKV, CPU/IO/Network load on TiDB/PD/TiKV and TiFlash if configured on the table).

Risks:
- introduction of bugs
  - in the DDL code
  - in the write path (double writing the changes for transactions running during the DDL)
- out of disk space
- out of memory
- general resource usage, resulting in lower performance of the cluster

---

### Design 2022 10 13 Mysql Compatible Auto Increment (`docs/design/2022-10-13-mysql-compatible-auto-increment.md`)

# Proposal: MySQL-Compatible `AUTO_INCREMENT`

- **Author(s)**: [tiancaiamao](https://github.com/tiancaiamao)
- **Discussion PR**: [#38449](https://github.com/pingcap/tidb/pull/38449)
- **Tracking Issue**: [#38442](https://github.com/pingcap/tidb/issues/38442)

## Abstract

This proposal outlines the implementation of a feature to align the behavior of `AUTO_INCREMENT` in TiDB with MySQL, ensuring compatibility.

## Background

MySQL operates as a single-machine database(for the most cases) and offers the [`AUTO_INCREMENT`](https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html) table attribute to generate unique identifiers for new rows.

In TiDB, we support the generation of `AUTO_INCREMENT` IDs that are **unique** and **monotonically increasing**, but they may **not be consecutive**.

The current behavior in TiDB does not fully align with MySQL.

TiDB is a distributed database, where each TiDB instance caches a batch of IDs for local allocation. When it exhausts its local cached IDs, it requests another batch. For example, TiDB instance A may be allocated the ID range [0-20000), and instance B takes the range [20000, 40000). Consequently, the next batch for TiDB instance A could be [40000, 60000), resulting in non-consecutive IDs. The ID sequence from instance A might appear as ...19998, 19999, [a gap here], 40000, 40001...

## Proposal

This proposal suggests the introduction of a centralized auto ID allocation service. `AUTO_INCREMENT` IDs will be allocated from this centralized service without any caching mechanism at the TiDB layer. This change ensures compatibility with MySQL's behavior.

## Syntax

The old implementation can still be retained as it offers better performance and may continue to meet the needs of some users.

There are several ways to handle compatibility:

1. **Option 1**: We can rename the syntax for the old implementation, for instance, using names like `AUTO_INCREMENT_FAST`, `AUTO_INCREMENT_OLD`, or `DEFICIT_AUTO_INCREMENT`. The advantage of this approach is that we can make the default syntax MySQL-compatible. However, the downside is that the new `AUTO_INCREMENT` behavior remains a compatibility breaker between old and new versions of TiDB.

2. **Option 2**: Alternatively, we can keep the old implementation unchanged and introduce a new syntax. The benefit of this approach is that our users will not encounter issues when upgrading TiDB.

3. **Option 3**: Another viable option is to reuse the `AUTO_ID_CACHE 1` table option, like this:

   ```sql
   CREATE TABLE t (id int key AUTO_INCREMENT) AUTO_ID_CACHE 1;
   ```

TiDB extends the syntax to control the AUTO ID CACHE size using the AUTO_ID_CACHE table option. Setting AUTO_ID_CACHE 1 is equivalent to no caching. This approach maintains the same semantics while changing the implementation. We believe this is the most optimal approach.

## Implementation

### Centralized Auto ID Allocation Service

The core of this implementation revolves around the introduction of a centralized auto ID allocation service. This service will consist of a single-point process responsible for the allocation of auto IDs.

(To be precise, the allocation service will be embedded within the TiDB process initially, possibly transitioning to a standalone process in the future. However, the fundamental concept remains the same.)

For every `AUTO_INCREMENT` ID allocation, TiDB will send a request to this central process. Internally, the process will increment the ID by one, ensuring that the generated IDs are **unique**, **monotonically increasing**, and **consecutive**.

### Handling Multiple Auto_INCREMENT IDs and Communication Protocol

In this implementation, the `+1` operation is conceptual, and a single request can allocate more than one ID. Multiple `AUTO_INCREMENT` IDs within one statement correspond to a `+n` operation. For instance, when executing a statement like `INSERT INTO t VALUES (null),(null),(null)`, it requests the allocation of 3 new values within one request.

For communication between components, gRPC is employed as the communication protocol. While this aspect is relatively straightforward, we won't delve into intricate details in this document.

Below is a brief overview of the gRPC message structures used:

```protobuf
message AutoIDRequest {
    int64 dbID = 1;
    int64 tblID = 2;
    uint64 n = 3;
    int64 increment = 4;
    int64 offset = 5;
}

message AutoIDResponse {
    int64 min = 1;
    int64 max = 2;
}

service AutoIDAlloc {
    rpc AllocAutoID(AutoIDRequest) returns (AutoIDResponse) {}
}
```

The fields increment and offset may seem to have no special significance here, but they are used to ensure compatibility with MySQL's behavior after setting @@auto_increment_increment and @@auto_increment_offset. It is worth noting that configuring two TiDB clusters for bidirectional master-master replication via this mechanism is not a common use case. Additional details can be found at [#14245](https://github.com/pingcap/tidb/issues/14245).

### High Availability (HA) of the Service

To address the issue of Single Point of Failure (SPOF), the centralized auto ID allocation service should have at least a primary and a backup process, and [etcd](https://etcd.io/) is used for managing this HA setup.

Both the primary and backup processes register themselves in etcd. The elected primary process serves the workload. In the event of a primary process failure (due to a crash, termination, or other reasons), the backup process takes over and continues providing the service. We can conveniently utilize the embedded etcd within TiDB, specifically the PD embedded etcd.

During a switch from the primary to the backup process, it is essential to preserve the information about the current maximum allocated ID. This ensures the uniqueness of IDs. The new primary process allocates IDs starting from the maximum allocated ID plus one.

While one approach could be to persist the maximum allocated ID every time, this can be resource-intensive. An alternative is to periodically persist the maximum allocated ID, and it is safe to allocate IDs in the range `[base, max persisted)`. In cases of abnormal crashes of the primary process, the backup process retrieves the max persisted ID as its base. This optimization may still result in non-consecutive IDs, but such occurrences are infrequent and considered acceptable.

**Note**: MySQL 8.0 has [introduced changes to auto-increment handling](https://dev.mysql.com/doc/refman/8.0/en/innodb-auto-increment-handling.html), making the current maximum auto-increment counter value persistent across server restarts, thus ensuring similar crash recovery behavior:

> In MySQL 8.0, this behavior is changed. The current maximum auto-increment counter value is written to the redo log each time it changes and saved to the data dictionary on each checkpoint. These changes make the current maximum auto-increment counter value persistent across server restarts.

### Client-Side Implementation

On the TiDB client side, support for service discovery is essential to ensure that clients always access the primary process and handle primary-backup switches automatically.

Service discovery is facilitated through etcd. All auto ID service processes register their addresses in etcd, allowing clients to retrieve this information and connect to the primary process seamlessly.

## Performance Evaluation

The introduction of a network round-trip in the auto ID allocation process does impact performance, although it remains acceptable. Within the same data center, the average latency is below 500 microseconds.

Preliminary testing indicates that to achieve a throughput of 20-40K QPS, it consumes approximately 100-200% CPU utilization on a local machine. This level of performance should be sufficient for typical usage scenarios.

## Performance Comparison

`AUTO_INCREMENT` demonstrates lower performance and scalability compared to TiDB alternatives such as `AUTO_RANDOM` and `SHARD_ROW_ID`. The following table provides performance metrics for different worker counts:

| Worker Count | QPS    | Average Latency (ms) | Server CPU Usage (%) |
| ------------ | ------ | --------------------- | -------------------- |
| 1            | 13,484 | 0.074192              | 115                  |
| 2            | 21,525 | 0.085926              | 135                  |
| 4            | 33,984 | 0.11579               | 160                  |
| 8            | 54,488 | 0.133927              | 203                  |
| 16           | 77,359 | 0.207223              | 248                  |
| 32           | 100,893| 0.332895              | 310                  |
| 64           | 118,471| 0.470853              | 357                  |
| 128          | 125,215| 0.977818              | 368                  |
| 256          | 125,901| 2.335869              | 379                  |

---

### Design 2022 11 17 Ttl Table (`docs/design/2022-11-17-ttl-table.md`)

# Proposal: Support TTL Table
- Author(s): [lcwangchao](https://github.com/lcwangchao)
- Tracking Issue: https://github.com/pingcap/tidb/issues/39262

## Table of Contents


* [Proposal: Support TTL Table](#proposal--support-ttl-table)
  * [Table of Contents](#table-of-contents)
  * [Introduction](#introduction)
  * [Detailed Design](#detailed-design)
    * [Syntax](#syntax)
      * [Create TTL Table](#create-ttl-table)
      * [Alter a Table with TTL](#alter-a-table-with-ttl)
      * [Alter to a non-TTL Table](#alter-to-a-non-ttl-table)
      * [Generated Columns](#generated-columns)
      * [Constraints](#constraints)
    * [TTL Job Management](#ttl-job-management)
    * [TTL Job Details](#ttl-job-details)
      * [Scan Tasks](#scan-tasks)
      * [Delete Tasks](#delete-tasks)
      * [Time Zone Consideration](#time-zone-consideration)
    * [New System Variables](#new-system-variables)
    * [New Metrics](#new-metrics)
  * [Known Issues](#known-issues)
  * [Future Works](#future-works)
    * [Performance Optimizations](#performance-optimizations)
    * [More Features to Support](#more-features-to-support)
  * [Alternative Solutions](#alternative-solutions)
  * [Testing Plan](#testing-plan)
    * [Functional Test](#functional-test)
    * [Performance Test](#performance-test)


## Introduction

The rows in a TTL table will be deleted automatically when they are expired. It is useful for some scenes, for example, delete the expired verification codes. A TTL table will have a column with the type DATE/DATETIME/TIMESTAMP which will be compared with the current time, if the interval between them exceeds some threshold, the corresponding row will be deleted.

## Detailed Design

### Syntax

#### Create TTL Table

The following example shows how to create a TTL table. The column `create_at` is used to specify the creation time of the rows which will be deleted 3 months after that.

```sql
CREATE TABLE t1 (
    id int PRIMARY KEY,
    created_at TIMESTAMP
) TTL = `created_at` + INTERVAL 3 MONTH;
```

We can use another `TTL_ENABLE` option to disable/enable the TTL job for the table. For example:

```sql
CREATE TABLE t1 (
    id int PRIMARY KEY,
    created_at TIMESTAMP
) TTL = `created_at` + INTERVAL 3 MONTH TTL_ENABLE = 'OFF';
```

The above table will not delete expired rows automatically because `TTL_ENABLE` is set to `OFF`. When the `TTL_ENABLE` is omitted, it uses value `ON` by default.

To make it compatible with mysql, TTL options also support the comment format. For example:

```sql
CREATE TABLE t1 (
    id int PRIMARY KEY,
    created_at TIMESTAMP
) /*T![ttl] TTL = `created_at` + INTERVAL 3 MONTH TTL_ENABLE = 'OFF'*/;
```

#### Alter a Table with TTL

We can alter an exist table with TTL options, for example:

```sql
ALTER TABLE t1 TTL = `created_at` + INTERVAL 3 MONTH;
```

TTL job is scheduled every 1 hour by default, if we want to custom the schedule interval, we can do it like this:

```sql
ALTER TABLE t1 TTL_JOB_INTERVAL='1d';
```

This alters the TTL job's schedule interval of table t1 to 1 day.

We should allow to update the existed TTL options. When it is updated, the running background job for this table should stop or restart according to the newest settings.

#### Alter to a non-TTL Table

Similar with mysql syntax "ALTER TABLE t REMOVE PARTITIONING", if we want to remove a table's TTL options, we can just do:

```sql
ALTER TABLE t1 REMOVE TTL;
```

#### Generated Columns

TTL table supports a generated column as the time column, but currently, there maybe a performance degradation if you use it. The main reason is that generated column does not support pushing down its expression to TiKV side and the scan phase will have more performance cost we'll discuss later. Another reason is that most date functions are not push down supported too. So, if we want to solve this problem, we must:

1. support pushing down generated column expression to TiKV side.
2. support pushing down some common date functions to TiKV side.

#### Constraints

- TTL does NOT work on a table that is referenced by a foreign key. For example, you cannot add TTL to the parent table, because it is referenced by a foreign key in the child table and deleting a row from the parent table could violate this constraint.

### TTL Job Management

We use a SQL-layer approach to delete expired rows. The "SQL-layer approach" means that the background jobs are using SQL protol to scan and delete rows. It is simple to implement and has a good compatibility with the tools such as BR and TiCDC.

In the current design, we'll schedule a job for each TTL table when needed. We will try to schedule the jobs from different tables to different TiDB nodes to reduce the performance affect. For one physical table, the job will be running in one TiDB node and the partition table will be recognized as several physical tables, so there can be multiple jobs running in different TiDB nodes at one time.

The TTL table status will be record in a new system table `mysql.tidb_ttl_table_status` with the definition:

```sql
CREATE TABLE `tidb_ttl_table_status` (
  `table_id` bigint(64) PRIMARY KEY,
  `parent_table_id` bigint(64),
  `table_statistics` TEXT DEFAULT NULL,
  `last_job_id` varchar(64) DEFAULT NULL,
  `last_job_start_time` timestamp NULL DEFAULT NULL,
  `last_job_finish_time` timestamp NULL DEFAULT NULL,
  `last_job_ttl_expire` timestamp NULL DEFAULT NULL,
  `last_job_summary` text DEFAULT NULL,
  `current_job_id` varchar(64) DEFAULT NULL,
  `current_job_owner_id` varchar(64) DEFAULT NULL,
  `current_job_owner_addr` varchar(256) DEFAULT NULL,
  `current_job_owner_hb_time` timestamp,
  `current_job_start_time` timestamp NULL DEFAULT NULL,
  `current_job_ttl_expire` timestamp NULL DEFAULT NULL,
  `current_job_state` text DEFAULT NULL,
  `current_job_status` varchar(64) DEFAULT NULL,
  `current_job_status_update_time` timestamp NULL DEFAULT NULL
);
```

It stores some information for each TTL table. The fields prefix `last_job_` present the information of the last job which is successfully executed, and the fields with prefix `current_job_` present the current job which has not been finished yet.

The explanation of the fields:

- `table_id`: The id of the TTL table. If the table is a partitioned table, it stands for the physical table id of each partition.
- `parent_table_id`: If the current row is a for table partition, it is the table id of its parent table. Otherwise, it equals to `table_id`.
- `table_statistics`: some statistics of the table.
- `last_job_id`: The id of the last success job.
- `last_job_start_time`: The start time of the last job.
- `last_job_finish_time`: The finish time of the last job.
- `last_job_ttl_expire`: The expired time used by the last job for TTL works.
- `last_job_summary`: The summary info for the last job.
- `current_job_id`: The id of the current job that is not finished. It not only includes the running job, but also includes the job that is failed or cancelled by user.
- `current_job_owner_id`: The id of the owner (a TiDB node) that runs the job. 
- `current_job_owner_addr`: The network address of the owner that runs the job.
- `current_job_owner_hb_time`: The owner of the job updates this field with the current timestamp periodically. If it is not updated for a long time, it means the previous owner is offline and this job should be taken over by other node later. 
- `current_job_start_time`: The start time of the current job.
- `current_job_ttl_expire`: The expired time used by the current job for TTL works.
- `current_job_state`: Some inner state for the current job. It can be used for the job's fail over.
- `current_job_status`: A enum with one of values: waiting, running, cancelling, cancelled, error
- `current_job_status_update_time`: The update time of the current status

TTL job for each table runs periodically according to the configuration of the system variable `tidb_ttl_job_run_interval` . For example, if we configure `set @@global.tidb_ttl_job_run_interval='1h'`, the cluster will schedule TTL jobs for each table every one hour to delete expired rows.

If you want to cancel a running job, you can execute a statement like this:

```sql
ADMIN CANCEL TTL JOB 123456789
```

In the above example, the status of the TTL job with ID `123456789` will first become `cancelling` and then finally be updated to `cancelled`.

### TTL Job Details

TiDB schedules TTL jobs to delete expired rows. One job is related to a TTL table and runs in one TiDB node. One TiDB node servers multiple workers where tasks from the TTL jobs are running. 

A running job contains two kinds of tasks: scan tasks and delete tasks. Scan tasks are used to filter out expired rows from the table and then send them to delete tasks which will do delete operations in batch. When all expired rows are deleted, the job will be finished. Let's talk about scan and delete tasks in detail.

#### Scan Tasks

When a job starts to run, it first splits the table to N (N >= 1) ranges according to their primary key. Each range will be assigned to a scan task and each scan task performs a range scan for the specified range. The pseudocode below shows how it works:

```
func doScanTask(tbl, range, expire, ch) {
    var lastRow
    for {
        selectSQL := buildSelect(tbl, range lastRow, expire, LIMIT)
        rows := execute(selectSQL)
        ch <- deleteTask{tbl, expire, rows}
        if len(rows) < LIMIT {
            break
        }
        lastRow := rows[len(rows)-1]
    }
}
```

As we see above, it builds some select queries in a loop. The first query is built like this:

```sql
SELECT LOW_PRIORITY id FROM t1
WHERE create_time < '2022-01-01 00:00:00' AND id >= 12345 AND id < 45678
ORDER BY id ASC
LIMIT 500;
```

In above example, the expired time is '2022-01-01 00:00:00' which is computed when the job started and the key range for the current scan task is `[12345, 45678)`. We also limit the max count of return rows as 500 which you can set the system variable `tidb_ttl_scan_batch_size` to change it. 

For most cases, we cannot get all expired rows in one query. So if the return row count equals to the limit we set, that means there are still some rows not read yet. Suppose the latest id we just queried is `23456`, we should schedule the next query like this:

```sql
SELECT LOW_PRIORITY id FROM t1
WHERE create_time < '2022-01-01 00:00:00' AND id >= 23456 AND id < 45678
ORDER BY id ASC
LIMIT 500;
```

The only difference with the first query is that the second one uses `23456` as the read start to skip the rows just read. This procedure will continue until all expired records are read.

The expired rows will be wrapped as `deleteTask` and then be sent to the delete workers simultaneously. Before we talk about delete works, there are still some things we should mention:

- As we see, the scan operation is heavy because it scans the whole table. For a large table, it is recommended to set the system variable `tidb_ttl_job_run_interval` to a longer value to reduce the resource cost in one day.
- When a table has no primary key or its primary key is not clustered, we'll use the hidden column `_tidb_rowid` instead as the row id.
- As we just mentioned, using a generated column as the time column is not efficient because TiDB currently cannot push down a generated column's condition to TiKV side, the TiDB has to do the filter works that requires more network traffics and CPU times.

#### Delete Tasks

There are several delete workers running in one TiDB node, and they consume tasks sent from the scan phase to delete expired rows. The following pseudocode shows how it works:

```
func doDelTask(ch) {
	for _, task := range ch {
		batches := splitRowsToDeleteBatches(task.rows)
		for _, batch := range batches {
			deleteBatch(task.tbl, task.batch, task.expire)
		}
	}
}
```

A delete worker receives tasks from a channel (a chan object in goland) and then splits the rows in it to several batches according to the system variable `tidb_ttl_delete_batch_size`. After that, each batch expired rows will be deleted by a multi row `DELETE` query. For example:

```sql
DELETE LOW_PRIORITY FROM t
WHERE id in (1, 2, 3, ...) AND create_time < '2022-01-01 00:00:00';
```

Notice that we are still using the condition `create_time < '2022-01-01 00:00:00'` to avoid deleting some "not expired" rows by mistake. For example, a row is expired when scanning, but updated to a not expired value before deleting it.

If there is no secondary index in a TTL table, we can assume that most of the delete operations can do a commit with 1PC. That is because the incoming rows are in the same region in most cases. So if you have a big table, keep no secondary indexes in this table may achieve a better performance for TTL jobs.

#### Distributed Task executions

As we mentioned above, a TTL job will be split to several scan tasks. In order to maximize the use of cluster resources, we can distribute these tasks to all TiDB nodes. Every time a new job is created, some rows will be inserted to a table named `mysql.tidb_ttl_task`. Each row in this table stands for a scan task. Every TiDB node will scan the table periodically and once a new task is discovered, the TiDB node will set the owner of the task to itself and then execute it.

#### Time Zone Consideration

Currently, we support three field types as the time column for TTL: `Date`, `DateTime` and `TimeStamp` . However, for `Date` and `DateTime`, they are not an absolute time, and we need another "time zone" information to determine what their accurate time point is. We have two options to select the time zone:

1. Use the system time zone which can be fetched from global variable `system_time_zone` and is determined when the cluster bootstraps. Because the `system_time_zone` will never changes, the row will be deleted at a certain time. However, it will have some problem when the user sets the cluster time zone `time_zone` to a different value other than `SYSTEM`. For example, if the `system_time_zone` is `+08:00` and `time_zone` is set to `UTC`, the record will be seen as expired immediately when the `tidb_ttl_job_run_interval` is less than 8 hours.

2. Use the cluster time zone `time_zone`. It is fine when cluster time zone `time_zone` does not change. But if user changes the `time_zone` settings, the TTL job should be aware of it in time to forbid deleting some unexpected rows. In this case, whether one row is expired or not can not be determined without knowing the `time_zone` at that time.

### New System Variables

Some new system variables will be introduced:

- `tidb_ttl_job_enable`
  - When this variable is `OFF`, the cluster will stop to schedule TTL jobs and the running jobs will be cancelled.
  - Scope: Global
  - Values: [ON, OFF]
  - Default: ON

- `tidb_ttl_job_schedule_window_start_time`
  - This variable is used to restrict the start time of the time window of scheduling the ttl jobs. 
  - Scope: Global
  - Type: Time
  - Default: 00:00 +0000

- `tidb_ttl_job_schedule_window_end_time`
  - This variable is used to restrict the end time of the time window of scheduling the ttl jobs.
  - Scope: Global
  - Type: Time
  - Default: 23:59 +0000

- `tidb_ttl_scan_worker_count`
  - The count of the scan workers in each TiDB node
  - Scope: Global
  - Range: [1, 256]
  - Default: 4

- `tidb_ttl_scan_batch_size`
  - The limit value of each SELECT query in scan task
  - Scope: Global
  - Range: [1, 10240]
  - Default: 500

- `tidb_ttl_delete_worker_count`
  - The count of the delete workers in each TiDB node
  - Scope: Global
  - Range: [1, 256]
  - Default: 4

- `tidb_ttl_delete_batch_size`
  - The batch size in one delete query when deleting expired rows.
  - Scope: Global
  - Range: [0, 10240]
  - Default: 100

- `tidb_ttl_delete_rate_limit`
  - The rate limit of the delete operations in each TiDB node. 0 is for no limit
  - Scope: Global
  - Range: [0, MaxInt64]
  - Default: 0

- `tidb_ttl_running_tasks`
  - The max count of running tasks in a cluster. -1 stands for auto determined by TiDB.
  - Scope: Global
  - Range: -1 or [1, MaxInt64]
  - Default: 0

### New Metrics

We'll introduce some new metrics to monitor the TTL jobs:

- `ttl_queries`
  - The total count of select queries in TTL jobs
  - Type: Counter
  - Labels: sql_type, result

- `ttl_processed_expired_rows`
  - The total count of expired rows processed in TTL jobs
  - Type: Counter
  - Labels: sql_type

- `ttl_query_duration`
  - The duration of the queries in TTL jobs
  - Labels: sql_type, result
  - Type: Histogram

- `ttl_job_status`
  - The status for the current TTL job. When the job is in the specified status, the value will 1, otherwise, it will be 0
  - Labels: table
  - Type: Gauge

- `ttl_phase_time`
  - The spent in different phases of each worker
  - Labels: type, phase
  - Type: Counter

- `ttl_insert_rows`
  - The total inserted rows to TTL tables
  - Type: Counter

In the above metrics, the optional values for sql_type label is 'select' and 'delete' and the optional values for result label is `ok` and `error`

## Known Issues

- Currently, the condition of generated column cannot be pushed down to TiKV. If a table uses generated column as a TTL time column, the filter will be performed in TiDB side. It brings some necessary network traffics and makes the query slow.

## Future Works

### Performance Optimizations

We'll do some performance optimizations in the future to reduce the execution time and performance cost of the TTL job:

- If a TTL table has some Tiflash replicas, we can scan the TiFlash instead of TiKV.
- If an index with the prefix of the TTL time column exists, we can use it to query expire rows instead of scanning the full table. It will reduce the execution time of the scan tasks.
- In most times, secondary indexes will not be created to avoid the hotspot of the insert. In this scene, we can also reduce some unnecessary scans by caching the statistical information. For example, we can cache the created time of the oldest row for each region after a job finished. When the next job starts, it can check the all the regions, if the data of one region do not have any updates and its cached time is not expired, just skip that region.
- If a table does not have any secondary index, we can do some further optimizations. One optimization is that to push down the scan and delete to TiKV side without data exchanging between TiDB and TiKV. It is somewhat like what GCWorker dose. In this way, a new coprocessor command "TTLGC" will be introduced and when a job starts, TiDB will send "TTLGC" commands to each region and TiKV will then scan and delete the expired rows (TiKV should delete expired rows in a non-transactional way).
- The resource control works in ongoing: https://github.com/pingcap/tidb/issues/38025 and the global resource control framework is still in design. We can take advantages of it in the future to maximize the resource utilization of the cluster.

### More Features to Support

There are also some features we can support in the future:

- Support TTL table as a parent table referred by a child table with 'ON DELETE CASCADE'. When some rows in a TTL table are deleted, the related rows in child table will be deleted too.
- Support pushing down generated column condition to TiKV side. Or use the definition of generated column to construct condition directly.
- Dynamically adjust the runtime settings according to the current overhead of the cluster.
- Add some builtin alters for cloud environment.

## Alternative Solutions

TiKV supports TTL on RawKV, so we may get question that whether we can implement TiDB TTL in same concept. IMO, this method has some downsides:
  - Not SQL awareness.
  - Customer may want to use any column as TTL Column, and may want to use Generated Column to convert other column type(JSON, varchar) to a DATETIME column as TTL Column.
  - No future foreign key support.
  - Not table awareness: TTL on RawKV is kv-level, can't easily set TTL on/off by Table
  - Not compatible with CDC, Backup, Secondary Index

There is another proposal to implement TTL by pushing configurations to TiKV: https://github.com/pingcap/tidb/pull/22763 . However, there are still some unresolved problems. For example, it may break the constraint of snapshot isolation.

CockroachDB also supports row-level TTL feature, and it is very similar with our design, for example:

```sql
CREATE TABLE events (
  id UUID PRIMARY KEY default gen_random_uuid(),
  description TEXT,
  inserted_at TIMESTAMP default current_timestamp()
) WITH (ttl_expire_after = '3 months');
```

The difference is that the CockroachDB is using a hidden column to store the "expire" time instead of "create_time". So when altering a table's TTL options, it will result in some data change and affect the performance depending on the table size, see: https://www.cockroachlabs.com/docs/stable/row-level-ttl.html#add-or-update-the-row-level-ttl-for-an-existing-table

## Testing Plan

### Functional Test

- Test DDL operations including:
  - Create a table with TTL options
  - Alter a non TTL table with DDL options
  - Alter a TTL table with new DDL options
  - Remove a table's DDL options
- Test a TTL table schedule background job and delete expire rows.
- Test a TTL table should not schedule job when `TTL_ENABLE` or `@@global.tidb_ttl_job_enable` is `OFF`
- Test TTL jobs should only be scheduled in time window.

### Performance Test

- Set up a 10 million rows table with 10 percent expire rows. Test the time it takes to clear the table.
- Start a benchmark test and then start a TTL job. Collect QPS/latency of the benchmark and compare it with that when TTL job is not running.

---

### Design 2022 11 22 View Hint (`docs/design/2022-11-22-view-hint.md`)

# View Hint Design Doc
- Author: Reminiscent
- Tracking Issue: https://github.com/pingcap/tidb/issues/37887

## Background
Hints that specify a table generally refer to tables in the DELETE, SELECT, or UPDATE query block in which the hint occurs, not to tables inside any views referenced by the statement. So we introduce the view hint to specify the table in view instead of embedding the hint in the view.

In Oracle, there are three ways to use the global hint. (Node: the `{}` part is only used for explanation)
```SQL
CREATE OR REPLACE VIEW v AS
SELECT {SEL$2} * from e1 join (select {SEL$3} * from e3) e2 on e1.a = e2.a;

SELECT {SEL$1} * FROM v;

A. SELECT /*+ INDEX(v.e2.e3 idx) */  * FROM v; // /*+ INDEX(@SEL$1 v.e2.e3 idx) */

B. SELECT /*+ INDEX(@SEL$2 e2.e3 idx) */ * FROM v;

C. SELECT /*+ INDEX(@SEL$3 e3 idx) */ * FROM v;
```

Compared with TiDB, Oracle has two differences:
1. Oracle can use `alias.table` to represent in subquery, such as e2.e3. Besides, TiDB can use `db.table` to represent a table.
2. The count for query block number treats view like a subquery, which means the select parts in view are counted.

Based on the difference, there are some reasons why TiDB can not just use the grammar from Oracle:
1. Compatibility
   1. Grammar.
      1. We can not use the `alias.table` to represent in subquery, such as e2.e3.
      2. We can use `db.table` to represent a table. So if we want to use the `view.table` to represent a table in view, we should change the grammar or it will conflict with db.table. 
   2. The count for the query block.
      1. Previously, the query block in view would not be counted. But now, if we take the view into consideration, it will change the origin count. For example, in the following part. The count of the query block for the `select a from t1` will be changed from `@SEL_2` to `@SEL_3`. So if we use the query block related hints for this part, it will be invalid or represent the content in the view.
            
```SQL
CREATE OR REPLACE VIEW v AS
SELECT {SEL$2} * FROM t;

SELECT {SEL$1} * FROM v JOIN (select {SEL$3} a from t1) t2 on v.a = t2.a;
```

So based on the above reasons, we should introduce another way to let hint take effect in the view.

## Detailed Design
### How does origin hint framework work?
1. Parser: parse the sql text and get the basic information about the hint. Handle hint syntax error in this phase.
2. Optimizer:
   1. Divide and mark the query block. Besides, group the hints in the same query blocks.
   2. In the plan builder phase, when we try to build select. We will handle the hints in the current query block. Including doing some simple checks and building the hints structure which can be used by planner. 
   3. When we build some logical operators, we will use the hints which belongs to the current query block. And tt will use the table in hint to match the table in the plan node. For example, when we build the `DataSource` operator, it will generate the possible access path based on the index hints. When we build the `Aggregation` operator, it will set the aggregation algorithm based on the agg hints. And for the `Join` operator, it will store the hint in the join node and use the hint information in the physical optimization phase. The warning about which table is not used in the hint will be recorded in this phase. 
   4. Use the hint information in the physical optimization phase to determine which physical algorithm should be used. And if the hint can not take effect, it will report warning. For example, if the join can not use the index join, but we set the index join hint in the sql text. It will report related warnings.

### View Hint Design
Based on the goal and current infrastructure for hint. I extend the current usage of the qb_name hint to a bigger scope to support the view hint.

An example to show the usage of the current `qb_name` hint.
```SQL
select /*+ stream_agg(@qb) merge_join(t1@qb)*/ * from (select /*+ qb_name(qb) */ count(*) from t1 join t2 on t1.a = t2.a) tt;
```
1. First, we define the name for some query blocks.
2. Then we can use the query block name to represent the query block.

Based on the meaning of `qb_name` hint now, we can expand it to support the view. The basic idea is the same here. We define the query block name in the view first. And then we can use the query block name to represent the contents in the view. Now the grammar is expanded from
`qb_name(name)` in the query block which you want to rename
To
`qb_name(name, viewName@queryBlockNum . {viewName}@queryBlockNum . ...)` in the first query block to represent any query block. Besides, we will reset the count for query block in every view. It means, for every view, it always counts from 1 and it will not effect the outer part.
For example:
```SQL
create table t(a int, b int);
create table t1(a int, b int);
create table t2(a int, b int);

create view v as select {@SEL_1}{5} t.a, t.b from t join (select {@SEL_2}{6} t1.a from t1 join t2 on t1.b=t2.b) tt on t.a = tt.a;

create view v1 as select {@SEL_1}{3} t.a, t.b from t join (select {@SEL_2}{4} from t1 join v on t1.b=v.b) tt on t.a = tt.a;

create view v2 as select {@SEL_1}{1} t.a, t.b from t join (select {@SEL_2}{2} t1.a from t1 join v1 join v3 on t1.b=v1.b) tt on t.a = tt.a;

select {@SEL_1} * from v2;

/* We can use the following part to represent the {1} - {6} */
1: qb_name(v2_sel1, v2@sel_1 . @sel_1)
2: qb_name(v2_sel2, v2@sel_1 . @sel_2)
3: qb_name(v1_sel1, v2@sel_1 . v1@sel_2 . @sel_1)
4: qb_name(v1_sel2, v2@sel_1 . v1@sel_2 . @sel_2)
5: qb_name(v_sel1, v2@sel_1 . v1@sel_2 . v@sel_2 . @sel_1)
6: qb_name(v_sel2, v2@sel_1 . v1@sel_2 . v@sel_2 . @sel_2)
```
Take the previous as example:
```SQL
CREATE OR REPLACE VIEW v AS
SELECT * from e1 join (select count(*) from e3) e2 on e1.a = e2.a;


/* In Oracle */
A1. SELECT /*+ INDEX(v.e2.e3 idx) */  * FROM v;

A2. SELECT /*+ INDEX(@SEL$1 v.e2.e3 idx) */ * FROM v;

B. SELECT /*+ INDEX(@SEL$2 e2.e3 idx) */ * FROM v;

C. SELECT /*+ INDEX(@SEL$3 e3 idx) */ * FROM v;

/* In TiDB */
SELECT /*+ qb_name(viewSub, v@sel_1 . @sel_2) use_index(e3@viewSub, idx) hash_agg(viewSub) */ * FROM v;
```

### Implementation
Parser part is easy to implement. Just to expand the origin `qb_name` hint grammar. The only problem maybe is how to express the nested view(use dot or blank or something else).

For the planner part:
1. At the beginning of the optimization, we should handle the query block name hint for view and the other method hints for view. And group these hints based on the query block name.
2. When we try to build the data source from the view, we have to traverse all of the query blocks for views. Check whether the view name in hint can match the data source or not. If there are some hints that can match, we pass it to the `buildDataSourceFromView`.
3. When we try to build the view plan, we first handle the hints which are passed by the caller. Distinguish which hints belong to the current view and which belongs to the nested view. If the hint belongs to the current view, we transform the hint to the normal hint. If the hints belong to the nested view. Then we will do the same thing, like step2.

Besides the planner part, we need support to show the query block for a sql to increase usability. The user can copy the result and use it in hint directly.

### Support Scope
1. We can support almost all physical algorithm's hints. Like join hints/ agg hints/ index etc.
2. Do not support the leading hints which may be across the view. But we can support the leading hint in the same view.

### Pros and Cons
Pros:
1. No compatibility problems. Just expand the usage of the existing hint.
2. It is easier to implement. It can use the origin hints' infrastructure as much as possible.
3. It can support almost all the hints which can take effect in the query block. Oracle can only support the join order, join method and access path hints.

Cons:
1. It may not be easy to write the query block name hint for a view.
2. The user should define the query block name hint first.

## Reference
[Oracle Global Hint](https://docs.oracle.com/cd/E18283_01/server.112/e16638/hintsref.htm#i27644)

---

### Design 2022 11 23 Batch Cop (`docs/design/2022-11-23-batch-cop.md`)

# Proposal: support batch coprocessor for tikv

* Authors: [cfzjywxk](https://github.com/cfzjywxk)
* Tracking issue: [39361](https://github.com/pingcap/tidb/issues/39361)

## Motivation

The fanout issue in index lookup queries is one cause of increased query latency and cost. If there are 
1,000 handles and they are distributed in 1,000 regions, TiDB would construct 1,000 small tasks to retrieve 
the 1000 related row contents, even when all the region leaders are in the same store. This results in the following problems:
1. Each task requires a single RPC request, there could be too many tasks or RPC requests though each 
request just fetches a few rows. Sometimes the cost of RPC could not be ignored.
2. Increasing task numbers may lead to more queueing. Tuning the related concurrency parameters or task scheduling 
policies become more complex and it’s difficult to get best performance.

In the current coprocessor implementation, key ranges in the same region would be batched in a single 
task(there is a hard coded 25000 upper limit), how about batching all the cop tasks which would 
be sent to the same store?

In a user situation, the index range scan returns 4000000 rows, and finally 400000 coprocessor table-lookup 
tasks are generated, which means the key ranges are scattered in different regions.

## Optimization

### The IndexLookUp Execution Review

Usually, the IndexLookUp executor may have an index worker which tries to read index keys and related row handles 
according to the index filter conditions. Each time it fetches enough row handle data, it would create a 
coprocessor table lookup task and send it to the table workers. The handle data size limit for one task could be configured 
by the [tidb_index_lookup_size](https://docs.pingcap.com/tidb/dev/system-variables#tidb_index_lookup_size) 
system variable.

When the table worker gets a coprocessor task, it would split the handle ranges according to the region 
information from the region cache. Then these region-aware tasks are processed by the coprocessor client 
which has a default concurrency limit configured by the [tidb_distsql_scan_concurrency](https://docs.pingcap.com/tidb/dev/system-variables#tidb_distsql_scan_concurrency) system 
variable.

### Batching Strategy

As coprocessor streaming is already deprecated, bringing it back may not be a good idea. To make the design 
simple, we could just do the batching for each coprocessor table task separately. Different coprocessor table 
tasks may still require different RPC requests, while row handle ranges within one task could be batched if 
their region leaders are in the same store. The main idea is trying to batch sending the tasks using one 
RPC for each original `copTask` if the row handle range-related region leaders are located in the same tikv store.

With the batching optimization, the number of RPC requests may be at most the number of store nodes for each table lookup task
. Consider an extreme case, if the index scan returns 4000000 rows and each task range is one row
, there could be as many as `4000000/25000=160` table lookup tasks each containg 25000 key ranges. But now the RPC number
would become at most `160 * store_numbers`, for example if store_number is 10, the total request number is
1600 which is much less than the previous 400000.

### Proto Change

Create a new structure for the batched tasks, including the request `StoreBatchTask` and response `StoreBatchTaskResponse` types.

```protobuf
message StoreBatchTask {
    uint64 region_id = 1;
    metapb.RegionEpoch region_epoch = 2;
    metapb.Peer peer = 3;
    repeated KeyRange ranges = 4;
    uint64 task_id = 5;
}
```

```protobuf
message StoreBatchTaskResponse {
    bytes data = 1 [(gogoproto.customtype) = "github.com/pingcap/kvproto/pkg/sharedbytes.SharedBytes", (gogoproto.nullable) = false];
    errorpb.Error region_error = 2;
    kvrpcpb.LockInfo locked = 3;
    string other_error = 4;
    uint64 task_id = 5;
    kvrpcpb.ExecDetailsV2 exec_details_v2 = 6;
}
```

Attach the batched tasks into the `Corprocessor` request. Reuse the `RegionInfo` mentioned above to store tasks
in different regions but the same store.
```protobuf
message Request {
    …

    // Store the batched tasks belonging to other regions.
    repeated StoreBatchTask tasks = 11;
}
```

Add batched task results in `Response`, different tasks may encounter different kinds of errors, collect them
together.
```protobuf
message Response {
   …
   repeated StoreBatchTaskResponse batch_responses = 13;
}
```

### The TiDB Side

Adding a flag in `kv.Request` to indicate if the batch strategy is enabled or not.
```golang
type Request struct {
    …
    // EnableStoreBatch indicates if the tasks are batched.
    EnableStoreBatch bool
}
```

Adding batch task related fields in `copr.copTask`. They would be collected when the `copTask` is being
prepared and the store batch is enabled.
```golang
type copTask struct {
    …
    //
    batchTaskList []kvproto.Coprocessor.RegionInfo
}
```

When building coprocessor tasks in the `buildCopTasks` function, try to fill the `batchTaskList` if
necessary.The steps are:
1. Creating a map to record `store address => *copTask`.If store batch is enabled, tasks would be appended
to existing `copTask` when the store address is the same.
2. Split the ranges according to the region information as usual. After this, all the tasks correspond
to a single region.
3. When processing a new `KeyLocation`, try to append it as the batch task to the existing coprocessor task 
if possible.

The coprocessor client just sends the tasks as usual, the `Coprocessor` request is still a unary RPC 
request though it may be batched. When handling `CopResponse`, if the batch path is enabled and 
there are region errors or other errors processing batch tasks, rescheduling the cop tasks or 
reporting errors to the upper layer. 

Note if the `keepOrder` is required, the partial query result could not be sent back until all the reads 
have succeeded.



### The TiKV Side

A simple way is to change the logic in `Endpoint.parse_and_handle_unary_request`, after parsing the 
original request, the batched task-related builder and handler could be also generated using the input 
information from the RPC context, region information, and key ranges as long as they are properly passed in 
the `Coprocessor` request.

All the request handling could be scheduled to the read pool at the same time, 
so before finishing something like `join_all` would be needed to wait for all the results of 
different tasks. If any error is returned, do fill in the error fields in the `Response`.

For the execution tracking, creating seperate trackers for the requests, all the execution details would be returned
to the client.

---

### Design 2022 11 25 Global Resource Control (`docs/design/2022-11-25-global-resource-control.md`)

# Global Resource Control in TiDB
- Author: [nolouch](https://github.com/nolouch), [BornChanger](https://github.com/BornChanger), [glorv](https://github.com/glorv), [Connor1996](https://github.com/Connor1996), [tiancaiamao](https://github.com/tiancaiamao)
- Tracking Issue: https://github.com/pingcap/tidb/issues/38825

## Summary

A Global Resource Control mechanism that limits multiple applications' resource usage in a shared TiDB cluster, avoids interference between applications.

## Background and Motivation

A TiDB cluster for multiple applications to share the same data service, and there are several Aurora or MySQL, or other database instances as the data service backend. TiDB has the advantage of scalability but also has some challenges in the big-size cluster. How to make the shared cluster provide stable, predictable performance for different Applications? Part of what needs to be done is to control the resource usage of each application.

Currently, TiDB lack of global admission control limits the request from the SQL layer to the storage layer, and different users or applications may influence each other in the shared environment. Use a global admission control to ensure that the cluster doesn't become overloaded, avoid interference between applications, and enforce the throughput limits requested by customers.

Moreover, this resource control mechanism can be used by Resource Manage in the future of TiDB Cloud. Users can pay for the actual usage.  So, consider scenarios. It supports two models.

- **Provisioned:** On-Premise deployment, multi-applications shared on the big cluster. In this mode, you provision the number of RU rate limits or(CPU, IO Rate) and priority for the users/tenant/sessions.
- **Serverless:** In this mode, the user can pay the total cumulative RU for the tenant or user. Then the resources can not be limited until the RU is exhausted. This requirement TiDB Cloud has sufficient flexibility. such as auto-scale resources.

## Detailed Design

Global Resource Control Architecture Overview



**Resource Group** helps users to control over its resources, to enable or restrict resource consumption. resource groups have attributes that define the group. all attributes can be set at group creation time and  modified any time thereafter. The attributes define how many resource units in this group relative CPU, IO, Memory and so on.
resource groups can be assigned to different resource objects. such as session/users/tenant.
There are two dimensions to control the resources, one is Global Quota dimension, which is more of a tenant-level application, users can plan the usage of resources in provision, to limit the resources usage. The other side is the scheduling(weight) dimension, to ensure better control behavior when the resources are insufficient.

**Global Quota dimension**  This part is the upper limiter and lower limit(reservation) for the resource group. This defines the provision of the resource usage of the application layer. Here mainly use a token bucket algorithm to limit the resources at the entry of TiDB, count total resource usage including sql and storage layer.

**Scheduling dimension**  Currently, this part is implemented only at the storage side but we may also add similar mechanism in the tidb side in the future. The propose of the new scheduler is to ensure the tasks from different resource group can always consume reasonable resources according to their RU settings so the QoS of each resource group is ensured. TiKV uses the dmclock algorithm to ensure the fairness between different resource groups.

Will introduce this two dimensions control mechanism in the following.

### User SQL interface

The `Request Unit` can be assigned to a different level, like user or tenant. The syntax is like MySQL resource group, but it is used differently:

```sql
CREATE RESOURCE GROUP resource_group_name RU_PER_SEC=20000 [PRIORITY=HIGH|MEDIUM|LOW] [BURSTABLE]
/*eg:*/
CREATE RESOURCE GROUP oltp_applicaton RU_PER_SEC=20000, PRIORITY=HIGH, burstable;
CREATE RESOURCE GROUP small_applicatoin RU_PER_SEC=5000;
CREATE RESOURCE GROUP olap_application RU_PER_SEC = 50000 PRIORITY=LOW, BURSTABLE;
/* bind resource group via DCL */
ALTER USER user_name RESOURCE GROUP resource_group_name;
CREATE USER user_name IDENTIFIED BY 'password' RESOURCE GROUP resource_group_name;

/* bind resource group to the current session */
SET RESOURCE GROUP resource_group_name

/* bind resource group to sql via optimizer hint */
SELECT /*+ RESOURCE_GROUP(resource_group_name) */ * from table_name;
```

### Global Quota Control(- Global admission control)

The global admission control can be an independent module that is easy to use and compiled by TiDB. And also, it's possible to be an independent service. Because its local controller part may be installed to the SQL layer first, or it may be moved from the SQL layer to the proxy layer with the evolution. And it also will be related to the billing system in the future. Therefore, it should be as decoupled as possible.
The subsystem can be enabled and disabled. Once enabled, it may bring some performance regression (1%~5% from TopSQL) due to the statistics and control overhead.

Overview



**Global Admission Controller(GAC):** The Global Admission Controller service centrally tracks the total consumption of the user or tenant in terms of tokens. And maintain the global token bucket with the setting refill rate(RU). It is also responsible for dynamically allocating and adjusting local token buckets. Global Admission Controller maintains some settings and consumption in the etcd, and uses etcd election to achieve high availability,

**Local Admission Controller(LAC):** Local Admission Controller has the Resource Measure part and a local token bucket part. The local token bucket uses it for admission control of the KV request. Each KV request consumes tokens and might need to wait until there are enough tokens available. CPU usage of SQL requests also consumes tokens but accounts for it after the fact.

### Request unit

Request unit (short as **RU**) is the uniformed abstract unit of system resource including CPU, IO, etc. Customers explicitly specified the capacity that an application user or tenant required in terms of requesting units (**RU**).

### Request unit Model

Here is to define a cost model relative to the actual cluster resource capacity. Each request will consume the resource capacity. The TiDB layer will cost CPU and memory for different SQL requests, and then SQL requests will transform into the KV requests. These KV requests include different types, requiring the resource of CPU/IO/Memory. All in one, our abstraction unit needs to be mapped to the resources of the cluster, including CPU/IO/Memory, and even the network. For now, we only consider two factors: CPU and IO.

$$RU=\alpha_r + \beta_r * IOBytes + \gamma_r * CpuSecs$$

The values of the coefficients α,β,γ vary in different environment, they require datasets from various tests then regress and fit a solution(values) that best maps the actual resource usage.
Currently, TiKV cannot control the IOPS well, the IO only considers the IO flow first. But we can continuously improve this model, such as adding IOPS, memory, etc. In addition, it is possible to subdivide the request type. such as distinguishing the consumption of the small query and big query, different query about: Update, Insert.

### Metering the Request unit

`SQL Request` and `KV Request` to describe the request stage across the SQL layer and Storage layer. In the prototype, SQL Request is not considered because one SQL instance corresponds to one tenant user, and the resource control is at the tenant level, so it only needs to calculate SQL instance CPUSecs. Here we should consider user level, it requires us to meter SQL query CPUSecs.

### Tag in request and collect resource usage

`TopSQL` has done some infrastructure before. TopSQL can aggregate at SQL digest level CPU consumption, which includes SQL query execution process but does not include parse process because SQL digest is labeled after the parser stage.  There is a problem with aggregating `SQL Digestlevel` to the `user` level, it may need to add an additional tag.  
After SQL Request transforms to KV request, the tag information like SQL digest will be set in the context of KV request. KV requests will be handled in the storage level, There exist different KV request types. Read requests including KV Request `Get/Scan/Coprocess` and so on. Write KV Requests including `Prewrite/Commit/Put/Lock `and so on.  After the request is handled, the KV response will collect the details of the resource usage response to the SQL layer.
After some of this, we can aggregate the actual RU consumption of the query. With these preparations, it can integrate with the admission control module to be mentioned later.

### Global Resource Quota Limiter
#### Distributed Token Buckets

The core of admission control is the distributed token buckets algorithm. The algorithm can be described as the Local Token Buckets in the TiDB Nodes (KV clients), and communicating with a centralized token buckets server in GAC. The tokens are **RRUs** or **WRUs**.  One TiDB Node may exist multiple token buckets for users. These local buckets will make local admission decisions and communicate with the server to reconfigure the local tokens at regular intervals (default 10s).
```go
ProtoBuf
message TokenBucketRequest {
  message RequestRU {
    repeated RequestUnitItem request_r_u = 1;
  }

  string resource_group_name = 1;
  RequestRU ru_items = 2;
  // Aggregate statistics in group level.
  Consumption consumption_since_last_request = 3;
  uint64 target_request_period_ms = 2;
  uint64 client_unique_id = 3;
}
message TokenBucketResponse {
  string resource_group_name = 1;
  repeated GrantedRUTokenBucket granted_r_u_tokens = 2;
}
message GrantedRUTokenBucket {
  RequestUnitType type = 1;
  TokenBucket granted_tokens = 2;
  int64 trickle_time_ms = 3;
}
enum RequestUnitType {
  RU = 0;
}
message TokenBucket {
  TokenLimitSettings settings = 1;
  // Once used to reconfigure, the tokens is delta tokens.
  double tokens = 2;
}
message TokenLimitSettings {
  uint64 fill_rate = 1;
  int64 burst_limit = 2;
  double max_tokens = 3;
}
message Error {
    string message = 1;
}
message Consumption {
  double r_r_u = 1;
  double w_r_u = 2;
  double read_bytes = 3;
  double write_bytes = 4;
  double total_cpu_time_ms = 5;
  double sql_layer_cpu_time_ms = 6;
  double kv_read_rpc_count = 7;
  double kv_write_rpc_count = 8;
}
```

In this protocol, there are some key fields:
- `target_request_period_ms`: This field is the lease interval for the local token buckets, it is configurable.
- `requested_r_u`: It's a load expect with load estimation. This is an exponentially weighted moving average of the load at the nod.

#### Bursting and Refill rate

Bucket Tokens have two parts.
- `burst`: it is an accumulated value, it absorbs temporal spikes in workloads of the tenant user. Moreover, if the system is elastic enough, such a cluster can be auto-scale in the cloud. It can be used as the budget for users to pay. If the burst is enough, customers feel free to use resources without limitation, which matches the main idea of the serverless product.
- `refill rate`: rate-limit resource consumption. grant the tokens over a specified period of time, according to a fraction of the global refill rate
Once a request with a token bucket server is completed, the node adjusts its local token bucket according to the response. Either adding burst tokens or setting up a refill rate.
#### Debt

The token buckets can be "debt", as we mentioned, due to some statistics only being accounted for after the fact (eg, the read size of coprocess request, the CPUSecs usage). When a local bucket is in debt, KV operations are blocked until the debt is paid. This may lead to the latency not being stable . There is an improvement that allows the debt to be paid over a time period from the refill rate.
#### Adaptive Capacity

When a request from the application arrives, the request deducts tokens. Eventually, the LAC will run out of tokens because of consumption or expiry. When the LAC runs out of tokens, it requests more tokens from Global Token Server immediately. The Glocal Token Server instance uses the information provided by the client to estimate the global token consumption and vends tokens available for the next time unit to the client's share of overall tokens. Thus, it ensures that workloads can adaptively turn the local bucket fill rage up to the maximum capacity.
#### Balance the consumed capacity

The data hosted on a single storage node could be wholly unrelated and belong to different users or tenants. where each application could be from a different customer and have varied traffic patterns. Co-location was a straightforward problem with provisioned performance for application. Balancing the requirements of the provision for user's data may need to be considered.

### Scheduling Control

Compared to Storage, SQL layer node is easier to scale out since it's stateless, especially with k8s.
Storage(TiKV/Tiflash) cluster sharing with QoS guarantee is more challenging. In this chapter, we will discuss our design on request scheduling at Storage side first. There are 3 goals:
- Requests from higher priority resource group are scheduled more
- No starving for lower priority request
- Soft quota limiters can be issued to resource groups

#### QoS Metadata management

Resource Manager keeps the persisted metadata of resource groups. Resource Manager will translate that metadata information from abstract RUs into system resources like vCPU, read bandwidth, write bandwidth, etc to TiKV/Tiflash nodes.

Metadata sync-up is bidirectional. Resource Manager notifies TiKV on resource group metadata change at DDL execution time via http API interface. And TiKV nodes inquire Resource Manager when local metadata is missing or might be stale. Resource group metadata is in memory only at TiKV nodes.

#### Soft quota limiters

We can specify the quota limits for some resource groups to prevent the overrun and for TiKV node protection, by reusing the front-end quota limiter (token bucket algorithm) framework of TiKV. With the quota limiter capping, requests from some resource group might be throttled even when the TiKV instance is not saturated.

#### New field in kv protobuf

TiDB needs to inject into gRPC requests a resource group related information, like the resource group id, in the protobuf message.

#### Front-end requests scheduling

Resource consumption on vCPU, read bandwidth and write bandwidth needs to be normalized into internal "Shares" represented as a number. At different modules and different phases, the normalization formulas are different.

Read request and write request handling are quite different in TiKV. Read request handling in TiKV is already in fine grain, and we can almost directly use request elapsed time as resource consumption, while write path handling is rather complex.

##### dmClock Algorithm

`mClock` is a priority-based scheduling algorithm. Each resource group maintains a separate task queue, the schedule always pops and executes a task for the queue whose next task has the minimum priority value. The
$$P_i = \max(P{i-1} + w, V_t)$$
$P_{i-1}$ is the accumulated weight of executed tasks. Vt is the minimum priority of all non-empty queues, it is used when queue i is empty.
`w` is a number that represents the resource consumed by this task.
It's easy to prove that by using the mclock algorithm, we can ensure a resource group to obtain its share of resources with reasonable latency.
`dmClock` extends the `mClock` algorithm to fit in the distribued environment. In a distributed system like TiDB, a SQL request is likely to be transfer to multiple kv request and sent to different store. If the data is unevenly distribute the `mClock` is not enough to gain fair scheduling globally. The `dmClock` changes `w` from the cost of a single task plus the cost of other tasks sent to other storages. Thus, the total $$P_i represent the total resource consumption of all tasks in all stores.

**Implement**

Because the standard mclock algorithm needs a FIFO queue for each resource group and a global priority queue to sort between these queues, it is not easy to implement a high-performance scheduler with the similar performance of yatp.
we make a few changes to the algorithm to make it easy for our usage and better performance.
To make things simple, we change the priority calculation formula to:

$$Vt_i = \sum{w_i}$$

$$P_i = Vt_{i-1} + w_i$$

And periodically renew Vt by increasing the Vt of each resource group by half the delta value of max Vt.
$$Vt_i = Vt_i + (\max{(\forall{Vt})}-V_i)/2$$

##### Absolute Priority

In addition to the `dmClock` based scheduling, we support an absolute priority at the resource group level. That is, the tasks priority is changed from single accumulated `weight` to `(priority, weight)`, so tasks bind to resource groups with higher priority will always be scheduled earily. This is usefully in case that when the total resource quota is not enough, the QoS of higher priority application can be ensured first. Note that absolute priority may lead to starvation of low-priority tasks in case the system's total resources are not enough.

##### Read path

Previously, all read requests are executed by the yatp thread pool, whose scheduler is a multi-level feedback queue, and each level is a FIFO queue.
Because the current yatp's scheduler is a FIFO queue, a new task is always put at the end of the queue, thus the latency of all tasks are high when there are a lot of tasks.

In the first implementation, the read path will only use the CPU time to calculation the cost of each task, we may change the statistics to also include other resources in the future.

##### Write Path

For one region, it may be written by requests with different priorities. As requests would be serialized to raft log, the high or low-priority requests may be interleaved and can't change the order. But it's okay, our goal is to keep the QoS of the high-priority requests. So we always handle the regions having high-priority requests first. And considering the real use case, one region would probably be touched only by one user, as business logic should be isolated in most cases.

###### Write path in a picture.



Here is the flow of typical txnkv write requests(use lease read), involving five thread pool to adapt with priority-based scheduling.
- Scheduler(grpc thread)
don't do any scheduling, the overhead for acquiring txn latch is small
- Scheduler worker
Once latch and region snapshot is acquired, txn constraint check, which is several gets and seeks, is handled by this worker. This pool is based on yatp, so simply reuse the work of read flow priority scheduling.
- Store batch system(usually call it raftstore)
The most critical one, elaborate below
- Async io pool
Assume that async-io is always enabled, all raft log entries are written to raft-engine here. Change the FIFO queue to a priority-based queue. The write batch including high priority requests are out first.
- Apply batch system
Committed entries are written to kvdb here. Should poll regions having committed entries of high-priority requests first.

###### Store batch system
Assumption: only considered for async-io enabled
Store batch system drives raft groups. Some messages are time critical, like raft heartbeat, so these shouldn't be delayed by priority scheduling.
```rust
fn poll() {
    loop {
        let fsms = fetch_fsms();
        let readies = vec![];
        for fsm in fsms {
            for msg in fsm.mail_box.recv() {
                handle_message(msg);
            }  
        let write = fsm.collect_ready();
        async_io_pool_sender.send(write); 
        }
    }
}
```
Propose messages and Raft append messages cause disk write. But due to async-io, the poll speed would be fast enough to handle any messages in a short time. So we only consider priority scheduling in async io pools and propose a queue.
Here are rules:
- When proposing a request with high priority, the fsm is set to high priority. When the message is handled, the fsm is set back to normal priority
- For fetch_fsms, fsms of high priority should be fetched first.
- High priority is set to the context of raft entry as well. So followers can know the region is of high priority.

#### Front-end requests vs back-end requests

Backend requests scheduling is also taken into account. They can be assigned to some predefined resource groups and quota limiters.  And schedulers can handle them along with front-end requests at some underneath level, where IO is more sensitive.

## Other Issues

### On-demand provisioning

Because the concept of request units is new to customers, it may be challenging to forecast the provisioned throughput. Also, the application's data distribution and workload non-uniform access may lead to not all data across all storage nodes. Although from the global perspective of the entire cluster, there remain many resources, the application setting may still be inappropriate. Hence, we should let the cluster have a capacity to burst at the node level, and it may need to do something about balancing the consumed capacity mentioned above.

### Diagnostics

Metrics on # of blocked requests due to out of token,  per user, per tenant.
HWM of RU for slow queries, for individual users and tenants
LWM, HWM, Average rate for individual resource group

### Reference

- Resource Abstract in other systems:
  - DynamoDB:  https://aws.amazon.com/dynamodb/pricing/provisioned/
  - MongoDB:https://www.mongodb.com/docs/atlas/billing/serverless-instance-costs/
  - CRDB: https://www.cockroachlabs.com/docs/cockroachcloud/serverless-faqs.html#what-is-a-request-unit
  - Cosmos DB https://docs.microsoft.com/en-us/azure/cosmos-db/request-units
- SET RESOURCE GROUP Statement https://dev.mysql.com/doc/refman/8.0/en/set-resource-group.html
- Amazon DynamoDB: A Scalable, Predictably Performant(2022) https://www.usenix.org/system/files/atc22-elhemali.pdf
- CRDB Distributed token bucket: https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20210604_distributed_token_bucket.md
- Ceph dmclock: https://github.com/ceph/dmclock

---

### Design 2022 12 06 Support Late Materialization (`docs/design/2022-12-06-support-late-materialization.md`)

# Proposal: Support late materialization

* Author: [Lloyd-Pottiger](https://github.com/Lloyd-Pottiger)
* Tracking issue: https://github.com/pingcap/tiflash/issues/5829

## Background

TiFlash is the key component that makes TiDB essentially an Hybrid Transactional/Analytical Processing (HTAP) database. 

Operating on positions opens a number of different query processing strategies centered around so-called "materialization". Roughly speaking, materialization is the process of switching positions back into values. The literature presents two main strategies: early and late materialization. The basic idea of late materialization is to operate on positions and defer tuple reconstruction for as long as possible. Refer to [A Comprehensive Study of Late Materialization Strategies for a Disk-Based Column-Store](https://ceur-ws.org/Vol-3130/paper3.pdf). 

There are two kinds of late materialization:
1. Late materialization in selection

    

2. Late materialization in join （#Fig.2）

    

**Only the late materialization in selection will be considered this time.**

Late materialization can help improve performance of some AP queries. Like `SELECT * FROM t WHERE col_str LIKE '%PingCAP%'` The normal execution processes are as follows:
- Read all the data pack of all the columns on table t
- Run the filter `col_str LIKE '%PingCAP%'`
- Return the result

With late materialization, the execution processes can be:
- Read all the data pack of col_str
- Run the filter `col_str LIKE '%PingCAP%'`
- Read the needed data pack of the rest columns on table t
- Return the result

And for more complex queries, like `SELECT * FROM t WHERE col_str1 LIKE '%PingCAP%' AND REGEXP_LIKE(col_str2, 'new\\*.\\*line')`, late materialization, the execution processes can be:
- Read all the data pack of col_str
- Run the filter `col_str1 LIKE '%PingCAP%'`
- Read the needed data pack of rest columns on table t
- Run the filter `REGEXP_LIKE(col_str2, 'new\\*.\\*line')`
- Return the result

Note that, `REGEXP_LIKE(col_str2, 'new\\*.\\*line')` is a heavy cost filter condition, filter out some data by `col_str LIKE '%PingCAP%'` first can reduce lots of useless calculation.

Therefore, when late materialization is enabled, we can not only reduce the number of data packs to be read but also reduce some useless calculation. If the selectivity of the pushed down filter is considerable, the performance of the query can be highly improved.

But TiFlash still does not support late materialization now. So, we are making a proposal to support it.

## Objective
- Improve performance of some AP queries.
- Without performance degradation of most queries.

## Design

In brief, we will divide the filter conditions of selection(whose child is tablescan) into two parts: 
- Those light and with high selectivity filter conditions, which will be pushed down to tablescan.
- The rest filter conditions, which will be executed after tablescan.

### TiDB side

We will decide which filter conditions will be pushed down to tablescan in TiDB planner. We should consider the following factors:
- Only the filter conditions with high selectivity should be pushed down.
- The filter conditions which contain heavy cost functions should not be pushed down.
- Filter conditions that apply to the same column are either pushed down or not pushed down at all.
- The pushed down filter conditions should not contain too many columns.

The algorithm is:
```
/* Detailed source-code truncated for AI context efficiency. */
```

Since we need statistics to calculate the selectivity of the filter conditions, so this algorithm should be executed in postOptimize phase.

Obviously, beacuse the selectivity of the filter conditions is accurate, and the algorithm is not optimal, we can not guarantee that the pushed down filter conditions are the best. In order to patch a workaround for performance degradation, we will add a variable `tidb_enable_late_materialization`, and `set @@tidb_enable_late_materialization=OFF` to disable optimizer to push down filter conditions.

Therefore, it should work like this:

```
/* Detailed source-code truncated for AI context efficiency. */
```

### TiFlash side

The Process of execution of tablescan should be changed to:
1. read <handle, delmark, version>, and do MVCC filtering. Return an MVCC bitmap, which represents the availability of each tuple.
2. read columns which pushed down filter conditions need, and do filtering, return a filtering bitmap.
3. do a bitwise AND operation on the two bitmaps, and return the final bitmap.
4. With final bitmap, just read the necessary data packs of the rest columns which are needed.
5. Apply the final bitmap to the data packs, and return the final result.



## Impact & Risks

There is no optimal algorithm to determine which filter conditions should be pushed down. We can only try to implement a good solution. So, the performance of some AP queries may degrade.
We will try to make sure most AP queries would not go with performance degradation. And we can add add a variable `tidb_enable_late_materialization` to decide whether to enable late materialization or not.

---

### Design 2022 12 07 Keyspace (`docs/design/2022-12-07-keyspace.md`)

# Proposal: Keyspace
* Authors: [ystaticy](https://github.com/ystaticy), [iosmanthus](https://github.com/iosmanthus), [AmoebaProtozoa](https://github.com/AmoebaProtozoa),[zeminzhou](https://github.com/zeminzhou)


## Motivation

We aim to store data from multiple applications in a TiKV cluster. For instance, in a multi tenant scenario, a common solution is to add a prefix to the key to differentiate the data of various applications. Therefore, we introduce a new concept referred to as `Keyspace` to describe the logical isolation among different business scenarios within a TiKV cluster.

## Architecture

In this section, we will outline the architecture when utilizing keyspaces.



### PD

PD is responsible for managing `Keyspace` metadata. It provides HTTP and RPC interfaces to create, load, and modify `Keyspace` metadata. All other components retrieve the keyspace metadata from PD.

### TiDB

After the keyspace is created on PD, it can be configured on multiple TiDB instances, forming a TiDB cluster for that keyspace. However, a TiDB instance can serve only one keyspace at a specific moment, unless it is restarted and configured to use a different keyspace.

### Client-go

In TiDB, client-go utilizes [codec V2](https://github.com/tikv/rfcs/blob/master/text/0069-api-v2.md#new-key-value-codec) to add a keyspace prefix when the keyspace is set. A client configured with a keyspace can only read and write data from the specified keyspace.

### TiKV

In TiKV, different keyspaces are isolated by different data key prefixes.

### TiFlash

In TiFlash, requests carry the keyspace prefix, and the data structures and storage paths are isolated by the keyspace ID.

## Usage

To use TiDB with `Keyspace`, the following configuration is required:
1. TiKV needs to [enable API V2](https://github.com/tikv/rfcs/blob/master/text/0069-api-v2.md#tikv-server).
2. The TiDB configuration should set `keyspace-name` to specify which keyspace is currently served by the TiDB instance.
3. BR, Lightning, Dumpling, and TiCDC specify the keyspace by setting `keyspace-name` on the command line.

## Implementation

### PD

#### PD Functionality

PD provides an HTTP interface and an RPC interface to create, load, change the state, and configure keyspace metadata, and is responsible for interacting with the keyspace metadata store. Users can request the `create keyspace` interface by specifying the keyspace name, which generates the keyspace metadata.
* [PD HTTP interface](https://github.com/tikv/pd/blob/098b802fcda75b5ae0527b0b50b95ba8b31403cf/server/apiv2/handlers/keyspace.go)
* [PD RPC interface](https://github.com/tikv/pd/blob/b95dddaa7e9decaad7c24becb401c67cea83fd3a/server/keyspace_service.go)

#### Keyspace Name

**Keyspace Name** is specified by the creator during the creation of the keyspace, and once the keyspace is created, the keyspace name cannot be bound to another keyspace.

#### Keyspace ID Allocation

**Keyspace ID** is allocated by PD createKeyspace interface. The keyspace id is assigned by auto-incrementing the id, so keyspace ids are not re-assigned. The max keyspace id is 16777216, no new keyspaces can be created after the maximum keyspace id has been reached.

#### Keyspace Metadata

[**Keyspace Meta**](https://github.com/pingcap/kvproto/blob/d9297553c9009f569eaf4350f68a908f7811ee55/proto/keyspacepb.proto#L26C1-L33C2) is built when a keyspace is created, and the keyspace management interface operates on this metadata. The keyspace state in the metadata changes according to the keyspace state machine. The state change logic is as follows:


### TiDB

#### Using API V2 and etcd namespace to isolate TiKV data and etcd path by Keyspace.

1. Configure the keyspace name by setting `keyspace-name` in the configuration file. 
   * When the TiDB server starts, it will open a TiKV driver. The driver has a TxnKV client object called `tikv.KVStore`. If `keyspace-name` is set, it will use `tikv.KVStore` via API V2 to access TiKV.
2. The etcd path should have a different prefix based on the etcd namespace. 
   * An etcd client is created during domain initialization. If `keyspace-name` is set, it will add an etcd namespace when creating the etcd client. 
   * The format of the etcd namespace is `/keyspaces/tidb/$keyspaceId`.

#### TiDB BR

If "keyspace-name" is set when executing the BR command, it supports restore and backup for the specified keyspace data. The BR task will parse the old keyspace prefix from the source data, and get target keyspace from KVStore.codec. The old keyspace prefix and new keyspace prefix are used to update the old key prefix and new key prefix of rewrite rules. Restore checksum also requires the old and new keyspace prefixes. The backup task needs to add a target keyspace prefix when building ranges in `BackupRequest` to scan for the data of the specified keyspace in TiKV.

#### TiDB Lightning

If `keyspace-name` is set when executing the `Lightning` command, it will encode the key to add the keyspace prefix before appending rows to the SST file, and decode the key before recording conflict data into the TiDB table.

#### TiCDC

If `keyspace-name` is set when creating a changefeed to the TiCDC server, the server will only capture the table data within that keyspace for the changefeed. For changefeeds configured with a keyspace, the TiCDC server will encode the table range with the keyspace prefix to subscribe to the table data from the TiKV server, and it will also decode the keyspace prefix from the key received from the TiKV server to retrieve the table data. If `keyspace-name` is not set, the TiCDC server will not capture the table data from [API V2](https://github.com/tikv/rfcs/blob/master/text/0069-api-v2.md#tikv-server).

#### TiDB GC

##### Concepts of GC management type:

1. Global GC:
   - Represents the previous default GC logic. There is a TiDB GC Worker that is responsible for calculating the global GC safe point for the entire cluster.
   - The default GC management type for a keyspace is global GC.
2. Keyspace Level GC:
   - Indicates that the keyspace will advance its own GC safe point.
   - `Keyspace` GC related data includes: minimum start timestamp, GC safe point, and service safe point, which are stored in the dedicated path of each keyspace in PD.

Previously, there was only one GCWorker leader for GC in the entire PD and TiKV cluster. After supporting keyspace level GC, the default GC management type for a keyspace is global GC. Alternatively, you can specify the GC management type as global_gc or keyspace_level_gc via the keyspace meta's configuration `gc_management_type`.

* When a specified keyspace uses global GC, this keyspace will have its own GCWorker leader. However, this GCWorker leader is not responsible for calculating the GC safe point or resolving locks. This keyspace will rely on the GC safe point produced by the GCWorker leader that is not configured with a keyspace in the cluster for GC, and will use its own keyspace specific GCWorker leader for deleting ranges.

* When a specified keyspace uses keyspace level GC, this keyspace will have its own GCWorker leader that computes its own GC safe point, resolves locks, and deletes ranges. The keyspace level safe point information is stored in PD, isolated by the keyspace prefix, and only GC the data within its keyspace range, without affecting other keyspaces.

#### Observability

Keyspace observability is essential for understanding and managing performance effectively.

1. Metric Filtering: TiDB metrics can be filtered by the `keyspace_id` label for precise monitoring.
2. Grafana Setup: Add a query box for `keyspace_id` in Grafana dashboards to visualize data specific to each keyspace.
3. Log Enhancement: Include the `keyspace_name` label in TiDB logs for better tracking and context in log analysis.

### TiKV

`Keyspace` can only be used when TiKV [enabled API V2](https://github.com/tikv/rfcs/blob/master/text/0069-api-v2.md#tikv-server).
For more details about keyspace in TiKV, please refer to the [API V2 RFC](https://github.com/tikv/rfcs/blob/master/text/0069-api-v2.md).

#### Keyspace Key encoding:

We use [`Keyspace` key encoding](https://github.com/tikv/rfcs/blob/master/text/0069-api-v2.md#key-encoding) as the key prefix for keyspace to isolate data between different keyspaces. When TiDB enables `Keyspace`, it operates in `TxnKV` mode. The prefix 'x' indicates the `TxnKV` key mode, followed directly by a 3-byte keyspace ID identifier, and then comes the user key.

#### Client-go

Client-go also supports API V2 and `Keyspace`. This will make all the codec logic transparent to applications. We currently maintain these implementations in tikv/client-go/api-v2. The new version of client-go unifies all the codec logic by introducing a new interface called `Codec`:
```
/* Detailed source-code truncated for AI context efficiency. */
```

This interface will encode the key-related request right before it is sent to the TiKV/TiFlash/PD server. It will decode the response immediately after it is received. This design aims to be neat enough to make encoding and decoding transparent to applications.

Typically, [`codecV2`](https://github.com/tikv/client-go/blob/239ac1b2b7fc67921b00e1d51d47f3716c2c2f0c/internal/apicodec/codec_v2.go#L41) implements the `Codec` interface and the codec logic related to `Keyspace`.
The encoding logic is trivial, but the decoding logic is somewhat complicated.
To achieve transparency, `codecV2` will map the region range to `[0, +inf)`, if the range is not overlapped with the current keyspace, it will return an error.
For instance, if the keyspace is `[x001, x002)`, then the region range `[x003, x004)` is invalid, and `[x000, x002)` is mapped to `[0, +inf)`.

client-go provides a function called `NewCodecPDClientWithKeyspace` to create a PD client with `Keyspace` support. It tries to fetch the keyspace id with the given keyspace name from PD, and create a `codecV2` with the keyspace id.
You could get the `Codec` within the `CodecPDClient` and use it to construct a TiKV gRPC client.

#### Coprocessor

TiKV Coprocessor uses the range specified in the request to determine which range to scan. After scanning, it transforms the key/value pairs into a columnar format and begins executing the DAG request. However, the original code cannot recognize the new format of the key. Therefore, the `RangeScanner` should be modified to support the new format of the key by ignoring the first 4 bytes if the request uses API V2.

### TiFlash

TiFlash is a columnar storage engine that acts as a coprocessor for TiKV. When TiDB is configured with a keyspace, TiFlash requests also include the keyspace prefix. TiFlash's data structures and storage paths are isolated by the keyspace ID.

#### Storage

Without a keyspace, TiFlash stores each table's columnar/schema data in a separate directory identified by the table ID. However, in a keyspace scenario, multiple keyspaces may have the same table ID, which means that the table ID alone cannot uniquely identify a table.

The storage path structure of TiFlash will be as follows:
```
.
├── data
│   ├── ks_1_t_92
│   │   ├── data
├── metadata
│   ├── ks_1_db_1
│   │   └── ks_1_t_92.sql
│   ├── ks_1_db_2
│   └── system
```

Each table directory will be identified by both the keyspace ID and the table ID.

#### Cache

When decoding row data into a columnar format, TiFlash ignores the keyspace prefix. Table-related cache structures will be refactored into a map of `<KeyspaceID, TableID> -> <ValueType>` instead of `<TableID> -> <ValueType>`.

#### Schema sync

When syncing the schema from TiDB to TiFlash, TiFlash adds the keyspace prefix to requests sent to TiKV for specific table schemas.

#### Request handling

TiFlash requests carry the keyspace prefix. TiFlash parses `<KeyspaceID, TableID>` from the encoded key range. It then uses this information to route requests to the relevant table storage.

### Placement Rules

Placement rules are isolated by keyspace. TiDB must name placement rules using the keyspace prefix, such as `keyspace-<keyspace_id>-xxxx`. Additionally, the key range of some rules must be encoded.

---

### Design 2023 03 17 Non Prepared Plan Cache (`docs/design/2023-03-17-non-prepared-plan-cache.md`)

# Proposal: Non-Prepared Plan Cache

* Author: [qw4990](https://github.com/qw4990)
* Tracking issue: https://github.com/pingcap/tidb/issues/36598

## Background
TP queries can get lots of performance benefits from Plan Cache, but the current [TiDB Plan Cache](https://docs.pingcap.com/tidb/dev/sql-prepared-plan-cache) can only support Prepare/Execute Statements. Most of our users are still using general(non-prepared) queries to access TiDB instead of Prepare/Execute. So if Plan Cache can support general queries, these users can gain some performance benefits as well.
Some other mature Databases have already supported this feature: 1) [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/19/tgsql/improving-rwp-cursor-sharing.html) and 2) [OceanBase](https://www.oceanbase.com/docs/common-oceanbase-database-cn-10000000001576952).

## Overview


As the left part of the above diagram show, Plan Cache can be split into 2 parts logically:
1. The Frontend: this part is used to deal with different protocols (binary or text), and prepare all arguments required by the backend (SQL, AST, Normalized Parameters, etc.)
2. The Backend: find an available cached Plan from the cache or generate a new Plan for the input arguments

And more specifically, the backend can be abstracted as a function `GetPlan(SQL, AST, Params)`, and it works as below:
1. Look up the Plan Cache to find a cached plan for the input SQL;
2. If it can find an available plan, fill this plan with the input parameters, and return the plan; (cache hit)
3. If not, pass `(AST, Params)` to the optimizer to generate a new plan, return this plan, and put this plan into the cache; (cache miss)

To support Non-Prepared Plan Cache, logically we can re-use the whole backend, and just update the frontend a little:
1. Check whether the current query is supported by Non-Prepared Plan Cache;
2. If not, just fall back to the normal optimization code path;
3. If yes:
   1. Normalize this query and prepare all arguments `(SQL, AST, Params)`;
   2. Pass these arguments to the Plan Cache backend to get a Plan;

## Details
### Scope & Limitations
Currently, TiDB only caches one plan for a parameterized query. 

For example, the queries `SELECT * FROM t WHERE a < 1` and `SELECT * FROM t WHERE a < 100000` share the same parameterized form, `SELECT * FROM t WHERE a < ?`, and thus share the same plan.

Due to the preceding risks and the fact that the execution plan cache only provides significant benefits for simple queries (if a query is complex and takes a long time to execute, using the execution plan cache might not be very helpful), TiDB has strict restrictions on the scope of non-prepared plan cache. 
The restrictions are as follows:

1. Queries or plans that are not supported by the Prepared plan cache are also not supported by the non-prepared plan cache.
2. Currently, only point get or range queries on a single table that contain `Scan`, `Selection`, or `Projection` operators are supported, such as `SELECT * FROM t WHERE a < 10 AND b in (1, 2)`.
3. Queries that contain complex operators such as `Agg`, `Limit`, `Window`, or `Sort` are not supported.
4. Queries that contain non-range query conditions are not supported, such as:
1. `LIKE` is not supported, such as `c LIKE 'c%'`.
2. `+` operation is not supported, such as `a+1 < 2`.
5. Queries that filter on columns of `JSON`, `ENUM`, `SET`, or `BIT` type are not supported, such as `SELECT * FROM t WHERE json_col = '{}'`.
6. Queries that filter on `NULL` values are not supported, such as `SELECT * FROM t WHERE a is NULL`.
7. Queries with more than 50 parameters after parameterization are not supported, such as `SELECT * FROM t WHERE a in (1, 2, 3, ... 51)`.
8. Queries that access partitioned tables, virtual columns, temporary tables, views, or memory tables are not supported, such as `SELECT * FROM INFORMATION_SCHEMA.COLUMNS`, where `COLUMNS` is a TiDB memory table.
9. Queries with hints, subqueries, or locks are not supported.
10. DML statements are not supported.

We'll solve these limitations step by step later on.

### Separated Cache
Prepared Plan Cache and Non-Prepared Plan Cache are totally separated, cached plans in them do not affect each other.

### Cacheable Check
We implement a cacheable checker to check whether a query can be supported by Non-Prepared Plan Cache(cacheable_checker).
If a query is not supported, we can just fall back to the normal optimization code path.

### Parameterization
Plan Cache uses parameterized SQL as the key, so we need a way that can parameterize any SQL fast.
For example, parameterize `select * from t where a<10` to `select * from t where a<?`;
Currently, we implement this on `AST`:
1. First, we iterate the `AST` and replace all constant values with `?`;
2. Then, we call `AST.Restore` to get the parameterized SQL;

### New Variables
Introduce 2 variables below to control Non-Prepared Plan Cache behaviors:
- `tidb_enable_non_prepared_plan_cache`: indicate whether to enable this feature;
- `tidb_non_prepared_plan_cache_size`: indicate the cache size;

---

### Design 2023 04 11 Dist Task (`docs/design/2023-04-11-dist-task.md`)

# Proposal: Unified Distributed Parallel Execution Framework

- Author: [Benjamin](https://github.com/Benjamin2037)
- Tracking Issue: https://github.com/pingcap/tidb/issues/41495

## Background and Benefits

TiDB is a distributed database that provides high scalability, availability, and performance for database service. This proposal introduces a unified distributed parallel execution framework to support all backend tasks, such as DDL, data import, TTL, analyze and backup&restore, in a distributed manner.
The framework may bring three outstanding benefits to TiDB users:
1. The distributed execution model provides better scalability and improved runtime performance for backend tasks.
2. It optimizes resource utilization within the TiDB cluster for backend tasks.
3. The framework enables resource management by treating backend tasks as a whole and scheduling different task executions according to user expectations.

## Goal and Non-goal

In this section, we define the goals and non-goals for the Phase I of the framework. Future versions will be described in the "Future Work" section.

### Goal

The Phase I of the framework aims to:
1. Build the fundamental component of the framework.
2. Support limited scenarios of backend tasks, including:
   1. Partition table create index in a distributed way for DDL.
   2. Maybe import table task execution in a distributed way for the Import service.
   
### Non-goal

The Phase I of the framework does not aim to:
1. Support query execution. For query distributed execution support, please see the TiFlash documentation.
2. Provide sophisticated high availability (HA) capability, which will be improved in future phase.
3. Support task runtime status, such as task execution progress, which will be provided in later phase.
4. Support TTL, auto-analyze, and BR, which will be supported in later phase.

## Architecture

This section we will describe the Architecture of the framework.


The architecture diagram shows the key modules required for the framework to handle incoming backend tasks in a distributed manner with high performance and good HA capability. These modules are:

1. Global task queue: used to store the backend tasks' runtime information.
2. Global subtask queue: used to store TiDB node-level subtask runtime information. It is split from the task handle data and is a TiDB node-level executor unit.
3. Dispatcher: task runtime owner. It generates planner for tasks, monitors task runtime status, and pushes tasks into the next stage of execution.
4. Scheduler: TiDB node-level subtask runtime owner. It picks up one subtask and runs it on one TiDB node in parallel ways, sets subtask status, monitors task status, and determines what to do next.
5. Subtask executor: the real worker that executes a slice of a subtask and returns the result and error, if any, back to the scheduler.
6. Resource pool: For the dispatcher, scheduler, and executor, we limit them into a pool according to class. a global resource manager take care of limit the framework runtime resource usage quantity.

## Detail Design

This section introduces the data structures and interfaces that define the detail design of the framework.

### System Variable

The system variable `tidb_enable_dist_task` is used to enable/disable the framework.

```sql
mysql> set global tidb_enable_dist_task = ON|OFF;
```

### Data Structure

In implementation, the following two tables are used to represent the global task queue and global subtask queue:


| Name              | Type                                           | Memo |
|-------------------|------------------------------------------------|------|
| id                | BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY |      | 
| task_key          | VARCHAR(256) NOT NULL                          |      |
| type              | VARCHAR(256) NOT NULL                          |      |
| dispatcher_id     | VARCHAR(256)                                   |      |
| state             | VARCHAR(64) NOT NULL                           |      |
| start_time        | TIMESTAMP                                      |      |
| state_update_time | TIMESTAMP                                      |      |
| meta              | LONGBLOB                                       |      |
| concurrency       | INT(11)                                        |      |
| step              | INT(11)                                        |      |

| Name              | Type                                       | Memo |
|-------------------|--------------------------------------------|------|
| id                | bigint not null auto_increment primary key |      |
| namespace         | varchar(256)                               |      |
| task_key          | varchar(256)                               |      | 
| ddl_physical_tid  | bigint(20)                                 |      |
| type              | int                                        |      |  
| exec_id           | varchar(256)                               |      |
| exec_expired      | timestamp                                  |      |
| state             | varchar(64) not null                       |      |
| checkpoint        | longblob not null                          |      | 
| start_time        | bigint                                     |      |        
| state_update_time | bigint                                     |      | 
| meta              | longblob                                   |      |                                            |      |

### Interface

Dispatcher
```go
// Dispatch defines the interface for operations inside a dispatcher.
type Dispatch interface {
	// Start enables dispatching and monitoring mechanisms.
	Start()
	// GetAllSchedulerIDs gets handles the task's all available instances.
	GetAllSchedulerIDs(ctx context.Context, gTaskID int64) ([]string, error)
	// Stop stops the dispatcher.
	Stop()
}
```
Scheduler
```go
// InternalScheduler defines the interface of an internal scheduler.
type InternalScheduler interface {
	Start()
	Stop()
	Run(context.Context, *proto.Task) error
	Rollback(context.Context, *proto.Task) error
}

// Scheduler defines the interface of a scheduler.
// User should implement this interface to define their own scheduler.
type Scheduler interface {
	InitSubtaskExecEnv(context.Context) error
	SplitSubtask(subtask []byte) []proto.MinimalTask
	CleanupSubtaskExecEnv(context.Context) error
	Rollback(context.Context) error
}
```

## Usage

The phase I of the unified distributed parallel execution framework is currently planned as an experimental feature. This feature is designed to support the execution of `Create index` or `Add index` tasks in a distributed manner.

To enable distributed `Add index` for DDL tasks, the following system variables and config parameters may be related:

**System Variables**:

* [tidb_ddl_reorg_worker_cnt](https://docs.pingcap.com/tidb/stable/system-variables#tidb_ddl_reorg_worker_cnt)
* [tidb_ddl_reorg_priority](https://docs.pingcap.com/tidb/stable/system-variables#tidb_ddl_reorg_priority)
* [tidb_ddl_error_count_limit](https://docs.pingcap.com/tidb/stable/system-variables#tidb_ddl_error_count_limit)
* [tidb_ddl_reorg_batch_size](https://docs.pingcap.com/tidb/stable/system-variables#tidb_ddl_reorg_batch_size)

**Fast DDL Path:**
* [tidb_ddl_enable_fast_reorg](https://docs.pingcap.com/tidb/stable/system-variables#tidb_ddl_enable_fast_reorg-new-in-v630)
* [tidb_ddl_disk_quota](https://docs.pingcap.com/tidb/stable/system-variables#tidb_ddl_disk_quota-new-in-v630)

**Config parameter:**
* [temp-dir](https://docs.pingcap.com/tidb/stable/tidb-configuration-file#temp-dir-new-in-v630)

## Future Work
1. Stabilize the framework capability and improve the user experience to make it more user-friendly and efficient for handling various tasks.
2. Expand the supported backend tasks to include more types of operations such as `Load Data`, `TTL`, `Auto-Analyze`, `Backup`, `Restore`, and more.
3. Implement the ability to pause and resume tasks, which would allow users to easily control and manage the execution of tasks based on their requirements and priorities.
4. Introduce a resource manager to provide better control and monitoring of the backend tasks' resource utilization, including CPU, memory usage. This will ensure that tasks are executed in a more optimized and efficient way.

---

--- METRICS ---
- Files Extracted: 101
- Estimated Token Budget: ~268574 tokens
- Canonical Reference: https://codewiki.google/github.com/pingcap/TiDB
