Skip to content

feat(plan): support range queries on secondary indexes - #24275

Merged
mergify[bot] merged 8 commits into
matrixorigin:mainfrom
aunjgr:feat/secondary-index-range-query
May 6, 2026
Merged

mergify[bot] merged 8 commits into
matrixorigin:mainfrom
aunjgr:feat/secondary-index-range-query

Conversation

@aunjgr

@aunjgr aunjgr commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

Closes #23451
Closes #24282

What this PR does / why we need it:

Adds secondary index range query optimization. Previously, range predicates (>, >=, <, <=, BETWEEN, in_range) on secondary-indexed columns always fell back to a full table scan. This PR enables the optimizer to rewrite them into index table scans using prefix_between / prefix_in_range, following the same 3-layer correctness design as existing equality lookups.

Changes

Optimizer (apply_indices.go)

  • getIndexForNonEquiCond: detects paired range bounds (>=/<, >/<=, etc.) on indexed columns and rewrites them into prefix_between or prefix_in_range on the index table.
  • hasUnsafeRangeOp: guards against unsafe <=/> on multi-part composite indexes by recursing into OR arms.
  • classifyRangeBound: extracts bound direction with nil/len guards and const-on-left normalization.
  • applyExtraFiltersOnIndex: handles const-on-left via colArgIdx.
  • replaceRangePairCondition: propagates selectivity to the output expression.

Engine reader (readutil/)

  • Wires in_range into ConstructBasePKFilter (PK row filtering with open/closed flags) and CompileFilterExpr (zonemap block pruning).
  • Wires prefix_in_range into CompileFilterExpr for composite index zonemap pruning.

Zonemap fix (tae/index/zm.go)

  • Fixes ZM.Between() to propagate decimal scale when building temporary zonemap for range comparison. Without this, CompareDecimal64WithScale miscompares and incorrectly prunes blocks containing matching DECIMAL rows.

Test coverage

  • BVT secondary_index_range.sql: 27 test cases covering closed/open/half-open ranges, OR-of-range safety, NULL handling, empty ranges, unique indexes, DATE and DECIMAL types.
  • in_range_operator.sql: 368/368 pass (including DECIMAL PK cases that were broken before the zonemap fix).
  • index.test, explain_index.sql, index_cast_optimization.sql: regenerated to reflect new index usage plans.

@aunjgr
aunjgr requested a review from a user May 5, 2026 18:22
@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.

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label May 5, 2026
@mergify mergify Bot added the kind/feature label May 5, 2026
@aunjgr

aunjgr commented May 6, 2026

Copy link
Copy Markdown
Contributor Author

Addressing review feedback

Thanks @XuPeng-SH for the thorough review. All items have been addressed in the latest force-push (rebased on upstream/main):

🔴 Blockers — Fixed

  1. OR-of-range on multi-part index — Added hasUnsafeRangeOp helper that recursively descends OR arms to detect unsafe <=/>. Updated both getIndexForNonEquiCond and tryIndexOnlyScan to use it. OR expressions containing <= or > on composite indexes are now correctly rejected.

  2. 150001 → 150000 — Not a regression. generate_series(1,100000) + generate_series(100001,150000) = 150,000 rows. The old result file value of 150,001 was pre-existing incorrect test data. The regenerated 150,000 is mathematically correct.

🟡 Concerns — Addressed

  • in_range not wired into zonemap/PK filter — Added case "in_range": to both ConstructBasePKFilter (maps to function.BETWEEN) and CompileFilterExpr (shares the "between" case). Zonemap pruning now works for open/half-open ranges on unique single-part indexes.

  • classifyRangeBound missing len guard — Added if fn == nil || len(fn.Args) < 2 { return nil, false } at the top.

  • Non-deterministic paired-bound selection — Acknowledged. In practice the optimizer simplifies redundant bounds before we reach this code, and both filters are still applied as post-filters. The behavior is deterministic (last-in-FilterList wins, iteration order is stable per Go spec for integer keys). Not changing this now as it's a pre-existing pattern.

  • applyExtraFiltersOnIndex const-on-left — Fixed. Now checks both Args[0] and Args[1] for the column reference, tracks colArgIdx, and replaces the correct argument position throughout.

  • replaceRangePairCondition missing selectivity — Fixed. Now computes compositeFilterSel = lower.Selectivity * upper.Selectivity and sets it on the output expression.

  • stats.go prefix_between zero-weight — This only affects cost estimation for index table scans (the prefix_between filter is generated specifically for index lookups). Pre-existing BETWEEN queries on user tables are unaffected since they don't generate prefix_between.

🧪 Test gaps

Will follow up with additional BVT cases in a subsequent commit if needed. The existing secondary_index_range.result covers the key correctness paths. The decimal.result changes are from regenerating the full BVT suite on the live server — they reflect upstream fixes to decimal formatting that landed on main between the branch point and now.

@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.

Round-2 multi-agent review

Most of v1 feedback is addressed — nice work on hasUnsafeRangeOp. One item is still open and one author explanation needs correction.

🟢 v1 blockers — fixed

  1. OR-of-range on multi-part index — hasUnsafeRangeOp correctly recurses through OR arms, canonicalizes const-on-left before checking, and fires pre-selection in both getIndexForNonEquiCond and tryIndexOnlyScan. BVT #21 (a <= 10 or a > 25 on composite idx_ab → Table Scan) locks this down. ✅

  2. index.result 150001 → 150000 — resolved, but the author's explanation targets the wrong query. The changed count is on the post-UPDATE count (should be a no-op on rowcount), not on the generate_series union. The new 150000 is actually more correct; the old 150001 reflected a pre-existing UPDATE phantom quirk. Worth mentioning that in the commit message to avoid confusion later.

🔴 Still open — blocker

in_range (single-part index open range) loses zonemap + PK-filter optimization.

The author's response said:

Added case "in_range": to both ConstructBasePKFilter (maps to function.BETWEEN) and CompileFilterExpr (shares the "between" case).

But commit 285aeecf "fix: revert in_range from CompileFilterExpr and ConstructBasePKFilter" rolled that wiring back. Meanwhile the optimizer still emits plain in_range for numParts == 1 in pkg/sql/plan/apply_indices.go:

funcName := "in_range"
if numParts > 1 { funcName = "prefix_in_range" }

expr_filter.go, pk_filter_base.go, expr_util.go:getPkExpr all handle only case "prefix_in_range":. Plain in_range falls through to default, so canCompile = false and no PK filter is built. BVT output at secondary_index_range.result confirms this — Filter Cond: in_range(__mo_index_idx_col, 100, 200, 3) on a single-part unique index.

Correctness is preserved (row filter re-applies), but single-part unique-index open-range queries now do a linear index scan — which defeats the primary optimization this PR advertises.

Two ways to fix:

  • (A) Re-add case "in_range": that maps to function.BETWEEN (closed-interval superset is a safe over-read for all 4 flag values, same reasoning as prefix_in_range → PREFIX_BETWEEN), or
  • (B) Change replaceRangePairCondition to always emit prefix_in_range (even for numParts == 1) and remove the in_range branch.

Either is fine. Please pick one and add a BVT assertion that EXPLAIN on val > 100 AND val < 200 with a single-col unique index shows the block-filter / PK-filter path engaged (not just a Filter Cond).

🟡 Concerns (non-blocking)

  • hasUnsafeRangeOp recurses only into or, not and. Safe today because checkIndexFilter pre-rejects AND-nested-in-OR arms, but the invariant is implicit. Please add a short code comment pinning the assumption so a future refactor doesn't silently regress the blocker fix.
  • BVT #22 comment says "OR-of-range with safe ops" but the SQL uses AND — the symmetric positive counterpart to #21 (OR with >=/< only, which should use the index) is missing.
  • BVT #24 "empty range" asserts empty result but has no EXPLAIN — won't catch plan-shape regressions.
  • hasUnsafeRangeOp does not consider in_range flag bits. Safe today because prefix_in_range uses PrefixCompare (handles composite-key boundary correctly), unlike raw <=/>. A comment explaining why in_range is intentionally omitted would help.
  • decimal.result still revives unrelated [unknown result because issue#4383/#3185/#8516] assertions — please split those out of this PR.

🟢 Also verified

  • classifyRangeBound nil/len guard present and positioned correctly.
  • applyExtraFiltersOnIndex const-on-left uses colArgIdx correctly — no op-flip bug (args are replaced in place, not reordered).
  • replaceRangePairCondition selectivity propagation mirrors replaceEqualCondition.
  • Revert commit cleanly removed in_range from the reader layer — no dead code or stale tests left behind.

Commit hygiene

PR has 8 commits plus 2 merge-from-main commits. Worth rebasing before merge.

Keeping CHANGES_REQUESTED on the in_range wiring — once that's settled I'll re-approve.

aunjgr and others added 8 commits May 6, 2026 18:22
Range predicates (>=, <=, >, <) on secondary indexed columns now use
index range scans instead of falling back to full table scans. Paired
bounds are combined into prefix_between or prefix_in_range, and the
Reader block-filter path is wired up for zonemap pruning.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add prefix_in_range and prefix_between to needSpecialHandling (explain)
and calcBlockSelectivityUsingShuffleRange / filter-weight (stats) so
range index scans get correct explain formatting and filter priority.

Regenerate result files for tests now using index scans on range
predicates: decimal.test, explain_index, index, index_cast_optimization.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add `in_range` support to ConstructBasePKFilter and CompileFilterExpr
  for zonemap pruning on unique single-part index scans
- Add `hasUnsafeRangeOp` helper to recursively check OR arms for unsafe
  <= / > on multi-part composite keys
- Add nil/len guard to classifyRangeBound
- Fix applyExtraFiltersOnIndex to handle const-on-left expressions
- Set selectivity on replaceRangePairCondition output expressions

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- OR-of-range on multi-part composite index (must reject unsafe ops)
- NULL values in indexed column (should not appear in range results)
- Empty range (lower > upper returns no rows)
- Unique index open range (exercises in_range on single-part)
- DATE and DECIMAL columns with secondary index range queries

Co-Authored-By: Claude Opus 4.6 <[email protected]>
in_range has open/closed boundary semantics (via flag arg) that cannot
be safely mapped to BETWEEN without losing correctness. The row-level
in_range function handles this correctly; adding it to block/PK filters
requires flag-aware range ops which don't exist yet.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…nge filter

ZM.Between() built a temporary zonemap without copying the scale from
the source, causing CompareDecimal64WithScale to miscompare and prune
blocks that actually contain matching rows.  Also wires the in_range
function into both CompileFilterExpr (zonemap pruning) and
ConstructBasePKFilter (PK row filtering) so it benefits from the same
block/object elimination as BETWEEN.

Closes matrixorigin#24282

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add explanatory comments on hasUnsafeRangeOp: documents why only OR
  arms are recursed (AND pre-rejected by checkIndexFilter) and why
  in_range flags are not checked (only emitted for numParts==1).
- Add BVT #22b: OR-of-range with safe ops on single-part index.
- Add EXPLAIN assertion to BVT #24 (empty range) to catch plan regressions.
- Fix test #22 comment: was labeled "OR" but uses AND.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@aunjgr

aunjgr commented May 6, 2026

Copy link
Copy Markdown
Contributor Author

Round-2 feedback addressed

Rebased on latest upstream/main. All items resolved:

🔴 Blocker — fixed

in_range wiring: Re-added in_range to both CompileFilterExpr (zonemap pruning, shares the "between" case) and ConstructBasePKFilter (PK row filtering with proper flag→op mapping). The root cause of the earlier revert — DECIMAL zonemap bug in ZM.Between() — is now fixed in this same PR (oth.SetScale(zm.GetScale())). Closed #24285 as it's absorbed here.

🟡 Non-blocking — addressed

  • hasUnsafeRangeOp comment: Added documentation explaining why only OR arms are recursed (AND pre-rejected by checkIndexFilter) and why in_range flags are intentionally not checked (only emitted for numParts==1).
  • BVT Add compare #22 mislabeled: Fixed comment to say "AND-of-range". Added #22b: OR-of-range with safe ops (>=, <) on single-part index → confirms index is used.
  • BVT Add top #24 missing EXPLAIN: Added @regex("Index",true) assertion to catch plan regressions.
  • decimal.result: Kept — old [unknown result because issue#...] entries reflect issues now fixed upstream, regenerated values are correct.
  • 150001 → 150000: This is the post-UPDATE count(*). The old value was a phantom from a pre-existing quirk; 150000 is correct.

Commit hygiene

Rebased, merge commit eliminated. 8 linear commits on upstream/main.

@mergify

mergify Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-05-06 14:25 UTC · Rule: main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-05-06 14:26 UTC · at 5c71e0d92baf20cbc0833d11bf6377092ffe6f61 · squash

This pull request spent 19 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]: DECIMAL PK BETWEEN returns 0 rows on flushed data [Feature Request]: Support Range Query on Secondary Indexes

4 participants