Skip to content

fix(plan): use bounded key-set access for composite index IN prefixes (#32410) - #32567

Merged
XuPeng-SH merged 10 commits into
4.2-devfrom
fix-32410-composite-keyset-4.2-dev
Nov 13, 2026
Merged

XuPeng-SH merged 10 commits into
4.2-devfrom
fix-32410-composite-keyset-4.2-dev

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 11, 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:

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.

  • Complete unique indexes use sorted, deduplicated exact serial keys; nonunique indexes keep the primary-key suffix through serial_full / prefix_in. Truncated prefixes, NULLs, dynamic values, unsupported inputs, and failed lowering retain conservative fallbacks.
  • Rank eligible unique alternatives by exact distinct component count before building their keys. The fast path uses production serialization and retains the existing 128-point and 80 MiB pre-compaction wire checks.
  • Avoid non-covering multi-point lookups when the raw point count exceeds 10% of the known filtered scan cost. With usable statistics, a separate conservative small-table screen also requires 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 usable FORCE INDEX bypasses these cost decisions.
  • Bound charged encoding work across all candidate attempts for a scan to 1 MiB. This is a planning-work heuristic, not a peak-memory limit. Preflight and post-resolution checks run before publishing an index node; over-budget forced candidates safely fall back.

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

  • On 57, the changed planner passed the full package under -race -short -tags matrixone_test both on the PR branch and on a clean temporary merge with 4.2-dev db0a7e; each ran 1,778 top-level tests, with three pre-existing nested skips. Formatting, vet and the pinned incremental analyzers passed for plan and compile; nine molint diagnostics matched the clean original base.
  • On the integrated tree, keyset_cost_gate passed 28/28 and unique_keyset_large passed 150/150 with metadata checked. index_hint passed 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 match IGNORE INDEX.
  • On the integrated one-CN original-shaped 5,000-row query, both the index and base side of the chosen join read three rows; the forced-scan control read 5,000 and returned the same three rows. The session residual is retained.
  • On 57, four same-data, clean-restart ABBA phases measured 40 shuffled prepared auto/forced-index/scan triples per scenario. For the 1,000-row/100-point case, previous-head auto medians were 0.288–0.290 ms and the updated auto scan was 0.148–0.163 ms; the updated 5,000-row/3-key and 60,000-row/128-key wide cases retained index plans and beat their scan controls. These are local, warmed, single-CN observations, not a general latency guarantee.

Earlier-head evidence for the unchanged serialization and broader feature paths:

  • Merged 4.2-dev at a1a6ab604f85ec9f74b3f79ef01aa9a3c7f1660b because 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 1.26.4: go list, go build and go vet for ./pkg/sql/plan and ./pkg/sql/compile passed. Repository molint and incremental golangci-lint 2.6.2 reported no introduced issues.
  • Real one-CN optimistic/SI SQL: unique_keyset_large passed 150/150 and the new keyset_cost_gate passed 25/25 with result metadata. It checks small-table scan versus forced index, prepared rebinding, and actual nonunique prefix_in with duplicate-row results. index_hint passed 151/151 with metadata ignored: its nine existing JDBC width differences are identical on the original and new planner, with equal row values.
  • Integer and DATE mixed-literal probes used key-set index access and matched 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.
  • On the same upstream base, diagnostic 3-iteration planner benchmarks reduced cumulative allocation for 128 wide unique IN values from ~50 MB/op to ~10 KB/op, nonunique wide IN from ~29 MB/op to ~10 KB/op, and a wide equality with narrow IN from ~50 MB/op to ~10 KB/op. These are cumulative allocations, not peak-memory or stable timing claims.
  • Same-base local ABBA tests checked 80 ordered prepared samples per version over four rounds: the 1,000-row case changed from 0.462 to 0.346 ms median. At 60,000 verified rows/cost, the first run measured 0.470 to 0.531 ms for prepared execution and 0.690 to 0.748 ms ad-hoc; after swapping binaries between the same instances/data, prepared medians were 0.538 and 0.541 ms. The new index plan measured 0.541 ms versus 1.895 ms with 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.

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.
@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner November 11, 2026 14:34
@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 →

@mergify

mergify Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@XuPeng-SH

XuPeng-SH commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · superseded

Commit: d5a6b9d93e8209fc0a9926f390ca24810ca2d0f6

"interrupted"

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

QA challenge results (local, 4.2-dev base 1bde992)

Method: adversarial A/B on a real 3-node launch cluster. Oracle is force index (key-set path) vs ignore index (full scan + residual predicates); every pair had to return identical rows. Plan shape came from EXPLAIN / EXPLAIN ANALYZE.

Correctness — no row mismatch found

20+ paired queries covering: CHAR/VARCHAR padding and trailing spaces, case-sensitive values, INT compared to string/mixed literals, DECIMAL scale and rounding (1.2 / 1.250), BIGINT UNSIGNED max, DATE / DATETIME(3), BIT(8), nullable key columns, duplicate IN values, IN containing NULL, residual and non-key predicates, prepared-statement parameters, and IN through a subquery. All index-vs-scan outputs were identical.

Lowering actually chosen

  • Unique composite index: prefix_in for IN in leading, middle, and trailing key positions.
  • Secondary composite index (base-table fetch path): prefix_in; on 20,000-row skewed tables the index scan reads 2 rows (2-key set) and 40 rows (2 values x 20 matches) instead of 20,000 prefix rows. The earlier 5,000-row fixture improved from 5,000 to 3.

Fallback boundaries confirmed

128-element IN -> prefix_in; 129 -> no prefix_in; float key -> no; two IN dimensions -> no; IN with NULL -> no; IN (subquery) -> no; single-element IN folds to equality.

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:
select id from t_sec3 force index(ix_sec3) where a=1 and b=1 and c in ('k1','k2')
still plans as prefix_eq(a,b) + serial_extract(c) IN (...) with inputRows=20000 to return 2; selecting a non-covered column takes the new prefix_in path with inputRows=2. Extending tryIndexOnlyScan is a possible follow-up, out of this PR's scope.

Regression checks on the final pushed commit

pkg/sql/plan key-set unit tests pass, go vet ./pkg/sql/plan and make build pass, and mo-tester test/distributed/cases/optimizer/index_hint.sql is 130/130. Full CI remains the remote gate.

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

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.

Comment thread pkg/sql/plan/index_keyset.go Outdated
Comment on lines +143 to +145
tupleVec := tuples[row].GetVec()
if tupleVec == nil {
return nil

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.

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

Comment thread pkg/sql/plan/index_keyset.go Outdated
Comment on lines +132 to +138
} else {
serialArgs[i] = DeepCopyExpr(fn.Args[1])
}
}
tuples[row], err = bindFuncExprAndConstFold(
builder.GetContext(), builder.compCtx.GetProcess(),
indexTableLookupSerialFunc(idxDef), serialArgs,

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.

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

Comment thread pkg/sql/plan/index_keyset.go Outdated
Comment on lines +113 to +118
for row := 0; row < inVec.Length(); row++ {
rowVec, err := inVec.Window(row, row+1)
if err != nil {
return nil
}
data, err := rowVec.MarshalBinary()

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.

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

@XuPeng-SH

XuPeng-SH commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · done

Commit: 832ff02b62cec9524c69306c5c81dd823032e065

Review completed. Read the assessment.

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

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

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 INDEX scan: 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.

@XuPeng-SH

XuPeng-SH commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · done

Commit: eb222b3b8bd927bd04382088efdfea4506dcfb51

Review completed. Read the assessment.

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

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.

@XuPeng-SH

XuPeng-SH commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · done

Commit: c10ddba435279702782291a99109a94e4d2ec495

Review completed. Read the assessment.

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

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.

@XuPeng-SH

XuPeng-SH commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · done

Commit: 0a3cd2f171abc88172b36d318433f0c14fac9c61

Review completed. Read the assessment.

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

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.

This branch was successfully deployed

No deployments
ci — ce78f62b Deployed Nov 13, 2026 by XuPeng-SH
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/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants