Skip to content

fix: optimize regular index order-by limit - #23966

Merged
mergify[bot] merged 10 commits into
matrixorigin:3.0-devfrom
LeftHandCold:order-by_limit
May 9, 2026
Merged

mergify[bot] merged 10 commits into
matrixorigin:3.0-devfrom
LeftHandCold:order-by_limit

Conversation

@LeftHandCold

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

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.

LeftHandCold and others added 2 commits March 26, 2026 18:50
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]>
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Mar 27, 2026
@LeftHandCold

Copy link
Copy Markdown
Collaborator Author

Reviewed and pushed follow-up fixes in 30e5ea959f:

  • Added BlockOrderBy / BlockLimit pushdown to the applyIndicesForProject regular-index top-sort path, so the optimized path also gets per-block early limiting instead of only top-value messaging.
  • Fixed the no-prefilter block read path so scalar OrderedLimit does not fall through to the IVF/vector TopN handler. Ordered scalar scans now build live rows after tombstones and apply first/last limit safely; vector TopN still uses the existing distance path.
  • Added focused tests for both paths.

Local validation passed: go test ./pkg/sql/plan ./pkg/sql/compile ./pkg/vm/engine/tae/blockio ./pkg/vm/engine/readutil -count=1. CI has been retriggered on the updated head.

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

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 BlockReadTopOp with OrderedLimit/Desc and 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 OrderBy settings.

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.

Comment thread pkg/vm/engine/tae/blockio/read.go Resolved

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 XuPeng-SH left a comment

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.

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 requires prefix_eq with serial(N args) where N == numKeyParts (excludes PK)
  • canUseRegularIndexHiddenSortKey: rejects unique indexes, verifies table layout (col0=hidden key, col1=PK), confirms ORDER BY targets col1
  • buildRegularIndexTopSortContext: bails on OFFSET/RankOption/multi-column ORDER BY
  • handleMessageFromTopToScan: enableBlockTop guarded by node.Offset == nil && node.RankOption == nil

Block-level pruning correctness

  • buildOrderedLiveRowsAsc: scans from row 0 forward, skipping tombstones, stops at limit — correct for sorted ASC blocks
  • buildOrderedLiveRowsDesc: scans from end backward, skipping tombstones, stops at limit, then reverses — correct because fillOutputBatchBySelectedRows expects physical-row-order selectRows
  • Unsorted blocks: returns all live rows without pruning — sort node handles reordering
  • handleOrderByLimitOnSelectRows with pre-filtered selectRows: ASC takes [:limit], DESC takes [len-limit:] — correct since pre-filter preserves physical order

Other

  • Parallel reader path correctly propagates OrderBy to each reader via SetOrderBy
  • OrderedLimit flag cleanly separates the new path from the existing IVFFlat distance-based TopN
  • The panic in handleMessageFromTopToScan is correctly replaced with return (the project path may have already set scan OrderBy)
  • Test coverage: prefix-complete/incomplete, ASC/DESC, block-top with/without offset, tombstone handling

@mergify

mergify Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-05-09 13:19 UTC · Rule: release-3.0
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-05-09 14:13 UTC · at 9dfbb73edd347b275baf8274d58c08efeefbb84d · squash

This pull request spent 54 minutes 8 seconds in the queue, including 53 minutes 52 seconds running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • branch-protection-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI (3.0) / Coverage
    • check-neutral = Matrixone Utils CI (3.0) / Coverage
    • check-skipped = Matrixone Utils CI (3.0) / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI (3.0) / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI (3.0) / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI (3.0) / SCA Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI (3.0) / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI (3.0) / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI (3.0) / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI (3.0) / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI (3.0) / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI (3.0) / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI (3.0) / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI (3.0) / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI (3.0) / Compatibility Test With Target on Linux/x64(LAUNCH)

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants