Skip to content

fix(plan): normalize decimal index range bounds - #26806

Merged
XuPeng-SH merged 5 commits into
mainfrom
fix/issue-26801-decimal-index-range
Aug 9, 2026
Merged

XuPeng-SH merged 5 commits into
mainfrom
fix/issue-26801-decimal-index-range

Conversation

@XuPeng-SH

Copy link
Copy Markdown
Contributor

Fixes #26801.

Composite secondary-index range rewrites serialized DECIMAL constants using the literal scale instead of the indexed column scale. This produced wrong lower-bound bytes and could under-fetch or over-fetch rows.

The fix losslessly normalizes range constants to the indexed DECIMAL type before serialization. Bounds that require rounding conservatively bypass the index rewrite. Equal-scale and non-DECIMAL paths remain unchanged.

Validation:

  • closed/open paired ranges
  • lower-only and upper-only bounds
  • equality and equal-scale controls
  • rounding-sensitive fallback
  • full pkg/sql/plan CGo suite
  • isolated secondary_index_range BVT: 197/197
  • git diff --check

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner August 8, 2026 23:57
@XuPeng-SH
XuPeng-SH requested a review from a user August 8, 2026 23:57
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Round 30 cross-regression validation passed on a service built from PR head 11151cf9c6b5d66bb383ba409b498e0e8cbbc2ae.

The persisted 50,005-row table has composite PK (tenant_id,id), VARBINARY values including empty/NUL prefixes, and both index orders:

KEY idx_amount_b_pk(amount,b,id,tenant_id),
KEY idx_b_amount_pk(b,amount,status,id,tenant_id)

It was validated after an indexed UPDATE changing DECIMAL values and binary lengths, a flush, and a service restart. Both hidden secondary tables remained exactly 50005 / 50005 / 50005 for row count, distinct encoded key, and distinct primary mapping.

Results on the PR binary:

amount BETWEEN 1000.000000 AND 2000.000000
  FORCE(amount,b) = scan = 10001 rows

same range AND b IN (empty, 0x00)
  FORCE(amount,b) = scan = 121 rows
  count/sum(id)/sum(amount) all match: 121 / 1808389 / 180838.9300

The baseline binary returned zero rows for the second FORCE query. The reverse (b,amount,PK) index still returns 242 because of independent #26807, which is a useful control: this PR fixes the leading DECIMAL range encoding without masking or conflating the VARBINARY prefix defect.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Additional independent validation on the PR binary found a stronger cross-scenario and passed it.

Setup: 60,000-row non-partitioned table with (amount,status,PK) and (status,amount,PK) secondary indexes plus a unique (tenant,natural_key) index. Then:

UPDATE t SET amount=amount-5000.0000, version=version+1 WHERE id%7=0;
UPDATE t SET amount=2000.0000, status='READY', version=version+1 WHERE id%101=0;
UPDATE t SET status='HOLD', amount=amount+0.1250, version=version+1 WHERE id%113=0;
FLUSH;

On current main plus the unrelated #26808 candidate:

default amount<2000                 5659
FORCE (amount,status,PK)            5659
FORCE (status,amount,PK)           20367
full-scan expression oracle        20367

On PR #26806 (11151cf9c6) using the same persisted table:

default                            20367
FORCE (amount,status,PK)           20367
FORCE (status,amount,PK)           20367
full-scan expression oracle        20367
SUM(id)                        522751754  (all four)
SUM(amount)                   562961.0000 (all four)

Before switching binaries, all physical tables were complete:

main table                         60000 rows / 60000 distinct PK
(amount,status,PK) hidden table    60000 rows / 60000 distinct PK
(status,amount,PK) hidden table    60000 rows / 60000 distinct PK
unique hidden table                60000 rows / 60000 distinct PK

This confirms the PR also closes a low-scale upper-bound case exposed only after indexed UPDATE introduced negative DECIMAL values; the failure is range-key rewriting, not hidden-index corruption.

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

Codex automated review

The composite serialized-key fix is correct and safely falls back for rounding-sensitive bounds. One non-blocking performance regression affects single-column UNIQUE DECIMAL indexes.

P2 - Restrict the decimal gate to serialized composite indexes (pkg/sql/plan/apply_indices.go:2275)

This guard is applied to every non-equality index candidate, but only multi-part indexes serialize range bounds. A one-column UNIQUE DECIMAL index keeps its hidden key in the original DECIMAL type, and replaceNonEqualCondition skips serialization when numParts == 1. Therefore a predicate such as price > 10.255000 now fails canSerializeDecimalIndexRangeBounds and skips an otherwise usable unique index, causing non-covering queries (and FORCE INDEX queries) to fall back to a table scan. Restrict the guard to serialized multi-part keys or preserve the scalar unique-index path.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reviewed head 11151cf9c6b5d66bb383ba409b498e0e8cbbc2ae against exact base 08770e1beeb23239c91165492f2fe85243a3c66a.

No additional blocking correctness findings. The lossless DECIMAL normalization is applied on both composite index-join and covering index-only rewrite paths; predicates that cannot be represented at the indexed scale retain a correct base-scan/residual path. The change introduces no resource, wait, or persistent-format edges.

I independently confirmed the existing non-blocking P2: the canSerializeDecimalIndexRangeBounds gate in getIndexForNonEquiCond also rejects rounding-sensitive bounds for one-column UNIQUE DECIMAL indexes even though those keys are stored directly and need no serialization. This can turn a non-covering range lookup (including FORCE INDEX) into a table scan, but does not change query results. Narrowing the gate to serialized-key indexes would avoid that regression; I do not consider it a blocker for this correctness fix.

Independent validation:

  • focused DECIMAL/range and paired-range planner tests: pass
  • go build -mod=readonly ./pkg/sql/plan: pass
  • go vet -mod=readonly ./pkg/sql/plan: pass
  • go test -mod=readonly -count=1 -timeout=120s ./pkg/sql/plan: pass
  • git diff --check: pass
  • current GitHub UT, coverage, CodeQL, and BVT checks: pass

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reviewed exact head c92d1e20852c63b710005db86cbb1f90f01a1ae3 against exact base 08770e1beeb23239c91165492f2fe85243a3c66a.

No actionable findings.

The previously reported P2 is closed systematically:

  • decimal representability and serialized-key operator restrictions are now applied only to candidates whose hidden index key is actually serialized;
  • a direct one-column UNIQUE index on the same leading column remains available as a fallback when the catalog-preferred serialized candidate cannot safely encode the bound;
  • ordinary catalog-order preference is preserved, paired ranges validate both bounds, and single-ended unsafe operators remain restricted only on serialized keys;
  • the covering index-only path uses the same serialized-key classification.

Regression coverage includes a public SQL-to-typed-plan FORCE INDEX assertion for the original single-column UNIQUE DECIMAL case, direct single/paired bounds, both mixed-candidate catalog orders, two-bound fallback, and serialized-only conservative fallback.

Independent validation:

  • focused DECIMAL/range and paired-range planner tests: pass
  • full pkg/sql/plan CGo suite (-count=1): pass
  • go build -mod=readonly ./pkg/sql/plan: pass
  • go vet -mod=readonly ./pkg/sql/plan: pass
  • full PR git diff --check: pass

Lifecycle/unhappy-path audit: no resource ownership or cleanup changes, no wait/blocking edges, and planner-local maps remain bounded by the index/filter lists. The newly triggered GitHub CI is still running; completed checks are passing at review time.

@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Aug 9, 2026

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Deep review completed on exact head 1c22b60cd86bb9f8648e4230c6cbff91710bcd10 against exact base ec06a68b80750b77d1b0eeb6634e2ba9f5529219.

No actionable findings.

The DECIMAL fix preserves correctness across the relevant physical-key shapes: losslessly representable higher-scale bounds are normalized to the indexed column type before serial/serial_full; rounding-sensitive bounds bypass serialized composite-key range access; and direct one-column UNIQUE keys remain eligible without unnecessary serialization restrictions. Paired/open/single-ended ranges, const-on-left forms, OR arms, candidate ordering, prepared/runtime values, and residual rechecks were traced. The direct-key residual path now maps column 0 directly, while serialized mappings handle bind failures conservatively and retain the original base-table predicate.

The latest prefix-index guard is intentionally conservative but correctness-preserving: prefix keys contain transformed values, so equality/range, covering projection, ordering, and join rewrites cannot safely consume predicates over the original values. All regular read entry points now reject those keys and fall back to the base table, including FORCE scopes; this may reduce prefix-index performance until a prefix-aware rewrite exists, but it avoids wrong results and does not affect index maintenance.

No ownership, cleanup, blocking, concurrency, persistent-format, wire-format, or unbounded-memory edges are introduced. Focused changed planner regressions and git diff --check pass; current head/base were revalidated immediately before submission.

@XuPeng-SH
XuPeng-SH force-pushed the fix/issue-26801-decimal-index-range branch from 08cbcaa to 38c88dc Compare August 9, 2026 13:27

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

size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Higher-scale DECIMAL lower bounds return wrong rows through composite secondary indexes

4 participants