Skip to content

Improve point-index selection for skewed equality predicates (4.2-dev backport) - #33094

Merged
XuPeng-SH merged 5 commits into
matrixorigin:4.2-devfrom
iamlinjunhong:loom-33088-20261123T064542-4.2-dev
Nov 23, 2026
Merged

XuPeng-SH merged 5 commits into
matrixorigin:4.2-devfrom
iamlinjunhong:loom-33088-20261123T064542-4.2-dev

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:

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

@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
@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: 47cd8f9caed1d2eba15db210a9571bdc19921f1d

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: 47cd8f9caed1d2eba15db210a9571bdc19921f1d

Assessment: request_changes

The cache-only sampler improves index selection on both warmed skew fixtures and preserves their results. The original lookup still selects the broad index on the first plan after ANALYZE in a fresh single-CN run, leaving the stated fix for #33088 incomplete.

Model: gpt-6.2-sol / xhigh

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

  • P2 pkg/sql/plan/apply_indices.go:2262: On a fresh single-CN instance, load the 150,000 rows from #33088, run ANALYZE TABLE runs, and immediately explain the unhinted lookup for task_id = 100010.
    Impact: The first plan still uses ix_flow, the broad access path reported in the issue. The same query selects ix_task after a separate scan reads all three key columns.
    Evidence: The assigned-head MySQL probe reproduced this sequence twice, once with only a test overlay and once with a diagnostic control that could disable sampling. The committed fixture warms the key columns before checking the plan at regular_index_point_skew.sql:31. Keep the safe cache-miss fallback and either cover the reported first-plan case within the no-storage-read constraint or explicitly scope the fix and its regression coverage to warmed caches.

Validation:

  • Verified the frozen patch, clean checkout, isolated runtime, and matching native inputs and archives.

  • Three focused unit tests passed. Replaying the checked-in fixture over MySQL on a three-CN embedded cluster selected the expected indexes in both skew directions and returned all six expected columns for each of the six SELECTs.

  • The single-CN issue probe confirmed the first-plan fallback and the plan change after warming. Matched the test logs to their receipts and accounted for all three discussion entries.

Limitations:

  • The first-plan reproduction used an embedded Linux cluster. The author reported a different result in a separate local setup.

  • The alternating timing probe measured EXPLAIN with different selected indexes. It did not establish an end-to-end latency regression.

@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: e5ab449709cf4f9119ef4db75cccbc22a78dd86a

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

Assessment: request_changes

The prior index-selection finding is resolved. With a test-only change to shorten the temporary directory, the first unhinted lookup after ANALYZE selected ix_task and read one row from each scan. The checked-in regression still needs a portable Unix socket path.

Model: gpt-6.2-sol / xhigh

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

  • P3 pkg/tests/issues/isolated/point_index_skew_test.go:33: Run TestPointIndexSelectionAfterAnalyze with a long GOTMPDIR, as in the assigned Linux executor.
    Impact: The embedded CN panics during startup, aborting the isolated test package before the new regression reaches SQL.
    Evidence: t.TempDir() picks up GOTMPDIR, and embed appends mysql0.sock to the resulting data path. The 141-byte socket path failed with bind: invalid argument in focused.jsonl, receipt checks/1795453782602131435-2.json. Use a short private temporary path with cleanup. Changing only the fixture to use os.MkdirTemp under the runtime TMPDIR passed all SQL assertions in short-temp.jsonl, receipt checks/1795453847948222197-2.json.

Validation:

  • Verified the frozen patch, clean checkout, isolation preflight, and native library hashes. See scope.log, preflight.log, and native.log.

  • Five focused object-cache, planner, and disttae tests passed. The same invocation recorded the checked-in SQL fixture startup failure. See focused.jsonl and checks/1795453782602131435-2.json.

  • With the temporary-path overlay, the single-CN regression verified ix_task, one input row per scan, and all output fields for the rare and dense cases. See short-temp.jsonl and checks/1795453847948222197-2.json.

  • Replayed the warmed SQL fixture over MySQL on an embedded three-CN cluster. Both skew directions selected the expected index, and all six SELECTs returned the expected fields. See warm-skew.jsonl and checks/1795453904386736748-2.json.

Limitations:

  • The warmed fixture replay used direct MySQL assertions. The full BVT runner and GitHub coverage remain unverified.

@XuPeng-SH

Copy link
Copy Markdown
Contributor

Additional black-box QA evidence for re-review: the baseline test TestMarkScanGuardSQL also exits 1 with the same listen unix .../mysql0.sock: bind: invalid argument error. This indicates the long Unix socket path failure is a shared pre-existing test-environment limitation, not a regression introduced by PR #33094. Please reassess the P3 finding that blocks this PR on portable socket-path setup. If shortening the new fixture path is useful, treat it as a non-blocking robustness improvement or separate shared test-infrastructure fix; judge the index-selection fix on its SQL behavior.

@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: e5ab449709cf4f9119ef4db75cccbc22a78dd86a

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

Assessment: approve

The first unhinted plan after ANALYZE selects ix_task for the reported rare key and reads one row from each scan. The bounded, cache-only sampler reuses existing index admission and execution, with the original ranking as its fallback when evidence is insufficient. The prior socket-path finding is a shared test-harness limitation and no longer blocks approval.

Model: gpt-6.2-sol / xhigh

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

Validation:

  • Verified the frozen head, patch and native inputs against retained execution receipts. Five focused object-cache, planner and disttae tests passed. See review-verification-confirmed.log and checks/1795455473751394273-2.json.

  • The exact-head single-CN regression passed with only the fixture's temporary-directory setup changed. It verified the first plan, both scan counts and all six result fields for rare and dense keys. See a28b21599e657c7972cabce6/attempt-1/short-temp.jsonl and checks/1795453847948222197-2.json in that attempt.

  • The warmed fixture replay through MySQL on an embedded three-CN cluster selected the expected index in both skew directions and matched all six fields for each SELECT. See a28b21599e657c7972cabce6/attempt-1/warm-skew.jsonl and checks/1795453904386736748-2.json in that attempt.

  • Private /tmp and loopback preflight passed. A fresh bind probe reproduced the socket error for both the unchanged baseline fixture's path and the new fixture's path. The short private path succeeded. See unix-socket-path.jsonl and checks/1795455447968379822-2.json.

Limitations:

  • The checked-in Linux fixture stopped at socket startup under the assigned long GOTMPDIR. The fresh probe tested socket binding, while the retained short-path run supplied the SQL evidence.

  • The warmed replay used direct MySQL assertions. Full BVT comparison mode, GitHub coverage and end-to-end latency were not independently verified.

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

mergify Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue · pull request dequeued

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

So far

  • ✅ Entered the queue Mon 23 Nov, 17:40 · rule release-4.2 · triggered by rule Automatic queue on approval for release-4.2
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 17:53 · feba5c1

Reason

Pull request #33094 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

@XuPeng-SH
XuPeng-SH merged commit b20154b into matrixorigin:4.2-dev Nov 23, 2026
@mergify mergify Bot added dequeued and removed queued labels Nov 23, 2026
XuPeng-SH added a commit that referenced this pull request Nov 24, 2026
## Summary

- Use short, UUID-based Unix socket paths for embedded test CNs.
- Preserve the existing `DataDir/mysql<I>.sock` layout for non-testing
clusters.
- Cover stale socket isolation, path stability and length, and a real
Unix socket connection.

## Root cause

`t.TempDir()` inherits `GOTMPDIR`. A long temporary directory makes the
generated `<data-dir>/mysql0.sock` exceed the Unix socket path limit,
causing frontend startup to panic with `bind: invalid argument`. This is
shared embedded-test infrastructure behavior, not a regression specific
to #33094.

Related: #33094

## Validation

- Reproduced the failure on base
`b757475d7582c14e85defa0c2c00ad119dce444a` with a 141-character
`GOTMPDIR`.
- The same `TestMarkScanGuardSQL` regression passes after the fix.
- Focused socket path and stale-file tests: PASS.
- Full `pkg/embed` package: PASS (199.395s), including multi-CN and
`StartNewCNService` tests.
- `go vet ./pkg/embed`: PASS.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
XuPeng-SH pushed a commit that referenced this pull request Nov 24, 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:

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](https://github.com/matrixorigin/matrixone/actions/runs/45151204454).
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](https://github.com/matrixorigin/matrixone/actions/runs/45177065475/attempts/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.

---------

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

This branch was successfully deployed

No deployments
ci — feba5c1d Deployed Nov 23, 2026 by mergify[bot]
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.

3 participants