Skip to content

[4.2-dev] perf(sql): use covering index order for bounded scans - #33532

Merged
XuPeng-SH merged 2 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:fix/31856-ordered-index-limit-4.2
Nov 30, 2026
Merged

XuPeng-SH merged 2 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:fix/31856-ordered-index-limit-4.2

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Improvement

Which issue(s) this PR fixes:

Refs #31856. Backport of #33530 to 4.2-dev.

What this PR does / why we need it:

A small ordered page can cost a full table scan on this release. The planner now considers a complete, full-valued covering index whose leading keys provide the requested SQL order. It reuses the release's index hint and range builders, block reader, and TopValue messages. Each sorted block can contribute up to LIMIT + OFFSET visible, qualified rows. The final Top merges candidates across overlapping blocks, CNs and transaction-local writes. When integer equality predicates fix every sort key, the planner removes the redundant sort and preserves pagination.

The reader also recognizes an unfiltered native primary key. Unsafe predicates, row-discarding joins, shared inputs, incompatible key orders and expensive pages retain their existing access paths. On this branch the filtered covering fast path uses the release's proven integer literal ranges. The branch already prevents a forced index from truncating the input to a selective JOIN. This change consolidates that decision at the Top and adds a persisted SQL regression. It also corrects the metadata delimiter for an empty prepared result in the same fixture, reproduced with the original release binary.

Automatic index choice

The block reader loads the packed key before applying a row limit. The optimizer compares that cost with reading the columns the query actually uses. It ranks eligible covering indexes by key width and uses column sizes already in the compiler cache, with schema widths as a fallback. Explicit index hints keep their existing behavior.

On one CN with 32,768 persisted rows in four blocks, both indexes started with the integer sort column. The wide index also contained a 1,024-byte binary value. The table shows storage read bytes for the automatic plan.

Query and available indexes Previous PR revision Revised plan
Select the integer, wide index available 32.79 MiB 128.63 KiB from the base column
Select the integer, wide and compact indexes available 32.79 MiB 71.24 KiB from the compact index
Select and order by the wide value too 32.79 MiB 32.79 MiB from the wide index

On separate 6,000-row tables, a narrow integer query used 2.08 KiB from the base column. For a projected composite key with a nullable string, decimal and PK, automatic selection used three candidates and 29.47 KiB. The base control used 6,000 rows and 71.39 KiB. Automatic, forced and ignored controls returned identical SQL results.

Observed scan work

One CN, 200,000 rows, 500 secondary-key values and four overlapping inserts. Both the base and index tables were flushed before running EXPLAIN ANALYZE. Values are scan inputRows.

Query Original 4.2-dev Backport
Secondary key, LIMIT 10 200,000 10
Descending secondary key, BETWEEN, LIMIT 10 40,400 40
Secondary key, LIMIT 10 OFFSET 1000 200,000 4,040
Native primary key, ascending / descending, LIMIT 10 8,192 / 848 10 / 10

Unbounded ordered output and DISTINCT early stopping remain separate work under #31856.

Verification

  • Reproduced the two pushdown EXPLAIN mismatches and the top mismatch with the previous fixtures. On the rebased tree both full suites passed in Proxy BVT mode (73 statements passed, one previously ignored). The native PK reader caps are 10, 30 and 300. The final SQL Top retains the requested limit and offset.
  • The new planner regression selects the wide index on the previous implementation and the compact index on this revision. It also covers missing and measured column widths, forced use and small tables.

For the 32,768-row narrow query, four warmups and 21 alternating samples on one connection gave an automatic-plan median of 3.176 ms on the previous PR revision and 0.552 ms on the rebased revision. The forced-wide control was 4.053 and 4.102 ms respectively. These are local timings. On the 200,000-row fixture, the original bounded scans retained the candidate counts above. Deep pagination retained its ordinary scan.

  • Compared automatic, forced and ignored index results through the SQL frontend, including NULLs, mixed order, non-covering output, exhausted and nested pages, prepared-statement re-execution and transaction-local inserts/deletes/rollback. Checked the release's existing FOUND_ROWS() result with and without a force hint.
  • Confirmed a two-CN physical plan used both CNs and matched control results for pagination and descending ranges.
  • Passed the planner, compiler and readutil package tests in short mode, focused race checks including block I/O, and all 300 SQL statements across the force-index, covering-range and cursor fixtures with strict result metadata.
  • Passed the release's error check and selected static analysis across 104 packages. The three planner regression groups fail on the original release before the backport.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@mergify

mergify Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@XuPeng-SH

XuPeng-SH commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · done

Commit: 35221772b3599601756d5681cd232957f5c80a46

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

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.

mo-bot review · mo-bot-local · review

Commit: 35221772b3599601756d5681cd232957f5c80a46

Assessment: request_changes

The change reuses the existing Top and reader mechanisms, but its automatic index selection can substantially increase I/O for narrow queries when a covering index has a wide trailing key.

Model: gpt-6.1-terra / max

Session: 01a22aff-bb68-7e31-ae71-ee4ab48ad9d0 · slot 0 · generation 45

  • P2 pkg/sql/plan/ordered_index.go:145: An unhinted query such as SELECT a FROM t ORDER BY a LIMIT 10 has an index on (a, b), where b contains wide, poorly compressible values.
    Impact: The optimizer can choose the covering index even though the query does not need b. The reader loads the full packed index key for each relevant block before applying the per-block limit, causing much more I/O and slower queries than scanning the narrow a column.
    Evidence: In a one-CN SQL fixture with 32,768 rows across four blocks and refreshed statistics, the automatic plan selected the index and returned the same rows as an IGNORE INDEX control. EXPLAIN ANALYZE reported 32.77 MiB read for the index plan versus 128.66 KiB for the base scan. Across nine alternating warm samples, median latency was 1.018 s versus 0.277 s; the timing was noisy, but the read amplification follows from loading the packed key. See wide-sql-probe-v4.log and checks/1796057201964635704-3.json. Account for the physical width of the packed key when choosing the automatic path, or retain the base scan when it is cheaper, while preserving explicit hint behavior.

Validation:

  • Private temporary-directory and loopback preflight passed.

  • Focused planner, compiler, reader and block-I/O tests passed; the short planner, compiler and readutil suites also passed.

  • The wide-key SQL comparison passed its result and plan assertions and retained its command receipt and log.

Limitations:

  • The SQL performance comparison used one embedded CN and showed noisy timings; its latency ratio is not a general benchmark.

  • Three unrelated short-mode subtests were skipped. The author's additional SQL, multi-CN and race results were not independently reproduced.

  • Earlier diagnostic SQL probes stopped on stale statistics or reviewer probe assumptions; the final comparison used a full statistics refresh.

Choose complete covering indexes for small ordered pages and bound candidate reads only after storage qualification. Preserve release-specific range, hint and backfill behavior.

Backport-of: ea0dcc9
@XuPeng-SH

XuPeng-SH commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · done

Commit: 01514ba404ce31d47ffd6bd12e7c2e5c29bad2d7

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

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.

mo-bot review · mo-bot-local · review

Commit: 01514ba404ce31d47ffd6bd12e7c2e5c29bad2d7

Assessment: approve

The earlier wide-key read-amplification concern is resolved for the reported case. The updated planner chooses the base scan for an unused wide index suffix, selects a compact covering index when available, and preserves forced-index behavior. The change reuses the existing Top, covering-index and reader mechanisms; the added width estimate addresses the demonstrated selection cost.

Model: gpt-6.1-terra / max

Session: 01a22aff-bb68-7e31-ae71-ee4ab48ad9d0 · slot 0 · generation 45

Validation:

  • Private temporary-directory and loopback preflight passed; retained native artifacts matched 170 source inputs and six build outputs.

  • Focused ordered-index, hint, compiler and reader tests passed; receipt checks/1796061470768150117-3.json.

  • The short planner, compiler and reader suites passed; receipt checks/1796061659426512299-3.json.

  • An embedded SQL reproduction returned the expected rows for automatic, base-scan and forced-index paths. The automatic base scan read 128.66 KiB versus 32.77 MiB for the forced wide index; after adding a compact index, the automatic plan selected it. Receipt checks/1796061598789823638-3.json.

Limitations:

  • The SQL reproduction used one embedded CN and four persisted blocks; it is not a general performance benchmark.

  • Distributed SQL BVT, multi-CN and race suites were not independently rerun. The author's reported results were not accompanied by local validation artifacts.

@XuPeng-SH
XuPeng-SH merged commit 34b63d7 into matrixorigin:4.2-dev Nov 30, 2026
32 checks passed
@XuPeng-SH
XuPeng-SH deleted the fix/31856-ordered-index-limit-4.2 branch November 30, 2026 18:39
XuPeng-SH added a commit that referenced this pull request Nov 30, 2026
## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Rolls out matrixorigin/CI#516. An example of the previous Shanghai
fallback was #33532.

## What this PR does / why we need it:

Pin the UT Coverage entrypoint, both standby worker routes and the
cross-repository contract to `f20738ba8bd33a8dceec265ed9193e064608a01e`,
the upstream squash commit of matrixorigin/CI#516. The protected
MatrixOne entrypoint on `main` serves eligible PRs targeting both `main`
and `4.2-dev`. PRs that inherit the S3 tests from their target branch
can now keep two-group coverage as those files evolve.

### Validation

- The MatrixOne cross-repository contract detected the previous pin when
run against the merged companion. After updating all four references, 76
MatrixOne tests passed across dispatch, identity, retry and cleanup.
- 165 Coverage companion tests passed on Linux/amd64 at the exact
upstream revision with networking disabled.
- Actionlint 1.7.12 passed for all three edited workflows. Verified the
complete diff changes four immutable SHA references.

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/enhancement size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants