Repository navigation
fix(plan): use bounded key-set access for composite index IN prefixes (#32410) - #32567
Conversation
A composite index whose leading columns are equality bound and whose trailing column is a bounded IN list was only usable through a broad prefix or a residual filter, so a lookup for a handful of keys could scan every row sharing the equality prefix. Recognize a single constant, non-NULL IN dimension on any user key part when all other key parts are equality bound, serialize one composite key per IN element, and feed the resulting tuple list to the existing PREFIX_IN index access primitive. The original SQL predicates stay on the base-table scan, so subsetting, NULL semantics and non-key filters keep their previous behavior. Multiple IN dimensions, NULL-containing lists, oversized lists/keys and unsupported key types fall back to the existing scans. The unique-point cost bypass is skipped for a key set, which is bounded by the list cardinality instead of one row. Tests: planner unit tests for unique/secondary indexes, IN in leading and middle key positions, duplicates, NULL and oversized lists; a distributed optimizer case asserting an index table scan with prefix_in and identical results with and without the index.
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
This pull request is merged. |
|
mo-bot review · Commit: "interrupted" |
QA challenge results (local, 4.2-dev base 1bde992)Method: adversarial A/B on a real 3-node launch cluster. Oracle is Correctness — no row mismatch found20+ paired queries covering: Lowering actually chosen
Fallback boundaries confirmed128-element Known limitation (pre-existing, not introduced here)Covering index-only access is not wired to the key set. On the 20,000-row secondary index: Regression checks on the final pushed commit
|
XuPeng-SH
left a comment
There was a problem hiding this comment.
Source review of commit d5a6b9d93e8209fc0a9926f390ca24810ca2d0f6.
The single-IN-dimension approach, per-element tuple serialization, and reuse of PREFIX_IN look reasonable for ordinary full-value composite keys. Keeping the original base-table predicates is also the right safeguard for residual filtering.
I found an unhandled lowering-failure path, a key-format mismatch for prefix-length indexes, and avoidable quadratic copying for long variable-length IN lists. Details and focused regression cases are inline.
These findings are derived from the source at this commit. I have not independently run the Go tests, SQL reproductions, or performance benchmarks. I read the added QA report; the mixed runtime-equality/literal-IN case, prefix-length indexes, and long variable-length lists still need targeted coverage.
| tupleVec := tuples[row].GetVec() | ||
| if tupleVec == nil { | ||
| return nil |
There was a problem hiding this comment.
[P1] Handle lowering failure before publishing the index scan
This nil return does not restore the old access path. applyIndexJoin accepts the result without checking it and creates FilterList: []*plan.Expr{idxFilter} (apply_indices.go:2555-2586). appendNode immediately recalculates statistics; when index statistics are available, calcScanStats writes filter.Selectivity through that nil filter (stats.go:1748-1753). The serialized-byte-limit and other failure returns have the same problem.
The candidate/lowerer contracts also disagree on equality values: checkIndexFilter accepts runtime constants, including parameters, while bindFuncExprAndConstFold calls ConstantFold(..., false, true) for serial/serial_full (base_binder.go:3102-3106). A mixed candidate such as a = ? AND b IN (2,3), with a non-covered projection, needs a focused regression because an equality value that remains dynamic leaves serial(...) unfolded and reaches this branch. The general prepared-statement QA result does not establish that this specific candidate reaches the new lowering successfully.
Please propagate lowering failure before appending any index node and retain a valid old index/scan path, or restrict candidate admission to values this lowerer can actually materialize. Source-derived finding; not independently reproduced.
| } else { | ||
| serialArgs[i] = DeepCopyExpr(fn.Args[1]) | ||
| } | ||
| } | ||
| tuples[row], err = bindFuncExprAndConstFold( | ||
| builder.GetContext(), builder.compCtx.GetProcess(), | ||
| indexTableLookupSerialFunc(idxDef), serialArgs, |
There was a problem hiding this comment.
[P1] Match the stored prefix-length index format before serializing lookup tuples
The new candidate matching includes prefix-length indexes, but this lowerer never reads idxDef.IndexAlgoParams or applies their truncation. The index write path reads those lengths and calls appendIndexPrefixProjection, which builds substring(value, 1, prefix_length) before storing the key (write path, truncation).
For an existing KEY idx_ab(a,b(4)) and a row (a=1,b='abcdef'), SELECT payload ... WHERE a=1 AND b IN ('abcdef','wxyz12') now probes the encoding of (1,'abcdef'), but the secondary index stores (1,'abcd',pk). PREFIX_IN cannot match those bytes, so the row is lost before the retained base-table predicate can run. Selecting a non-covered payload exercises the backfill path. The previous partial lookup on a could return this row correctly.
Please conservatively exclude prefix-length indexes from this new path, or apply exactly the write-side key transformation to every tuple and keep the residual. Add an indexed-versus-IGNORE INDEX execution test with an IN value longer than its indexed prefix. Source-derived finding; not independently reproduced.
| for row := 0; row < inVec.Length(); row++ { | ||
| rowVec, err := inVec.Window(row, row+1) | ||
| if err != nil { | ||
| return nil | ||
| } | ||
| data, err := rowVec.MarshalBinary() |
There was a problem hiding this comment.
[P2] Compact the single-element varlen payload instead of marshaling the whole IN area per tuple
Vector.Window slices the row descriptors but keeps the original entire varlen area (vector.go:5348-5353). MarshalBinary includes and copies that complete area (vector.go:953-968,1021-1027). Consequently this loop copies O(K * B) bytes for K IN elements with B total string/binary payload bytes. The subsequent constant-fold helper also deep-copies each temporary expression.
At the allowed 128 elements, an approximately 8 MiB payload consisting of 128 approximately 64 KiB strings entails approximately 1 GiB of payload copying in this marshal loop alone, despite both input and serialized result remaining below the 80 MiB budget. This is a source-derived traffic calculation, not a measured latency or peak-memory result.
Please build a compact one-element vector/scalar representation that only owns the selected value, and add a long VARCHAR/VARBINARY planning benchmark near the list-size limit. The current byte budget does not bound cumulative copying.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 832ff02b62cec9524c69306c5c81dd823032e065
Assessment: approve
The bounded key-set path coherently reuses existing serialization, PREFIX_IN and index joins. Earlier lowering, prefix-format and copying concerns are resolved. No actionable findings remain.
Model: gpt-6.1-sol / max
Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0
Validation:
-
Receipts and retained logs reconciled in validation-audit.json; source unchanged.
-
Planner build, vet, all 10 focused tests and owning-package tests passed; three unrelated subtests skipped.
-
Exact index_hint BVT passed 151/151 on three CNs using supplied executors.
-
Independent SQL checks matched IGNORE INDEX and observed three index input rows for unique and secondary key sets on 5,000 rows.
-
Varlen compaction test and benchmark passed.
Limitations:
-
Covering index-only key-set optimization remains outside this change.
-
Full repository CI, baseline latency benchmarks and the author's broader historical type sweep were not independently run.
XuPeng-SH
left a comment
There was a problem hiding this comment.
QA re-challenge on eb222b3b8bd927bd04382088efdfea4506dcfb51: one confirmed performance regression remains.
On a flushed/analyzed 1,000-row table with a non-covering UNIQUE(a,b) index, the 100-point IN case is admitted by the new 10% cost gate. After warming both plans, 80 interleaved prepared EXECUTE pairs measured:
- PR automatic key-set: 0.2071875 ms median, 0.253375 ms p95.
- PR
IGNORE INDEXscan: 0.134479 ms median, 0.182333 ms p95. - Base automatic scan: 0.1602085 ms median.
The automatic PR plan is therefore 54.07% slower than its own scan oracle and 29.32% slower than base. Results are identical (count=100, sum=5050), so this is a performance regression rather than a correctness failure. The adjacent 101-point case falls back to a scan and has no comparable regression; the earlier 128-point case also falls back. The small-table problem has thus moved to the still-admitted 100-point boundary rather than being fully closed.
Please tighten the non-covering key-set break-even decision and add a prepared-execution benchmark around 100/101 points on a flushed 1,000-row table. Reproduction and evidence: #32644.
Other checks on this exact head passed: 35 indexed/scan pairs (70 result oracles) matched across base/head, the full planner race test passed, the previous wide-IN planning amplification was eliminated, and the flushed 60,000-row target case retained an approximately 2.15× improvement over its scan oracle.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: eb222b3b8bd927bd04382088efdfea4506dcfb51
Assessment: request_changes
New same-head execution evidence changes the prior approval: the 10% gate admits a slower small-table plan. Serialization, candidate ranking and shared work-budget design remain accepted.
Model: gpt-6.1-sol / max
Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0
- P2
pkg/sql/plan/index_keyset.go:291: A warmed prepared non-covering UNIQUE(a,b) lookup with a=1 and 100 distinct b values on a flushed/analyzed 1,000-row table.
Impact: The gate admits 100 probes at scan cost 1,000. Reported median EXECUTE latency is 0.2071875 ms versus 0.1602085 ms for base automatic execution (+29.32%) and 0.134479 ms for the head's scan control (+54.07%).
Evidence: Review #5880370760 and issue #32644 report 80 interleaved shuffled AB/BA pairs with equal results; the adjacent 101-point case falls back without comparable slowdown. Integrated tests explicitly preserve this admission boundary. Recalibrate the shared non-covering cost gate and validate the prepared boundary while preserving FORCE behavior and profitable large-table access.
Validation:
-
Reused authenticated exact-head review #5879342497's complete assessment and reported planner, race, build/vet and SQL coverage.
-
Traced admission and fallback consumers and 100/101-point tests; reconciled all 33 discussion items and both linked issues.
-
CI snapshot records successful build, unit, static and BVT checks. Local input/discussion/result audit passed; receipt checks/1794511038737717235-3.json and matching logs are retained.
Limitations:
- Timing results are supplied reports; raw samples were unavailable and measurements were not independently reproduced. No local Go tests or SQL runtime checks were rerun for this discussion follow-up.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: c10ddba435279702782291a99109a94e4d2ec495
Assessment: approve
The shared admission screen resolves the reported small-table regression while retaining the original bounded-access case. Serializer reuse, candidate ranking and necessary exhaustive fallback form a coherent design. No actionable findings remain.
Model: gpt-6.1-sol / max
Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0
Validation:
-
Reviewed all 16 changed files, relevant owners/consumers, both linked issues and all 35 discussion entries.
-
Preflight and native prerequisite build passed. All 40 focused tests and 100 independent-builder race repetitions passed.
-
Planner race run (-short, matrixone_test): 1778 top-level tests passed. Plan and compile passed build and vet.
-
Formatting, diff, source-clean and receipt/log audits passed; evidence retained in validation-audit.json.
Limitations:
-
Three unchanged, unrelated nested tests were skipped. Current CI was pending in the supplied snapshot.
-
Public SQL/BVT and controlled ABBA latency results were assessed from supplied reports, without raw logs or local reruns. Admission remains a statistics-based heuristic.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 0a3cd2f171abc88172b36d318433f0c14fac9c61
Assessment: approve
The shared admission screen and per-scan work budget resolve the earlier findings. Existing serializers and index joins are reused; ranking limits materialization while exhaustive fallback preserves safe selection. No actionable findings remain.
Model: gpt-6.1-sol / max
Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0
Validation:
-
Reviewed all 16 changed paths, affected owners/consumers, both linked issues and all 37 discussion entries.
-
Supplied preflight passed; 173 native build inputs and 46 retained outputs were independently verified.
-
Go 1.26.4: all 40 focused tests, 100 independent-builder stress repetitions and 1,778 planner-package top-level tests passed under -race -short -tags matrixone_test using the supplied executor.
-
Plan and dependent compile packages passed build and vet. Source, formatting, fixture arithmetic, discussion coverage and receipt/log audits passed.
-
Assessed author-reported integrated SQL/BVT and controlled ABBA results against maintained result, scan-control and plan oracles.
Limitations:
-
Three unchanged nested tests were skipped; relevant CI checks remained pending in the frozen snapshot.
-
Public SQL/BVT and latency comparisons were not independently rerun; their raw logs were unavailable.
-
Admission remains a statistics-based heuristic; the encoding-work budget does not bound total or peak memory.
What type of PR is this?
Which issue(s) this PR fixes:
Fixes #32410.
Fixes #32644.
What this PR does / why we need it:
A predicate such as
user_id = ? AND run_id = ? AND idempotency_key IN (...)could scan a broad composite-index prefix before filtering the IN values. Recognize one bounded constant IN dimension with equality-bound remaining key parts and use a finite composite key set while retaining the base-table predicates.serialkeys; nonunique indexes keep the primary-key suffix throughserial_full/prefix_in. Truncated prefixes, NULLs, dynamic values, unsupported inputs, and failed lowering retain conservative fallbacks.1500 + 32 * raw point count <= total table rows; this is a workload-dependent heuristic, not a guarantee of the fastest plan. Unknown/default statistics retain the 1,000-row fallback policy; a usableFORCE INDEXbypasses these cost decisions.The design and invariants are documented in composite index key-set planning. The original design was independently approved at
b12e7c0; the small-table admission amendment was reviewed separately before implementation.Validation
-race -short -tags matrixone_testboth on the PR branch and on a clean temporary merge with4.2-devdb0a7e; each ran 1,778 top-level tests, with three pre-existing nested skips. Formatting, vet and the pinned incremental analyzers passed forplanandcompile; nine molint diagnostics matched the clean original base.keyset_cost_gatepassed 28/28 andunique_keyset_largepassed 150/150 with metadata checked.index_hintpassed 151/151 with metadata ignored for its previously reported JDBC width differences. The new 100-point aggregate EXPLAIN fails against the previous head and passes on this change; results matchIGNORE INDEX.Earlier-head evidence for the unchanged serialization and broader feature paths:
4.2-devata1a6ab604f85ec9f74b3f79ef01aa9a3c7f1660bbecause the PR branch prohibits force pushes; the resulting source tree is identical to the rebased and tested tree. The full planner package passed normally and under-race; concurrent independent builders, budget accounting, cancellation, hints, dynamic values and fallback are covered.go list,go buildandgo vetfor./pkg/sql/planand./pkg/sql/compilepassed. Repositorymolintand incremental golangci-lint 2.6.2 reported no introduced issues.unique_keyset_largepassed 150/150 and the newkeyset_cost_gatepassed 25/25 with result metadata. It checks small-table scan versus forced index, prepared rebinding, and actual nonuniqueprefix_inwith duplicate-row results.index_hintpassed 151/151 with metadata ignored: its nine existing JDBC width differences are identical on the original and new planner, with equal row values.IGNORE INDEX; a DECIMAL column cast to DOUBLE used a table scan and produced the same results. An over-budget forced wide-equality query safely fell back and matched its ignore-index control.IGNORE INDEX. The variation limits attribution of the first difference and does not prove the absence of regressions.Existing limitations
Raw prepared equality parameters that remain non-foldable continue to use the existing fallback; this PR does not claim an indexed plan for that shape. The earlier
IN (repeat(...), repeat(...))planner stack overflow recorded in this PR remains outside this change. A previous full-repository race run timed out before reaching planner shards; the local planner race pass does not establish the cause or resolve that repository-wide timeout. The previous head's CI rerun completed its required checks; checks for this update are separate. The small-table screen can still choose a slower plan or reject a useful index for other row widths, distributions, or stale statistics. One exploratory task-owned service stalled during shutdown; its cause was not established, while the subsequent ABBA and SQL instances shut down cleanly.