Repository navigation
Description
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:
matrixone/pkg/sql/plan/expr_opt.go
Lines 2380 to 2395 in 1a44f3d
| } 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 engine already supports open/closed prefix range checks against the object sort-key zonemap:
matrixone/pkg/vm/engine/tae/index/zm.go
Lines 732 to 747 in 1a44f3d
| 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 | |
| } | |
| } | |
matrixone/pkg/vm/engine/readutil/expr_filter.go
Lines 1028 to 1043 in 1a44f3d
| 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 | |
| } |
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 ANALYZEshowed 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 == nilandloadOp != nil; for single-columnCLUSTER 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
Optimize leading ranges on composite sort keys (#29513)
[4.2-dev] Backport #29513: composite range pruning and DECIMAL256 saf…
Ariznawlll commentedon Oct 2, 2026
测试版本
maind59cc02ef6ca68f340c9570e56f7eb71d90e42e7原问题验证
构造
CLUSTER BY(request_at, account_id)表,关闭自动 merge,逐批写入并 flush,形成 329 个 live objects / 329 行;执行首列[lower, upper)范围并附加account_id = 1的查询。最新计划保留原始
request_at/account_id行过滤条件,同时生成上下界两个prefix_in_range(__mo_cbkey, ...)条件,object sort-key zonemap 可以在读取普通列元数据前完成对象级裁剪。正常路径覆盖
边界与保守路径覆盖
白盒验证
以下定向测试连续执行 3 轮均通过:
pkg/sql/plan:首列范围、反向操作数、SQL 可达性、独立上下界、unsafe encoding、block-only metadata 列等用例pkg/vm/engine/readutil:TestCompositeLeadingRangeExcludesObjectsBeforeMetadataLoadpkg/partitionprune:TestFilter回归测试
已加入 MOTR PR #209,commit
3b4d80060724d3f19c672d9f039c5df951d63c81,用例:suites/14_issue_regression/t/issue_29507_29510_29511_29512_filter_pruning.test14_issue_regression并发套件中该新增用例通过本问题属于确定性的优化器条件生成与对象裁剪逻辑,验证不依赖数据量阈值、spill 或内存压力;SQL 回归加定向白盒测试已覆盖,因此不另加 big-data。
测试结论
原问题在最新 main 已修复,结果正确,object-level pruning 生效,回归用例已补充。
测试通过。