Repository navigation
Description
Is there an existing issue for the same bug?
- I have checked the existing issues.
Searched both open and closed issues for COUNT/sort, redundant sorting, and ORDER BY in derived tables. #30164 concerns implicit fulltext relevance ordering, and #26768 is a broader optimizer roadmap; neither tracks this specific COUNT-consumer case.
Branch Name
Observed on v4.1.5. A focused fix is intended for main; the minimized fixture below has not yet been executed on main.
Commit ID
Observed production binary: 864583c9767612257b7d2b0723bf0a6cb5a78f8a (v4.1.5).
Current implementation baseline: 8f9c50468ea06cd52554f2a5ef94cfb137d930f6 (main). This is not a claim of runtime reproduction on that revision.
Other Environment Information
- Production: Linux amd64, Go 1.26.4, three CNs with 12 CPU cores / 128 GiB memory each.
- Evidence collected on 2026-10-22 using ordinary EXPLAIN / EXPLAIN VERBOSE.
- No EXPLAIN ANALYZE or business-query rerun was performed during this investigation.
Actual Behavior
An application wraps a multi-column DISTINCT query in an outer COUNT to obtain a total. The inner query orders by ordinary selected columns but has no LIMIT/OFFSET:
SELECT COUNT(1)
FROM (
SELECT DISTINCT ...
FROM ...
ORDER BY file_type, file_name
) AS count_source;The actual production EXPLAIN retains this normalized shape:
Project
Aggregate: count(1)
Sort: file_type, file_name
Aggregate: DISTINCT over six selected columns
Join / filtered scans
The Sort has an estimated output of 159525.31 rows. This is an optimizer estimate, not an actual execution measurement.
A read-only control removed only the inner ORDER BY from the same production statement and ran ordinary EXPLAIN again. The Sort disappeared while the multi-column DISTINCT and join structure remained:
Project
Aggregate: count(1)
Aggregate: DISTINCT over the same six selected columns
Join / filtered scans
The ordering is not observed by the outer COUNT, so retaining it introduces unnecessary blocking sorting and associated state. This issue does not attribute the entire production query duration or cluster memory usage to that Sort, and no speedup has been measured.
Expected Behavior
The optimizer should eliminate the inner Sort when it can prove that its order is unobservable to the COUNT consumer, without requiring the application to rewrite its SQL.
Preserve:
- the input row set and all DISTINCT keys;
- COUNT NULL/duplicate/empty-input semantics and result metadata;
- observable expression evaluation, including volatile or potentially failing expressions hidden behind aliases;
- pagination, window/ordered consumers, and order required by another shared-plan consumer.
This should be a semantic planner rule, not a SQL-text or customer-schema special case. Do not remove all derived-table ORDER BY clauses indiscriminately.
Steps to Reproduce
The evidence above comes from the original production query and its ORDER-BY-free EXPLAIN control. The following is a proposed independent, minimized fixture for development; it has not yet been executed and is not presented as an already validated reproduction:
CREATE TABLE count_sort_repro (
id INT PRIMARY KEY,
category VARCHAR(32),
name VARCHAR(32)
);
INSERT INTO count_sort_repro VALUES
(1, 'a', 'x'),
(2, 'a', 'x'),
(3, 'a', NULL),
(4, 'b', 'y'),
(5, NULL, 'z');
EXPLAIN
SELECT COUNT(1)
FROM (
SELECT DISTINCT category, name
FROM count_sort_repro
ORDER BY category, name
) AS s;
-- Equivalent control: only the unobserved ORDER BY is removed.
EXPLAIN
SELECT COUNT(1)
FROM (
SELECT DISTINCT category, name
FROM count_sort_repro
) AS s;
DROP TABLE count_sort_repro;For this fixture, both queries should count the same four distinct tuples. Validate the smallest fixture against the baseline, then assert that the optimized reachable plan removes only the redundant Sort. If the minimized fixture takes a different existing rewrite path, retain the smallest join/derived-query shape needed to reproduce the observed plan.
Additional information
Acceptance should include typed planner regression coverage and small SQL result tests, with negative controls for LIMIT/OFFSET/Top-K, nullable counts, order-dependent consumers, unsafe expressions, and shared subplans. No wall-clock threshold is needed in UT/BVT.
Related but different: #27889 removes constant ordering after singleton/primary-key grouping. It does not cover an outer COUNT over a derived table sorted by ordinary varying columns as reported here.
Keep this fix separate from EXISTS/SEMI join predicate normalization, TRIM/index matching, and query cancellation/pipeline lifecycle issues.
Activity
fix(plan): eliminate unobserved sorts below scalar COUNT (#30828)
slyunnn commentedon Oct 26, 2026
Regression and extended verification for #30819 (2026-10-26)
Verification Environment
main:4769417cdce5531c9771644eca49f1e71d8f654c—fix(plan): preserve replayable defaults and dump fingerprints (#31067). The binary was rebuilt and restarted from this commit;git_version()matched on all tested SQL routes.2 CN / 1 TN / 1 Log service / Proxy. The actual fixture queries andEXPLAINwere run over MySQL text-protocol connections through Proxy6001, CN116001, and CN216002separately.bc84bd142600b745503e225cb89cb1526df8d35e—fix(plan): eliminate unobserved sorts below scalar COUNT. This commit is an ancestor of the testedmain.What Was Covered
DISTINCT(category,name)fixture returnedCOUNT(1)=4. Its reachableEXPLAINplan contained theDISTINCTaggregate and scan but noSort; the only-ORDER BY-removed control had the same count and plan shape at all3endpoints.COUNT(name)=3; after truncation, ordered and unordered counts and nullable count all returned0.DISTINCTover a two-tableJOINlikewise preserved all grouping keys and removed the unobservable ordinary-columnSortin a minimal join-shaped control.SortforLIMIT 2,LIMIT 2 OFFSET 1, and an outer orderedLIMITquery; paginated counts returned2.Findings
The reported redundant
Sortno longer appears for the issue's minimized fixture or a comparable multi-column join shape on currentmain. A separateORDER BY lower(name)exploration still retainedSort; the merged rule intentionally requires a proof that removing key evaluation is safe. This does not show that the reported ordinary selected-column case regressed. The exact historical production statement remains unverified on this local fixture.Large-data regression required: No for correctness of the planner rule. The
EXPLAINshape and count semantics are observable with5rows. The historical estimate of159525.31sorted rows was not an actual execution measurement, and no QPS/memory claim is being made; a production performance acceptance would need the original workload separately.MOTR / BVT Coverage
The merged PR already contains typed planner tests (
count_sort_elimination_test.go) and distributed SQL coverage (count_derived_sort.sql) for positive and negative cases. The6targetedTestCount*planner tests passed locally with the rebuilt revision's native dependencies. The full distributed SQL file was not rerun in this verification. No duplicate MOTR test or weekly PR change was made for this already-covered fix.Final Conclusion
Fixed for the reported redundant-
Sortplanner defect on the testedmain: the issue's minimized reproducer and a join-shaped control no longer retain an unobservableSort, while observable ordering remains intact. The original production SQL was not supplied, so its latency or memory improvement is a separate, unmeasured performance question—not a blocker to this functional verdict.Ariznawlll commentedon Oct 26, 2026
测试版本
main,完整 commit:861a2c4cb68961d8b6b01f18e0aa6ac52a3a505f。bc84bd142600b745503e225cb89cb1526df8d35e,已核实为本轮 main 的祖先。mo-service,MySQL 协议直连独立端口43001,git_version()返回861a2c4cb6。另有 issue 中 2026-10-26 的 2 CN / 1 TN / 1 LogService / Proxy 三入口独立 QA 记录,本评论的次数不借用其结果。原问题验证
使用 issue 给出的五行
DISTINCT(category,name)派生表,在三个新建数据库中分别执行带内层ORDER BY category,name和去掉该排序的等价 COUNT 查询。两者每轮均返回4;带排序语句的EXPLAIN可达计划均无Sort,没有再保留对外层 COUNT 不可观察的排序。结果:3/3。Happy Path 覆盖
COUNT(1):带/不带不可观察排序均为4;重复值和多列 DISTINCT 未被错误折叠。COUNT(name):NULL 不计入,返回3。ORDER BY id DESC LIMIT 2 OFFSET 1的 COUNT 返回2,计划仍含Sort,可观察排序未被误删。0;每轮均清理独立测试库。Unhappy Path 覆盖
本缺陷没有错误输入路径;用上述分页/空表/NULL 对照防止优化过度。生产原始六列业务 SQL 未提供可运行数据,因此未声称生产规模耗时或内存收益;本轮验证的是 issue 所述可观察的计划缺陷与结果合同。
白盒验证
检查修复已包含 typed planner 回归和分布式 SQL 正反例;本轮未重跑整套 Go UT/race。前述独立 QA 已运行 6 个定向
TestCount*planner 测试,不把它冒充本轮执行。回归测试
修复 PR 已包含 count_derived_sort.sql 与 typed planner 测试,涵盖正反排序、分页、NULL、空表、JOIN/多列 DISTINCT 和失败表达式;故未再提交重复 MOTR case。PR 的 UT、SCA、Proxy BVT、multi-CN BVT、Coverage、
CI Required均显示成功;未把整套 suite 宣称为本地重跑。测试证据
/private/tmp/mo-six-qa-20261026/qa/verify_sql.py;输出30819 PASS 1/2/3 count=4 nullable=3 page=2 empty=0 no-inner-sort,并在脚本中对计划节点逐轮断言。测试结论
测试通过。