Repository navigation
feat(plan): support prefix range PK filters on composite keys - #24289
Conversation
ⓘ You've reached your Qodo monthly free-tier limit. Reviews pause until next month — upgrade your plan to continue now, or link your paid account if you already have one. |
Extend composite PK optimization to handle one-sided range filters (< <= > >=) and in_range on non-terminal PK columns by emitting prefix_in_range with the equality prefix as a bound fence. Co-Authored-By: Claude Opus 4.6 <[email protected]>
When a range filter (<, <=, >, >=, in_range) is on the first column of a composite PK with no equality prefix preceding it, bail out instead of emitting a raw comparison on the serialized key which would break the workspace reader's bytes.Compare logic. Co-Authored-By: Claude Opus 4.6 <[email protected]>
When all PK columns are covered (len(filterIdx) == numParts) and the last filter is a range op (<, <=, >, >=), the code previously emitted a raw comparison on the serialized key. This produced incorrect results because e.g. `>(cpkey, serial(5,10))` matches keys with c1>5, not just c1=5 AND c2>10. Now always emit prefix_in_range which uses PrefixCompare to enforce the equality prefix fence. Also fix stray closing brace in in_range col2filter handling. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add len(vals[2]) == 0 guard in ConstructBasePKFilter to prevent panic when prefix_in_range flag slice is empty. Add unit tests for CollectOffsetsByPrefixInRangeFactory and LinearCollectOffsetsByPrefixInRangeFactory covering all hint values (0=both closed, 1=left open, 2=right open, 3=both open), asymmetric prefix fence bounds, and empty vectors. Co-Authored-By: Claude Opus 4.6 <[email protected]>
prefix_in_range and in_range carry a flag (0=both closed, 1=left open, 2=right open, 3=both open). Previously both fell through to PrefixBetween/Between which always uses closed-interval semantics. Add ZM.PrefixInRange(lb, ub, hint) and ZM.InRange(lb, ub, hint) that tighten the pruning condition for open bounds — blocks whose min/max exactly equals an excluded boundary are now correctly pruned. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Implement seekOp for prefix_eq, prefix_between, prefix_in_range, between, in_range, prefix_in, and in filter types - Implement canQuickBreak for all above filter types - Fix prefix_eq/prefix_between seekOp: use monotonic predicate PrefixCompare(max, target) >= 0 instead of PrefixBetween - Fix AND compound seekOp: use max() not min() - Fix OR compound seekOp: seed accumulator with blockCnt not 0 Fixes matrixorigin#24305 Co-Authored-By: Claude Opus 4.6 <[email protected]>
Before building filterIdx, detect paired range conditions on the same column (e.g., `a > 3 AND a < 10`) and merge them into a single `between` or `in_range` expression. This allows the composite PK optimization to emit a proper two-sided prefix_in_range instead of a one-sided range that only uses one bound. Only merges when col2filter currently points to a range op — existing =, between, in, or in_range filters take priority. Co-Authored-By: Claude Opus 4.6 <[email protected]>
When an OR arm has no seekOp (nil), the entire OR cannot skip any blocks — any arm might match from block 0. Previously the OR seekOp seeded at blockCnt, so if all children were nil it returned blockCnt (skip everything), causing empty results for OR filters on flushed data. Co-Authored-By: Claude Opus 4.6 <[email protected]>
When a range filter like `id >= '2.0200101e7'` has its constant value cast to an incompatible type (e.g., date), it becomes a NULL literal. Merging two such filters into `between(col, NULL, NULL)` triggers a panic in opBetweenFixed which doesn't handle null bounds. Skip the merge if either bound in the resulting expression is a null literal — the original individual filters handle NULLs safely via three-valued comparison logic. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add type casts (appendCastBeforeExpr) when merging >= and <= into between/in_range so the runtime receives uniform types (fixes decimal BETWEEN returning empty results) - Construct between/in_range nodes directly (makeBetweenExpr/makeInRangeExpr) bypassing BindFuncExprImplByPlanExpr's hidden fallback that silently rewrites to AND(>=, <=) on type mismatch - Add null bound guards to all 8 between/in_range operator variants - Fix opBetweenBool/inRangeBool: correct alwaysTrue/alwaysFalse logic (only BETWEEN FALSE AND TRUE is always-true, not BETWEEN TRUE AND FALSE) - Remove duplicate range-pair detection from apply_indices.go (single merge in expr_opt.go is now the only mechanism) - Remove @bvt:issue#5150 tags from between_and_operator test Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Use uint8 for range hint in zm.go, search.go, pk_filter.go, expr_filter.go — the flag is 0–3, no reason for int/int64 - Fix expr_filter.go and pk_filter_base.go: read hint as vals[2][0] instead of types.DecodeInt64 which panics on 1-byte folded uint8 - Add TestPrefixInRange and TestInRangeZM for zm.go - Add operator_between_test.go covering null guards, bool logic, and inRange with all 4 flags - Add CompileFilterExpr tests for between, in_range, prefix_in_range (all flags), and prefix_eq/prefix_between seekOp generation Co-Authored-By: Claude Opus 4.6 <[email protected]>
XuPeng-SH
left a comment
There was a problem hiding this comment.
Review (v2): updated PR with 11 commits
The new commits (5-11) add significant value: exact zonemap pruning for open bounds, seekOp/canQuickBreak implementation, paired range-filter merging (a > 3 AND a < 10 → in_range), and various runtime fixes. The logic is well-reasoned overall.
Bug: ConstructBasePKFilter returns Valid=true on invalid flag (must fix)
In pk_filter_base.go, both in_range and prefix_in_range cases set filter.Valid = true before the switch on the flag byte. If an unexpected flag value hits the default: return path, the function returns a filter with Valid=true and Op=0 (which is function.EQUAL). This would cause the PK filter logic to treat a range operation as an equality check — potentially returning wrong results.
// Current (buggy):
filter.Valid = true
switch vals[2][0] {
case 0: filter.Op = function.BETWEEN
// ...
default: return // ← returns with Valid=true, Op=EQUAL
}
// Fix: move Valid=true after the switch, or add filter.Valid=false in defaultImpact: Low in practice since flags always come from the optimizer as 0-3, but this is a correctness issue that should be fixed defensively.
Other observations (non-blocking)
-
Zonemap pruning (zm.go):
PrefixInRangeandInRangewith all 4 hint values are correct. The boundary conditions properly tighten pruning for open bounds. -
seekOp logic (expr_filter.go): AND uses
max(seek to furthest), OR usesminwith immediate return of 0 when any child lacks seekOp — both correct. -
Range-pair merging (expr_opt.go): Detection, type casting, NULL-bound skipping, and construction of between/in_range are all correct. The
classifyRangeBound/canonicalRangeOphelpers properly handle reversed operands. -
operator_between.go: NULL guards and bool logic fixes are correct.
opBetweenBoolnow correctly identifiesBETWEEN FALSE AND TRUEas always-true. -
Test result formatting changes:
.resultfiles still contain unrelated format changes (type annotations, separators). Consider splitting these out to reduce merge conflict surface.
ConstructBasePKFilter has a named return (filter BasePKFilter). The in_range and prefix_in_range cases set filter.Valid = true before the switch on the flag byte, so a bare `return` in `default:` returned a filter with Valid=true and Op=0 (= function.EQUAL). A range op with an unexpected flag would silently be treated as an equality filter. Move filter.Valid = true after the switch so invalid flags produce Valid=false. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Thanks for the thorough re-review @XuPeng-SH.
|
XuPeng-SH
left a comment
There was a problem hiding this comment.
The blocking issue from my previous review is fixed in commit a9977ec.
filter.Valid = true is now correctly set after the flag switch in both in_range and prefix_in_range cases, so an unexpected flag value produces Valid=false instead of Valid=true, Op=EQUAL.
LGTM — approving.
Merge Queue Status
This pull request spent 2 hours 34 minutes 48 seconds in the queue, with no time running CI. Waiting for any of
All conditions
ReasonThe merge conditions cannot be satisfied due to failing checks HintYou may have to fix your CI before adding the pull request to the queue again. |
…k-filter # Conflicts: # pkg/vm/engine/readutil/pk_filter_base.go
…o feat/prefix-range-pk-filter
Merge Queue Status
This pull request spent 23 seconds in the queue, including 3 seconds running CI. Required conditions to merge
|
What type of PR is this?
Which issue(s) this PR fixes:
Ref #23451
Fixes #24305
What this PR does / why we need it:
Extends the composite primary key optimization to handle one-sided range filters (
<,<=,>,>=) andin_rangeon non-terminal PK columns by emittingprefix_in_rangewith the equality prefix as a bound fence.Previously, only
=,IN, andBETWEENwere folded into the composite PK filter. Range comparisons on intermediate columns were left as plain runtime filters that couldn't leverage zonemap pruning or sorted PK search.Changes
Planner
expr_opt.go:</<=/>/>=andin_rangeincol2filter/filterIdxloop. For prefix cases, emitprefix_in_range(key, prefixArg, boundArg, flag).a > 3 AND a < 10) intobetween/in_rangeunconditionally before composite key folding, enabling two-sided prefix filters.between/in_rangenodes directly (makeBetweenExpr/makeInRangeExpr), bypassingBindFuncExprImplByPlanExpr's hidden fallback that silently rewrites toAND(>=, <=)when type check fails — this was causing decimal BETWEEN queries to return empty.appendCastBeforeExpr) so thebetween/in_rangeruntime receives uniform types.apply_indices.go: removed the duplicate range-pair detection pass; the merge inexpr_opt.gois now the single source of truth.Runtime operators (
operator_between.go)between/in_rangevariants (fixed, fixed-with-fn, bytes, bool); previouslyIsConstNullbounds could produce garbage or panic.opBetweenBool:alwaysTrue := lval != rvalincorrectly treatedBETWEEN TRUE AND FALSEas always-true. Correct semantics: onlyBETWEEN FALSE AND TRUEis always-true;BETWEEN TRUE AND FALSEis always-false.inRangeBoolwith a uniformcheckclosure using int8 comparison; the old flag-dispatch had the same always-true mis-logic.Engine / PK filter
pk_filter_base.go:prefix_in_rangemaps toPrefixRangeLeftOpen/RightOpen/BothOpenops based on flag byte.pk_filter.go: wireuint8hint through to vector search.search.go:CollectOffsetsByPrefixInRangeFactoryand linear variant for row-level filtering with open/closed bounds.stats.go): selectivity estimate forprefix_in_range.Zonemap (
zm.go)PrefixInRange(lb, ub, hint)andInRange(lb, ub, hint)with exact open/closed bound semantics.Block filter (
expr_filter.go)seekOpforprefix_eq,prefix_between,prefix_in_range,between,in_range,prefix_in,in.canQuickBreakfor all above filter types.seekOpusedmin()(should bemax()since all conditions must hold).seekOpseeded accumulator at 0 (min(0, pp)always returns 0). Fixed to seed atblockCntwith early return to 0 if any child lacks a seekOp.Hint type
uint8for the range hint end-to-end (zonemap → search → pk_filter → expr_filter). The flag is 0–3; previouslyexpr_filter.goandpk_filter_base.goweretypes.DecodeInt64-ing a 1-byte folded uint8 — latent panic / garbage read.Example
```sql
-- PK(a, b, c): "a=2 AND b < 3" now uses prefix_in_range
EXPLAIN SELECT * FROM t WHERE a = 2 AND b < 3;
-- Filter Cond: prefix_in_range(t.__mo_cpkey_col)
-- PK(a, b): "a=5 AND b > 3 AND b < 100" merges paired range then folds
EXPLAIN SELECT * FROM t WHERE a = 5 AND b > 3 AND b < 100;
-- Filter Cond: in_range(t.__mo_cpkey_col)
```