Repository navigation
Description
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. SaveSpillIntermediateRowsserializesargCntand every retained argument for each selected group.UnmarshalSpillFromReaderreconstructs 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
- A single-group high-NDV exact
COUNT(DISTINCT)completes under a finite memory limit that cannot hold all distinct keys at once. - Results match an independent no-spill exact oracle for fixed, varlen, and multi-column keys, including duplicates, NULL, signed zero, and forced hash collisions.
- Peak accounted memory remains within the configured limit plus an explicitly bounded recovery reserve.
- Multiple groups and a skewed hot group complete without requiring the complete hot-group state to be resident during reload.
- Spill, recursive repartition, finalization, cancellation, injected write/read failures, and cleanup leave no files, goroutines, allocation-account debt, or reusable-state contamination.
- Low-NDV and no-spill controls do not regress materially and do not allocate partition machinery on the normal path.
- Unit tests use injected spill thresholds and small deterministic datasets; no sleeps or large-data UTs. Add a constrained-memory integration regression separately.
Related
- perf: linearize DISTINCT aggregate preflight deduplication #27688 optimizes bounded batch-local DISTINCT preflight and does not change spill semantics.
- arenaskl: cached Inserter can admit a duplicate successor key #27691 fixes cached skiplist Inserter duplicate admission.
- [Bug]: ClickBench Q10 is significantly slower in MatrixOne than DuckDB #27672 and perf: parallelize high-cardinality mixed DISTINCT aggregation #27693 cover a high-NDV mixed-aggregation performance path, but not single-hot-group bounded-memory spill.
Activity
perf(sql): distribute distinct pairs after local deduplication (#27790)
feat: support bounded exact distinct-key spill (#28003)
perf(sql): distribute distinct pairs after local deduplication (matri…
feat: support bounded exact distinct-key spill (matrixorigin#28003)
perf(sql): distribute distinct pairs after local deduplication (matri…
feat: support bounded exact distinct-key spill (matrixorigin#28003)
perf(sql): distribute distinct pairs after local deduplication (matri…
feat: support bounded exact distinct-key spill (matrixorigin#28003)
Ariznawlll commentedon Sep 18, 2026
设计分流:精确 DISTINCT 的单热点组有界内存路径
本 issue 不是现有修复的 QA 验收项,也不是 #27693 的遗留测试失败;它要求新增“单个/少数热点最终组也能完成精确 DISTINCT”的执行与 spill 能力。因此保持 Open,先进入研发设计,不应在没有候选实现时添加通过基线或关闭。
已有实现边界
(active GROUP BY keys, DISTINCT arguments)key 分区,以暴露单组、少组或热点组的并行度。实现前必须交付的设计内容
argSkl。COUNT(DISTINCT)的正式适用范围,以及SUM/AVG/GROUP_CONCAT DISTINCT等 saved-argument aggregate 的明确边界。验收与回归分层
COUNT(DISTINCT)SQL,spill on/off 精确结果一致;失败后状态和复用连接正常。MOTR 目前不应承担该内存阈值/实际 spill 合同;Chaos 也不适用,除非设计把节点、网络或对象存储故障纳入正式支持承诺。
下一步
请先指定研发设计 owner,并将上述设计评审链接回本 issue;建议由熟悉 #27688/#27693/#27720 的 DISTINCT 聚合维护者参与评审。设计通过后再拆实现 PR 与 big-data 验收,不在本 comment 中声明测试结论。
Ariznawlll commentedon Nov 25, 2026
已在修复合入后的当前
main上完成 #27698 验收,覆盖 focused 普通/race、真实 SQL 硬内存限制、独立精确结果 oracle、no-spill 对照及公开 SQL 回归,现予关闭。验收版本与范围
568f0f4fdee3c34373f27b04316a2adf7d32a78a。f9657a3e6d5bcfac5a46d6092fbde0df750a160d是该 SHA 的祖先。1.27.1,单 LOG / TN / CN 独立实例;Go 测试均为-mod=readonly -count=1,普通模式与-race分开执行。1. Focused DISTINCT spill 普通/race
在
pkg/sql/colexec/group实际执行distinct_spill_test.go的 28 个顶层测试:-race覆盖包括:
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 及实际结果:
EXPLAIN PHYPLAN ANALYZE直接观察到目标 Aggregate 的真实指标:GroupDistinctSpillActivations=5、GroupDistinctSpillBytes=67235832、GroupDistinctSpillKeys=1026、GroupDistinctSpillMaxLevel=2、GroupDistinctSpillRepartitions=36、GroupDistinctSpillUniqueKeys=1026。GroupDistinctSpillActivations=5、GroupDistinctSpillBytes=67249170、GroupDistinctSpillKeys=1026、GroupDistinctSpillMaxLevel=2、GroupDistinctSpillRepartitions=47、GroupDistinctSpillUniqueKeys=1026。GroupSpillRecords=1、GroupSpillReloadRecords=1;普通EXPLAIN ANALYZE同时显示SpillRows=1 SpillSize=123 bytes。因此不是仅凭“查询成功”推断修复,而是同时见证了完整集合大于 hard cap、真实 DISTINCT key spill/repartition、热点组 finalization spill 和精确行集。
3. 独立 oracle 与 no-spill 对照
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 确实生效。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。清理
验收数据库已删除,新建连接
SELECT 1成功;随后停止专属mo-servicePID 43044,RC=0。SQL/debug/LOG 端口 17698、17699、17700、17710–17712 均已无 listener,未触碰其他任务实例。产品源码工作树保持未修改,未进行 git commit/push。