Repository navigation
feat(plan): support range queries on secondary indexes - #24275
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. |
Addressing review feedbackThanks @XuPeng-SH for the thorough review. All items have been addressed in the latest force-push (rebased on upstream/main): 🔴 Blockers — Fixed
🟡 Concerns — Addressed
🧪 Test gapsWill follow up with additional BVT cases in a subsequent commit if needed. The existing |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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
-
OR-of-range on multi-part index —
hasUnsafeRangeOpcorrectly recurses through OR arms, canonicalizes const-on-left before checking, and fires pre-selection in bothgetIndexForNonEquiCondandtryIndexOnlyScan. BVT #21 (a <= 10 or a > 25on compositeidx_ab→Table Scan) locks this down. ✅ -
index.result150001 → 150000 — resolved, but the author's explanation targets the wrong query. The changed count is on the post-UPDATEcount (should be a no-op on rowcount), not on thegenerate_seriesunion. The new150000is actually more correct; the old150001reflected 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 bothConstructBasePKFilter(maps tofunction.BETWEEN) andCompileFilterExpr(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 tofunction.BETWEEN(closed-interval superset is a safe over-read for all 4 flag values, same reasoning asprefix_in_range → PREFIX_BETWEEN), or - (B) Change
replaceRangePairConditionto always emitprefix_in_range(even fornumParts == 1) and remove thein_rangebranch.
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)
hasUnsafeRangeOprecurses only intoor, notand. Safe today becausecheckIndexFilterpre-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. hasUnsafeRangeOpdoes not considerin_rangeflag bits. Safe today becauseprefix_in_rangeusesPrefixCompare(handles composite-key boundary correctly), unlike raw<=/>. A comment explaining whyin_rangeis intentionally omitted would help.decimal.resultstill revives unrelated[unknown result because issue#4383/#3185/#8516]assertions — please split those out of this PR.
🟢 Also verified
classifyRangeBoundnil/len guard present and positioned correctly.applyExtraFiltersOnIndexconst-on-left usescolArgIdxcorrectly — no op-flip bug (args are replaced in place, not reordered).replaceRangePairConditionselectivity propagation mirrorsreplaceEqualCondition.- Revert commit cleanly removed
in_rangefrom 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.
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]>
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]>
Round-2 feedback addressedRebased on latest upstream/main. All items resolved: 🔴 Blocker — fixed
🟡 Non-blocking — addressed
Commit hygieneRebased, merge commit eliminated. 8 linear commits on upstream/main. |
Merge Queue Status
This pull request spent 19 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:
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 usingprefix_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 intoprefix_betweenorprefix_in_rangeon 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 viacolArgIdx.replaceRangePairCondition: propagates selectivity to the output expression.Engine reader (
readutil/)in_rangeintoConstructBasePKFilter(PK row filtering with open/closed flags) andCompileFilterExpr(zonemap block pruning).prefix_in_rangeintoCompileFilterExprfor composite index zonemap pruning.Zonemap fix (
tae/index/zm.go)ZM.Between()to propagate decimal scale when building temporary zonemap for range comparison. Without this,CompareDecimal64WithScalemiscompares and incorrectly prunes blocks containing matching DECIMAL rows.Test coverage
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.