Skip to content

[Feature Request]: Optimize mixed and multiple DISTINCT aggregates beyond the single-aggregate rewrite #30768

Open

Description

@XuPeng-SH

Is there an existing issue for the same feature request?

  • I have checked the existing issues.

This is the scoped successor to #9049. Searched open DISTINCT aggregation requests and all-state mixed-DISTINCT titles. Related #27720 owns adaptive partition-parallel execution for exact distinct keys; #27698 owns bounded COUNT DISTINCT spill; #29934 concerns window aggregates. This request retains the unresolved mixed/multiple-aggregate optimization scope from #9049 rather than duplicating those execution projects.

Is your feature request related to a problem?

Source inspection of main c232b6d2a1b5a94ac624c4954586569841c1e153 shows that the checklist in #9049 no longer describes the implementation accurately.

Already implemented:

Remaining boundary: canOptimizeDistinctAgg in pkg/sql/plan/distinct_agg.go rejects nodes whose AggList has more than one expression. Mixed and multiple aggregates therefore do not receive this logical deduplication rewrite. COUNT DISTINCT has exact merge support, but RequiresSingleStageDistinctAgg conservatively requires single-stage execution for remaining non-COUNT DISTINCT states. Existing tests explicitly preserve the mixed AVG DISTINCT fallback.

Representative shapes to investigate:

SELECT g, COUNT(DISTINCT a), SUM(b), COUNT(*) FROM t GROUP BY g;
SELECT g, AVG(DISTINCT a), SUM(b) FROM t GROUP BY g;
SELECT g, COUNT(DISTINCT a), COUNT(DISTINCT b) FROM t GROUP BY g;
SELECT g, SUM(DISTINCT a), AVG(DISTINCT b), COUNT(*) FROM t GROUP BY g;

These are source-confirmed optimization boundaries, not newly executed wrong-result, OOM, or benchmark reproductions. In particular, the historical TPCH SF=100 Q16 OOM from #9049 has not been rerun on this revision.

Describe the feature you'd like

Optimize eligible ordinary GROUP BY/global aggregation nodes containing DISTINCT alongside normal aggregates, or multiple DISTINCT aggregates, while retaining exact SQL semantics and avoiding unnecessary repeated deduplication work.

Acceptance criteria:

  • Preserve normal aggregate input multiplicity: deduplicating a must not change SUM(b) or COUNT(*).
  • Preserve independent DISTINCT domains for different arguments and reuse compatible deduplication work only when equivalence is proven.
  • Preserve empty-input/global-versus-grouped results, NULL handling (including multi-argument COUNT), numeric overflow/decimal/AVG behavior, canonical string equality and signed zero.
  • Retain correct conservative fallbacks for unsupported shapes. Do not enable partial-state merge for SUM/AVG DISTINCT without a proven exact merge contract.
  • Demonstrate the selected optimization through public SQL and typed plans, including same/different argument sets, skew, high NDV, and ordinary-aggregate controls.
  • Measure time and peak/accounted memory against the unmodified baseline for the targeted shapes. Reject rewrites whose extra scans, joins or materialization outweigh their benefit; retain a bounded fallback.
  • Exercise cancellation, allocation/spill failures, cleanup, prepared reuse and applicable distributed boundaries whenever the chosen implementation changes those owners or contracts.

Describe implementation you've considered

Start from the existing distinct rewrite, canonical equality keys, aggregate state and Group/MergeGroup/spill owners. Design cost-aware deduplication domains and routing for mixed/multiple aggregates; a multi-AGG rewrite is a candidate, not a mandatory implementation.

Do not apply the current single-aggregate rewrite blindly to mixed aggregates: it would discard multiplicity needed by ordinary aggregates. Avoid a parallel aggregate framework or new state/lifecycle when existing owners can express the correction. Coordinate with #27720 for partition ownership and with #27698 for exact COUNT spill; do not reimplement their mechanisms here.

Documentation, Adoption, Use Case, Migration Strategy

Analytical reports commonly combine unique-user counts with totals/averages, or compute unique counts over several columns. Document eligibility, cost-based fallback, and limitations of any new path. No schema or SQL syntax change is requested. DISTINCT window aggregates remain outside this scope (#29934).

Additional information

Supersedes the remaining optimization checklist in #9049. Closing #9049 as superseded does not assert that every original requirement or the historical OOM scenario is resolved.

Source references at the inspected main revision:

Activity

  1. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    Collaborator

    结论

    测试不通过。本地验证到同一查询包含两个不同参数的 COUNT(DISTINCT) 时,结果正确,但在本次数据分布下明显慢于将两个聚合分别计算的等价写法;这属于本 issue 已描述的优化边界。

    关键证据

    • 版本:main@bbfe55669a1440424914d45a283a1d0e36f722fa;本地隔离双 CN、单 TN。分别从两个 CN 入口连接,不代表每条查询都跨 CN 执行。
    • 构造与查询:
    CREATE TABLE t AS
    SELECT result AS id,
           CASE WHEN MOD(result, 251) = 0 THEN NULL ELSE MOD(result, 28) END AS k
    FROM generate_series(960160) g;
    
    SELECT COUNT(DISTINCT id), COUNT(DISTINCT k) FROM t;
    
    SELECT (SELECT COUNT(DISTINCT id) FROM t),
           (SELECT COUNT(DISTINCT k) FROM t);
    • 两种写法均返回 (960160, 28);各入口交替运行每种写法 10 次,合并写法中位数分别为 0.492 / 0.508 秒,两个子查询为 0.070 / 0.065 秒。均为本机热缓存测量,不代表线上延迟或所有数据分布,也不说明重写一定应被采用。
    • 另在三组既有数据上、每组每入口交替 10 次,每种写法结果均一致;合并写法中位数 0.532–0.597 秒,对照为 0.034–0.057 秒。无效列名报错后,源表计数/求和及连接检查正常。
    • 同三组数据的 GROUP BY tenant 变体,将两个 DISTINCT 聚合分别按非空 tenant 分组后关联作为对照;每入口每种写法交替 5 次,完整分组结果均一致。合并写法中位数 0.490–0.618 秒,对照为 0.070–0.107 秒;该对照增加了一次扫描与 JOIN,结果仅适用于本次数据和关联条件。
    • 反例(不同版本和数据): main@d39d8a40343ccd40bf665036388df7a40ee867f8 的隔离双 CN 环境,三次新建但分布相同的约 96 万行数据,使用 GROUP BY g 同时计算 COUNT(DISTINCT id), SUM(v), COUNT(v);分组键非空,v 含 NULL。与分别聚合再按 g 关联的对照比较,两个入口各交替 5 次,完整结果均一致。全表样本合并计算的中位数为 0.0266–0.0489 秒,对照为 0.0271–0.0494 秒,未发现合并写法稳定更慢;窄过滤和空结果也一致。此处增加的扫描和 JOIN 是对照的一部分,且本机热缓存样本不代表所有分布。该反例说明优化需要成本判断,不能仅依据前述样本一律拆分。
    • EXPLAIN ANALYZE 的一个既有数据样本中,合并写法的聚合节点输入 960160 行、记录 MemorySize=136.28 MiB;对照出现单 DISTINCT 的分组去重路径。节点统计不是全查询峰值内存。白盒上 canOptimizeDistinctAgg 在聚合表达式数量不为 1 时返回 false,与本 issue 的范围一致;这不是对耗时根因的独立证明。

    待解决点

    • 对不同 DISTINCT 参数集合、NULL 与数据分布建立成本模型,并保持精确语义;不要仅依据该样本假定两次扫描总是更快。
    • 尚未完成真正跨 CN、spill、取消和更长时性能验证;当前数据不足以评估生产场景及资源峰值。
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