Skip to content

Support bounded distinct-key spill for high-NDV exact DISTINCT aggregates #27698

Done

Description

@XuPeng-SH

Motivation

Exact DISTINCT aggregates retain one key per distinct value. For a query with one or a few hot groups, such as:

SELECT COUNT(DISTINCT user_id) FROM events;

the resident aggregate state grows with the global NDV. Existing Group spill partitions by the group hash. It can evict independent groups, but it cannot subdivide the DISTINCT keys owned by one hot group. A spilled hot group must therefore be reconstructed as one complete in-memory argSkl during reload; recursive group spill cannot make progress when that single state still exceeds the memory budget.

This is an existing architectural limitation, not a regression introduced by #27688. #27688 removes the independent O(B²) duplicate scan inside a bounded 256-row preflight work unit, but deliberately leaves persistent DISTINCT state and Group spill unchanged.

Current behavior

  • Batch-local DISTINCT admission is bounded and temporary.
  • Persistent exact DISTINCT arguments are retained in aggState.argSkl, with O(global NDV) state.
  • SaveSpillIntermediateRows serializes argCnt and every retained argument for each selected group.
  • UnmarshalSpillFromReader reconstructs the complete skiplist for that group.
  • Group spill chooses buckets from group hashes, so every key belonging to one aggregate group remains inseparable.
  • Under a hard allocation limit, a single high-NDV group can repeatedly spill and reload without reducing its required resident state, eventually returning the controlled maximum-partition-depth error. Wide VARCHAR, UUID, multi-column keys, and parallel partial states increase the risk.

The behavior preserves correctness, but it does not provide bounded-memory completion for supported exact DISTINCT workloads.

Expected behavior

Provide an exact, bounded-memory execution path for high-NDV DISTINCT state, including the single-global-group case. The implementation should partition retained DISTINCT tuples by a stable hash of the DISTINCT key, or (group key, DISTINCT arguments) when grouping is present, so one hot aggregate group can be processed in independently reloadable partitions.

The result must remain exact. Falling back to approximate counting, truncating keys, dropping partitions, or changing NULL and equality semantics is not acceptable.

Design requirements

This is a design-level executor and spill change. A design document should be reviewed before implementation and should define:

  • ownership and lifecycle of resident partitions, spill files, reload scratch, and finalization state;
  • partition key and canonical equality for fixed, varlen, multi-column, const-vector, NULL, floating signed zero, and hash-collision cases;
  • exact finalization for COUNT(DISTINCT) and the applicability boundary for other saved-argument DISTINCT aggregates such as SUM, AVG, and GROUP_CONCAT;
  • integration with local partial aggregation, distributed merge, and existing group spill;
  • a hard memory bound including partition metadata, write/read buffers, hash tables, skiplist or sort state, and recovery reserve;
  • repartition or external-sort behavior when one partition still exceeds the limit, with a bounded depth and a controlled no-progress error;
  • cancellation, I/O failure, truncated/corrupt spill, retry boundaries, cleanup, Reset/Free, and repeated spill/reload behavior;
  • performance behavior for low NDV, high NDV, skew, wide keys, many groups, and a single hot group;
  • observability for spilled bytes, rows/keys, partitions, repartitions, reloads, peak resident state, and cleanup failures.

Acceptance criteria

  1. A single-group high-NDV exact COUNT(DISTINCT) completes under a finite memory limit that cannot hold all distinct keys at once.
  2. Results match an independent no-spill exact oracle for fixed, varlen, and multi-column keys, including duplicates, NULL, signed zero, and forced hash collisions.
  3. Peak accounted memory remains within the configured limit plus an explicitly bounded recovery reserve.
  4. Multiple groups and a skewed hot group complete without requiring the complete hot-group state to be resident during reload.
  5. Spill, recursive repartition, finalization, cancellation, injected write/read failures, and cleanup leave no files, goroutines, allocation-account debt, or reusable-state contamination.
  6. Low-NDV and no-spill controls do not regress materially and do not allocate partition machinery on the normal path.
  7. Unit tests use injected spill thresholds and small deterministic datasets; no sleeps or large-data UTs. Add a constrained-memory integration regression separately.

Related

Activity

  1. assigned and unassigned on Sep 4, 2026
  2. Ariznawlll commented on Sep 18, 2026

    @Ariznawlll
    Collaborator

    设计分流:精确 DISTINCT 的单热点组有界内存路径

    本 issue 不是现有修复的 QA 验收项,也不是 #27693 的遗留测试失败;它要求新增“单个/少数热点最终组也能完成精确 DISTINCT”的执行与 spill 能力。因此保持 Open,先进入研发设计,不应在没有候选实现时添加通过基线或关闭。

    已有实现边界

    实现前必须交付的设计内容

    1. 精确 canonical equality/hash:fixed/varlen、多列、NULL、常量向量、decimal、collation、signed zero、NaN(如适用)与 hash collision 的语义。
    2. 分区归属、resident state、spill file、reload scratch、finalize/Reset/Free 的所有权;一个热点 group 不能在 reload 时重新组装完整 argSkl。
    3. COUNT(DISTINCT) 的正式适用范围,以及 SUM/AVG/GROUP_CONCAT DISTINCT 等 saved-argument aggregate 的明确边界。
    4. 内存上限、recovery reserve、递归 repartition 或 external-sort 的无进展终止条件,以及 cancelled/read/write/truncated spill 的清理和重试边界。
    5. 与 [Enhancement]: Add adaptive partition-parallel execution for exact DISTINCT aggregates #27720 的 planner/runtime 选择、DOP、多 CN exchange 和 observability 合同:partition 数、skew、input/surviving keys、spill bytes/files、reload 与 peak accounted memory。

    验收与回归分层

    层级 必须证明的内容
    Go UT + focused race 注入小阈值的 exact result oracle;fixed/varlen/multi-column/NULL/signed-zero/hash-collision;spill/reload/repartition;write/read failure、cancel、Reset/Free 与无资源泄漏。
    BVT 小而确定的公开 COUNT(DISTINCT) SQL,spill on/off 精确结果一致;失败后状态和复用连接正常。
    nightly big-data 实际跨过内存阈值并发生 spill 的单全局 group、少组和热点组;记录行数、NDV/倾斜、拓扑、阈值、peak memory、spill files/bytes、精确结果、OOM/restart 与成功/失败清理。
    性能对照 与 no-spill oracle、#27693 的均衡多组控制和 DOP=1 对照;同时报告 CPU、allocation、wall time、exchange bytes 与 partition skew。

    MOTR 目前不应承担该内存阈值/实际 spill 合同;Chaos 也不适用,除非设计把节点、网络或对象存储故障纳入正式支持承诺。

    下一步

    请先指定研发设计 owner,并将上述设计评审链接回本 issue;建议由熟悉 #27688/#27693/#27720 的 DISTINCT 聚合维护者参与评审。设计通过后再拆实现 PR 与 big-data 验收,不在本 comment 中声明测试结论。

  3. Ariznawlll commented on Nov 25, 2026

    @Ariznawlll
    Collaborator

    已在修复合入后的当前 main 上完成 #27698 验收,覆盖 focused 普通/race、真实 SQL 硬内存限制、独立精确结果 oracle、no-spill 对照及公开 SQL 回归,现予关闭。

    验收版本与范围

    • MatrixOne 完整 SHA:568f0f4fdee3c34373f27b04316a2adf7d32a78a。
    • 已确认修复 PR feat: support bounded exact distinct-key spill #28003 的 merge commit f9657a3e6d5bcfac5a46d6092fbde0df750a160d 是该 SHA 的祖先。
    • 环境:macOS/arm64,Go 1.27.1,单 LOG / TN / CN 独立实例;Go 测试均为 -mod=readonly -count=1,普通模式与 -race 分开执行。
    • 本结论是上述版本的功能、生命周期和受限内存集成验收,不冒称 Linux/amd64 性能基准或多 CN 性能测试。

    1. Focused DISTINCT spill 普通/race

    在 pkg/sql/colexec/group 实际执行 distinct_spill_test.go 的 28 个顶层测试:

    模式 顶层测试 含子测试 PASS 记录 FAIL DATA RACE RC
    普通 28 75 0 无 0
    -race 28 75 0 无 0

    覆盖包括:

    • H0 单全局组、单热点组、多组、Group/MergeGroup finalization、多 chunk drain、跨 worker exact-key 和 mixed aggregate。
    • fixed/varlen、多参数 NULL、signed zero、forced hash collision、external sort、多轮及递归 repartition。
    • 1/2 MiB hard account 下精确结果、实际 spill keys/records、peak 上限,以及终态 disk/FD/allocation-account debt 清理。
    • no-spill 普通路径、发布顺序、取消、内部及 external-sort I/O 失败、损坏 envelope 和 terminal-state 边界。

    2. 真实 SQL:完整 distinct payload 大于 query hard cap

    独立实例配置:

    • processLimitationSize = 33554432(32 MiB);
    • processLimitationSpillSize = 1073741824;
    • max_dop = 1;
    • agg_spill_mem = 8388608(8 MiB 正常字节阈值,未使用 256/2 等调试注入值)。

    实际 fixture 为 1026 行、1026 个不同 TEXT value;每个 value 长 65472 bytes,总 payload 67174272 bytes(约 64.06 MiB),明显大于 32 MiB query cap。

    原 SQL 及实际结果:

    SELECT COUNT(*), COUNT(DISTINCT wide_value) FROM wide_values;
    -- 1026, 1026
    
    SELECT hot_key, COUNT(*), COUNT(DISTINCT wide_value)
    FROM wide_values
    GROUP BY hot_key;
    -- hot_key=1, 1026, 1026

    EXPLAIN PHYPLAN ANALYZE 直接观察到目标 Aggregate 的真实指标:

    • H0:GroupDistinctSpillActivations=5、GroupDistinctSpillBytes=67235832、GroupDistinctSpillKeys=1026、GroupDistinctSpillMaxLevel=2、GroupDistinctSpillRepartitions=36、GroupDistinctSpillUniqueKeys=1026。
    • 单热点组:GroupDistinctSpillActivations=5、GroupDistinctSpillBytes=67249170、GroupDistinctSpillKeys=1026、GroupDistinctSpillMaxLevel=2、GroupDistinctSpillRepartitions=47、GroupDistinctSpillUniqueKeys=1026。
    • 同一热点组 finalization 还实际复用了普通 group spill:GroupSpillRecords=1、GroupSpillReloadRecords=1;普通 EXPLAIN ANALYZE 同时显示 SpillRows=1 SpillSize=123 bytes。

    因此不是仅凭“查询成功”推断修复,而是同时见证了完整集合大于 hard cap、真实 DISTINCT key spill/repartition、热点组 finalization spill 和精确行集。

    3. 独立 oracle 与 no-spill 对照

    • 对 1026 个完整 TEXT value 逐行计算 SHA2(wide_value, 256),流式取回后独立审计:ID 恰好为 1–1026、每行长度均为 65472、1026 个不同 SHA256,与两条目标 SQL 的 COUNT(DISTINCT)=1026 完全一致。
    • 辅助的完整 SELECT DISTINCT / 带 ORDER BY 的 digest 查询在 32 MiB cap 下曾被 resource admission 拒绝;这些失败没有算作通过,最终采用上述不物化完整集合的逐行 digest oracle。该受控拒绝也确认 cap 确实生效。
    • 同一 32 MiB 实例、同一 8 MiB 正常阈值下,16 行小 fixture 的 H0 和 grouped 结果均为 16/16;两条 PHYPLAN 均无 GroupDistinctSpill* / GroupSpill*,SpillSize=0B、SpillRows=0,证明 no-spill 普通路径没有被迫启用分区 spill。

    4. 公开 SQL 回归

    在当前源码已有的 test/distributed/cases/qexec/group_h0_spill.sql 上运行 mo-tester,并与仓库 group_h0_spill.result 比对:

    • TOTAL=35 SUCCESS=35 FAILED=0 IGNORED=0 ABNORMAL=0,RC=0。
    • 覆盖公开 fixed/varlen、multi-argument NULL、mixed aggregate、spill on/off 精确结果对照及已有 ordered spill 指标断言。
    • 该稳定 SQL 回归已在主库,本轮未新增测试 PR,也未把 debug 小阈值 BVT 冒充真实 32 MiB 集成证据。

    清理

    验收数据库已删除,新建连接 SELECT 1 成功;随后停止专属 mo-service PID 43044,RC=0。SQL/debug/LOG 端口 17698、17699、17700、17710–17712 均已无 listener,未触碰其他任务实例。产品源码工作树保持未修改,未进行 git commit/push。

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