Skip to content

fix(plan): eliminate unobserved sorts below scalar COUNT - #30828

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
ck89119:issue-30819-main
Oct 23, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
ck89119:issue-30819-main

Conversation

@ck89119

@ck89119 ck89119 commented Oct 22, 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 #30819

What this PR does / why we need it:

A scalar COUNT can retain an unnecessary derived-table Sort, including this shape:

SELECT COUNT(*)
FROM (
    SELECT DISTINCT category, name
    FROM items
    ORDER BY category, name
) AS s;

Add a narrowly scoped planner rule after simple-projection cleanup. It removes a direct, unbounded Sort input only when the scalar aggregate contains ordinary COUNTs and both the ordering keys and COUNT arguments have proven-safe evaluation. It follows aliases and DISTINCT group keys through their current reachable producers, rather than relying on potentially stale binding-tag ownership.

The rewrite preserves the complete DISTINCT tuple and only rewires the COUNT consumer; it does not mutate a Sort still used by another consumer. Pagination, rank, COUNT DISTINCT, mixed aggregates, unsafe/volatile expressions, window-derived keys, unproven producer boundaries, and SQL_CALC_FOUND_ROWS remain conservative. This does not broaden the existing singleton-group sort rule.

Validation (Go 1.27.1, darwin/arm64):

  • Before the fix, six positive planner regressions failed because the reachable Sort remained. After the fix, positive and negative cases pass, including alias provenance, multiple counts, shared consumers, and outer ordering.
  • Full pkg/sql/plan tests via .agents/skills/mo-dev/scripts/mo-cgo-test, with -count=1: passed; package statement coverage 85.3%, new rule 97.3% (73/75 statements).
  • Worktree-local native build and full mo-service build: passed.
  • go vet ./pkg/sql/plan and changed-code golangci-lint: passed.
  • New test/distributed/cases/dml/select/count_derived_sort.sql: generated expected results with mo-tester, manually checked counts/errors/metadata, then passed normal comparison and same-instance rerun (30/30 each). Covers duplicates, NULLs, empty input, multi-column DISTINCT, JOIN, pagination, windows, failing casts, ordinary ordering, and repeated prepared execution. Database cleanup was verified after each run.
  • A live EXPLAIN confirms COUNT → DISTINCT aggregate → scan, without Sort.

This PR targets main only, with no release-branch backports. It removes the proven redundant work; it does not claim measured latency/memory gains or resolve the separate join, cancellation, and long-running-query issues from the original investigation.

…branches

removeUnobservedCountSorts proved the COUNT arguments and ORDER BY keys
total, but a Sort may also hold the last unreferenced binding of a LEFT
JOIN right branch. Dropping such a Sort let removeEffectlessLeftJoins
prune that branch and swallow runtime errors from its ON predicates or
scan filters, so a failing CAST above a scalar COUNT returned rows
instead of raising error 20203.

Track, per binding tag, the ancestor-level references that actually
protect it from join pruning (OnList references excluded, mirroring
removeEffectlessLeftJoins counting). When a Sort releases the last
protection of a binding produced below it, allow the elimination only
if every LEFT JOIN right branch on the release path is provably
effect-free to prune: plain scan/project/join nodes whose expressions
are all total and free of volatile or side-effecting payloads.
Otherwise keep the Sort.
@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 Oct 22, 2026
@ck89119
ck89119 marked this pull request as ready for review October 23, 2026 03:55
@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 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.

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

Commit: 9010f2ee41d359e06553d66c1a7e4fad04ca41d7

Assessment: approve

Reviewed the complete five-file delta and affected planner owners. The narrow COUNT-consumer rewrite reasonably removes unobserved ordering while preserving DISTINCT, pagination, unsafe expressions and diagnostic branches. It reuses established expression-safety proofs without adding an execution path or persistent state. No actionable defects remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • Verified the frozen head and unchanged source checkout. Independently reconciled 194 native build inputs, 63 artifacts and the build-owner receipt/log; isolation preflight passed.

  • Eight additional SQL planner probes passed on the candidate and a control using the exact merge-base query_builder.go. Comparisons preserved reachable non-sort nodes, join types, diagnostic functions and DISTINCT key widths.

  • Five planner benchmarks ran with three samples per variant. SELECT/DDL allocation counts were unchanged; INSERT added 184 bytes and three allocations per plan; the target COUNT DISTINCT case saved 2,056 bytes and 31 allocations.

  • Independently checked BVT expected counts, NULL/duplicate handling, pagination, errors, prepared execution and cleanup. The frozen CI snapshot reports successful UT, coverage, SCA and both BVT groups.

  • Reconciled eight completed check receipts with retained logs and overlay hashes. Evidence is retained under /home/xupeng/.local/state/mo-bot/jobs/6865282813a8d6163f559e81/attempt-1 in validation-audit.json, probe-analysis.json, benchmark-analysis.json and review-record.json; final-audit.log confirms reconciliation.

Limitations:

  • Additional local checks exercised planning, not live SQL execution. Raw author/CI logs were not supplied; author-reported BVT runs were not independently replayed.

  • Benchmark timings varied; no production latency or execution-memory improvement is claimed.

  • The linked issue body was absent from frozen evidence; review covered the concrete contract and exclusions recorded in the PR.

@mergify mergify Bot added the queued label Oct 23, 2026
@mergify

mergify Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-23 05:14 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ❌ Checks failed · in-place
  • 🚫 Left the queue — 2026-10-23 06:48 UTC · at fd864af9de7d727b5ecf60c26b5446e39f2e00fd

This pull request spent 1 hour 34 minutes 2 seconds in the queue, with no time running CI.

Reason

The merge conditions cannot be satisfied due to failing checks

  • CI Required

Failing checks:

Hint

You may have to fix your CI before adding the pull request to the queue again.
If you update this pull request, to fix the CI, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

@mergify mergify Bot added dequeued and removed queued labels Oct 23, 2026
@XuPeng-SH
XuPeng-SH merged commit bc84bd1 into matrixorigin:main Oct 23, 2026
49 of 52 checks passed
@ck89119
ck89119 deleted the issue-30819-main branch October 23, 2026 06:51

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

dequeued 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.

[Bug]: COUNT over a derived table retains unobservable ORDER BY

3 participants