Repository navigation
perf(sql): use covering index order for bounded scans - #33530
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
This pull request is merged. |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: ea0dcc998f7609f48f142834eeb2b0ab06b6fc5d
Assessment: approve
No actionable defects found. The change reuses the existing index, Top and reader machinery, retains a final Top to merge candidates, and guards early limits across filters, joins and shared inputs. Unbounded ordered streams and DISTINCT early termination remain outside this PR's scope.
Model: gpt-6.1-terra / max
Session: 01a22aff-bb68-7e31-ae71-ee4ab48ad9d0 · slot 0 · generation 45
Validation:
-
The isolation preflight passed. The complete planner, compiler and readutil package suites passed at the frozen head; receipt 1796051504419417263-3.json and owner-packages.log.
-
Focused block-reader and planner ownership tests passed; receipts 1796051319967372164-3.json and 1796051388317636454-3.json.
-
A temporary single-CN MySQL probe matched an unindexed control for pagination, ranges, NULLs and transactional changes, and checked the join regression and SUM metadata; sql-probe.log and followup.log.
-
A temporary two-CN MySQL probe matched an unindexed control with overlapping indexed blocks. The global Top received 30 candidates for a 15-row page; receipt 1796051779691344926-3.json and multicn-v2.log.
-
Native source inputs matched the checkout. The CGo library was rebuilt after its retained output hashes differed from the older ledger; native-audit.log and native-build.log.
Limitations:
- The full mo-tester suites and performance benchmarks reported by the author were not independently rerun.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: b243e351a5c9fce367151d9249f5268bd790a4d3
Assessment: request_changes
The earlier review’s functional evidence remains applicable because the production code is unchanged. A new current-head SQL comparison identifies a material performance regression for wide covering indexes that the earlier review and narrow-key benchmark did not cover.
Model: gpt-6.1-terra / max
Session: 01a22aff-bb68-7e31-ae71-ee4ab48ad9d0 · slot 0 · generation 45
- P2
pkg/sql/plan/ordered_index.go:136: An unhinted query such as SELECT a FROM t ORDER BY a LIMIT 10 has a covering index on (a, b), where the unused b column contains wide, poorly compressible values.
Impact: The row-count heuristic can select the index even though the reader must load the full packed key, including b, from each relevant block before applying its limit. This can make the automatic plan substantially slower and increase I/O for an otherwise narrow query.
Evidence: On the current head, a one-CN SQL probe with 32,768 rows across four blocks and refreshed statistics returned identical rows for the automatic and IGNORE INDEX plans. 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 406.6 ms versus 7.33 ms; the single-CN timings were noisy, but the full packed-key read explains the amplification. See current-sql-probe-v2.log and checks/1796058992071148895-3.json. Account for packed-key bytes when selecting the automatic path, or retain the base scan when it is cheaper, while preserving explicit hint behavior.
Validation:
-
The isolation preflight passed.
-
A current-head SQL probe confirmed the three changed explain expectations and compared the wide-key automatic plan with an equivalent base-scan control.
-
Reused the prior same-PR planner, compiler, reader, block-I/O, single-CN and two-CN functional checks after verifying that only two expected-result files changed since their assessed head.
Limitations:
-
The performance comparison used one embedded CN; its latency ratio is not a general benchmark, and multi-CN performance was not measured.
-
The full changed mo-tester files were not independently rerun.
-
The initial toolchain bootstrap timed out at the configured proxy, and the first temporary probe used an unsupported cluster option. Both setup issues were corrected before the passing probe.
b243e35 to
def04e6
Compare
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: def04e64b763cab6552f92b9592d37daaef8cc0f
Assessment: approve
The change reuses the existing covering-index, Top, and reader mechanisms with a bounded width-based cost guard. The earlier wide-index regression is resolved in the reproduced case. No actionable defects remain.
Model: gpt-6.1-terra / max
Session: 01a22b07-00b6-7e32-b0a1-3099d0b867c7 · slot 1 · generation 39
Validation:
-
The full planner, compiler, and readutil package suites passed on the assigned head; receipt checks/1796063739605588007-3.json.
-
A current-head public SQL probe with 32,768 rows and four persisted blocks selected a compact index, declined the wide index automatically, and returned the same rows as base-scan and forced-wide controls. Receipt checks/1796063600572221615-3.json and wide-cost-probe-v2.log.
-
Reused the earlier same-PR two-CN and transaction/metadata probes for the unchanged forced-index ordering and merge path, after comparing intervening changes.
-
Isolation preflight passed, and the retained native build matched all 195 current tracked native inputs.
Limitations:
-
The full distributed mo-tester suite and a new latency benchmark were not independently run.
-
The initial local test compile lacked native include flags, and the first temporary SQL probe used a nonconstant flush argument. Both setup issues were corrected; the retained successful retries are identified above.
## What type of PR is this? - [x] 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.
What type of PR is this?
Which issue(s) this PR fixes:
Refs #31856.
What this PR does / why we need it:
The planner used filter selectivity to choose secondary indexes and missed an inexpensive covering read for
ORDER BY … LIMIT. An order hint could also pass a block quota through a join and discard its only matching rows. A reproducible query onmainreturned two rows withIGNORE INDEXand zero withFORCE INDEX FOR ORDER BY.Consider the required order while choosing a covering regular index. When the requested columns match its leading key, their SQL comparators agree with physical order, and the bounded read is cheaper, use the same key for the existing Top and block-pruning messages. Each sorted block can contribute up to
LIMIT + OFFSETqualified, visible candidates. Native primary keys use the same reader budget. A residual filter, a join, an earlier page, or a shared scan prevents an unsafe quota. The ordinary access path continues to handle large pages and non-covering projections.Blocks from different objects, readers and CNs can overlap. The final bounded Top merges their candidates and transaction-local rows. When equality predicates fix every sort key, the planner removes the sort and preserves the original pagination.
Cost of an ordered covering scan
The reader loads a whole key block before it returns a bounded set of rows. Automatic selection now compares that read and the final Top input with the columns needed by the base scan. It reuses the regular-index byte estimates, including serialization, the separate PK column where needed, and column sizes already in the compiler cache. Unmeasured extra key fields use the encoder’s schema bound. Explicit order hints keep their existing behavior.
On a one-CN SQL workload with 32,768 persisted rows and four blocks, the narrow query ordered one integer column and returned ten rows. The wide index also contained a 1,024-byte binary value. All three access choices returned the same rows. Review finding
For the narrow query with only the wide index available, the automatic plan took 3.203 ms on the reviewed revision and 0.470 ms on the revised service. Each median covers 21 runs after four warmups, with automatic, forced and excluded paths interleaved.
A separate 65,536-row fixture illustrates the limit of the cost estimate. The sort column contained just two values and compressed to 1.43 KiB in the base scan. A forced index read 514.85 KiB yet sent only 40 rows to Top. With warm data, the automatic base scan took 0.640 ms and the forced index took 0.364 ms. The planner estimates bytes and candidate work from existing statistics. It cannot predict cache residency.
Two 6,000-row controls made different choices. For the narrow integer query the base scan read 2.08 KiB. For a projected binary string, decimal and PK the covering scan sent three rows to Top and read 29.47 KiB, compared with 6,000 rows and 71.39 KiB on the base scan. The SQL collation and NULL-order checks continue to control when packed order is usable.
Observed scan work
Single CN, 200,000 rows, 500 distinct secondary keys, four overlapping batches, 28 flushed blocks. Counts are scan
inputRowsfromEXPLAIN ANALYZE.On this fixture the revised automatic plan and the same service with the secondary index excluded took 0.301 and 1.357 ms for Top-10, 0.428 and 0.875 ms for the descending range with a PK tie-breaker, and 1.077 and 2.622 ms for OFFSET 1000. The deep-page control at OFFSET 155000 took 15.298 and 15.412 ms. These are warm medians from 21 interleaved runs on one local connection.
Unbounded ordering and
DISTINCT … LIMITeach still consumed 200,000 rows on this fixture. A full ordered stream across blocks needs a merge that guarantees global order. Distinct early termination must count distinct keys across inputs. The issue stays open for those cases.Validation
DECIMAL(32,0)result type forSUM(INT).