Skip to content

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

Closed

Description

@ck89119

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

  1. added
    kind/bug
    on Oct 22, 2026
  2. added
    severity/s0
    and removed on Oct 22, 2026
  3. added a commit that references this issue on Oct 23, 2026
    bc84bd1
  4. slyunnn commented on Oct 26, 2026

    @slyunnn

    Regression and extended verification for #30819 (2026-10-26)

    Verification Environment

    • MatrixOne 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.
    • Topology: 2 CN / 1 TN / 1 Log service / Proxy. The actual fixture queries and EXPLAIN were run over MySQL text-protocol connections through Proxy 6001, CN1 16001, and CN2 16002 separately.
    • Associated fix: MatrixOne PR #30828, merge commit bc84bd142600b745503e225cb89cb1526df8d35e — fix(plan): eliminate unobserved sorts below scalar COUNT. This commit is an ancestor of the tested main.

    What Was Covered

    • OK — The issue's proposed five-row DISTINCT(category,name) fixture returned COUNT(1)=4. Its reachable EXPLAIN plan contained the DISTINCT aggregate and scan but no Sort; the only-ORDER BY-removed control had the same count and plan shape at all 3 endpoints.
    • OK — Nullable and empty-input semantics: COUNT(name)=3; after truncation, ordered and unordered counts and nullable count all returned 0.
    • OK — A six-column DISTINCT over a two-table JOIN likewise preserved all grouping keys and removed the unobservable ordinary-column Sort in a minimal join-shaped control.
    • OK — Pagination/observable-order controls retained Sort for LIMIT 2, LIMIT 2 OFFSET 1, and an outer ordered LIMIT query; paginated counts returned 2.
    • Not covered — The original production SQL and production-scale plan were not supplied as a runnable fixture. No business-query latency, memory, or speedup measurement is claimed.
    • Not covered — Runtime fault/volatile-expression and shared-plan paths were not independently fault-injected in this run; the merged planner UT/BVT owns those guards.

    Findings

    The reported redundant Sort no longer appears for the issue's minimized fixture or a comparable multi-column join shape on current main. A separate ORDER BY lower(name) exploration still retained Sort; 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 EXPLAIN shape and count semantics are observable with 5 rows. The historical estimate of 159525.31 sorted 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. The 6 targeted TestCount* 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-Sort planner defect on the tested main: the issue's minimized reproducer and a join-shaped control no longer retain an unobservable Sort, 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.

  5. Ariznawlll commented on Oct 26, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:官方 main,完整 commit:861a2c4cb68961d8b6b01f18e0aa6ac52a3a505f。
    • 修复:MatrixOne PR #30828,合入提交 bc84bd142600b745503e225cb89cb1526df8d35e,已核实为本轮 main 的祖先。
    • 部署方式:独立本机 1 LogService / 1 TN / 1 CN;从该 SHA 的干净 worktree 构建 mo-service,MySQL 协议直连独立端口 43001,git_version() 返回 861a2c4cb6。另有 issue 中 2026-10-26 的 2 CN / 1 TN / 1 LogService / Proxy 三入口独立 QA 记录,本评论的次数不借用其结果。
    • 测试日期:2026-10-26。

    原问题验证

    使用 issue 给出的五行 DISTINCT(category,name) 派生表,在三个新建数据库中分别执行带内层 ORDER BY category,name 和去掉该排序的等价 COUNT 查询。两者每轮均返回 4;带排序语句的 EXPLAIN 可达计划均无 Sort,没有再保留对外层 COUNT 不可观察的排序。结果:3/3。

    Happy Path 覆盖

    1. COUNT(1):带/不带不可观察排序均为 4;重复值和多列 DISTINCT 未被错误折叠。
    2. COUNT(name):NULL 不计入,返回 3。
    3. ORDER BY id DESC LIMIT 2 OFFSET 1 的 COUNT 返回 2,计划仍含 Sort,可观察排序未被误删。
    4. 删除五行后,原 COUNT 返回 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,并在脚本中对计划节点逐轮断言。
    • 修复 PR 与 CI 记录。

    测试结论

    测试通过。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions