Skip to content

[Performance]: COUNT(DISTINCT) forced to single stage and one CN, 34x slower than GROUP BY #32060

Closed

Description

@Ariznawlll

Summary

COUNT(DISTINCT col) with a single high-NDV group is planned as a single-stage, ForceOneCN distinct aggregate — while the semantically identical GROUP BY col (then count) gets the parallel shuffle path. On a 10M-row / 10M-distinct-value table the DISTINCT form takes 481 ms vs 14 ms for the GROUP BY form (34×). The gap is structural: the distinct-agg path forfeits both multi-core parallelism and the partition-shuffle trick, and it also defeats the per-object min/max fast path that makes plain scans of the same column 2ms.

Reproduction (main@HEAD, c6683bd)

CREATE TABLE big8m (k INT PRIMARY KEY, k2 INT, KEY idx_k2 (k2));  -- 10,000,000 rows, k unique
-- FLUSH + ANALYZE

SELECT COUNT(DISTINCT k) FROM big8m;
-- Mon Mar-style: Aggregate[3] -> Aggregate[2] (hashmapSize=10000000) -> Aggregate[1] -> Table Scan
-- ~481 ms (543 ms at first run, 320 ms warm on 8M rows; consistently ~0.5 s)

SELECT SUM(g) FROM (SELECT k AS g FROM big8m GROUP BY k) t;   -- semantically comparable volume
-- partition shuffle + parallel group: ~14 ms

SELECT MIN(k), MAX(k) FROM big8m;                            -- zone-map fast path
-- ~2 ms

Verified row equality both ways (GROUP BY result has exactly 10,000,000 rows; both count the same distinct set). The scan baseline SELECT SUM(k2) FROM big8m is 13 ms, so the 481 ms is all in the distinct agg execution, not I/O.

EXPLAIN VERBOSE shows the reason directly: the distinct plan carries dop=0 blockNum=123 hashmapSize=10000000 on a single aggregate chain with outcnt=1000000-style intermediate materialization, while the GROUP BY form gets shuffle-partitioned aggregation. Grep-confirmed gate: pkg/sql/plan/stats.go:3316 —

if node.NodeType == plan.Node_AGG && RequiresSingleStageDistinctAgg(node) {
    ...
    setNodeDOP(p, rootID, 1)      // dop forced to 1
    node.Stats.ForceOneCN = true  // and pinned to one CN

Root cause

CalcNodeDOP treats all distinct aggregates as non-partitionable and forces dop=1 + single-CN. That is only necessary when the DISTINCT-uniqueness cannot be preserved by re-partitioning on the group key — i.e. when there are multiple group keys with multiple distinct aggregates where row-level re-grouping could double count. For the single-distinct / no-group-key case (and generally for a distinct on the shuffle key), a two-phase (local distinct → shuffle by value → global distinct) is exact and parallelizable — the same trick the GROUP BY path already uses.

The plan also shows the whole 10M-entry distinct-set hashmap on one core — memory-pressure-wise this is the worst possible placement on a multi-core box.

Suggestions

  1. When RequiresSingleStageDistinctAgg is true only because of a single distinct aggregate with zero or simple group keys, allow the shuffle-by-distinct-value two-phase plan (same machinery the GROUP BY path uses), restoring multi-core dop.
  2. At minimum: for high-NDV estimates (hashmapSize > some threshold), warn or fall back, since the current plan's one-core 10M-entry hashmap is both 34× slower and a memory ceiling.

Environment

MO multi-CN local launch config, main@HEAD c6683bd, host 16GiB. Numbers are single-query wall clock with warm page cache; ratios stable across 3 reruns.

Activity

  1. added
    kind/bug
    on Nov 3, 2026
  2. added this to the MO-202611 milestone on Nov 3, 2026
  3. added theissue type on Nov 3, 2026
  4. gouhongshen commented on Nov 13, 2026

    @gouhongshen
    Contributor

    Existing-fix audit

    Assessment: already fixed on current main

    Fixed evidence

    Merged #29136 / a1220de introduced the COUNT exemption and unary distinct-key preaggregation path. Subsequent merged #31250 / fbfba33 preserves DISTINCT statistics. Proof: pkg/sql/plan/distinct_agg_test.go tests TestOptimizeSingleCountDistinctBuildsLocalPreDedupPath and TestOptimizeSingleCountDistinctPathSelectionAndFallbacks assert shuffle, parallel DOP, and global aggregation selection. Merged #30998 / 70e48cb retains docs/evidence/30998-tuple-distinct/perf-1-unary-physical.txt showing unary COUNT DISTINCT executing with mcpu=8 and shuffle; perf-summary.json records approximately 23.6 ms on its separate fixture.

  5. XuPeng-SH commented on Nov 13, 2026

    @XuPeng-SH
    Contributor

    QA 交接:单一高 NDV COUNT(DISTINCT) 并行路径

    先更正上条 audit 的来源:#29136 是 HNSW cosine 修复,不是 DISTINCT 优化。已核对的实际 main 合并项为 #27790,merge SHA 4ec5bca64d93483d6f28256060ecabaff12c8dc2:局部键去重后按 DISTINCT key shuffle,再完成全局去重/count;#31250(fbfba33b04ccfda3ca40815f2a9668e0da34ea0d)补充 DISTINCT 统计传播及分区复用。

    当前 main 的 distinct_agg_test.go 保留全局单一 COUNT DISTINCT、多个物理 owner、DOP 与保守 fallback 测试。#27790 的完整讨论中,早期 pre-shuffle MergeGroup 瓶颈及缺失 NDV fallback 缺陷已修复,最终评审 #27790 (review) 明确认可修复和设计。未见本 issue 当前适用的已验证反例或未完成开发 follow-up,交 QA 复核,而非验收通过。

    真实证据与限制:#30998(merge 70e48cbef1235a8ef4b6c887cb37b0947bace714)保留的 docs/evidence/30998-tuple-distinct/perf-1-unary-physical.txt 显示历史 unary 控制的 mcpu: 8 和 shuffle,perf-summary.json 中该独立 fixture 的 candidate 中位数约 23.568 ms、相对 baseline +5.06%,不是原报告 10M fixture 的性能改善证明。该 PR 本身主要改 tuple,不能当成 unary 优化来源。本轮仅远端核对代码、记录及历史证据,未运行测试,也未复现原 481 ms/14 ms 比值;不能承诺所有 DISTINCT 都多 CN 或达到 GROUP BY 时延。#32368/#32372 是独立正确性修复,不把它们视作本性能问题的修复证明。

    建议 QA 在原 10M 数据与统计条件下检查实际物理计划、DOP/shuffle、准确计数、延迟及内存;补一/多 CN、DOP=1/多 DOP、NULL/空输入、低/缺失 NDV、重复/倾斜、spill 和 prepared reuse 对照。混合 aggregates、SUM(DISTINCT)、不支持类型/表达式等保守 fallback 不属于承诺的加速范围;比较计数时请使用真正等价的 COUNT/GROUP BY 基准,原文 SUM(g) 不是 COUNT 的值等价表达式。

  6. Ariznawlll commented on Nov 16, 2026

    @Ariznawlll
    CollaboratorAuthor

    测试版本

    原问题验证

    EXPLAIN 已不再是单个高 NDV distinct aggregate 被强制 ForceOneCN/dop=1 的计划:局部按 distinct key 去重后,经 hash shuffle 进入全局 distinct/count。10M 行高 NDV 数据的 COUNT(DISTINCT k) 返回精确结果。

    Happy Path 覆盖

    1. 100k 行高 NDV 列:COUNT(DISTINCT k)=100000,与 value-equal GROUP BY 计数一致;低 NDV 列返回 10。
    2. 10M 行原问题规模计数正确;本地单次高 NDV 查询约 449–622ms。
    3. NULL 被正确跳过、空输入返回 0、50k 个重复值叠加 100 个不同值时返回 100。
    4. prepared 使用不同参数及重复执行均返回精确计数。

    Unhappy Path 覆盖

    覆盖空表、NULL、严重重复倾斜及 prepared 参数边界,结果均符合 SQL 语义;没有把异常或部分结果当作正确输出。

    白盒验证

    核对 #27790 的局部 dedup/hash shuffle 两阶段 distinct 路径,以及 #31250 的 DISTINCT 统计与 aggregate partition 复用。计划形态有上游 pkg/sql/plan distinct aggregate 单测约束,本地 SQL 验证聚焦结果语义。

    回归测试

    已追加 matrixorigin/motr#349:14_issue_regression/issue_32060_distinct_count(25 语句)。录制后普通 diff 模式 3 并发连续两轮通过;PR 4 项 CI 全部成功。用例标记 @target-branch: main。

    验证边界

    PK 上的 GROUP BY 可能走元数据短路,不能把其延迟直接当作等价 distinct 性能基准。本次没有将本地结果表述为完整 34 倍提升或多 CN 生产压测验收;验证结论针对已合入的两阶段计划及其正确性。

    测试结论

    测试通过。

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

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triage

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions