Repository navigation
fix(plan): eliminate unobserved sorts below scalar COUNT - #30828
Conversation
…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.
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? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
Merge Queue Status
This pull request spent 1 hour 34 minutes 2 seconds in the queue, with no time running CI. ReasonThe merge conditions cannot be satisfied due to failing checks
Failing checks: HintYou may have to fix your CI before adding the pull request to the queue again. Waiting for any of
All conditions
Tick the box to put this pull request back in the merge queue (same as
|
What type of PR is this?
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:
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):
pkg/sql/plantests 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).mo-servicebuild: passed.go vet ./pkg/sql/planand changed-codegolangci-lint: passed.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.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.