Repository navigation
fix: optimize regular index order-by limit - #23966
Conversation
Address matrixorigin#23965 by teaching the planner to reuse the physical order of non-unique regular secondary indexes for ORDER BY primary-key LIMIT queries when all non-PK key parts are fixed by equality filters. Rewrite the sort anchor to the hidden serialized key, wire top-value messaging directly between sort and scan, and add focused planner tests for the optimized and non-optimized cases. Co-authored-by: Copilot <[email protected]>
Add an explicit index-table layout guard for the regular secondary index ORDER BY LIMIT rewrite and extend planner coverage to validate ASC ordering as well. Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
|
Reviewed and pushed follow-up fixes in
Local validation passed: |
There was a problem hiding this comment.
Pull request overview
This PR addresses #23965 by enabling ORDER BY (PK) + LIMIT queries on non-unique regular secondary indexes to reuse the index table’s physical ordering (via its hidden serialized key), reducing unnecessary full scans + explicit sorts and improving early-termination behavior.
Changes:
- Planner: detect eligible regular-index ORDER BY PK LIMIT patterns, rewrite the sort anchor to the hidden serialized key, and wire MsgTopValue messaging from Sort → Scan (plus BlockTop pushdown).
- Engine: extend
BlockReadTopOpwithOrderedLimit/Descand add an “ordered limit” fast path in block reading that avoids IVF-Flat TopN handling. - Tests: add focused planner and blockio tests; ensure parallel scan readers receive
OrderBysettings.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| pkg/vm/engine/tae/blockio/read.go | Adds ordered-limit handling paths and refactors live-row selection for TopN/limit pushdown. |
| pkg/vm/engine/tae/blockio/read_test.go | Adds unit tests for ordered-limit behavior in select/live-row handling. |
| pkg/vm/engine/readutil/reader.go | Sets up BlockReadTopOp for ordered-limit vs IVF-Flat TopN and adjusts dist-vec handling accordingly. |
| pkg/sql/plan/message.go | Avoids panic and adds regular-index hidden-key rewrite + optional BlockTop pushdown when pushing MsgTopValue. |
| pkg/sql/plan/apply_indices.go | Introduces regular-index top-sort context detection, hidden-key rewrite, BlockTop setup, and MsgTopValue wiring. |
| pkg/sql/plan/apply_indices_test.go | Adds planner tests validating when the regular-index PK-order optimization should/shouldn’t apply. |
| pkg/sql/compile/scope.go | Ensures parallel scan readers receive SetOrderBy alongside SetBlockTop. |
| pkg/sql/compile/scope_test.go | Adds test validating parallel readers get OrderBy and block-top settings. |
| pkg/objectio/types.go | Extends BlockReadTopOp with OrderedLimit and Desc flags. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
LeftHandCold
left a comment
There was a problem hiding this comment.
Reviewed the latest head d9eda9f after the follow-up fixes.
I pushed two fixes during review:
- added ordered block-limit tombstone/fallback test coverage for the Coverage gate;
- disabled regular-index BlockOrderBy/BlockLimit pushdown when the SORT has OFFSET or RankOption, so the scan no longer truncates each block to the plain LIMIT when upper offset/tie semantics need more candidates.
The hidden-key rewrite and MsgTopValue path remain enabled for the safe cases, and the focused planner/blockio tests plus the related package tests passed locally. I do not see remaining correctness blockers.
XuPeng-SH
left a comment
There was a problem hiding this comment.
LGTM. The optimization is sound and well-guarded.
Core correctness argument
For a non-unique regular secondary index (k1, k2, ..., pk), the hidden key is serial(k1, k2, ..., pk). When ALL non-PK key parts are fixed by prefix_eq(hidden_key, serial(k1_val, k2_val, ...)), the hidden key ordering within that prefix is exactly the PK ordering. Rewriting ORDER BY pk LIMIT N to ORDER BY hidden_key LIMIT N is therefore semantics-preserving.
Guard conditions verified
isRegularIndexFullPrefixEquality: correctly requiresprefix_eqwithserial(N args)where N == numKeyParts (excludes PK)canUseRegularIndexHiddenSortKey: rejects unique indexes, verifies table layout (col0=hidden key, col1=PK), confirms ORDER BY targets col1buildRegularIndexTopSortContext: bails on OFFSET/RankOption/multi-column ORDER BYhandleMessageFromTopToScan:enableBlockTopguarded bynode.Offset == nil && node.RankOption == nil
Block-level pruning correctness
buildOrderedLiveRowsAsc: scans from row 0 forward, skipping tombstones, stops at limit — correct for sorted ASC blocksbuildOrderedLiveRowsDesc: scans from end backward, skipping tombstones, stops at limit, then reverses — correct becausefillOutputBatchBySelectedRowsexpects physical-row-order selectRows- Unsorted blocks: returns all live rows without pruning — sort node handles reordering
handleOrderByLimitOnSelectRowswith pre-filtered selectRows: ASC takes[:limit], DESC takes[len-limit:]— correct since pre-filter preserves physical order
Other
- Parallel reader path correctly propagates
OrderByto each reader viaSetOrderBy OrderedLimitflag cleanly separates the new path from the existing IVFFlat distance-based TopN- The panic in
handleMessageFromTopToScanis correctly replaced withreturn(the project path may have already set scan OrderBy) - Test coverage: prefix-complete/incomplete, ASC/DESC, block-top with/without offset, tombstone handling
Merge Queue Status
This pull request spent 54 minutes 8 seconds in the queue, including 53 minutes 52 seconds running CI. Required conditions to merge
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #23965
What this PR does / why we need it:
Address #23965 by teaching the planner to reuse the physical order of non-unique regular secondary indexes for ORDER BY primary-key LIMIT queries when all non-PK key parts are fixed by equality filters.
Rewrite the sort anchor to the hidden serialized key, wire top-value messaging directly between sort and scan, and add focused planner tests for the optimized and non-optimized cases.