Skip to content

fix(plan): preserve correlated pagination per outer row - #32459

Merged
XuPeng-SH merged 3 commits into
4.2-devfrom
codex/issue-32441-correlated-limit
Nov 10, 2026
Merged

XuPeng-SH merged 3 commits into
4.2-devfrom
codex/issue-32441-correlated-limit

Conversation

@XuPeng-SH

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

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

Fixes #32441

What this PR does / why we need it:

Correlated ORDER BY ... LIMIT could run globally before the correlated predicate, returning NULL or another key's top row. Preserve the pagination boundary: rank by proven inner equality keys when sufficient; otherwise rank supported scalar LIMIT 1 queries after joining all predicates, using a unique outer-row occurrence. Keep OFFSET ordering, scalar cardinality errors, and the distinction between an absent row and a selected NULL.

For a provable integer extremum, avoid ranking entirely. A simple scalar that returns the same direct integer column as its sole sort key, with literal LIMIT 1 and zero OFFSET, becomes MIN/MAX when NULL ordering permits. Reuse the existing equality and non-equality scalar-aggregate decorrelation owners. Existing pagination preflight runs first; unsafe or unsupported queries retain their prior path. Outer-domain filters must be total before the existing aggregate-key pushdown can copy them; binder-inserted integer-literal casts reuse the binder's existing range check. The mixed aggregate route requires the actual original single scan and physical Row_ID, and fixed integer/Row_ID outer columns, preserving duplicate occurrences without grouping wide payloads. No new executor, cache, configuration or execution state is introduced.

Keep existing successful string-key plans. Direct same-type CHAR/VARCHAR equality can rank inner keys only as the existing fallback when an outer occurrence identity is unavailable, such as UNION ALL. Outer-only correlated predicates retain their existing pagination/aggregate owner. For eligible single implicit scalar aggregates, a positive literal LIMIT with zero OFFSET is redundant; reuse the existing aggregate owner after proving its arguments preserve empty-input/NULL-extension behavior, including the supported CAST/OR, numeric DISTINCT and multi-argument COUNT DISTINCT cases. LIMIT 0 retains its separate table-dependency and prepared-metadata handling.

Validation

At 4e681ac8eb39, with merge-base ba5d0fd13f2a on 4.2-dev, Go 1.26.6, GOAMD64=v3, GOEXPERIMENT=simd and matching MatrixOne CGo:

  • Complete owning package ./pkg/sql/plan normal and race tests passed, including the new extremum, literal-fit boundary and selective point-lookup regressions. Gofmt, Go vet, diff checks and repository-configured incremental golangci-lint v2.6.2 over the complete PR delta passed; lint reports 0 issues.
  • The SQL/result case passed twice on an isolated CN, each 158/158 statements with no failed, ignored or abnormal statements and database teardown checked. Four additional hand-written result sets cover NOT NULL MIN, nullable ascending NULL-first behavior, scalar NULL extension and sequential scalar consumers; the previous 154 commands remain.
  • Final public SQL QA verifies equality/range/NULL-safe predicates, no match and real NULL, duplicate outer occurrences without a PK, signed/unsigned 64-bit extremes, different projections and tied sort keys, OFFSET, scalar LIMIT 2 error and recovery, prepared parameter reuse, and NOT NULL scalar IS NULL behavior. Two separate 1,000-row result sets matched both an independent grouped query and manually calculated expected rows.
  • A forced two-CN test flushed 20,000 parent rows across ten flushes. The plan contains the correlated MAX aggregate and no pagination window; both CNs actually read parent batches. Queries through each coordinator returned count 20,000 and the expected mixed/equality sums 300,000/400,000. This proves the forced topology, not default distributed scheduling.
  • Prior valid evidence for unchanged paths includes binary-protocol LIMIT/OFFSET parameter order/reuse, session-hint changes and isolation, inner table SELECT authorization, CHAR/VARCHAR byte-key and multibyte grouping controls, and exact-base compatibility/error comparisons. Current GitHub CI is separate from these local results.

Performance

Compare against the previous correct PR implementation d4e606e, rather than the old incorrect global-LIMIT plan. Same machine, isolated CNs, empty session hints, 20,000 inner rows/100 keys and 1,000 outer rows; queries run serially in alternating version order with two warmups and seven measured samples. Every measured result was checked. Medians:

Query shape Previous PR Optimized Speedup
Integer equality, one selected outer row 73.40 ms 5.57 ms 13.2x
Integer equality, 100 outer keys 74.62 ms 4.04 ms 18.5x
Equality plus range, 1,000 repeated-key outer rows 730.10 ms 83.41 ms 8.8x
Same range query, 16 additional fixed integer columns 714.94 ms 207.43 ms 3.4x

The final selective samples use the final source; unfiltered/control samples reuse the otherwise identical implementation before its outer literal-cast admission fix. OFFSET, a different projected value, and a wide outer-schema control retained their window plans and were approximately unchanged. One-row mixed medians were 9.36/10.71 ms with overlapping 4–17 ms ranges, so no small-latency improvement is claimed. A separate same-final-source scaling run measured mixed 1/10/100/1,000 outer rows at 3.78/4.25/11.03/79.04 ms; independent grouped controls were 3.49/3.89/8.78/54.70 ms.

Scope and remaining limits

The extremum rule is deliberately limited to its proven direct-integer value/order identity and eligible projection contexts. Different projections, nullable ascending NULL-first order, noninteger order values, positive OFFSET, wide mixed outer bindings, many joined/derived outer inputs, WHERE-consumed subquery conjuncts and CAST-wrapped prepared point filters can retain the window path and its cost. Equality may still scan the full inner relation; mixed predicates still materialize matching join candidates. These fixture timings do not establish production incidence, concurrency capacity, spill behavior or total peak memory. Partitioned-table correlation has not been independently exercised.

Some dynamic bounds, volatile/unsafe expressions, nested pagination, binary-key and aggregate/EXISTS shapes remain explicit NYI. The conservative aggregate proof can reject previously executable deterministic expressions whose NULL-extension behavior is unproved. Non-equality scalar aggregate pagination that can remove its row remains NYI because its existing owner cannot preserve that boundary; some such OFFSET queries previously returned incorrect results. Previously verified unrelated defects remain outside scope: early errors from invalid inner expressions when outer predicates are false, column-remapping failures for some combinations of scalar aggregates, and no-LIMIT correlated grouped COUNT/COALESCE/ROLLUP cases.

The tested base is recorded above; no merged-result or pending-CI pass is claimed.

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner November 10, 2026 05:48
@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 →

@XuPeng-SH

XuPeng-SH commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 7e9fd9996f61bf5e76dd8f7ae5e77cba82ae7c12

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: 7e9fd9996f61bf5e76dd8f7ae5e77cba82ae7c12

Assessment: approve

The rewrite preserves pagination at the correlation boundary: equality keys share inner ranks, while supported mixed predicates rank joined candidates per unique outer occurrence. Existing partition/window, projection and aggregate owners are reused; separate paths and row markers are necessary for duplicate, OFFSET and empty/NULL semantics. Conservative NYI restrictions and the disclosed fanout cost are coherent with the stated scope. No actionable source or design defect remains.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Complete eight-file delta, baseline decorrelator, window/remap/compile consumers and linked issue #32441 reviewed. Both discussion entries are informational and covered in discussion-assessment.json. Existing overflow-safe LEAD behavior and row-identity contracts close the relevant boundary controls.

  • Independent SQLite oracle matched 27 compatible value queries and 128 expected rows; all 62 SQL/result statements align. This validates expected results for NULL/empty aggregates, duplicates, OFFSET/ties, parameters, EXISTS and UPDATE, not candidate execution or JDBC metadata. Receipt checks/1794292693968392878-4.json; sqlite-oracle.py and sqlite-oracle.log.

  • Diff check and formatting of all six changed Go files passed with empty logs: checks/1794293002592807008-3.json and checks/1794293002643406231-3.json. Source remains clean at the frozen head.

  • Considered current PR-body reports of full planner normal/race/vet checks, two 62/62 public comparison runs and targeted multi-CN/pruning checks as reported validation. Their raw execution artifacts were not supplied. Frozen CI build/UT/SCA/coverage is pending and was not counted as passing.

  • Isolation preflight passed. The local focused planner attempt stopped before compilation/test execution because cgo/libmo.so is missing: checks/1794292744330243045-3.json and planner-focused.log. This is an environment diagnostic, not a product test result.

Limitations:

  • Local MatrixOne package and service execution was unavailable with the supplied read-only checkout/native prerequisites; independent checks cover source and expected-value oracles. Author-reported execution and pending CI were not independently reproduced.

  • Partitioned-table correlation was not independently exercised. The author's narrow fanout control does not establish general throughput or peak-memory bounds; mixed-path candidate materialization remains proportional to join fanout.

  • Nested/dynamic, unsafe-expression and other explicitly rejected pagination forms remain NYI; no broader support claim is made.

@XuPeng-SH

XuPeng-SH commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 60c2aca70c8e0596ab12abbd021a5f8ec6da504d

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: 60c2aca70c8e0596ab12abbd021a5f8ec6da504d

Assessment: approve

The rewrite preserves pagination at the correlation boundary using existing partition/window, projection and aggregate owners. Equality-key sharing and per-outer post-join ranking serve distinct supported cases; markers and rank-ordered LEAD preserve empty/NULL and OFFSET semantics. The added complexity is justified within the explicit NYI and fanout limits. No actionable findings remain.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Reviewed the complete eight-file change, baseline and affected consumers, all four discussion entries and linked issue #32441.

  • Source/evidence audit and diff check passed. All eight feature files and eight execution consumers match the supplied prior reviewed head; helper bodies, six-file formatting and all 62 SQL/result statements verified. Receipts: checks/1794299415462089008-3.json, checks/1794299415668874879-3.json.

  • Reused the supplied prior independent SQLite expected-value report for identical inputs and attributed current author planner normal/race/static, public comparison, multi-CN, pruning and narrow fanout results.

  • Terminal commands, source fingerprints, exits and retained logs reconciled in validation-ledger.json; checkout unchanged.

Limitations:

  • No fresh local MatrixOne/native execution; cgo/libmo.so is absent and raw author runtime logs were not supplied. Pending CI build/UT/SCA/coverage checks are not passes.

  • Mixed-path materialization remains proportional to matching join fanout; the supplied narrow control does not establish general throughput or peak-memory bounds. Partitioned-table correlation was not independently exercised.

  • Explicitly rejected nested, dynamic, unsafe-expression and other unsupported shapes remain NYI; no broader support claim is made.

@matrix-meow matrix-meow added size/XXL Denotes a PR that changes 2000+ lines and removed size/XL Denotes a PR that changes [1000, 1999] lines labels Nov 10, 2026
@XuPeng-SH

XuPeng-SH commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: d4e606ecd91ca0fa4b3ff250e368985e322c6e85

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: d4e606ecd91ca0fa4b3ff250e368985e322c6e85

Assessment: approve

The rewrite preserves pagination at the correlation boundary while reusing existing window, projection and aggregate owners. Separate ranking paths and markers are justified by duplicate, OFFSET and empty/NULL semantics. No actionable findings remain.

Model: gpt-6.1-sol / max

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

Validation:

  • Reviewed all eight changed files, baseline, affected consumers and six discussion entries. Source/format audit passed: checks/1794314126399798288-2.json; source-audit.log.

  • Independent SQLite oracle matched 77 queries and 291 expected rows; all 154 command batches align: checks/1794313849246184497-2.json; sqlite-oracle.log.

  • Isolation preflight passed: checks/1794313797506682547-2.json; preflight.log.

  • Considered author-reported planner normal/race/static, SQL and binary-protocol checks; raw logs were unavailable. Frozen CI reports eight successful, nine skipped, three neutral and eight in-progress checks.

Limitations:

  • No local MatrixOne execution: native prerequisites are absent. SQLite verifies expected values, not MatrixOne errors or protocol metadata.

  • Explicit NYI restrictions and fanout costs remain. Historical timings provide no general performance bound; partitioned-table correlation was not independently exercised.

@mergify

mergify Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@XuPeng-SH

XuPeng-SH commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 4e681ac8eb39bd9cef9b98175a354e7889b042ee

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: 4e681ac8eb39bd9cef9b98175a354e7889b042ee

Assessment: approve

The guarded MIN/MAX normalization reuses existing aggregate and binder owners to avoid ranking eligible integer extrema. NULL-order, outer-identity and fallback constraints preserve pagination semantics. No actionable findings remain.

Model: gpt-6.1-sol / max

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

Validation:

  • Reviewed all eight changed files and reconciled nine discussion entries. Source/format audit passed: source-audit.log; checks/1794317788059604285-2.json.

  • Independent SQLite oracle matched 81 queries/319 rows. Algebraic checks covered 9,160 eligible extremum cases and four correlation/identity controls. Receipts and logs are reconciled in validation-ledger.json.

  • Isolation preflight passed: preflight.log; checks/1794317461992533263-2.json.

  • Considered author-reported planner, SQL, forced two-CN and performance checks; raw logs were unavailable. Frozen CI: eight successful, nine skipped, three neutral and eight in progress.

Limitations:

  • No local MatrixOne/native execution; native prerequisites are absent. Independent oracles verify values/algebra, not planner execution, protocol metadata or MatrixOne errors.

  • Performance evidence is fixture-specific. General concurrency, spill, peak-memory capacity and partitioned-table correlation remain unverified.

This branch was successfully deployed

No deployments
ci — 33f7d704 Deployed Nov 10, 2026 by XuPeng-SH
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 kind/enhancement size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: correlated ORDER BY LIMIT returns NULL for a matching row

2 participants