Skip to content

feat(plan): support prefix range PK filters on composite keys - #24289

Merged
mergify[bot] merged 16 commits into
matrixorigin:mainfrom
aunjgr:feat/prefix-range-pk-filter
May 8, 2026
Merged

mergify[bot] merged 16 commits into
matrixorigin:mainfrom
aunjgr:feat/prefix-range-pk-filter

Conversation

@aunjgr

@aunjgr aunjgr commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Feature
  • Documentation
  • Test and CI
  • Code Refactoring

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 (<, <=, >, >=) and in_range on non-terminal PK columns by emitting prefix_in_range with the equality prefix as a bound fence.

Previously, only =, IN, and BETWEEN were 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:
    • Recognize </<=/>/>= and in_range in col2filter / filterIdx loop. For prefix cases, emit prefix_in_range(key, prefixArg, boundArg, flag).
    • Pre-merge paired range conditions on the same column (e.g., a > 3 AND a < 10) into between/in_range unconditionally before composite key folding, enabling two-sided prefix filters.
    • Merge constructs between / in_range nodes directly (makeBetweenExpr / makeInRangeExpr), bypassing BindFuncExprImplByPlanExpr's hidden fallback that silently rewrites to AND(>=, <=) when type check fails — this was causing decimal BETWEEN queries to return empty.
    • Bounds cast to column type (appendCastBeforeExpr) so the between / in_range runtime receives uniform types.
  • apply_indices.go: removed the duplicate range-pair detection pass; the merge in expr_opt.go is now the single source of truth.

Runtime operators (operator_between.go)

  • Add null-bound guards to all 8 between / in_range variants (fixed, fixed-with-fn, bytes, bool); previously IsConstNull bounds could produce garbage or panic.
  • Fix pre-existing bug in opBetweenBool: alwaysTrue := lval != rval incorrectly treated BETWEEN TRUE AND FALSE as always-true. Correct semantics: only BETWEEN FALSE AND TRUE is always-true; BETWEEN TRUE AND FALSE is always-false.
  • Rewrite inRangeBool with a uniform check closure using int8 comparison; the old flag-dispatch had the same always-true mis-logic.

Engine / PK filter

  • pk_filter_base.go: prefix_in_range maps to PrefixRangeLeftOpen / RightOpen / BothOpen ops based on flag byte.
  • pk_filter.go: wire uint8 hint through to vector search.
  • search.go: CollectOffsetsByPrefixInRangeFactory and linear variant for row-level filtering with open/closed bounds.
  • Stats (stats.go): selectivity estimate for prefix_in_range.

Zonemap (zm.go)

  • New PrefixInRange(lb, ub, hint) and InRange(lb, ub, hint) with exact open/closed bound semantics.

Block filter (expr_filter.go)

  • Implement seekOp for prefix_eq, prefix_between, prefix_in_range, between, in_range, prefix_in, in.
  • Implement canQuickBreak for all above filter types.
  • Fix pre-existing bug: AND compound seekOp used min() (should be max() since all conditions must hold).
  • Fix pre-existing bug: OR compound seekOp seeded accumulator at 0 (min(0, pp) always returns 0). Fixed to seed at blockCnt with early return to 0 if any child lacks a seekOp.

Hint type

  • Use uint8 for the range hint end-to-end (zonemap → search → pk_filter → expr_filter). The flag is 0–3; previously expr_filter.go and pk_filter_base.go were types.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)
```

@qodo-code-review

Copy link
Copy Markdown
ⓘ 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.

@mergify mergify Bot added the kind/feature label May 6, 2026
@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label May 6, 2026
@aunjgr
aunjgr requested review from a user and Copilot May 6, 2026 19:13
aunjgr and others added 11 commits May 8, 2026 15:36
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 XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 default

Impact: 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)

  1. Zonemap pruning (zm.go): PrefixInRange and InRange with all 4 hint values are correct. The boundary conditions properly tighten pruning for open bounds.

  2. seekOp logic (expr_filter.go): AND uses max (seek to furthest), OR uses min with immediate return of 0 when any child lacks seekOp — both correct.

  3. Range-pair merging (expr_opt.go): Detection, type casting, NULL-bound skipping, and construction of between/in_range are all correct. The classifyRangeBound / canonicalRangeOp helpers properly handle reversed operands.

  4. operator_between.go: NULL guards and bool logic fixes are correct. opBetweenBool now correctly identifies BETWEEN FALSE AND TRUE as always-true.

  5. Test result formatting changes: .result files 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]>
@aunjgr

aunjgr commented May 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough re-review @XuPeng-SH.

Valid=true bug — real correctness issue; you're right. ConstructBasePKFilter has a named return, so the bare return in default: after filter.Valid = true returned Valid=true, Op=0 (=EQUAL) — a range op with an unexpected flag would silently become an equality filter. Fixed in a9977ec0b by moving filter.Valid = true after the switch, plus a regression test (TestConstructBasePKFilter_InvalidRangeFlagNotValid) covering both in_range and prefix_in_range.

.result formatting — I'll leave those files as-is. The format "upgrade" is what mo-tester emits today; the old-format lines were already stale relative to the current renderer. Hand-editing them back to the pre-upgrade format would leave a mixed-format file that's harder to maintain than either pure format. The genuine semantic changes in those files (new prefix_in_range plan output, new covering test cases for composite-PK prefix ranges) are all behavioral changes from this PR.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@mergify

mergify Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-05-08 10:02 UTC · Rule: main
  • ✅ Checks started · in-place
  • 🚫 Left the queue — 2026-05-08 12:37 UTC · at 3412276c2664155c4005d084d39fb64e073cc26f

This pull request spent 2 hours 34 minutes 48 seconds in the queue, with no time running CI.

Waiting for any of
  • check-neutral = Matrixone Utils CI / Coverage
  • check-skipped = Matrixone Utils CI / Coverage
  • check-success = Matrixone Utils CI / Coverage
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • branch-protection-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI / SCA Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)

Reason

The merge conditions cannot be satisfied due to failing checks

Hint

You may have to fix your CI before adding the pull request to the queue again.
If you update this pull request, to fix the CI, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

@mergify

mergify Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-05-08 17:51 UTC · Rule: main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-05-08 17:52 UTC · at 525d3c73980dae74bb97708cc63be74fed9d22df · squash

This pull request spent 23 seconds in the queue, including 3 seconds running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • branch-protection-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI / SCA Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage

This branch was previously deployed

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

Labels

kind/bug Something isn't working kind/enhancement kind/feature size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: AND/OR seekOp always returns 0 due to min() with zero-initialized accumulator

5 participants