Skip to content

planner: recognize order on common handle PK (#66645) - #70460

Open
takaidohigasi wants to merge 1 commit into
pingcap:release-8.5from
takaidohigasi:cherry-pick-66645-to-release-8.5
Open

takaidohigasi wants to merge 1 commit into
pingcap:release-8.5from
takaidohigasi:cherry-pick-66645-to-release-8.5

Conversation

@takaidohigasi

@takaidohigasi takaidohigasi commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

This is a manual cherry-pick of #66645 to release-8.5, replacing the automated cherry-pick #67107 which contains unresolved merge conflict markers in pkg/planner/core/casetest/rule/BUILD.bazel (causing its build / unit-test / check-dev2 CI jobs to fail).

What problem does this PR solve?

Issue Number: close #66644

Problem Summary:

Common handle PKs were not recognized as providing order after the index columns, while integer PKs were. This caused unnecessary TopN/Sort operators for ORDER BY <pk columns> queries on clustered (common handle) tables scanned via a secondary index.

What changed and how does it work?

Manual cherry-pick of #66645 (commit 3032ee1) onto release-8.5.

  • pkg/planner/core/find_best_task.go applies cleanly (no conflicts).
  • The only conflict was in pkg/planner/core/casetest/rule/BUILD.bazel; resolved by adding rule_common_handle_ordering_test.go to srcs and bumping shard_count from 21 to 22 (master is at 23 because it has an extra test file that does not exist on release-8.5).

As in the original PR: matchProperty now builds an effective index column list that includes the common handle PK suffix for non-unique secondary indexes, so ORDER BY on PK columns can be satisfied with keep order:true. The v0 CommonHandleVersion + new collation string handle case is excluded for correctness.

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.

Local verification on this branch:

  • make bazel_prepare (no diff beyond the resolved BUILD.bazel)
  • go test --tags=intest ./pkg/planner/core/casetest/rule/ -run TestCommonHandleIndexOrdering passes (all 10 cases, with failpoints enabled)

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

Summary by CodeRabbit

  • Bug Fixes

    • Improved query ordering for CommonHandle indexes, including multi-column, unique, descending, and mixed-direction indexes.
    • Corrected ordering detection for clustered keys with string, binary, and mixed data types.
    • Added safeguards for legacy collations to prevent incorrect ordering assumptions.
  • Tests

    • Expanded coverage for ordered scans, partial key matches, clustered keys, and sort-plan behavior.

@ti-chi-bot ti-chi-bot Bot added release-note-none Denotes a PR that doesn't merit a release note. do-not-merge/cherry-pick-not-approved contribution This PR is from a community contributor. size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. sig/planner SIG: Planner needs-ok-to-test Indicates a PR created by contributors and need ORG member send '/ok-to-test' to start testing. labels Aug 12, 2026
@ti-chi-bot

ti-chi-bot Bot commented Aug 12, 2026

Copy link
Copy Markdown

Hi @takaidohigasi. Thanks for your PR.

I'm waiting for a pingcap member to verify that this patch is reasonable to test. If it is, they should reply with /ok-to-test on its own line. Until that is done, I will not automatically test new commits in this PR, but the usual testing commands by org members will still work. Regular contributors should join the org to skip this step.

Once the patch is verified, the new status will be reflected by the ok-to-test label.

I understand the commands that are listed here.

Details

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.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The planner now recognizes ordering through eligible CommonHandle indexes by extending index columns with missing handle columns. It excludes unsafe v0 new-collation string handles. New Cascades tests cover secondary and clustered index ordering cases.

Changes

CommonHandle ordering

Layer / File(s) Summary
CommonHandle ordering matching
pkg/planner/core/find_best_task.go
matchProperty now uses effective CommonHandle columns and lengths for prefix and order checks. It skips extension for v0 handles with non-binary string columns under new collation.
Secondary-index ordering tests
pkg/planner/core/casetest/rule/rule_common_handle_ordering_test.go, pkg/planner/core/casetest/rule/BUILD.bazel
Tests cover overlapping and multi-column indexes, unique-index scans, descending order, and mixed directions. The Bazel target includes the test and uses 22 shards.
Clustered-key ordering tests
pkg/planner/core/casetest/rule/rule_common_handle_ordering_test.go
Tests cover prefixed clustered keys and clustered primary keys using varchar, varbinary, and mixed int/varchar columns.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

Suggested labels: type/cherry-pick-for-release-8.5

Suggested reviewers: ti-chi-bot

Poem

I’m a rabbit in the planner lane,
Sorting keys now hop in order again.
Varchar, binary, mixed columns too,
Keep-order scans know what to do.
Tests stamp softly: “green!” 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the planner change for recognizing order on common-handle primary keys.
Description check ✅ Passed The description includes the issue, problem, implementation, testing, side effects, documentation, and release-note sections.
Linked Issues check ✅ Passed The changes address issue #66644 by recognizing common-handle primary-key suffix ordering and adding coverage for the behavior.
Out of Scope Changes check ✅ Passed The implementation, tests, and BUILD.bazel update are directly related to the linked issue and cherry-pick objective.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

Error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions
The command is terminated due to an error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@takaidohigasi

Copy link
Copy Markdown
Contributor Author

Local verification results on this branch (macOS arm64, worktree of latest release-8.5):

Unit test — passed ✅

$ make failpoint-enable
$ go test --tags=intest ./pkg/planner/core/casetest/rule/ -run TestCommonHandleIndexOrdering -v
=== RUN   TestCommonHandleIndexOrdering
=== RUN   TestCommonHandleIndexOrdering/off
--- PASS: TestCommonHandleIndexOrdering (1.21s)
    --- PASS: TestCommonHandleIndexOrdering/off (1.21s)
PASS
ok      github.com/pingcap/tidb/pkg/planner/core/casetest/rule 4.707s
$ make failpoint-disable

All 10 cases in TestCommonHandleIndexOrdering pass on release-8.5 (only the non-cascades mode exists on this branch, so RunTestUnderCascades runs the off subtest).

Bazel metadata — clean

make bazel_prepare produces no diff beyond the resolved BUILD.bazel (srcs + shard_count = 22).

A full local bazel build --config=ci //... --//build:with_nogo_flag=true --//build:with_rbe_flag=true is still in progress; I will follow up with the result.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
pkg/planner/core/casetest/rule/rule_common_handle_ordering_test.go (1)

38-301: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a regression case for hasV0NewCollationStringHandle.

The current cases use DDL-created tables with CommonHandleVersion == 1. Add a focused case with CommonHandleVersion == 0, new collation enabled, a non-binary string primary key, an IN predicate, and ORDER BY on the handle. Assert correct row ordering and that the plan does not use PropMatchedNeedMergeSort.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/planner/core/casetest/rule/rule_common_handle_ordering_test.go` around
lines 38 - 301, Add a focused regression scenario within
TestCommonHandleIndexOrdering using CommonHandleVersion == 0 with new collation
enabled, a non-binary string clustered primary key, an IN predicate, and ORDER
BY on the primary-key handle. Assert the returned rows are correctly ordered and
verify the EXPLAIN plan does not contain PropMatchedNeedMergeSort, reusing the
test’s existing setup and assertion helpers.

Source: Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/planner/core/casetest/rule/rule_common_handle_ordering_test.go`:
- Around line 70-73: Update every positive ordering assertion in the test cases,
including the blocks around explainHas checks for “keep order:true” at the
referenced cases, to also assert that explainHas(rows, "Sort") is false.
Preserve the existing TopN rejection and apply the same Sort check consistently
to all positive ordering cases.

---

Nitpick comments:
In `@pkg/planner/core/casetest/rule/rule_common_handle_ordering_test.go`:
- Around line 38-301: Add a focused regression scenario within
TestCommonHandleIndexOrdering using CommonHandleVersion == 0 with new collation
enabled, a non-binary string clustered primary key, an IN predicate, and ORDER
BY on the primary-key handle. Assert the returned rows are correctly ordered and
verify the EXPLAIN plan does not contain PropMatchedNeedMergeSort, reusing the
test’s existing setup and assertion helpers.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fbfba9f7-d140-4b6a-b3af-0008cf64de8c

📥 Commits

Reviewing files that changed from the base of the PR and between f5fa13c and 33d962c.

📒 Files selected for processing (3)
  • pkg/planner/core/casetest/rule/BUILD.bazel
  • pkg/planner/core/casetest/rule/rule_common_handle_ordering_test.go
  • pkg/planner/core/find_best_task.go

Comment on lines +70 to +73
require.True(t, explainHas(rows, "keep order:true"),
"case 1: expected keep order:true for basic CommonHandle ordering")
require.False(t, explainHas(rows, "TopN"),
"case 1: unexpected TopN sort")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Check for Sort in the positive plan assertions.

The objective requires removal of both TopN and Sort. These assertions only reject TopN, so a regression to Sort passes the test.

Proposed test change
- require.False(t, explainHas(rows, "TopN"),
+ require.False(t, explainHas(rows, "TopN") || explainHas(rows, "Sort"),

Apply the same check to every positive ordering case.

Also applies to: 91-94, 111-114, 144-147, 225-228, 257-260, 289-292

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/planner/core/casetest/rule/rule_common_handle_ordering_test.go` around
lines 70 - 73, Update every positive ordering assertion in the test cases,
including the blocks around explainHas checks for “keep order:true” at the
referenced cases, to also assert that explainHas(rows, "Sort") is false.
Preserve the existing TopN rejection and apply the same Sort check consistently
to all positive ordering cases.

@takaidohigasi

Copy link
Copy Markdown
Contributor Author

Follow-up: the full local bazel build also passed ✅

$ bazel build --config=ci //... --//build:with_nogo_flag=true --//build:with_rbe_flag=true
INFO: Found 1257 targets...
INFO: Elapsed time: 3932.397s, Critical Path: 611.59s
INFO: 26684 processes: 1539 internal, 25145 darwin-sandbox.
INFO: Build completed successfully, 26684 total actions

All local verification is now complete: bazel build (with nogo), make bazel_prepare (no diff), and TestCommonHandleIndexOrdering (all cases pass).

@takaidohigasi

Copy link
Copy Markdown
Contributor Author

I am glad if we can get ok-to-test on it

@takaidohigasi

Copy link
Copy Markdown
Contributor Author

@terry1purcell would you please check for this?

@takaidohigasi

Copy link
Copy Markdown
Contributor Author

@qw4990 sorry for the mention.

this is originally merged to master branch, but change for 8.5 is stopped because bazel config conflict did not resolved.

would you give us ok-to-test label on this PR if you are OK?

@terry1purcell

Copy link
Copy Markdown
Contributor

/ok-to-test

@ti-chi-bot ti-chi-bot Bot added ok-to-test Indicates a PR is ready to be tested. and removed needs-ok-to-test Indicates a PR created by contributors and need ORG member send '/ok-to-test' to start testing. labels Aug 13, 2026
@codecov

codecov Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.48780% with 8 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (release-8.5@f5fa13c). Learn more about missing BASE report.

Additional details and impacted files
@@               Coverage Diff                @@
##             release-8.5     #70460   +/-   ##
================================================
  Coverage               ?   55.1154%           
================================================
  Files                  ?       1852           
  Lines                  ?     667027           
  Branches               ?          0           
================================================
  Hits                   ?     367635           
  Misses                 ?     271996           
  Partials               ?      27396           
Flag Coverage Δ
integration 38.1837% <80.4878%> (?)
unit 65.0953% <80.4878%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
dumpling 55.3108% <0.0000%> (?)
parser ∅ <0.0000%> (?)
br 54.8106% <0.0000%> (?)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@takaidohigasi

takaidohigasi commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor Author

test setup failed.

  [tikv:9001]PD server timeout
    ...
    session.BootstrapSession
    realtikvtest.CreateMockStoreAndDomainAndSetup

tests in //tests/realtikvtest/statisticstest:statisticstest_test,
TestNewCollationStatsWithPrefixIndex / TestBlockMergeFMSketch / TestAsyncMergeFMSketch /
TestNoNeedIndexStatsLoading

this is not related to this PR change.

[2026/08/13 15:51:53.756 +00:00] [WARN] [client.go:252] ["[pd] request failed with a non-200 status"] [caller-id=pd-http-client] [name=GetMinResolvedTSByStoresIDs] [uri=/pd/api/v1/min-resolved-ts] [method=GET] [target-url=] [source=tikv-driver] [url=http://127.0.0.1:2379/pd/api/v1/min-resolved-ts] [status="500 Internal Server Error"] [body="\"[PD:cluster:ErrNotBootstrapped]TiKV cluster not bootstrapped, please start TiKV first\""]
[2026/08/13 15:51:53.757 +00:00] [INFO] [store_cache.go:1145] ["refresh full store list failed"] [error="type:NOT_BOOTSTRAPPED message:\"cluster is not bootstrapped\" "] [errorVerbose="type:NOT_BOOTSTRAPPED message:\"cluster is not bootstrapped\" \ngithub.com/tikv/pd/client.(*client).respForErr\n\texternal/com_github_tikv_pd_client/client.go:1579\ngithub.com/tikv/pd/client.(*client).GetAllStores\n\texternal/com_github_tikv_pd_client/client.go:1207\ngithub.com/tikv/client-go/v2/internal/locate.(*storeCacheImpl).fetchAllStores\n\texternal/com_github_tikv_client_go_v2/internal/locate/store_cache.go:128\ngithub.com/tikv/client-go/v2/internal/locate.(*storeCacheUpdater).tick\n\texternal/com_github_tikv_client_go_v2/internal/locate/store_cache.go:1143\ngithub.com/tikv/client-go/v2/internal/locate.(*bgRunner).schedule.func1\n\texternal/com_github_tikv_client_go_v2/internal/locate/region_cache.go:630\nruntime.goexit\n\tsrc/runtime/asm_amd64.s:1693\ngithub.com/tikv/pd/client.(*client).respForErr\n\texternal/com_github_tikv_pd_client/client.go:1579\ngithub.com/tikv/pd/client.(*client).GetAllStores\n\texternal/com_github_tikv_pd_client/client.go:1207\ngithub.com/tikv/client-go/v2/internal/locate.(*storeCacheImpl).fetchAllStores\n\texternal/com_github_tikv_client_go_v2/internal/locate/store_cache.go:128\ngithub.com/tikv/client-go/v2/internal/locate.(*storeCacheUpdater).tick\n\texternal/com_github_tikv_client_go_v2/internal/locate/store_cache.go:1143\ngithub.com/tikv/client-go/v2/internal/locate.(*bgRunner).schedule.func1\n\texternal/com_github_tikv_client_go_v2/internal/locate/region_cache.go:630\nruntime.goexit\n\tsrc/runtime/asm_amd64.s:1693"]
[2026/08/13 15:51:53.757 +00:00] [WARN] [client.go:252] ["[pd] request failed with a non-200 status"] [caller-id=pd-http-client] [name=GetMinResolvedTSByStoresIDs] [uri=/pd/api/v1/min-resolved-ts] [method=GET] [target-url=] [source=tikv-driver] [url=http://127.0.0.1:2382/pd/api/v1/min-resolved-ts] [status="500 Internal Server Error"] [body="\"[PD:cluster:ErrNotBootstrapped]TiKV cluster not bootstrapped, please start TiKV first\""]
[2026/08/13 15:51:53.757 +00:00] [WARN] [client.go:252] ["[pd] request failed with a non-200 status"] [caller-id=pd-http-client] [name=GetMinResolvedTSByStoresIDs] [uri=/pd/api/v1/min-resolved-ts] [method=GET] [target-url=] [source=tikv-driver] [url=http://127.0.0.1:2384/pd/api/v1/min-resolved-ts] [status="500 Internal Server Error"] [body="\"[PD:cluster:ErrNotBootstrapped]TiKV cluster not bootstrapped, please start TiKV first\""]
[2026/08/13 15:51:53.757 +00:00] [WARN] [client.go:252] ["[pd] request failed with a non-200 status"] [caller-id=pd-http-client] [name=GetMinResolvedTSByStoresIDs] [uri=/pd/api/v1/min-resolved-ts] [method=GET] [target-url=] [source=tikv-driver] [url=http://127.0.0.1:2379/pd/api/v1/min-resolved-ts] [status="500 Internal Server Error"] [body="\"[PD:cluster:ErrNotBootstrapped]TiKV cluster not bootstrapped, please start TiKV first\""]
[2026/08/13 15:51:53.758 +00:00] [WARN] [client.go:252] ["[pd] request failed with a non-200 status"] [caller-id=pd-http-client] [name=GetMinResolvedTSByStoresIDs] [uri=/pd/api/v1/min-resolved-ts] [method=GET] [target-url=] [source=tikv-driver] [url=http://127.0.0.1:2382/pd/api/v1/min-resolved-ts] [status="500 Internal Server Error"] [body="\"[PD:cluster:ErrNotBootstrapped]TiKV cluster not bootstrapped, please start TiKV first\""]
[2026/08/13 15:51:53.758 +00:00] [WARN] [client.go:252] ["[pd] request failed with a non-200 status"] [caller-id=pd-http-client] [name=GetMinResolvedTSByStoresIDs] [uri=/pd/api/v1/min-resolved-ts] [method=GET] [target-url=] [source=tikv-driver] [url=http://127.0.0.1:2384/pd/api/v1/min-resolved-ts] [status="500 Internal Server Error"] [body="\"[PD:cluster:ErrNotBootstrapped]TiKV cluster not bootstrapped, please start TiKV first\""]
[2026/08/13 15:51:55.450 +00:00] [WARN] [backoff.go:179] ["pdRPC backoffer.maxSleep 40000ms is exceeded, errors:\nloadRegion from PD failed, key: \"6D44444C5461626C65FF56657273696F6E00FE0000000000000073\", err: type:NOT_BOOTSTRAPPED message:\"cluster is not bootstrapped\"  at 2026-08-13T15:51:48.826279407Z\nloadRegion from PD failed, key: \"6D44444C5461626C65FF56657273696F6E00FE0000000000000073\", err: type:NOT_BOOTSTRAPPED message:\"cluster is not bootstrapped\"  at 2026-08-13T15:51:51.441372784Z\nloadRegion from PD failed, key: \"6D44444C5461626C65FF56657273696F6E00FE0000000000000073\", err: type:NOT_BOOTSTRAPPED message:\"cluster is not bootstrapped\"  at 2026-08-13T15:51:53.318564114Z\ntotal-backoff-times: 20, backoff-detail: pdRPC:20, maxBackoffTimeExceeded: true, maxExcludedTimeExceeded: false\nlongest sleep type: pdRPC, time: 41546ms"]
    testkit.go:137: 
        	Error Trace:	tests/realtikvtest/testkit.go:137
        	            				tests/realtikvtest/testkit.go:110
        	            				tests/realtikvtest/statisticstest/statistics_test.go:194
        	Error:      	Received unexpected error:
        	            	[tikv:9001]PD server timeout: 
        	            	github.com/pingcap/errors.(*Error).GenWithStackByArgs
        	            		external/com_github_pingcap_errors/normalize.go:177
        	            	github.com/pingcap/tidb/pkg/store/driver/error.ToTiDBErr
        	            		pkg/store/driver/error/error.go:119
        	            	github.com/pingcap/tidb/pkg/store/driver/txn.extractKeyErr
        	            		pkg/store/driver/txn/error.go:166
        	            	github.com/pingcap/tidb/pkg/store/driver/txn.(*tikvSnapshot).Get
        	            		pkg/store/driver/txn/snapshot.go:61
        	            	github.com/pingcap/tidb/pkg/store/driver/txn.(*tikvTxn).Get
        	            		pkg/store/driver/txn/txn_driver.go:201
        	            	github.com/pingcap/tidb/pkg/kv.GetValue
        	            		pkg/kv/kv.go:109
        	            	github.com/pingcap/tidb/pkg/structure.(*TxStructure).Get
        	            		pkg/structure/string.go:37
        	            	github.com/pingcap/tidb/pkg/meta.(*Mutator).CheckDDLTableVersion
        	            		pkg/meta/meta.go:749
        	            	github.com/pingcap/tidb/pkg/session.InitDDLJobTables.func1
        	            		pkg/session/session.go:3436
        	            	github.com/pingcap/tidb/pkg/kv.RunInNewTxn
        	            		pkg/kv/txn.go:132
        	            	github.com/pingcap/tidb/pkg/session.InitDDLJobTables
        	            		pkg/session/session.go:3434
        	            	github.com/pingcap/tidb/pkg/session.bootstrapSessionImpl
        	            		pkg/session/session.go:3632
        	            	github.com/pingcap/tidb/pkg/session.BootstrapSession
        	            		pkg/session/session.go:3600
        	            	github.com/pingcap/tidb/tests/realtikvtest.CreateMockStoreAndDomainAndSetup
        	            		tests/realtikvtest/testkit.go:136
        	            	github.com/pingcap/tidb/tests/realtikvtest.CreateMockStoreAndSetup
        	            		tests/realtikvtest/testkit.go:110
        	            	tests/realtikvtest/statisticstest/statisticstest_test.TestBlockMergeFMSketch
        	            		tests/realtikvtest/statisticstest/statistics_test.go:194
        	            	testing.tRunner
        	            		GOROOT/src/testing/testing.go:1934
        	            	runtime.goexit
        	            		src/runtime/asm_amd64.s:1693
        	Test:       	TestBlockMergeFMSketch
�--- FAIL: TestBlockMergeFMSketch (41.58s)

@takaidohigasi

Copy link
Copy Markdown
Contributor Author

/test check-dev2

@takaidohigasi

Copy link
Copy Markdown
Contributor Author

all the CI passed. ready!

@takaidohigasi

Copy link
Copy Markdown
Contributor Author

please take a look when you have time🙏

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Manually backports common-handle PK ordering recognition to release-8.5.

Changes:

  • Extends secondary-index order matching with common-handle PK columns.
  • Adds ten ordering regression scenarios.
  • Registers and shards the new Bazel test.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
pkg/planner/core/find_best_task.go Recognizes common-handle PK suffix ordering.
pkg/planner/core/casetest/rule/rule_common_handle_ordering_test.go Tests planner and result ordering.
pkg/planner/core/casetest/rule/BUILD.bazel Registers the new test.

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +973 to +979
alreadyInIndex := false
for _, col := range idxCols {
if col != nil && col.EqualColumn(handleCol) {
alreadyInIndex = true
break
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the observation — the scenario is real, but it is a missed optimization rather than a correctness issue, and it is intentional (pre-existing) behavior faithfully mirrored from master. Keeping this cherry-pick identical to master, so no change here; a follow-up on master would be the right place.

Details:

  1. No correctness impact. The matcher's case-1 check requires idxColLens[colIdx] == types.UnspecifiedLength, so a prefix column can never be treated as providing order. With KEY idx(d, a1(2)) + PRIMARY KEY (a1, a2), the dedup drops the full a1, matching stops at a1(2), and we return PropNotMatched — i.e. we fall back to an explicit sort, which is exactly the behavior before this change. This PR never loses an ordering we previously recognized; it only declines to recognize a new one in the prefix-overlap corner.

  2. The suggested dedup guard alone would not enable the optimization. Even if we kept the full a1 (effective columns (d, a1(2), a1, a2)), the matcher would still stop at a1(2) because there is no rule to skip a prefix column when the same column follows in full form. Supporting this corner needs both the length-aware dedup and a prefix-skip rule in the matcher, plus an argument that prefix ordering is monotonic under the column's collation (sort-key prefixes and collation contractions make this non-trivial — the same class of concern that motivated excluding v0 new-collation string handles here).

  3. This block is byte-for-byte identical to master (see matchProperty in pkg/planner/core/find_best_task.go on master), so a behavior change belongs there first and can then be backported if desired. I'd suggest tracking the prefix-overlap enhancement (and a regression case pinning today's sort-fallback behavior) as a follow-up issue against master rather than diverging in this backport.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I agree @takaidohigasi. The AI reviews provide additional opportunities for improvement - but they should not delay the cherry pick.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks, please tell me if there is anything I can help you or anything I need to cope with

@ti-chi-bot ti-chi-bot Bot added the needs-1-more-lgtm Indicates a PR needs 1 more LGTM. label Aug 20, 2026
@ti-chi-bot

ti-chi-bot Bot commented Aug 20, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: terry1purcell

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

The pull request process is described here

Details 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

ti-chi-bot Bot commented Aug 20, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-08-20 08:38:47.705497659 +0000 UTC m=+145362.876591766: ☑️ agreed by terry1purcell.

@ti-chi-bot ti-chi-bot Bot added the approved label Aug 20, 2026
@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 Oct 4, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved cherry-pick-approved Cherry pick PR approved by release team. contribution This PR is from a community contributor. needs-1-more-lgtm Indicates a PR needs 1 more LGTM. ok-to-test Indicates a PR is ready to be tested. release-note-none Denotes a PR that doesn't merit a release note. sig/planner SIG: Planner size/XL Denotes a PR that changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants