Repository navigation
Description
Summary
After ANALYZE, the planner estimates filter selectivity with a pure uniform-distribution assumption (equality = 1/NDV, ranges = linear interpolation) plus a hardcoded floor, with no MCV list or histogram support (ANALYZE TABLE t UPDATE HISTOGRAM ON col is a 1064 syntax error). On skewed data the errors reach 900× for equality on a hot value and 100× for BETWEEN, and they directly push the planner into wrong index/join choices.
Reproduction (2-CN local cluster, etc/launch-multi-cn)
CREATE TABLE sel_t (
seq INT PRIMARY KEY, uni INT, skew INT, corr INT,
KEY idx_uni (uni), KEY idx_skew (skew)
);
-- 100,000 rows: uni = i%10000 (uniform), skew = 1 for 90% of rows else 2..1000, corr = i
SELECT mo_ctl('DN','FLUSH','db.sel_t');
ANALYZE TABLE sel_t;Estimated (EXPLAIN VERBOSE scan outcnt) vs actual rows:
| predicate | estimated | actual | error |
|---|---|---|---|
uni < 1000 (10%) |
10,011 | 10,000 | 1.0× OK |
uni < 100 (1%) |
1,000 | 1,000 | 1.0× OK |
uni < 10 (0.1%) |
1,000 | 100 | 10× over (1% selectivity floor) |
uni = 5555 |
10 | 10 | 1.0× OK (1/NDV) |
skew = 1 (hot, 90%) |
100 | 90,000 | 900× under |
skew = 999 (rare) |
100 | 10 | 10× over |
corr < 1000 |
1,001 | 1,000 | 1.0× OK |
uni BETWEEN 1000 AND 1999 |
100 | 10,000 | 100× under |
skew > 5 |
99,700 | 9,960 | 10× over (uniform range assumption) |
Notes:
skew = 1gets exactly1/NDV = 1/1000— the 90% frequency is invisible; there is no most-common-value tracking.BETWEEN 1000 AND 1999estimatesselectivity=0.001— a magic default that also shows up onskew = 999and several other nodes; it is not derived from the (correct)< 1000estimate.skew > 5assumes uniform value distribution over the range (≈99.5% pass) while the real pass rate is 10%.
Plan-level damage
Same table, two literal values, identical plan shape — chosen because the estimate is 100 rows for both:
| query | chosen plan | actual rows | median latency |
|---|---|---|---|
SELECT seq, uni FROM sel_t WHERE skew = 1 |
idx_skew lookup + join-back | 90,000 | 294.8 ms |
SELECT seq, uni FROM sel_t WHERE skew = 999 |
idx_skew lookup + join-back | 10 | 2.0 ms |
... WHERE skew = 1 forced full scan (control) |
table scan | 90,000 | 234.8 ms |
The hot value is pushed into an index-lookup plan that loses to a full scan (1.26× at only 100k rows; the gap widens with table size). In a join (sel_t JOIN dim ON skew = dim.k WHERE dim.name='d1') the estimated join output is 3.12 rows vs 90,000 actual (28,846× under), with hashmapSize=100 — any downstream operator sized from that estimate is mis-provisioned.
Expected behavior
ANALYZE should collect distribution statistics sufficient to bound the error on common skew patterns (MySQL 8 equivalent: ANALYZE TABLE t UPDATE HISTOGRAM ON col, which is currently a syntax error). At minimum, equality-selectivity for values whose frequency is a large multiple of 1/NDV should not be off by three orders of magnitude after ANALYZE.
Related: #31993 (table-level row estimates never refresh — the companion refresh-path defect), #31880.
Activity
Ariznawlll commentedon Nov 2, 2026
Follow-up on the same table (
sel_t, 100k rows, ANALYZEd): two more estimate defects beyond the uniform-distribution assumption.1.
BETWEENsyntax gets a magic 0.001 selectivity; the equivalent>= AND <=form is exact.uni BETWEEN 1000 AND 1999uni >= 1000 AND uni <= 1999uni < 2000 AND uni >= 1000Same semantics, 100× estimate gap depending on surface syntax. The
BETWEENpath bypasses the (working) range interpolation and falls into a default.2.
IN-list selectivity ignores the element count.uni IN (1,2,3)uni = 1 OR uni = 2 OR uni = 3uni IN (...100 values...)Three elements and one hundred elements produce the identical estimate (another magic ~1% default instead of
count × 1/NDV). Equality OR-chains inherit the same default rather than summing the (correct) per-value1/NDV.Both patterns are common in generated SQL (ORMs emit
INfor batch fetches andBETWEENfor time ranges), so these defaults hit production queries even on perfectly uniform data.Ariznawlll commentedon Nov 2, 2026
Code-level follow-up (main @ current HEAD),
pkg/sql/plan/stats.go:Uniform-equality root cause —
estimateEqualitySelectivity(stats.go:723): returns1/ndvwhenever NDV is known, with no MCV/frequency structure anywhere inpb.StatsInfo. A value held by 90% of rows is estimated identically to one held by 0.01%.BETWEEN magic number —
estimateExprSelectivity(stats.go:1004) dispatch:The binder rewrites surface
BETWEENintoprefix_between, which short-circuits to the hardcoded0.001and never reaches the min/max interpolation that makes the>= AND <=form exact. Same forprefix_in_range. This is one-line-fixable by routingprefix_betweenthroughestimateNonEqualitySelectivity.IN-list — the
inbranch computescard/ndv, but empiricallyIN (1,2,3)andIN (...100 values...)on a NDV=10,000 column produce the identical estimate (selectivity ≈ 0.0095 ≈1-(1-1/NDV)^100), i.e. the OR-rewrite path (orSelectivitychain) with per-element1/NDV— except the 3-element list should then be ≈0.0003, not 0.0095. The 3-vs-100 identical estimate suggests the list length is lost somewhere before estimation (possiblyExpr_Vecpath in the binder); the black-box matrix is in the issue body comment above.Other hardcoded defaults in the same switch (for the record):
!=→ 0.9,like→ 0.2, unknown funcs → 0.15, non-column filters → 0.01, and a global 1% floor viaclampSelectivity. These are probably intentional pragmas, butprefix_between = 0.001sits next to a working implementation for its>= AND <=equivalent, which is why the 100× syntax-dependent divergence looks like a bug rather than a tuning choice.[-][Bug]: selectivity assumes uniform distribution: 900x off on hot values[/-][+][Performance]: selectivity assumes uniform distribution: 900x off on hot values[/+]Ariznawlll commentedon Nov 2, 2026
Retest on a binary built from current main (HEAD c6683bd, built 2026-11-02; original report was against a 2026-09-22 4.0.8 build) — both core defects persist:
BETWEEN magic selectivity still present:
uni BETWEEN 1000 AND 1999on a 100k ANALYZEd uniform column estimatesselectivity=0.001(6.39 rows at the consumer node) vs 1,000 actual — while the equivalent>= AND <=form interpolates correctly. Theprefix_between → 0.001hardcode inestimateExprSelectivityis still there.Hot-value equality still uniform-only, and worse: after rebuilding the skewed column (90,010 rows with
skew=777out of 100,010, FLUSH + ANALYZE),WHERE skew = 777estimates 4.58 rows vs 90,010 actual (~19,600× under). No MCV tracking after ANALYZE; the estimate even undercuts plain 1/NDV at the consuming node, suggesting the join-back estimate compounds the error.Ariznawlll commentedon Nov 4, 2026
结论
补充同类性能边界:倾斜数据叠加复合主键前缀过滤时,AUTO 选择单列索引回表,反而绕开了更便宜的基表块裁剪路径。不是新发现的数据错误,也不是对某个修复 PR 的验收结论,因此不另开重复 issue。
关键证据
0f6c07639604c40d7ca880cb63d1d282239def08,同 SHA 干净源码构建;本地隔离双 CN。本段耗时测量均在同一 CN,不能作为多机性能结论。PRIMARY KEY(tenant,id)、KEY ik(k)、KEY itk(tenant,k),另有时间/金额索引;amount DECIMAL(18,4)、80 字符 payload。原始序号 1..262144:tenant=i%16,约 90% 的非 NULL k=7,其余 k=i,i%31=0 时 k=NULL;随后修改 4 行、删除 4 行。主表和隐藏索引 flush 后 ANALYZE。3 个新建数据库中分别重新建表、复制相同完整数据并 flush/ANALYZE,均复现;这是三个独立对象代次,不是三种不同分布。实际比较的 SQL 仅有索引提示差异,输出为一行聚合,避免大量客户端传输干扰:
每个路径预热 5 次,再交替正序/逆序执行 20 对。中位耗时如下,60/60 对 AUTO 都更慢:
第一代执行计划的关键计数:
tenant=0 AND k BETWEEN 10000 AND 10032在原表 AUTO 中位 0.676 ms、IGNORE 1.044 ms,说明并非所有索引路径都慢。pkg/sql/plan/stats.go:1045–1063的 IN/prefix_IN 仍依赖基数/NDV及默认估算;apply_indices.go的 encodedRegularIndexCostContext 用选择率估算候选及回表行数。这里提供估算与实际计划证据,不把单一计数推断成已经完整定位的唯一根因。待解决点
需要将倾斜值频率、复合主键残余过滤及基表实际裁剪收益一起纳入索引选择验证。这里的 IGNORE 不是物理全表扫描;热缓存、同机配对数据也不代表冷缓存或独占硬件基准。尚未证明调整统计估算后一定会选择最优计划。
Ariznawlll commentedon Nov 4, 2026
结论
补充进程缓存边界:此前热点复合条件的索引选择差距,在重启隔离实例后的首次执行也能观察到。本次不是新的独立问题或修复验收结论。
关键证据
0f6c07639604c40d7ca880cb63d1d282239def08,沿用上一条评论的fact_skew数据和聚合 SQL;AUTO 与 IGNORE 路径分别重启全部自有实例后,在第二个本地 CN 首次执行,然后各热跑 5 次。另开独立重启轮次采集首条 EXPLAIN ANALYZE,避免先执行计划把实际查询预热。inputRows=228313,之后基表扫描 2 块;直接基表路径不需要该索引扫描。首次执行与后续热执行都不是“索引越多越快”。LocalFS的enableDiskCacheForLocalFS默认关闭,当前 DISK-V2 实际没有启用 MO 磁盘缓存;上述重启清除了进程内缓存,但未清理主机 OS 页缓存。共享主机上没有执行全局缓存清理,因此这些数字不能当作物理冷盘或独占硬件基准。待解决点
本次补充不能消除统计估算/路径选择问题,也不能替代远端对象存储、受控 OS 冷缓存的性能测试。更广泛的并发测试仍单独记录,不提前写成长稳通过。
fix(plan): intersect BETWEEN selectivity with column domain (#32224)