Skip to content

plan: bound composite unique index trailing IN lookups - #32577

Merged
mergify[bot] merged 4 commits into
matrixorigin:4.2-devfrom
gouhongshen:agent/issue-32410-4.2-dev-658d76ea
Nov 16, 2026
Merged

mergify[bot] merged 4 commits into
matrixorigin:4.2-devfrom
gouhongshen:agent/issue-32410-4.2-dev-658d76ea

Conversation

@gouhongshen

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

Related to #32410

What this PR does / why we need it:

A query with equalities on the leading columns of a composite unique secondary index and a finite IN list on the remaining key part must be able to use bounded exact-key access, including when a forced index cannot supply a requested ORDER BY/GROUP BY and when competing unique indexes have no useful statistics.

The updated 4.2-dev base now contains the general composite key-set implementation, exact serialization, comparison/prefix guards, admission controls, and work budgets. This PR integrates with that implementation and retains only the two remaining deltas:

  • Allow filter-phase access for an eligible full-value bounded unique key set when a forced index cannot provide the requested ordering/grouping. The base predicates, residual filters, backfill, and separate sort remain in place. A mixed full-value/prefix hint set remains protected so complete-equality fallback cannot expose a truncated prefix key.
  • With unavailable statistics, rank complete unique equality above a bounded unique key set, and both above nonunique/partial fallback. Strictly higher rank wins; ties retain catalog order. Known-statistics costing is unchanged.

The regression suite covers the reported 5,000-row reproduction, exact rows and bounded index/base access, duplicates and absent keys, NULL, prepared execution, residual predicates, nontrailing IN, full and declared-prefix indexes, forced hints, unmatched ordering, competing declaration orders, and unavailable statistics.

Validation

  • .agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=20m ./pkg/sql/plan (retained test binary): full package passed after the merge resolution.
  • go list -mod=readonly ./pkg/sql/plan, go build -mod=readonly ./pkg/sql/plan, and go vet -mod=readonly ./pkg/sql/plan: passed with the repository CGo environment.
  • go build -mod=readonly ./cmd/mo-service: passed with the resolved merge.
  • Isolated mo-tester execution of test/distributed/cases/optimizer/composite_unique_in_index.sql against the resolved binary and checked-in expected results: 55/55 statements passed; no result regeneration was used.

Residual risks and validation limits

  • Declared-prefix and malformed-prefix indexes intentionally retain safe fallback planning. Bounded exact-key access applies to eligible full-value composite unique indexes.
  • Local runtime validation uses an isolated single-CN service. Broader distributed behavior remains covered by CI.
  • The performance proof uses operator row counts and bounded key access; it is not a latency or throughput benchmark.

Support finite trailing IN key sets on composite unique secondary indexes
while preserving exact residuals, backfill, and forced-index prefix safety.
Prefer complete unique equality over trailing IN candidates when statistics
are unavailable.

Add focused planner regressions and public SQL coverage for bounded access,
prepared and boundary inputs, prefix and competing indexes, and both catalog
orders.

Related to matrixorigin#32410
@gouhongshen

gouhongshen commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

UT Coverage and its downstream Coverage merge are blocked by a 4.2-dev recurrence of the lazy-cache IOVector ownership leak tracked in #27145. The failed job panicked after pkg/tools/toolfs passed, with the allocation originating in TestLazyCacheFSEvictsOldEntriesWhenOverLimit. The current target still lacks the eviction-helper cleanup merged on main in #27147. This PR changes planner code and regressions only; pkg/sql/plan is not a dependency of the failing toolfs test package. The downstream Coverage job stopped with prerequisites_ready=false because that producer did not publish a complete profile; no coverage verdict was calculated. The final CI Required job only aggregated the UT Coverage and Coverage failures as matrixone-ut-coverage: failure and matrixone-coverage-merge: failure; it ran no independent product tests. The recurrence and dependency evidence are recorded in this issue comment.

@mergify

mergify Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

@XuPeng-SH

XuPeng-SH commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 077180db16e546726608424ff224303e1961486d

Review completed. Read the assessment.

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

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

Commit: 077180db16e546726608424ff224303e1961486d

Assessment: approve

The scoped rewrite reuses existing serialization and index-join machinery while preserving residual filters, backfill, NULL semantics, prefix-index safety and singleton equality preference. No actionable findings remain.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Reviewed the complete four-file delta, baseline behavior, affected consumers and all four discussion entries.

  • Reused the reported merged-head planner build, vet and full-suite success, 55/55 public SQL regression, and successful frozen-head CI reports.

  • Historical coverage blockage is superseded by current successful coverage reports.

  • Local artifact audit passed: checks/1794476512463483629-3.json and final-audit.log confirm clean frozen source, matching patch and complete discussion coverage.

Limitations:

  • No local Go or SQL tests were run; supplied author and CI reports were reused.

  • Performance evidence establishes bounded row access, not latency or throughput.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@Mergifyio queue

@mergify

mergify Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue · queue conditions no longer match

1 min in the queue, with no time running CI.

So far

Reason

Pull request #32577 has been dequeued

Queue conditions are not satisfied:

  • -conflict [📌 queue requirement]

To get back in the queue

  • Push a change if one is needed: the pull request is queued again once its queue conditions match.
  • If no change is needed, tick the box below to queue it again as it is.

Requeue requested — the merge queue status continues in this comment ↓.

Times in UTC · dashboard · how the merge queue works

@XuPeng-SH

XuPeng-SH commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 077180db16e546726608424ff224303e1961486d

New discussion was assessed; the previous review remains unchanged.

Resolve the apply_indices.go conflict by integrating the PR with the target's
general composite key-set implementation. Preserve forced filter access only
for eligible full-value bounded unique key sets and prefer complete unique
equality over a multi-key set when statistics are unavailable.

Adapt the planner regressions to exact literal vectors and typed comparison
expressions, and retain prefix-index fallback coverage.
@mergify mergify Bot removed the dequeued label Nov 16, 2026
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/XL Denotes a PR that changes [1000, 1999] lines labels Nov 16, 2026
@mergify mergify Bot added the queued label Nov 16, 2026
@mergify
mergify Bot merged commit dec4ce9 into matrixorigin:4.2-dev Nov 16, 2026
@mergify

mergify Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

✅ Merged into 4.2-dev as dec4ce9 at 11:46 UTC

Less than a minute in the queue, with no time running CI.

So far

  • ✅ Entered the queue Mon 16 Nov, 11:46 · rule release-4.2 · triggered by rule Automatic queue on approval for release-4.2
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged 11:46 · dec4ce9 · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

@mergify mergify Bot removed the queued label Nov 16, 2026
XuPeng-SH pushed a commit that referenced this pull request Nov 17, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Related to #32410.

## What this PR does / why we need it:

### Root cause

A complete composite unique secondary index had ordinary equality/range
access, but no key-set candidate for equality-bound key parts plus one
finite `IN` dimension. The planner therefore could not lower the
predicate to exact serialized keys or cap candidate work by the finite
key count. A less selective secondary index or table scan could win and
read the entire run history. Forced-index fallback and
unknown-statistics candidate ordering also lacked the guards needed to
expose bounded access safely.

This adapts merged PR #32577 and its required composite key-set support
from #32567 to `main`.

### Changes

- Add `KeySetIndexCondition` candidate matching, cost/cardinality caps,
index-only and base-row backfill integration, forced-hint and
declared-prefix safety, unknown-statistics ranking, bounded
reservation/retry handling, and cancellation propagation.
- Recognize complete full-value composite unique keys with equality on
every other part and one finite non-`NULL` constant `IN`; reject dynamic
values, multiple set dimensions, malformed metadata, and declared
prefixes.
- Bound admitted sets to 128 points, 1 MiB of planning work, and 8 MiB
of wire data. Serialize sorted, deduplicated exact keys and retain
ordinary access fallback when admission fails.
- Add focused planner coverage for fixed-width and string key encoding,
duplicates, absent and `NULL` values, residual filters,
index-only/backfill plans, hints, competing indexes, missing statistics,
incomplete keys, prefixes, resource limits, retries, revalidation, and
cancellation.
- Cover every supported literal-bound variant against the authoritative
serial encoded-size contract, plus malformed metadata, runtime values,
`NULL`, unsupported types, string byte boundaries, and planning-budget
rejection.
- Add the 5,000-row SQL reproduction and semantic/plan controls,
including a nine-input/eight-distinct fast-path case.

### Issue-to-test proof

- **#32410 red/green:** on base `b815a4cfb5b2`, the focused
trailing-`IN` planner case selected `idx_c` instead of `uk_abc`; the
same case passes after this change with an exact unique-key set.
Equality and fallback controls retained their expected behavior.
- The real 5,000-row SQL reproduction now selects `uq_user_run_key` for
ordinary and forced trailing-`IN` queries. Base-table and unique-index
`inputRows=3 outputRows=3` bound work by the three requested keys
instead of scanning 5,000 history rows. The query returns `event_idx` 1,
2, and 3 with residual filtering, noncovered projection, backfill, and
ordering preserved.
- Duplicate and absent keys do not fabricate rows; prepared reuse and
`NULL` retain SQL three-valued semantics. Declared prefixes,
incomplete/nontrailing key shapes, mixed hints, competing indexes, and
missing-statistics controls return the intended rows.
- Direct fixed-width and string encoder tests compare every generated
key byte-for-byte with authoritative serial folding after sorting and
deduplication. Nine raw values produce eight distinct exact keys; the
strengthened SQL case returns `event_idx` 1 through 7.
- Independent black-box Challenge PASS: all 12 retained regressions
passed against the approved tree, including reproduction, related,
happy, unhappy, and corner coverage.

### Validation

- RED baseline: `.agents/skills/mo-dev/scripts/mo-cgo-test -o
/tmp/issue-32410-main-plan-baseline.test -v -count=1 -timeout=10m -run
'^(TestCompositeUniqueTrailingInPointAccess|TestCompositeUniqueTrailingInRejectsPrefixLengths|TestCompositeUniqueForcedOrderRejectsPrefixPointAccess|TestCompositeUniqueForcedOrderRejectsCompetingPrefixAccess|TestCompositeUniqueMissingStatsPreferCompleteEquality)$'
./pkg/sql/plan` — intended bounded-access failures on the clean base.
- Focused encoder proof: `.agents/skills/mo-dev/scripts/mo-cgo-test -o
/tmp/issue-32410-main-fast-path-review.test -v -count=1 -timeout=10m
-run
'^(TestFastExactKeySetMatchesSerialFolding|TestCompositeUniqueKeySetCardinalityAndFastPath)$'
./pkg/sql/plan` — PASS in 2.026s.
- Coverage-repair focused proof:
`.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=120s
-run
'^(TestIndexKeySetLiteralBoundVariants|TestIndexKeySetLiteralBoundRejectsInvalidInputs)$'
-coverprofile=/Users/ghs-mo/MOWorkSpace/tmp/issue-fix/issue-fix-loop/state/artifacts/issue-32410/pr-event-focused-literal-tests.cover.out
./pkg/sql/plan` — PASS; both tests and all 34 subtests passed.
- Coverage-gate projection: overlaying that focused profile on the
failed CI changed-code profile covers 22 previously uncovered blocks in
`index_key_set.go`, raising changed-code coverage from 293/412 (71.12%)
to a projected 315/412 (76.46%), above the strict 75% gate. Production
files are unchanged between the profiles. Exact-head CI run
[43970538694](https://github.com/matrixorigin/matrixone/actions/runs/43970538694)
subsequently passed Coverage and CI Required on
`bb3ee9b9132463de9e894b76fbd18f7fac08ab0b`.
- Complete owning package, without `-run`:
`.agents/skills/mo-dev/scripts/mo-cgo-test -o
/tmp/issue-32410-main-plan-ci-fix.test -v -count=1 -timeout=30m
./pkg/sql/plan` — PASS in 159.218s.
- Related planner regressions:
`.agents/skills/mo-dev/scripts/mo-cgo-test -o
/tmp/issue-32410-main-plan-related.test -v -count=1 -timeout=10m -run
'^(TestRegularIndexSelector.*|TestEncodedIndex.*|TestIndexHint.*|TestForceIndex.*|TestScopedForceIndex.*|TestApplyIndicesForFilters.*|TestApplyExtraFiltersOnIndex.*|TestResolveRegularIndexBackfillResidualAccess|TestRangeBackfill.*|TestRegularIndexOnly.*|TestReplaceEqualCondition.*|TestReplaceNonEqualCondition.*)$'
./pkg/sql/plan` — PASS in 2.420s; also included in the final unfiltered
package run.
- Real SQL BVT: `java -Xms1024M -Xmx1024M -cp
/Users/ghs-mo/MOWorkSpace/mo-tester:/Users/ghs-mo/MOWorkSpace/mo-tester/lib/*
-Dconf.yml=/Users/ghs-mo/MOWorkSpace/tmp/issue-fix/issue-fix-loop/state/artifacts/issue-32410/main-runtime/mo.yml
-Drun.yml=/Users/ghs-mo/MOWorkSpace/tmp/issue-fix/issue-fix-loop/state/artifacts/issue-32410/main-runtime/run.yml
io.mo.Tester method=run rate=100` — 56/56 success, 0 failed, 0 abnormal
after result generation and manual review.
- Build: `make -j8 build-with-prebuilt-native` — PASS.
- Vet: `go vet -mod=readonly ./pkg/sql/plan` with the repository CGo
environment — PASS.
- Scoped lint: `golangci-lint run -c .golangci.yml --new-from-rev
b815a4c ./pkg/sql/plan` — 0 issues.
- Final `gofmt`, tracked/untracked whitespace, and delivery-scope checks
passed.

### Residual risks and limits

- Admission remains conservative for dynamic or `NULL`-containing
inputs, multiple `IN` dimensions, declared prefixes, malformed metadata,
broad estimates, and resource-limit excess; these cases preserve
semantics through ordinary fallback.
- The complete owning planner package and focused real-SQL case passed.
A repository-wide test suite was not run and remains for CI.
- `EXPLAIN ANALYZE` row counts establish bounded operator work for this
fixture; they are not latency or throughput benchmarks.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch was previously deployed

1 inactive deployment
ci — 199acc49 Deployed Nov 16, 2026 by gouhongshen
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 size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants