Skip to content

[Enhancement]: Add adaptive partition-parallel execution for exact DISTINCT aggregates #27720

Open

Description

@XuPeng-SH

Motivation

Exact DISTINCT aggregation currently derives most of its parallelism from ownership of the final GROUP BY key. This works well when there are enough balanced groups, but it does not provide robust parallelism when the final group cardinality is small or skewed.

Examples:

SELECT COUNT(DISTINCT user_id) FROM events;

SELECT region_id, COUNT(DISTINCT user_id)
FROM events
GROUP BY region_id;

In the first query there is only one final group. In the second query, a few regions or one hot region can own most rows. Hashing only by region_id therefore limits useful aggregate parallelism to the number and balance of regions, regardless of DOP. Increasing DOP alone cannot remove that bottleneck.

The current exact argument state also uses an ordered per-group skiplist. Admission requires key encoding, comparisons, pointer traversal, and retained-key storage. Partial-state merging can add another pass over those keys. These costs grow with DISTINCT NDV even when the final number of groups remains small.

The optimization in #27693 improves the balanced, many-group path by assigning each complete group to one owner and avoiding an expensive downstream exact-state merge. This issue covers the complementary execution shapes that cannot obtain enough parallelism from the final group key alone.

Required invariant

Exact DISTINCT work must be distributable by the identity being deduplicated, not only by the final aggregate group:

canonical key = (active GROUP BY keys, DISTINCT arguments)

Every equal canonical key must reach exactly one final deduplication owner, while different keys—even within one hot aggregate group—may be processed concurrently. Final aggregate results must remain bit-for-bit equivalent to the existing exact semantics.

Proposed execution model

Introduce an adaptive partition-parallel path for mergeable exact DISTINCT aggregates:

  1. Project and encode the canonical (group keys, DISTINCT arguments) key once per input row or vector batch.
  2. Compute its stable hash once and carry/reuse it across local admission, exchange, and final partitioning.
  3. Perform optional thread-local batch/vectorized deduplication.
  4. Partition surviving keys by the canonical-key hash, rather than only by the final group key.
  5. Finalize partitions concurrently; each partition performs exact deduplication independently.
  6. Feed unique (group keys, DISTINCT arguments) rows into the ordinary final aggregate by group key.

The implementation should reuse existing pipeline, shuffle, hash-table, and spill ownership primitives where their contracts fit. A new framework is justified only if those contracts cannot express independently owned DISTINCT partitions with lower total complexity.

Adaptive path selection

No single topology is optimal for every data shape. Planning and/or bounded runtime sampling should select among:

  • Small input or low NDV: keep the simple local path and avoid partition machinery.
  • Enough balanced final groups: keep the group-owner fast path introduced by perf: parallelize high-cardinality mixed DISTINCT aggregation #27693.
  • One/few groups or high group skew: partition by (group keys, DISTINCT arguments) to expose key-level parallelism.
  • High duplicate ratio: deduplicate locally before exchange to reduce CPU and network bytes.
  • Nearly all keys unique: avoid repeated local hash probes that cannot remove meaningful input; append/partition directly and deduplicate during partition finalization.

Selection must be based on general cardinality, skew, memory, and ownership estimates—not query text, benchmark names, fixed schemas, or issue-specific constants. Missing or unreliable statistics require a conservative fallback.

Correctness and ownership requirements

The design document must be reviewed before implementation and define:

  • canonical equality and hashing for fixed/variable-width values, multiple DISTINCT arguments, NULL, constants, decimals, collations, floating signed zero/NaN behavior, and hash collisions;
  • applicability to COUNT(DISTINCT) and the explicit boundary for other DISTINCT aggregates;
  • sharing of one deduplication pipeline by aggregates with identical DISTINCT arguments and compatible filters;
  • behavior with aggregate filters, grouping sets, empty input, one/multiple CNs, DOP=1, cancellation, errors, Reset/Free, and operator reuse;
  • ownership and lifecycle of local tables, partition buffers, exchange batches, final tables, and any spill state;
  • bounded memory accounting and integration with Support bounded distinct-key spill for high-NDV exact DISTINCT aggregates #27698, without creating a second incompatible spill mechanism;
  • prevention of duplicate hash computation, unbounded per-row allocation, per-key goroutines, locks, or high-cardinality metrics;
  • planner cost inputs, including effective owner count and skew—not only global argument NDV or final group count.

Performance requirements

  • A single-group high-NDV COUNT(DISTINCT) must use multiple workers when DOP > 1.
  • Few-group and hot-group workloads must scale through canonical-key partitions rather than being capped by final group count.
  • The existing balanced many-group Q10 path covered by perf: parallelize high-cardinality mixed DISTINCT aggregation #27693 must not regress materially; the adaptive selector should retain that topology when it is cheaper.
  • Local pre-deduplication must reduce exchanged rows/bytes when duplicates are common and avoid material overhead when keys are nearly unique.
  • Common fixed-width keys should use a compact vectorized/hash-table path; an ordered skiplist should not remain mandatory when aggregate semantics require only equality.
  • CPU, allocations, peak accounted memory, exchanged rows/bytes, and partition skew must be measured before and after. Wall-clock time alone is insufficient.

Validation matrix

Cover independent dimensions rather than one benchmark-shaped case:

Dimension Required cases
Final groups global/one, few, 64+, high cardinality
Distribution uniform, one hot group, Zipf-like skew
DISTINCT NDV low, medium, near input cardinality
Duplicate ratio high duplicate, mixed, nearly all unique
Key shape fixed width, VARCHAR, multi-column, NULL-containing
Execution DOP=1 and multi-DOP; one CN and multi-CN
Memory no spill and forced bounded-memory spill via injection
Lifecycle success, error, cancellation, Reset/Free, repeated reuse

Correctness tests must compare with an independent exact oracle and include deliberate hash collisions. Plan-shape assertions may supplement but cannot replace result assertions.

Unit tests must use small deterministic data and injected thresholds. Do not add sleeps, large-data UTs, or timing-only assertions. Put larger scaling and performance measurements in a dedicated benchmark/integration job.

Acceptance criteria

  1. Exact results match the independent oracle across the full validation matrix.
  2. A global or single-hot-group high-NDV case demonstrates real multi-worker partition finalization and meaningful speedup over DOP=1 on the same hardware.
  3. The balanced many-group control does not regress materially relative to perf: parallelize high-cardinality mixed DISTINCT aggregation #27693.
  4. Identical DISTINCT argument sets are deduplicated once and safely shared where semantics permit.
  5. Peak accounted memory respects the configured bound and the spill lifecycle satisfies Support bounded distinct-key spill for high-NDV exact DISTINCT aggregates #27698's cleanup and failure-path requirements.
  6. Runtime path selection is observable through bounded counters/profile labels for selected topology, partition count/skew, input/surviving keys, exchanged bytes, and spill activity.
  7. Focused benchmarks report CPU time, allocations, memory, network/shuffle volume, and wall time for every relevant topology.

Related

Activity

  1. XuPeng-SH commented on Aug 27, 2026

    @XuPeng-SH
    ContributorAuthor

    #27753 tracks a possible generic transport/reuse contract for canonical grouping hashes. This issue retains ownership of the DISTINCT-specific canonical identity (active GROUP BY keys, DISTINCT arguments) and adaptive partitioning semantics. The two should share machinery only if their equality, lifecycle, and cost contracts are actually compatible; #27720 must not depend on carrying a hash when recomputation is cheaper.

  2. assigned and unassigned on Aug 30, 2026
  3. Ariznawlll commented on Sep 1, 2026

    @Ariznawlll
    Collaborator

    最新 main 阶段性验证结果(2026-09-01)

    本次验证针对当前 main 已合入的实现子集。当前实现并未覆盖 issue 中完整的自适应 DISTINCT 聚合设计,因此下面区分“已合入路径验证结果”和“仍待实现项”。

    测试环境

    已合入优化路径

    500 万唯一键:

    select count(distinct id) from pk_big;

    执行计划命中:

    AP QUERY PLAN ON MULTICN(8 core)
    Aggregate: outer COUNT
      -> Aggregate: shuffle by DISTINCT key
           -> Aggregate: local DISTINCT pair pre-dedup
                -> Table Scan
    

    结果:

    • COUNT(DISTINCT id) 精确返回 5,000,000。
    • id % 8 形成 8 个热点组时,每组精确返回 625,000。
    • 计划在多 CN 下完成本地 pair 去重、按 DISTINCT key 重分布、最终去重和外层 COUNT。

    100 万近唯一键:

    • 全局 DISTINCT:1,000,000。
    • VARCHAR DISTINCT:1,000,000。
    • NULL 列:900,000 个非 NULL DISTINCT 值。
    • 8 个最终组:每组 125,000。
    • Proxy、CN1、CN2 三个入口结果一致。
    • 与独立 Oracle 一致:
    select g, count(*)
    from (
        select g, d
        from distinct_unique
        where d is not null
        group by g, d
    ) x
    group by g;

    200 万重复数据:

    • 全局 DISTINCT:500,000。
    • 8 个热点组:每组 62,500。
    • 高重复输入的结果与独立 Oracle 一致。

    DOP 验证

    同一硬件、同一 100 万唯一键查询,连续三次结果:

    DOP 墙钟时间
    1 0.37–0.39 秒
    8 约 0.25 秒
    16 0.24–0.25 秒

    所有 DOP 均返回 1,000,000;当前环境下 DOP=8/16 相比 DOP=1 约有 1.5 倍加速。

    正确性和回退路径

    以下场景均得到精确结果:

    • 唯一键、重复键、热点组和全局单组。
    • BIGINT、VARCHAR、NULL、空输入。
    • WHERE 过滤和 prepared 查询。
    • DOP=1/8/16;Proxy、CN1、CN2。
    • 低 NDV:COUNT(DISTINCT filler)=10。
    • 浮点回退:500,000。
    • 表达式回退:COUNT(DISTINCT d+0)=500,000。
    • SUM(DISTINCT d)=124999750000。
    • 混合聚合:COUNT(DISTINCT d)=500000、SUM(filler)=9000000。
    • 多列 DISTINCT:COUNT(DISTINCT g,d)=500000。
    • 全 NULL 和空输入均返回 0。

    执行计划确认:

    • 高 NDV、单个 COUNT(DISTINCT 直接列) 命中 DISTINCT-key 重分布路径。
    • 低 NDV、浮点 key、表达式、SUM(DISTINCT)、混合聚合和多列 DISTINCT 使用已有保守路径,没有错误套用当前优化。

    自动化验证

    • TestOptimizeSingleCountDistinct*:通过。
    • TestOptimizePadSpaceCountDistinct*:通过。
    • TestDistinctKeyPreAggregation*:通过。
    • 完整 go test ./pkg/sql/plan -count=1:通过。

    当前尚未完成的 issue 验收项

    当前 main 主要覆盖单个 COUNT(DISTINCT 直接列) 的部分固定宽度/字符串类型路径,以下内容仍未达到 issue 的完整验收条件:

    1. 多列 canonical key 的分区并行路径。
    2. 其他 DISTINCT 聚合以及相同 DISTINCT 参数集的安全共享。
    3. aggregate filter 和更完整的 grouping sets 组合。
    4. 有界内存和强制 spill,包括失败与清理路径。
    5. error、cancellation、Reset/Free 和重复复用生命周期。
    6. 近唯一键场景跳过无收益本地去重的自适应选择。
    7. 分区数量/倾斜、输入/存活 key、exchange bytes、spill 等运行时指标。
    8. 故意 hash collision 和完整多类型 canonical equality 矩阵。

    结论

    当前已合入的高 NDV 单 COUNT(DISTINCT 直接列) 路径,在单组、热点少组、多 DOP 和多 CN 场景下结果正确,并观察到并行收益;本轮未在该实现子集中发现新的结果错误。

    但整个 #27720 仍是部分实现状态,建议继续保持打开,后续补齐上述 validation matrix 后再做完整验收。

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions