Skip to content

Improve point-index selection for skewed equality predicates - #33093

Merged
XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
iamlinjunhong:loom-33088-20261123T064542-main
Nov 24, 2026
Merged

XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
iamlinjunhong:loom-33088-20261123T064542-main

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Nov 23, 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:

issue #33088

What this PR does / why we need it:

For an ordered LIMIT 1 query with competing non-unique indexes that require a base-table lookup, the planner can favor a broad composite key even when the task key matches one row. This change evaluates each candidate's equality predicates on the same bounded sample of cached base-table rows. The planner changes its choice only when the estimated work bounds clearly favor one candidate. Cold or incomplete cache data, ineligible inputs, and overlapping estimates retain the existing ranking. Sampling issues no storage reads.

On main, the original fixture keeps the one-row plan. On the adjacent fixture, the automatic plan now reads one index row and one base-table row, down from 49,152 and 8,192, matching the narrow-index control. The result matches all six columns, and the plan retains all predicates, ORDER BY created_at, id, and LIMIT 1. The dense control still reads 15,665 rows at both operators and returns the same complete row. Reversing the data skew makes the planner choose the composite index when its joint key is rare.

Local validation on Darwin arm64 covered the native and Go build, targeted CGo tests in objectio, sql/plan and disttae, five-package vet and incremental lint, and the optimizer BVT directory (2,919 passed, 4 skipped). The new regression passed 19/19 twice on the same instance. CI Required, Ubuntu x86 UT and pessimistic multi-CN BVT passed on the reviewed head. CI run. The sample provides relative estimates, and cache coverage varies by workload.

The follow-up at 14f698d821a287279987bc89f9418493e05a915e makes the optional sampler decline a busy column-cache shard and fall back to the native ranking. It releases any cache entries already acquired before that miss.

Validation of the follow-up on Darwin arm64

  • The focused mo-cgo-test -race tests in fileservice, fileservice/s3fifo, objectio, sql/plan, and disttae passed. The contention test returns a miss while the S3-FIFO shard remains locked.
  • The service build, go vet, and incremental golangci-lint passed. Replaying regular_index_point_skew.sql through MySQL on an isolated one-CN service verified both index choices, all six result rows, and the ordering and limit. Ubuntu/x86 UT and CI Required passed on that head. CI attempt 2.

The follow-up at 2cb327a27fed29d852446077d2ced4b52f5c6cff keeps the native index when the sampled winner's lower bound exceeds the existing runtime-filter key limit. The selector can still switch when only the upper bound exceeds the limit.

  • On Darwin arm64, focused mo-cgo-test planner cases, go vet ./pkg/sql/plan, incremental golangci-lint, and the service build passed. The new selector test reproduced the over-capacity switch before the fix and passed after it.
  • The isolated one-CN MySQL replay of regular_index_point_skew.sql passed for both index choices and preserved all six result rows, ordering and limits. Linux CI for this follow-up runs after push.

Backport to 4.2-dev in #33094, where the adapted code was built and tested independently.

@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 added the kind/bug Something isn't working label Nov 23, 2026
@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Nov 23, 2026
@mergify

mergify Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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

@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: afd4d39e692cf19e1bb9e09dc4b450ba499c0dfb

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: afd4d39e692cf19e1bb9e09dc4b450ba499c0dfb

Assessment: request_changes

The sampler reuses the existing scorer and metadata reader, reduces scan work in the skewed fixture, and preserves the original one-row plan on main. The new column-cache lookup can delay cancellation during optional planning.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

  • P2 pkg/objectio/cached_index_sample.go:168: An eligible point-index query reaches sampling while another goroutine holds the memory-cache shard for one of its selected column extents.
    Impact: The optimizer waits for the shard lock even after the query deadline expires. The extent and byte caps bound the sample size, while cancellation still depends on the lock holder releasing the shard.
    Evidence: ReadCachedInt32Rows calls ReadCache, which reaches MemCache.Read and the blocking S3-FIFO Get. A controlled LocalFS.ReadCache probe stayed blocked past its deadline and completed after the shard was released. The existing metadata contention test returned immediately. The pinned index-planning design at docs/design/20261107-index-planning-owners.md:172 calls for optional observations to decline on lock contention. Use the cache's try-lookup semantics for sampled columns and fall back to the native ranking when a shard is busy.

Validation:

  • Verified the frozen patch, native inputs, isolation preflight, and all three discussion entries.

  • Five focused unit tests passed. The checked-in skew fixture replayed over MySQL with both expected index choices, ordering and limits preserved, and all six SELECT results matching.

  • The sampling-disabled control reduced adjacent rare-case input from 16,384 index rows and 8,192 base rows to one each when sampling was enabled. The original issue fixture used one input row per scan in both arms.

  • Matched the SQL and cache-contention probes to their terminal receipts in review-validation.md.

Limitations:

  • The local SQL comparison used one CN. The frozen CI snapshot records successful pessimistic multi-CN BVT.

  • The contention probe controlled lock timing. Production contention frequency and duration remain unmeasured.

@iamlinjunhong

Copy link
Copy Markdown
Contributor Author

The column-cache contention finding is fixed in 14f698d821a287279987bc89f9418493e05a915e. The sampler uses S3-FIFO's try-lookup and falls back to the native ranking on a busy shard. The new regression returned a miss with the shard held, and the skew fixture preserved both expected index choices and all six result rows.

@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 14f698d821a287279987bc89f9418493e05a915e

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: 14f698d821a287279987bc89f9418493e05a915e

Assessment: request_changes

The cache try-lookup resolves the prior contention finding, and point sampling reuses the existing index cost model. A selector probe confirmed that sampled ranking can replace the native winner with a backfill whose estimated lower bound exceeds the runtime-filter key limit.

Model: gpt-6.2-sol / xhigh

Session: 01a20682-9189-75a0-839a-f36d8b2372a5 · slot 1 · generation 3

  • P2 pkg/sql/plan/apply_indices.go:2847: Two non-covering equality indexes pass native admission. The sample favors the narrower index on estimated work, even though its estimated lower bound is about 32,000 keys against a limit of 19,660.
    Impact: If actual build rows cross the limit, the executor abandons the runtime filter after reading the index. The base scan then proceeds without primary-key pruning from that filter. Before replacing the native winner, apply the existing key-capacity check to the sampled winner’s lower bound.
    Evidence: selector-final.jsonl and receipt checks/1795455484546830358-2.json show the native control choosing the wide index and the sampled case switching to the narrow index. The scorer probe quantifies the bounds in recovered/same-head/sample-capacity-focused.jsonl. The selector discards the scorer’s rejection result, and pkg/sql/colexec/indexbuild/build.go:260 abandons the filter when the build exceeds its limit.

Validation:

  • Verified the frozen patch, pinned policy, native inputs and whitespace. Private /tmp and loopback preflight passed.

  • Recovered passing same-head race results for fileservice, S3-FIFO and objectio, including busy-shard fallback and retained cache references. The focused planner race checks and local joint-match sampling test also passed.

  • The corrected selector probe passed its native control and failed its sampled capacity assertion. The first run’s planner compile error was in the diagnostic fixture and was corrected for the follow-up.

  • Frozen CI reports successful Ubuntu unit and coverage checks and Proxy and pessimistic multi-CN BVT.

Limitations:

  • The selector probe supplied sample counts through a test provider. The executor impact follows from the existing overflow path. No end-to-end latency measurement was taken for this case.

  • Local SQL comparisons used the predecessor head on one CN. The original linked lookup read one row per scan in both arms, while adjacent skew cases showed lower scan work with sampling.

XuPeng-SH pushed a commit that referenced this pull request Nov 23, 2026
… backport) (#33094)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue #33088

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

Backport of #33093, adapted to the 4.2-dev planner and cache APIs.
Competing non-unique point indexes that require a base-table lookup are
compared using joint equality matches on a bounded sample of cached
base-table rows. The planner changes its choice only when the estimated
bounds clearly favor one candidate. For incomplete column-cache data,
the planner includes the full uncertainty of the missing sample rows in
each candidate interval. A cold cache, ineligible inputs, and
overlapping estimates retain the existing ranking. Sampling issues no
storage reads.

On the original 150,000-row fixture, the first automatic plan after
`ANALYZE` selects `ix_task` with or without a preceding diagnostic
count. Index and base-table inputs drop from 49,152 and 150,000 rows to
one row each, matching the narrow-index control. Both plans return the
same six columns with all predicates and `ORDER BY created_at, id LIMIT
1`. The dense case retains 15,665 index reads and 991 base-table reads,
matching the control and its complete result. The reverse-skew fixture
selects the composite index when its joint key is rare.

Local validation independently rebuilt the native and Go artifacts on
4.2-dev and ran the SQL against that build. Targeted CGo tests,
five-package vet and incremental lint passed. The new optimizer BVT
passed 19/19 twice on the same instance and failed only the two expected
index-selection checks on the original 4.2-dev baseline. The optimizer
directory passed 2,346 checks with 13 skipped. The local sampling and
work observations are from a single CN.

**Follow-up validation for `e5ab449709cf`**

- Fresh Darwin/arm64 single-CN regression
`TestPointIndexSelectionAfterAnalyze` ran the original 150,000-row SQL.
The first unhinted `EXPLAIN ANALYZE` after `ANALYZE TABLE` used
`ix_task` and read one index and one base row, matching the narrow-index
control. Both paths returned all six expected fields for the rare and
dense keys.
- Five focused sampler and planner unit tests, native build, six-package
`go vet`, and incremental lint passed. Local replay of the Coverage
parser with unchanged blocks from the original CI profiles and new local
profiles reached 158/204 changed blocks (77.45%, threshold >75%). The
new Linux CI run will verify the merged coverage on GitHub. [Original
Coverage
job](https://github.com/matrixorigin/matrixone/actions/runs/45151300145/job/137636589290)

---------

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

Copy link
Copy Markdown
Contributor Author

Commit 2cb327a27fed29d852446077d2ced4b52f5c6cff checks the sampled winner's lower-bound key count against the existing runtime-filter limit before replacing the native winner. The selector regression reproduced the over-capacity switch before the fix, then confirmed that the native winner is kept in that case and the sampled winner can still be selected when only its upper bound exceeds the limit. The skew SQL replay preserved both index choices and all six result rows. Review finding.

@XuPeng-SH

XuPeng-SH commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 2cb327a27fed29d852446077d2ced4b52f5c6cff

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: 2cb327a27fed29d852446077d2ced4b52f5c6cff

Assessment: approve

The sampler reuses the existing index scorer and observes cached rows without storage reads. Busy cache shards trigger native fallback. The new guard keeps the native index when the sampled winner’s estimated lower key count exceeds runtime-filter capacity.

Model: gpt-6.2-sol / xhigh

Session: 01a20682-9189-75a0-839a-f36d8b2372a5 · slot 1 · generation 3

Validation:

  • Verified the frozen patch, pinned policy, native inputs, and isolation preflight. Thirteen of fifteen patch sections match the preceding review byte for byte.

  • An isolated probe of the current planner guard confirmed rejection above the 19,660-key limit and acceptance when only the upper estimate exceeded it. See checks/1795497004882869969-2.json.

  • Independent fixture arithmetic matched all six expected SQL rows. Retained race results cover the unchanged cache path. Frozen current-head CI reports passing Ubuntu unit tests and both enabled multi-CN BVT jobs.

Limitations:

  • Both local package race attempts timed out before reporting test results. The passing local probe exercised the extracted guard with fixed work estimates.

  • The retained one-CN SQL comparison ran on an earlier head with the same fixture. The linked 1.5-million-row QA run targeted 4.2-dev. This main sampler declines tables estimated above 262,144 rows.

@mergify mergify Bot added the queued label Nov 24, 2026
@mergify

mergify Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue · pull request dequeued

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

So far

  • ✅ Entered the queue Tue 24 Nov, 05:13 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 06:38 · d9631e7

Reason

Pull request #33093 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

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.

Merge conditions not met when it left the queue

  • any of · required by GitHub branch protection:
    • check-neutral = CI Required
    • check-skipped = CI Required
    • check-success = CI Required

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request
2 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection

Times in UTC · dashboard · how the merge queue works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/bug Something isn't working size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants