Skip to content

[Performance] Use object sort-key zonemap for first-column range on composite CLUSTER BY #29507

Closed

Description

@XuPeng-SH

Summary

A time range on the first column of a composite CLUSTER BY key can prune data blocks, but the planner misses the cheaper object-level sort-key zonemap filter. For CLUSTER BY (request_at, account_id), request_at >= lower AND request_at < upper is folded into in_range(request_at, lower, upper, right-open); doMergeFiltersOnCompositeKey returns without generating prefix_in_range on the hidden composite key when the range is on the first component and no preceding equality component exists.

This is an optimization opportunity, not evidence of wrong results or of failed block pruning. It is also not yet proven to be the dominant cause of any particular production query's latency.

Reproduction (v4.2.5, commit 1a44f3db3056e32975fde86ca0ab69a094996a3f)

CREATE TABLE t (
  request_at DATETIME(6) NOT NULL,
  account_id INT UNSIGNED,
  cu DOUBLE
) CLUSTER BY (request_at, account_id);

EXPLAIN VERBOSE
SELECT cu FROM t
WHERE request_at >= '2026-09-29 00:00:00'
  AND request_at <  '2026-09-30 00:00:00'
  AND account_id = 1
ORDER BY cu DESC LIMIT 10;

The scan's filter and block filter contain in_range(t.request_at, ...), but no prefix_in_range predicate on the hidden composite sort key. In the planner's in_range branch, len(filterIdx) < numParts && len(serialArgs) == 0 returns the original filters:

} else if lastFuncName == "in_range" {
if !hasNonNilFunctionArgs(lastFn, 4) {
return filters
}
serialArgs := make([]*plan.Expr, len(filterIdx)-1)
for i := 0; i < len(filterIdx)-1; i++ {
serialArgs[i] = filters[filterIdx[i]].GetF().Args[1]
}
if len(filterIdx) < numParts && len(serialArgs) == 0 {
return filters
}
tmpSerialArgs := DeepCopyExprList(serialArgs)
tmpSerialArgs = append(tmpSerialArgs, lastFn.Args[1])
leftArg, ok := builder.bindCompositeKeySerial(tmpSerialArgs)
. The equivalent early return also exists for one-sided first-component ranges.

The engine already supports open/closed prefix range checks against the object sort-key zonemap:

func (zm ZM) PrefixInRange(lb, ub []byte, hint uint8) bool {
zmin := zm.GetMinBuf()
zmax := zm.GetMaxBuf()
switch hint {
case 1: // (lb, ub]
return types.PrefixCompare(zmax, lb) > 0 && types.PrefixCompare(zmin, ub) <= 0
case 2: // [lb, ub)
return types.PrefixCompare(zmax, lb) >= 0 && types.PrefixCompare(zmin, ub) < 0
case 3: // (lb, ub)
return types.PrefixCompare(zmax, lb) > 0 && types.PrefixCompare(zmin, ub) < 0
default: // [lb, ub]
return types.PrefixCompare(zmax, lb) >= 0 && types.PrefixCompare(zmin, ub) <= 0
}
}
and
case "prefix_in_range":
colExpr, vals, ok := mustColConstValueFromBinaryFuncExpr(exprImpl)
if !ok || len(vals) < 3 || len(vals[2]) == 0 {
canCompile = false
return
}
hint := vals[2][0]
colDef := getColDefByName(expr, colExpr.Col.Name, colExpr.Col.ColPos, tableDef)
_, isSorted := isSortedKey(colDef)
if isSorted {
fastFilterOp = func(obj *objectio.ObjectStats) (bool, error) {
if obj.ZMIsEmpty() {
return true, nil
}
return obj.SortKeyZoneMap().PrefixInRange(vals[0], vals[1], hint), nil
}
. When there is no fast sort-key filter, the ordinary request_at column zonemap path may load object metadata before it can reject old objects.

Local observations

  • Used a local Docker binary containing the exact commit above. Inserted one row and flushed after each write; disabled automatic merge for the test table. The manifest showed 329 live objects / 402 rows.
  • With one row in the target day, EXPLAIN ANALYZE showed 1 scanned block; an adjacent empty day showed 0 scanned blocks. Removing the time predicate scanned 329 blocks / 402 rows. Thus the time filter does prune data correctly.
  • At 329 local objects, the bounded query took about 2 ms first run and 0.3 ms warm. This small local workload does not reproduce a seconds-long production query.
  • A temporary white-box test compiled the plan's in_range(request_at, ...) shape: for a composite cluster key, fastFilterOp == nil and loadOp != nil; for single-column CLUSTER BY(request_at), fastFilterOp != nil. The targeted test passed; the temporary file and local test database were removed.

Expected improvement and validation

Generate a safe hidden-key prefix range for the first component when possible, so old objects can be rejected using resident sort-key zonemaps before loading their column metadata. Keep the original column predicate as a residual correctness check.

Please validate the encoding/prefix invariant and edge cases before changing the guard: [lower, upper), (lower, upper], inclusive BETWEEN, NULLs, DATETIME/TIMESTAMP conversions and precision, empty/reversed bounds, and objects spanning the boundary. Compare results and selected blocks with the existing path; benchmark object metadata requests and latency as object count grows, including a cold cache. Avoid adding per-query work when the conversion cannot be proven safe.

Related but distinct: #26741 / #26918 addressed a DATETIME/TIMESTAMP cast that hid request_at from pruning entirely. Here the column is visible and block pruning works; the missing piece is early pruning from the composite sort-key zonemap. #24289 introduced the existing prefix_in_range machinery for ranges with an equality prefix.

Activity

  1. self-assigned this
    on Sep 29, 2026
  2. added a commit that references this issue on Sep 30, 2026
    76862df
  3. added a commit that references this issue on Sep 30, 2026
  4. Ariznawlll commented on Oct 2, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:main
    • commit:d59cc02ef6ca68f340c9570e56f7eb71d90e42e7
    • 部署方式:本地单机 one-CN,默认配置
    • 测试日期:2026-10-02

    原问题验证

    构造 CLUSTER BY(request_at, account_id) 表,关闭自动 merge,逐批写入并 flush,形成 329 个 live objects / 329 行;执行首列 [lower, upper) 范围并附加 account_id = 1 的查询。

    • 目标日期范围:扫描 1 block / 1 row
    • 相邻空日期范围:扫描 0 blocks / 0 rows
    • 去掉时间范围的对照查询:扫描 329 blocks / 329 rows

    最新计划保留原始 request_at / account_id 行过滤条件,同时生成上下界两个 prefix_in_range(__mo_cbkey, ...) 条件,object sort-key zonemap 可以在读取普通列元数据前完成对象级裁剪。

    正常路径覆盖

    1. 有数据的首列半开区间:20 次平均 0.214 ms,结果正确。
    2. 相邻无数据区间:20 次平均 0.173 ms,返回空集且未扫描 block。
    3. 无时间范围对照:20 次平均 1.214 ms,按预期扫描全部 329 个 blocks。

    边界与保守路径覆盖

    1. 相邻空区间不会误选对象。
    2. 原始 SQL 行过滤条件仍保留,object 级条件仅作为补充裁剪,不改变结果语义。
    3. 不满足安全编码条件的类型仍走保守路径,避免错误的前缀裁剪。

    白盒验证

    以下定向测试连续执行 3 轮均通过:

    • pkg/sql/plan:首列范围、反向操作数、SQL 可达性、独立上下界、unsafe encoding、block-only metadata 列等用例
    • pkg/vm/engine/readutil:TestCompositeLeadingRangeExcludesObjectsBeforeMetadataLoad
    • pkg/partitionprune:TestFilter

    回归测试

    已加入 MOTR PR #209,commit 3b4d80060724d3f19c672d9f039c5df951d63c81,用例:
    suites/14_issue_regression/t/issue_29507_29510_29511_29512_filter_pruning.test

    • 新用例本地连续 10 轮:640/640 statements 通过
    • 完整 14_issue_regression 并发套件中该新增用例通过
    • 离线契约 CI 的 Python 3.10 / 3.12 / 3.13 jobs 全部通过

    本问题属于确定性的优化器条件生成与对象裁剪逻辑,验证不依赖数据量阈值、spill 或内存压力;SQL 回归加定向白盒测试已覆盖,因此不另加 big-data。

    测试结论

    原问题在最新 main 已修复,结果正确,object-level pruning 生效,回归用例已补充。

    测试通过。

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