Skip to content

Conversation

@ti-chi-bot
Copy link
Member

This is an automated cherry-pick of #63961

What problem does this PR solve?

Issue Number: close #57090

Problem Summary:

For the following case, the explain analyze output shows unInitialized for that expression index(idx_expr), which is confusing.

set @@global.tidb_enable_auto_analyze = 'OFF';
drop table if exists t1;
-- This is required to make sure the expression collation is same when creating table and using it in select stmt.
set names utf8mb4;
create table t1(id int, c1 int, c2 varchar(100), primary key(id), key idx_expr ((cast(json_unquote(json_extract(`c2`, _utf8mb4'$.location_id')) as char(255)) collate utf8mb4_bin)));
insert into t1 values(1, 1, '{"foo": "bar"}'), (2, 1, '{"foo": "bar"}');
analyze table t1 all columns;
-- You may need to run multiple times to trigger load stats
explain analyze select /*+ use_index(t1, idx_expr) */ * from t1 where (cast(json_unquote(json_extract(`c2`, _utf8mb4'$.location_id')) as char(255)) collate utf8mb4_bin) > '100'  and c2 > 'abc';

TiDB [email protected]:test> explain analyze select /*+ use_index(t1, idx_expr) */ * from t1 where (cast(json_unquote(json_extract(`c2`, _utf8mb4'$.location_id')) as char(255)) collate utf8mb4_bin) > '100'  and c2 > 'abc';
+-----------------------------+---------+---------+-----------+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------+-----------+------+
| id                          | estRows | actRows | task      | access object                                                                                                              | execution info                                                                                                                                                                                                                                                                                 | operator info                                                                     | memory    | disk |
+-----------------------------+---------+---------+-----------+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------+-----------+------+
| Projection_4                | 1.00    | 0       | root      |                                                                                                                            | time:631.5µs, open:72.2µs, close:10.5µs, loops:1, RU:0.48, Concurrency:OFF                                                                                                                                                                                                                     | test.t1.id, test.t1.c1, test.t1.c2                                                | 10.1 KB   | N/A  |
| └─IndexLookUp_10            | 1.00    | 0       | root      |                                                                                                                            | time:614.3µs, open:62µs, close:7.71µs, loops:1                                                                                                                                                                                                                                                 |                                                                                   | 182 Bytes | N/A  |
|   ├─IndexRangeScan_7(Build) | 1.00    | 0       | cop[tikv] | table:t1, index:idx_expr(cast(json_unquote(json_extract(`c2`, _utf8mb4'$.location_id')) as char(255)) collate utf8mb4_bin) | time:410.6µs, open:0s, close:0s, loops:1, cop_task: {num: 1, max: 343.8µs, proc_keys: 0, copr_cache_hit_ratio: 0.00, build_task_duration: 20.8µs, max_distsql_concurrency: 1}, fetch_resp_duration: 384.4µs, rpc_info:{Cop:{num_rpc:1, total_time:297.6µs}}, tikv_task:{time:185.4µs, loops:0} | range:("100",+inf], keep order:false, stats:partial[_v$_idx_expr_0:unInitialized] | N/A       | N/A  |
|   └─Selection_9(Probe)      | 1.00    | 0       | cop[tikv] |                                                                                                                            |                                                                                                                                                                                                                                                                                                | gt(test.t1.c2, "abc")                                                             | N/A       | N/A  |
|     └─TableRowIDScan_8      | 1.00    | 0       | cop[tikv] | table:t1                                                                                                                   |                                                                                                                                                                                                                                                                                                | keep order:false, stats:partial[_v$_idx_expr_0:unInitialized]                     | N/A       | N/A  |
+-----------------------------+---------+---------+-----------+----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------+-----------+------+

For expression index idx_expr, there will be both original column stats and index stats when calculating selectivity.

Check the following debug output, you can see the column stats is unInitialized and the index stats is ready. So for expression index, should use index stats and its column stats.

(dlv) p coll.columns[4].Info
("*github.com/pingcap/tidb/pkg/meta/model.ColumnInfo")(0x14038993ce0)
*github.com/pingcap/tidb/pkg/meta/model.ColumnInfo {
	ID: 4,
	Name: github.com/pingcap/tidb/pkg/parser/ast.CIStr {
		O: "_V$_idx_expr_0",
		L: "_v$_idx_expr_0",},
	Offset: 3,
	OriginDefaultValue: interface {} nil,
	OriginDefaultValueBit: []uint8 len: 0, cap: 0, nil,
	DefaultValue: interface {} nil,
	DefaultValueBit: []uint8 len: 0, cap: 0, nil,
	DefaultIsExpr: false,
	GeneratedExprString: "cast(json_unquote(json_extract(`c2`, _utf8mb4'$.location_id')) a...+32 more",
	GeneratedStored: false,
	Dependences: map[string]struct {} [
		"c2": {},
	],
	FieldType: github.com/pingcap/tidb/pkg/parser/types.FieldType {
		tp: 253,
		flag: 8,
		flen: 255,
		decimal: -1,
		charset: "utf8mb4",
		collate: "utf8mb4_bin",
		elems: []string len: 0, cap: 0, nil,
		elemsIsBinaryLit: []bool len: 0, cap: 0, nil,
		array: false,},
	State: StatePublic (5),
	Comment: "",
	Hidden: true,
	ChangeStateInfo: *github.com/pingcap/tidb/pkg/meta/model.ChangeStateInfo nil,
	Version: 2,}
(dlv) p coll.columns[4].StatsLoadedStatus
github.com/pingcap/tidb/pkg/statistics.StatsLoadedStatus {statsInitialized: false, evictedStatus: 0}
(dlv) p coll.indices[1].Info
("*github.com/pingcap/tidb/pkg/meta/model.IndexInfo")(0x140389c0f00)
*github.com/pingcap/tidb/pkg/meta/model.IndexInfo {
	ID: 1,
	Name: github.com/pingcap/tidb/pkg/parser/ast.CIStr {
		O: "idx_expr",
		L: "idx_expr",},
	Table: github.com/pingcap/tidb/pkg/parser/ast.CIStr {O: "", L: ""},
	Columns: []*github.com/pingcap/tidb/pkg/meta/model.IndexColumn len: 1, cap: 1, [
		*(*"github.com/pingcap/tidb/pkg/meta/model.IndexColumn")(0x14038b5c4e0),
	],
	State: StatePublic (5),
	BackfillState: BackfillStateInapplicable (0),
	Comment: "",
	Tp: IndexTypeBtree (1),
	Unique: false,
	Primary: false,
	Invisible: false,
	Global: false,
	MVIndex: false,
	VectorInfo: *github.com/pingcap/tidb/pkg/meta/model.VectorIndexInfo nil,
	InvertedInfo: *github.com/pingcap/tidb/pkg/meta/model.InvertedIndexInfo nil,
	FullTextInfo: *github.com/pingcap/tidb/pkg/meta/model.FullTextIndexInfo nil,}
(dlv) p coll.indices[1].StatsLoadedStatus
github.com/pingcap/tidb/pkg/statistics.StatsLoadedStatus {statsInitialized: true, evictedStatus: 0}

What changed and how does it work?

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test
    • I checked and no code files have been changed.

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

Please refer to Release Notes Language Style Guide to write a quality release note.

None

@ti-chi-bot ti-chi-bot added do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. release-note-none Denotes a PR that doesn't merit a release note. sig/planner SIG: Planner size/S Denotes a PR that changes 10-29 lines, ignoring generated files. type/cherry-pick-for-release-8.5 This PR is cherry-picked to release-8.5 from a source PR. labels Dec 1, 2025
@ti-chi-bot
Copy link
Member Author

@guo-shaoge This PR has conflicts, I have hold it.
Please resolve them or ask others to resolve them, then comment /unhold to remove the hold label.

@ti-chi-bot
Copy link

ti-chi-bot bot commented Dec 1, 2025

@ti-chi-bot: ## If you want to know how to resolve it, please read the guide in TiDB Dev Guide.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the ti-community-infra/tichi repository.

@ti-chi-bot
Copy link

ti-chi-bot bot commented Dec 1, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign hawkingrei for approval. For more information see the Code Review Process.
Please ensure that each of them provides their approval before proceeding.

The full list of commands accepted by this bot can be found here.

Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@ti-chi-bot
Copy link

ti-chi-bot bot commented Dec 1, 2025

@ti-chi-bot: The following tests failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
idc-jenkins-ci-tidb/build 6260717 link true /test build
idc-jenkins-ci-tidb/unit-test 6260717 link true /test unit-test
idc-jenkins-ci-tidb/check_dev 6260717 link true /test check-dev
idc-jenkins-ci-tidb/check_dev_2 6260717 link true /test check-dev2

Full PR test history. Your PR dashboard.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

@ti-chi-bot ti-chi-bot bot added cherry-pick-approved Cherry pick PR approved by release team. and removed do-not-merge/cherry-pick-not-approved labels Dec 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cherry-pick-approved Cherry pick PR approved by release team. do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. release-note-none Denotes a PR that doesn't merit a release note. sig/planner SIG: Planner size/S Denotes a PR that changes 10-29 lines, ignoring generated files. type/cherry-pick-for-release-8.5 This PR is cherry-picked to release-8.5 from a source PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants