Repository navigation
Description
Summary
TPC-H 1TB currently performs well, but the TPC-DS 1TB failures in #26742, #26743,
#26744, and #26745 expose optimizer assumptions that are reliable mainly for relatively
flat TPCH-shaped star joins. The current behavior is better described as workload-shape
overfitting than as four query-specific defects.
The static evidence and incident symptoms support these working failure chains:
invalid/lossy statistics and cardinality estimates
-> fragile greedy join order and build/probe choice
-> local hash join instead of shuffle
-> selected topology has no effective spill path
-> HashBuild exhausts the query budget
ROLLUP/CUBE and CTE expansion
-> duplicate large scan/join subtrees
-> concurrent HashJoin/Aggregate fan-out
-> local per-operator admission misses query-wide peak memory
-> operators collectively exhaust the 40 GiB query budget
Q64 has verbose cardinality evidence. For Q4/Q74/Q80, the structural plan problems are
confirmed but the complete runtime causal chains still require controlled reruns and operator
timelines.
This issue tracks the systematic optimizer roadmap. It must not be closed by query IDs,
SQL-text matching, benchmark-specific hints, or isolated threshold tuning.
Evidence
The investigation used 103 logical EXPLAIN plans covering all 99 TPC-DS queries,
a verbose Q64 plan, and optimizer statistics for all 25 TPC-DS tables. The plan corpus
contains:
| Property | Count |
|---|---|
| Table scans | 1,445 |
| Joins | 1,156 |
| Shuffled joins | 221 |
| Aggregates | 356 |
UNION ALL nodes |
141 |
| Large fact/returns/inventory scans | 482 |
Confirmed findings:
- ROLLUP/CUBE creates one complete Select/From/Where subtree per grouping set and joins
the branches withUNION ALL. - Q14 statement 1 contains 285 scans and 210 joins; its three sales fact tables are each
scanned 35 times (105 fact scans in total). - Q80 creates three grouping-set copies of three channel subtrees, producing nine large
sales-left-returns joins. - CTE reuse rejects estimated materializations above 32 MiB and all variable-width output,
so expensive analytical CTEs such as Q64cross_salesremain inline. - 23 integer-column NDVs exceed the discrete domain allowed by their collected min/max.
- Join predicate NDV is calculated, but the main inner-join cardinality formula divides by
min(left.Outcnt, right.Outcnt)instead of using the join-key NDVs. - Standalone Filter uses a fixed 5% estimate, aggregate HAVING uses 0.01%, and
UNION DISTINCTretains a fixed 70%. - Q64 is estimated at 712,868 rows where the corresponding actual stream is approximately
411,865,042 rows (about 578x underestimation); this changes the shuffle/spill topology. - Join ordering uses a high-NDV graph plus selectivity/out-count sorting and first-eligible
greedy expansion rather than candidate-plan cost search. - Of 482 large scans, 406 have no direct filter and only one large fact scan has a runtime
filter probe. Runtime-filter placement requires a direct table-scan child. - Q40, Q78, and Q80 contain 13 instances of a filtered dimension being joined after a large
sales-left-returns outer join. - Shuffle admission is row-count/threshold based and does not estimate query-wide concurrent
build bytes. - Q4, Q11, and Q74 retain constant-true/false branches through physical plan construction.
Only Q64 currently has verbose actual/estimated evidence. Structural findings for other queries
are confirmed, but their exact per-node estimation error still requires analyzed plans or runtime
profiles.
The collected plans/stats are not yet committed with a reproducible collector and checksums.
M0 must preserve the raw artifacts, collection commands, commit/config/data identity, and parser
used to derive the aggregate counts. Until then, those counts are investigation evidence rather
than a self-contained repository regression.
System invariants
The roadmap should restore these general contracts:
- Statistics validity: NDV, null counts, min/max, uniqueness, and key domains satisfy
type-aware mathematical and trusted-schema constraints before entering the cost model. - Cardinality relevance: physical decisions use the statistics of the actual join/filter
keys and preserve known uniqueness/domain constraints. - Shared logical input: grouping-set count and CTE reference count do not multiply a
common expensive input when sharing/materialization is semantically valid and cheaper. - Resource feasibility: every memory-sensitive physical candidate has a byte estimate,
concurrent lifetime, and explicit spill capability; selected plans fit the query budget with
reserve or spill before exhausting it. - Rewrite stability: semantically equivalent SQL forms do not cause order-of-magnitude
changes in scans, build bytes, or peak memory without a data-dependent reason. - Semantic safety: join reorder, runtime-filter placement, and common-subtree reuse preserve
NULL, outer-join, correlation, volatility, and early-stop semantics.
Roadmap
P0 independent correctness work
The optimizer roadmap does not replace the execution-layer fixes in the original incidents:
- preserve the original HashBuild resource error instead of returning only
context canceled; - make pipeline terminal delivery and cleanup correct under failure/cancellation;
- preserve spill forward progress and recovery headroom under the shared HashBuild budget;
- verify the local/non-shuffle versus shuffle spill contract explicitly.
These remain independently testable even when a better plan avoids the original failure shape.
M0: measurement and regression baseline
- Reproduce each original incident under the same commit/config/data snapshot and preserve the
plan, optimizer trace, HashBuild budget-owner timeline, spill counters, and terminal result. - Commit or publish the raw plan/stats artifacts, checksums, collection commands, and analysis
script needed to reproduce the static findings. - Add typed optimizer decision traces for cardinality, build/probe, distribution, runtime-filter,
materialization, spillability, candidate rejection, and final selection. - Collect per-operator estimated/actual rows, row width, build bytes, hash peak, shuffle bytes,
spill bytes, DOP, and wall time. - Build fixed TPCH 1TB, TPC-DS 1TB, minimized counterexample, and semantic-equivalence corpora.
- Track cardinality q-error, plan size, fact scans/bytes, compile time, peak memory, spill,
completion rate, and execution time.
M0 is the acceptance foundation for all later milestones and must avoid unbounded per-row,
per-batch, or high-cardinality diagnostic cost.
M1: eliminate deterministic plan multiplication
- Propagate an empty-relation representation through Filter, Join, and Union; eliminate
Filter(true)and statically empty branches before physical pipeline construction. - Reuse the existing spillable materialized source when costing deterministic, explicit,
multi-reference, full-drain CTEs. Remove the fixed-width/32 MiB hard rejection only after
memory/disk/read cost and cancellation/error behavior are covered. - Design and prototype shared-input grouping sets. Compare extending the existing Group
GroupingFlag/rollup machinery with an existing materialized producer plus multiple aggregate
consumers before introducing a new operator family.
M2: make statistics trustworthy
- Enforce type-aware NDV/domain/null/uniqueness invariants at the stats ownership boundary.
Single-column uniqueness and tuple uniqueness for composite keys must be handled separately;
integer-domain checks must not use lossyfloat64min/max outside its exact range. - Replace object-count divisors and arbitrary NDV multipliers with mergeable, bounded-error
sketches or a validated extrapolation model. - Add confidence/freshness metadata and conservative fallback when validation fails.
- Prioritize trusted PK/FK, uniqueness, multi-column NDV/correlation, MCV/range distribution,
null fraction, and join-domain overlap for topology-changing keys. Unverified constraints must
not be treated as data facts.
M3: repair topology-critical cardinality estimation
- Add an explicit two-side key-stat API and use left-key NDV, right-key NDV, overlap, null
fraction, uniqueness, and trusted PK/FK relationships for equi-join estimates. The existing
predicate NDV is not a substitute for two-side key statistics. - Replace universal Filter/HAVING factors when column statistics or expression structure are
available. - Estimate multi-column groups without unconditional independent-NDV multiplication.
- Represent estimate uncertainty or bounds so low-confidence underestimates cannot select a
non-spillable high-risk topology.
M4: resource-aware physical candidates
- Propagate output row width through Project, Filter, Join, Aggregate, and Union.
- Cost HashBuild, exchange, materialization, and aggregation in bytes, including metadata,
DOP, and concurrency. - Generate local-hash, broadcast, shuffle-hash, and spillable alternatives where legal.
- First use the existing statement/CN-scoped
HashBuildBudgetowner data to measure overlap,
admission, and spill-recovery headroom. Add conservative query-level peak estimation only where
those measurements demonstrate that local candidate cost is insufficient. - Treat spillability as a property of a physical candidate, not an after-the-fact flag.
M5: reduce fact data early
- Place runtime filters through supported Project/Filter/join subtrees to their owning scans.
- Use expected saved rows/bytes/blocks minus build/delivery cost instead of only a 10% NDV ratio.
- Add legality-checked preserved-side outer-join reorder for shapes such as
(sales LEFT JOIN returns) JOIN filtered_dimension.
M6: bounded join-plan search
- Use bounded DP for small connected inner equi-join components (initially a measured threshold
such asN <= 8) and retain a hard candidate/time budget. - Prune dominated candidates using intermediate bytes, network, peak memory, and spill cost.
- For large graphs, use an explicit uncertainty-aware heuristic fallback that considers multiple
starts and retains a robust spillable candidate. - Keep outer, semi, anti, mark, single, and correlated joins outside the initial enumeration;
handle their legality through separately tested rewrite boundaries.
This milestone comes after trustworthy statistics/cardinality and byte-based candidate cost. A
general memo/property framework should not be introduced merely to search the current invalid estimates and
duplicated logical trees more expensively.
M7: runtime feedback and adaptive behavior
- Feed actual cardinalities into later statements and stats refresh decisions.
- Consider parameter-sensitive plans and bounded stage-boundary re-optimization.
- Add dynamic repartition/spill fallback when build size exceeds the selected estimate.
M7 must not be used to hide deterministic logical expansion or invalid base statistics.
Proposed implementation subissues
The umbrella should be implemented as independently reviewable issues, not one monolithic PR:
- Stats: enforce type-aware NDV invariants and publish invalid-stat telemetry.
- Cardinality: estimate equi-joins from both-side NDV, overlap, NULLs, and trusted keys.
- CTE: cost spillable multi-reference CTE reuse with the existing materialized source.
- Grouping sets: execute a shared input once without cloning its relational subtree.
- Relational rules: prune compile-time empty relations and identity filters before pipeline
construction. - Runtime filter: place profitable probes through transparent nodes and explicitly safe join
paths. - Join rewrite: reassociate INNER over LEFT JOIN when predicates use only the preserved side.
- Physical cost: propagate output widths and cost hash/shuffle candidates in bytes.
- Join order: bounded DP for small connected inner equi-join components, dependent on Stats,
Cardinality, and byte cost. - Execution/HashBuild: preserve spill recovery headroom under the existing shared query budget.
The general memo optimizer, generic common-subexpression elimination, and a complete pipeline
lifetime framework are intentionally deferred until measured recurring needs justify them.
Validation matrix
Every implementation subtask needs an invariant, its negation, a public-path witness where
externally visible, a typed white-box oracle, and an independent SQL/result or resource oracle.
Whole EXPLAIN text snapshots are not sufficient.
| Contract | Minimal witness | Nearby control | White-box oracle | Black-box/metamorphic oracle |
|---|---|---|---|---|
| Grouping sets share input | one table with two-key ROLLUP | plain GROUP BY; DISTINCT aggregate | one input scan and native grouping metadata | result equals explicit UNION ALL reference |
| CTE reuse is cost based | deterministic wide CTE referenced twice | volatile/correlated/early-stop consumer | shared producer only when legal | result equals inline form; bounded materialization memory |
| Stats respect domain | sampled bounded integer column | sparse range, NULL, unique key | validated stats object | refreshed table_stats satisfies invariants |
| Join estimate uses keys | deterministic PK/FK join | many-to-many, disjoint ranges, NULL | estimate follows key metadata | actual/estimate remains within agreed bounds |
| Runtime filter reaches scan | filtered dimension behind Project/Filter | unsupported expression/unsafe join | probe reaches owning fact scan | same rows with fewer scanned rows/blocks |
| Outer reorder is legal | filter on LEFT JOIN preserved side | predicate references nullable side | typed tree changes only when legal | results equal rewrite-disabled control including unmatched rows |
| Plan fits memory | two concurrent large hash builds | one small or skewed build | byte/lifetime estimates exist | bounded-memory execution completes or spills without OOM |
| Empty branches disappear | UNION ALL branch with WHERE false |
plan-time unknown parameter | empty removed, parameter branch retained | same rows and result types |
Acceptance gates
This tracking issue is complete only when the following are demonstrated without query-specific
rules:
- each original incident has a controlled baseline with preserved raw artifacts and final result;
- zero invalid base-statistics invariants in the fixed TPC-H/TPC-DS datasets;
- Q14/Q67/Q77/Q80 fact scans no longer multiply with grouping-set count;
- Q64 no longer selects a non-spillable topology from the observed low-confidence underestimate;
- Q80 completes or spills under the same 40 GiB query limit without exceeding its memory budget;
- semantic-equivalent query rewrites do not cause order-of-magnitude scan/build/peak-memory changes;
- TPCH 1TB completion and agreed core-query performance do not regress;
- TPC-DS 1TB completion, peak memory, compile time, and runtime changes are reported per milestone;
- [Bug]: TPC-DS 1TB Q64 exhausts HashBuild budget instead of spilling #26742–[Bug]: TPC-DS 1TB Q4 returns context canceled instead of the HashBuild failure #26745 retain independent execution/error/cleanup regressions where applicable.
Milestone-specific gates should include:
- Stats deterministic fixtures: join-cardinality median q-error at most 2 and p95 at most 10,
reported separately for PK/FK, many-to-many, disjoint-range, NULL, stale, and missing Stats; - grouping sets: the common input executes once, input scan bytes do not grow linearly with the
grouping-set count, and plan size isO(base subtree + grouping metadata); - CTE reuse above the existing in-memory retention bound: spill is observed, retained memory
remains bounded, and variable-width/cancel/error/prepared-reuse paths pass; - bounded DP: the chosen plan is not dominated by another enumerated legal candidate in build
bytes, network bytes, and peak hash bytes, while planner p95 latency stays within a measured
hard budget; - Q64/Q80 under 40 GiB: execution completes or spills without memory-admission failure, peak
query memory stays within the configured cap, and spill disk/FD use stays within budget; - the full suite reports all 99 TPC-DS queries, geometric-mean runtime/scan bytes, maximum
single-query regression, planning time, plan nodes, peak memory, and spill bytes.
Exact q-error and performance thresholds should be set from the M0 baseline rather than chosen
without measurement. Each milestone must report before/after distributions, not only one query.
Scope boundaries
In scope:
- optimizer observability needed to evaluate the roadmap;
- statistics validity and topology-critical cardinality estimation;
- logical plan sharing and dead-branch elimination;
- resource-aware physical candidates, runtime filters, join reorder, and bounded join search;
- regression and benchmark gates preventing TPCH-shaped overfitting.
Out of scope for this umbrella issue:
- query-ID or SQL-text special cases;
- closing execution lifecycle/error-propagation defects solely because a faster plan avoids them;
- a full optimizer framework rewrite before the measured invariants require it;
- runtime adaptivity used as a substitute for fixing deterministic planner defects;
- assigning implementation to one monolithic PR. Each milestone should be split into independently
reviewable subissues with its own owner and acceptance evidence.
Related issues
- [Bug]: TPC-DS 1TB Q64 exhausts HashBuild budget instead of spilling #26742
- [Bug]: TPC-DS 1TB Q74 fails with pipeline end signal delivery failed #26743
- [Bug]: TPC-DS 1TB Q80 join-spill cannot admit minimum allocation at 40 GiB #26744
- [Bug]: TPC-DS 1TB Q4 returns context canceled instead of the HashBuild failure #26745
- [Bug]: HashBuild can bypass spill and trigger system OOM during large hash table growth #25782
Activity
aptend commentedon Aug 7, 2026
Additional M2 finding from the code-level stats review:
MatrixOne currently lacks an ANALYZE-style path that samples and reads actual column values. At object-write time, each non-PK column builds an HLL, but only the scalar
uint32(Estimate())is persisted; the mergeable sketch is discarded. GlobalStats later sums object-level scalar NDVs, scales the sum by sampled-row ratio, and applies object-layout/zone-map heuristics. Once the sketch and sampled values are discarded, cross-object overlap, MCVs, histograms, correlation, and multi-column distributions cannot be recovered.Roadmap requirement:
This is a prerequisite for replacing the current NDV extrapolation heuristics; improving those heuristics alone cannot reconstruct information that was never retained.
perf: bound set and cumulative min-max execution state (#27913)
perf(plan): expose safe subquery predicates before join costing (#27915)
perf(plan): make outer and anti join planning fail-closed (#27934)
perf(group): reduce fixed-width DISTINCT spill overhead (#28108)
perf: reuse shared computation in analytic plans (#27914)
fix(plan): make analyzed stats safe for join planning (#28348)
perf(plan): eliminate implied semi joins using key containment (#28462)
perf(plan): reduce redundant scans with scalar fusion and bounded run…
perf(vector): avoid redundant metadata work in UnionOne (#28666)
perf: bound repeated work in analytic queries (#28752)
23 remaining items
perf(group): reduce fixed-width DISTINCT spill overhead (matrixorigin…
perf: reuse shared computation in analytic plans (matrixorigin#27914)
fix(plan): make analyzed stats safe for join planning (matrixorigin#2…
perf(plan): eliminate implied semi joins using key containment (matri…
perf(plan): reduce redundant scans with scalar fusion and bounded run…
perf(vector): avoid redundant metadata work in UnionOne (matrixorigin…
perf: bound repeated work in analytic queries (matrixorigin#28752)
perf: improve large-query planning and adaptive memory control (#29646)
XuPeng-SH commentedon Oct 31, 2026
合并范围核对:#31761 已于 2026-10-31 09:30:15 UTC 合入 main,merge SHA
6e5f2ce0fa52b834e39fb4ada00984fa57c02c14。它覆盖分析型 join/aggregation 的部分通用优化,包括集合成员关系化简、分组表达式移动、深层 runtime filter、投影与批处理;并不完成本总项的 M0–M7 路线图及全部验收门槛。因此本 issue 继续由研发 aptend 跟进,不将整个总项转为 QA 验收。证据边界:PR 作者报告了指定历史版本上的 TPC-DS 1T 五个查询文件测量、TPCH 对照及受影响包/race 验证;最新评审已确认设计补充解决旧评审意见,并引用冻结 head 的 CI 证据。这里仅核对远端合并状态、正文及完整讨论,没有运行本轮本地产品测试或复现这些基准,不能据此宣布本总项验收通过。
仍需按子项独立跟进统计采样/有效性、基数估算、共享 grouping-set/CTE 输入、资源可行物理计划及完整 99-query 等门槛;#26742–#26745 的执行错误传播、取消清理和 spill 回归也不能仅因部分查询加速而视为完成。后续可按独立已完成子项交 QA,验证优化前后结果一致性、NULL/外连接语义、内存与 spill 边界及性能回退。
perf(sql): bound local set/window parallelism and batch hash-join pro…
XuPeng-SH commentedon Nov 2, 2026
新增合并范围核对:#31998 已于 2026-11-02 10:37:48 UTC 合入 main,merge SHA
8ff3c0d81da1924afb03800371ba74437fddd10c。它交付有界的本地 UNION DISTINCT、完整分区 Window、INTERSECT/EXCEPT DISTINCT 并行路径及 HashJoin 定宽重复行批量投影;不修改基数估计、join ordering、自动 spill 策略或 merge 默认值,不能完成本总项 M0–M7 路线图。因此仍保留研发 aptend,不把整个总项改派 QA,也不宣布验收通过。证据与限制:旧设计/运行证据 follow-up 已经后续评审确认解决,不作为永久阻塞。作者报告历史源
defe806fe9d123285449cc8db406c85dcbc31b9a的 TPC-DS 1 TB 99/99 文件(103 statements)完成、保留的结果比较和资源回收记录;这是历史作者证据,不是本轮对 merge SHA 的本地实测。最新 PR head28ecdb7a269339b381e239ac37e81c88cbec3284的远端 CI Required 为 failure,UT/SCA/coverage 及部分 BVT cancelled,shared build success,兼容性 skipped;不能沿用旧 head 的绿色 CI 当作本轮成功。保留记录中的 UNION cancellation 仅覆盖注册阶段,INTERSECT 无独立取消捕获。后续可按独立完成子项安排 QA,特别核对单 CN、非 prepared AP、显式正 spill threshold 的选路与自动/prepared/多 CN fallback;比较 NULL/重复键/完整分区结果、DOP 与 128 MiB-per-owner 边界、取消/错误清理及内存压力。membership 的 threshold 只限制 fanout,不代表它新增 spill 能力。M0–M7 的统计、共享输入、资源可行性及 #26742–#26745 独立执行回归仍需分别完成。
perf(execution): reduce projection, spill and allocation overhead (#3…
XuPeng-SH commentedon Nov 9, 2026
新增合并范围核对:#32391 已合入 main,merge SHA
a8d561d0d056da6f32f86653e6ca17e5d9ea6297。它交付 unique HashJoin 定宽行批量投影、Group 变长 spill 行直接写入已记账缓冲、Window 固定状态按输出组数分配,以及 mmap cache 已满时的提前拒绝。PR 明确不改变查询计划、SQL 语义、spill threshold 或并发策略,不能完成本总项 M0–M7 及独立执行错误/取消清理门槛。本项继续由 aptend 负责,不把整个路线图转测或关闭。证据边界:作者报告相同 64 逻辑 CPU 主机的 TPC-DS 1 TB 部分查询 A/B,Q67 的 26.4%–29.8% 时间降低是在 DOP cap 16、4 GiB aggregate threshold 下测得,不能当作默认配置或完整套件加速;Q78 只有一组完成的 A/B。这些测量早于 rebase;早期 99-file/103-statement 全跑仅含前两项改动,完整四改动版本没有全套重跑,TPC-H runtime non-regression 尚未建立。作者还报告
62d0420dfd七个 owning packages normal tests 和默认构建模式全仓 SCA 通过,额外 SIMD SCA 的两项 unchanged-file checkunsafe 失败不能略去。本轮只核对远端合并及 issue 记录,未本地实测这些基准。后续按独立子项验证结果/EXPLAIN 一致性、NULL 与 metadata fallback、Window chunk/NULL 初始化、spill 字节及磁盘记账、取消/直接写 fallback、mmap 最终锁内容量和 unmap 路径。完整头的 TPC-H/TPC-DS 回退、资源峰值及路线图统计/基数/共享输入/资源可行性门槛仍需独立完成,不能由局部提速替代。
perf(sql): reduce redundant aggregation and preserve analytic paralle…
XuPeng-SH commentedon Nov 13, 2026
新增合并范围核对:#32625 已合入 main,merge SHA
437c648450ffd9f87c574036534c5ca546e88594。本次覆盖受完整输入确定性/totality 证明约束的 DECIMAL SUM 预聚合、grouped-key 必要域过滤、有界 grouped CTE 复用、同布局 MIN/MAX Window 融合、inline-string HashJoin 投影、DISTINCT/set 并行所有权及 ANTI 成本修正。它是本路线图的部分进展,不完成 M0–M7 和全部资源/统计/执行回归验收;本总项继续保持 open、由研发 aptend 跟进,不改派 QA。旧 grouped-SUM CAST 反例已由后续完整 fact/dimension 输入 totality guard 和公开 SQL 回归处理,最新评审确认该 follow-up 解决,不将旧反例永久当作当前阻塞。作者报告历史 TPC-DS 1 TB 99/99 完成、端到端时间降低 18.7%;这不是当前 main 的隔离 A/B,且早于最终 review-fix,不能当作合并版本的新基准。输出比较中的 tie 内顺序变化及 Q39 浮点最大绝对差 6.67e-16 也不能写成全部逐字一致。后续 owning-package/SCA、103 个 TPC-DS statements 和 22 个 TPC-H plan fixtures 是作者/评审报告;plan 一致不是 TPC-H runtime 回退验证。本轮仅做远端状态与完整讨论核对,没有本地运行测试或基准。
后续独立子项 QA 应保留 skipped-vs-demanded CAST/error 边界、DECIMAL 类型、NULL/外连接、Window/CTE drain 与取消清理、DISTINCT 完整所有权、spill/并发预算及当前基线性能对照。完整路线图及 #26742–#26745 的独立执行错误传播、资源和清理门槛仍须分别完成;不因局部优化合并而宣布总项验收通过或要求 backport。