Skip to content

[Performance]: selectivity assumes uniform distribution: 900x off on hot values #31994

Open

Description

@Ariznawlll

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 = 1 gets exactly 1/NDV = 1/1000 — the 90% frequency is invisible; there is no most-common-value tracking.
  • BETWEEN 1000 AND 1999 estimates selectivity=0.001 — a magic default that also shows up on skew = 999 and several other nodes; it is not derived from the (correct) < 1000 estimate.
  • skew > 5 assumes 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

  1. added
    kind/bug
    on Nov 2, 2026
  2. added this to the MO-202611 milestone on Nov 2, 2026
  3. added theissue type on Nov 2, 2026
  4. Ariznawlll commented on Nov 2, 2026

    @Ariznawlll
    CollaboratorAuthor

    Follow-up on the same table (sel_t, 100k rows, ANALYZEd): two more estimate defects beyond the uniform-distribution assumption.

    1. BETWEEN syntax gets a magic 0.001 selectivity; the equivalent >= AND <= form is exact.

    predicate est. selectivity est. rows actual
    uni BETWEEN 1000 AND 1999 0.001 100 (scan) 10,000
    uni >= 1000 AND uni <= 1999 0.1 10,001 10,000
    uni < 2000 AND uni >= 1000 0.1001 10,011 10,000

    Same semantics, 100× estimate gap depending on surface syntax. The BETWEEN path bypasses the (working) range interpolation and falls into a default.

    2. IN-list selectivity ignores the element count.

    predicate est. selectivity est. rows actual
    uni IN (1,2,3) 0.0095 160 30
    uni = 1 OR uni = 2 OR uni = 3 0.0095 160 30
    uni IN (...100 values...) 0.0095 160 1,000

    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-value 1/NDV.

    Both patterns are common in generated SQL (ORMs emit IN for batch fetches and BETWEEN for time ranges), so these defaults hit production queries even on perfectly uniform data.

  5. Ariznawlll commented on Nov 2, 2026

    @Ariznawlll
    CollaboratorAuthor

    Code-level follow-up (main @ current HEAD), pkg/sql/plan/stats.go:

    Uniform-equality root cause — estimateEqualitySelectivity (stats.go:723): returns 1/ndv whenever NDV is known, with no MCV/frequency structure anywhere in pb.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:

    case ">", "<", ">=", "<=", "between", "in_range":
        ret = estimateNonEqualitySelectivity(expr, funcName, builder)
    ...
    case "prefix_between", "prefix_in_range":
        ret = 0.001

    The binder rewrites surface BETWEEN into prefix_between, which short-circuits to the hardcoded 0.001 and never reaches the min/max interpolation that makes the >= AND <= form exact. Same for prefix_in_range. This is one-line-fixable by routing prefix_between through estimateNonEqualitySelectivity.

    IN-list — the in branch computes card/ndv, but empirically IN (1,2,3) and IN (...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 (orSelectivity chain) with per-element 1/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 (possibly Expr_Vec path 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 via clampSelectivity. These are probably intentional pragmas, but prefix_between = 0.001 sits 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.

  6. changed the title [-][Bug]: selectivity assumes uniform distribution: 900x off on hot values[/-] [+][Performance]: selectivity assumes uniform distribution: 900x off on hot values[/+] on Nov 2, 2026
  7. Ariznawlll commented on Nov 2, 2026

    @Ariznawlll
    CollaboratorAuthor

    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:

    1. BETWEEN magic selectivity still present: uni BETWEEN 1000 AND 1999 on a 100k ANALYZEd uniform column estimates selectivity=0.001 (6.39 rows at the consumer node) vs 1,000 actual — while the equivalent >= AND <= form interpolates correctly. The prefix_between → 0.001 hardcode in estimateExprSelectivity is still there.

    2. Hot-value equality still uniform-only, and worse: after rebuilding the skewed column (90,010 rows with skew=777 out of 100,010, FLUSH + ANALYZE), WHERE skew = 777 estimates 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.

  8. Ariznawlll commented on Nov 4, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    补充同类性能边界:倾斜数据叠加复合主键前缀过滤时,AUTO 选择单列索引回表,反而绕开了更便宜的基表块裁剪路径。不是新发现的数据错误,也不是对某个修复 PR 的验收结论,因此不另开重复 issue。

    关键证据

    • 2026-11-04,官方 main 0f6c07639604c40d7ca880cb63d1d282239def08,同 SHA 干净源码构建;本地隔离双 CN。本段耗时测量均在同一 CN,不能作为多机性能结论。
    • 表有 262,140 行,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 仅有索引提示差异,输出为一行聚合,避免大量客户端传输干扰:

    SELECT COUNT(*), SUM(amount), SUM(LENGTH(payload))
    FROM hot
    WHERE tenant=0 AND k IN (7,8,10000,10016);
    
    SELECT COUNT(*), SUM(amount), SUM(LENGTH(payload))
    FROM hot IGNORE INDEX(ik,itk,it,ia)
    WHERE tenant=0 AND k IN (7,8,10000,10016);

    每个路径预热 5 次,再交替正序/逆序执行 20 对。中位耗时如下,60/60 对 AUTO 都更慢:

    新建代次 AUTO IGNORE(二级索引禁用,保留主键/块裁剪)
    1 20.558 ms 2.005 ms
    2 22.244 ms 2.150 ms
    3 21.948 ms 2.560 ms

    第一代执行计划的关键计数:

    EXPLAIN VERBOSE / AUTO:
      Index Table Scan hot.ik: outcnt=10
    
    EXPLAIN ANALYZE / AUTO:
      Index Table Scan hot.ik: inputBlocks=28 inputRows=228313 outputRows=12681
        prefix_in(__mo_index_idx_col)
        serial_extract(__mo_index_pri_col, 0, INT) = 0
      Base Table Scan: inputBlocks=2 inputRows=12681 outputRows=12681
    
    EXPLAIN ANALYZE / IGNORE:
      Base Table Scan: inputBlocks=2 inputRows=16382 outputRows=12681
    
    • 索引扫描估计输出 10 行,实际输出 12,681 行;扫描输入与估计输出不是同一口径,未将两者直接作估计误差比较。AUTO 额外处理 228,313 条索引记录;基表凭 tenant 主键前缀即可缩到 2 块。
    • 所有聚合值、命中行的完整列值均与隔离 MySQL 8.0.45 一致。旁路冷门键条件 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 不是物理全表扫描;热缓存、同机配对数据也不代表冷缓存或独占硬件基准。尚未证明调整统计估算后一定会选择最优计划。

  9. Ariznawlll commented on Nov 4, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    补充进程缓存边界:此前热点复合条件的索引选择差距,在重启隔离实例后的首次执行也能观察到。本次不是新的独立问题或修复验收结论。

    关键证据

    • 同一干净构建 0f6c07639604c40d7ca880cb63d1d282239def08,沿用上一条评论的 fact_skew 数据和聚合 SQL;AUTO 与 IGNORE 路径分别重启全部自有实例后,在第二个本地 CN 首次执行,然后各热跑 5 次。另开独立重启轮次采集首条 EXPLAIN ANALYZE,避免先执行计划把实际查询预热。
    • 三轮首次执行耗时,AUTO:57.598 / 48.648 / 54.837 ms;IGNORE(二级索引禁用、仍保留主键/块裁剪):8.577 / 9.012 / 7.738 ms。完整结果与 MySQL 控制值一致。
    • 冷启动计划仍显示 AUTO 索引扫描 inputRows=228313,之后基表扫描 2 块;直接基表路径不需要该索引扫描。首次执行与后续热执行都不是“索引越多越快”。
    • 必须限定“冷”的含义:LocalFS 的 enableDiskCacheForLocalFS 默认关闭,当前 DISK-V2 实际没有启用 MO 磁盘缓存;上述重启清除了进程内缓存,但未清理主机 OS 页缓存。共享主机上没有执行全局缓存清理,因此这些数字不能当作物理冷盘或独占硬件基准。

    待解决点

    本次补充不能消除统计估算/路径选择问题,也不能替代远端对象存储、受控 OS 冷缓存的性能测试。更广泛的并发测试仍单独记录,不提前写成长稳通过。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triage

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions