Skip to content

perf(sql): cost literal LIKE prefix ranges with analyzed distributions - #31940

Merged
XuPeng-SH merged 10 commits into
mainfrom
codex/31867-like-range
Nov 2, 2026
Merged

XuPeng-SH merged 10 commits into
mainfrom
codex/31867-like-range

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 31, 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 #31867.

What this PR does / why we need it:

Literal byte-ordered LIKE 'prefix%' can use a regular index through a typed half-open range. Exact predicates remain where serialized or Unicode bounds need a residual. Manual ANALYZE collects bounded byte-range samples through its existing reader, and publishes an owned generation with schema/type/population checks; unavailable or invalid samples retain conservative automatic access. No new execution or storage path, persistent cache, per-SQL probe, or background task is added.

All regular-index candidates use the existing common ranking. Ordinary point/range matching and the single-column cost exemption retain main's policy. Only newly admitted prefix access gets conservative backfill/disabled-pruning admission checks; capacity remains based on transferred keys. New AUTO prefix access retains the scan or ordinary candidate when independently estimated base input is at most BlockMaxRows. This is a conservative policy budget, not a minimum block size or a claim about cache residency. FORCE bypasses cost/admission while preserving semantic safety.

This deliberately changes the original 500-row expectation: it returns the same 150 matches and supports FORCE prefix access, while AUTO can retain its faster scan. Same-binary text/prepared experiments found the index slower even before flushing; a larger selective workload supplies the automatic-index performance witness. Some useful small-input index paths may be declined. The rule does not promise the fastest plan for every layout or stale estimate.

Validation:

  • Rebased on main at 2e2b814ae3. Linux amd64 / Go 1.27.1: full owning-package race validation, owning normal tests plus targeted normal/race rechecks for the final policy changes; final test-only review corrections reran the affected boundary/public race tests. Configured incremental go vet, pinned molint, and golangci-lint pass across the five affected packages, with affected-package rechecks after the last test changes.
  • Warm-cache validation includes a 14-scenario ABBA matrix, text/prepared execution, exact result checks, and fresh admission-boundary controls. Short-batch variance was retained and checked with pinned-CPU controls and 20,000-query profiles/bracketed baselines; those investigations did not reproduce the initially flagged slowdowns. This does not establish a universal latency guarantee.
  • In the measured 131,072-row fixtures, sparse prefix covering access is about 70%/76% faster (text/prepared) with warm application cache and 88%/89% faster with application cache disabled; the one-third-match covering fixture improves about 27%/30% warm and 33%/24% with cache disabled. Ordinary AUTO controls retain main's plans. Application-cache miss is not a claim about cold disk or S3 performance.
  • Public SQL verifies memory/persisted data, FORCE/IGNORE agreement, NULL/NUL/Unicode, prepared reuse, error domains, and sample invalidation during workspace updates followed by rollback. Planner tests preserve ordinary and moderate-selectivity controls, covering/backfill capacity, and the admission boundary.
  • Replayed affected optimizer SQL and reconciled actual plans; restored ordinary EXPLAIN expectations rather than retaining the earlier global cost-model changes. The arithmetic fixture restores its optimizer hint to avoid leaking service-level state.
  • Remote CI and the complete distributed BVT sequence remain subject to the updated PR's checks; no pending job is claimed as passed.

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

@XuPeng-SH

XuPeng-SH commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 6dbafb54f0633a1e8c1c549a1c0afc6799f91409

"interrupted"

@XuPeng-SH

XuPeng-SH commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 655cff09c423043c4161c3ad4bee151de85b086a

"interrupted"

@XuPeng-SH

XuPeng-SH commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 033a6a4c9979bf1e98abff8017bd77e5a011f5ab

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: 033a6a4c9979bf1e98abff8017bd77e5a011f5ab

Assessment: request_changes

One P2 regression: prefix candidates can suppress existing selective IN backfill access.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

  • P2 pkg/sql/plan/apply_indices.go:3483: An analyzed query combines LIKE 'abc%' with selective same-column IN values and projects a non-indexed column.
    Impact: The selective IN lookup disappears. A 100,000-row SQL check processed 8,192 base-table rows, versus two base rows and two index rows for an equivalent residual-LIKE control. Results remain correct.
    Evidence: The non-prefix preference updates firstFilters, but rangeFilters retains prefix-first ordering. matchRangeBackfill returns that prefix immediately; when costing rejects it, the IN candidate is never considered. Planner and public SQL probes confirm this in prefix-priority-evidence.txt and prefix-priority-scale-evidence.txt. Apply the preference to backfill matching, or score both candidates, and add a non-covering regression test.

Validation:

  • Full planner, disttae and analyze package tests passed; wire round-trip testing passed.

  • Focused planner/statistics-lifetime race checks and sampler/wire race suites passed.

  • TestLikePrefixIndex passed. Diagnostic planner and SQL probes confirmed the finding with matching query results.

  • Command/source/exit receipts and retained logs reconciled in validation-audit.json. Source remained unchanged.

Limitations:

  • Full repository CI and standalone mo-tester BVT were not run locally.

  • Performance evidence establishes changed plans and row processing; author-reported latency improvements were not independently reproduced.

@XuPeng-SH

XuPeng-SH commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: c56fd067b9e423849e61fac8fc0f4b9a867fb4bf

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

Assessment: approve

No actionable findings. The selective-IN issue remains resolved, and the new prefix safety guard preserves baseline error behavior. All discussion entries were reconciled; source remains unchanged.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

Validation:

  • 35 selected planner tests and standalone TestLikePrefixIndex passed.

  • All 24 error-domain observations matched the merge-base control across memory, persisted and re-analyzed states.

  • Five-package go vet, formatting, isolation preflight and native-input verification passed.

  • An initial exploratory assertion failed identically on candidate and merge base; both failed controls were retained.

  • Receipts and logs reconciled in /home/xupeng/.local/state/mo-bot/jobs/97b2385106f5e2bab6abe3dd/attempt-1/validation-summary.json.

Limitations:

  • No fresh full CI, distributed BVT, race suite or latency benchmark. Applicable unchanged coverage from the supplied prior review was reused.

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

Codex automated review

Reviewed #31940 at head c56fd06 against origin/main (34 files, 4228 insertions, 504 deletions). The PR costs literal LIKE byte-prefix ranges using analyzed ByteRangeDistribution stats, rewrites optimizable LIKEs to prefix_eq via a rune-aware successor/range construction, integrates prefix candidates into the encoded regular-index cost model (covering, backfill, IN/prefix_in alternatives), and collects the new stats with clone-on-write publication that nils ByteRangeMap on merge, patch, and snapshot paths. Verified from first principles: runtime LIKE semantics (anchored dotall case-sensitive regexp for text domains via (?s:) in prepareLikeRegexp, bytewise compiled pattern for binary domains) make prefix_eq replacement exact for admitted domains; in_range flag 2 half-open bounds, serial-key encoding with PrefixCompare, and stringPrefixRangeIsExact residual retention are sound for single-part in_range and multi-part prefix_in_range paths; backfill keeps the original filter on the base scan so correctness never depends on range exactness; the stability gate (regularIndexFiltersHaveStableEvaluation, literalStringINIsTotal, regularIndexFixedInputs) preserves evaluation domains for throwing residuals and dynamic prepared values; the sha256-priority bottom-k reservoir, 64-byte truncation invariant, NULL-inclusive SampleRows, and conservative upper margin in ByteRangeUpper are coherent and bounded; the new proto field 14 sits after reserved tag 13 and is backward compatible. Prior review history was loaded first: mo-bot's two request_changes on older commits (selective-IN backfill suppressed by the new prefix) are resolved at this head by the matchRangeBackfills same-class/other-class tie swap plus TestLikePrefixKeepsSelectiveINBackfill and BVT assertions, so they are not re-reported; the two reviews on this exact head concur with approval, there are no unaddressed findings, and there are zero inline review comments. Remaining deltas are deliberate, documented, plan-only tradeoffs in the safe direction: CHAR, PadSpace, and UCA columns are excluded from LIKE rewrites (the UCA index path was unreachable anyway and the retained LIKE is exact), escaped no-wildcard patterns lose the naive base prefix candidate (whose double-backslash derivation was itself wrong), mixed patterns re-estimate LIKE as a necessary condition with selectivity 1.0 while the prefix carries analyzed frequency, and broad or uncosted prefix access conservatively falls back to the table scan; unit and BVT tests document both directions of every intentional plan flip. Tests run locally with -v -count=1 and recorded under $TMPDIR/mo-31940/: pkg/statistics/analyze PASS (exit 0) and pkg/pb/statsinfo PASS (exit 0). Limitation: pkg/sql/plan, pkg/vm/engine/disttae, and the cluster-backed BVT and sqlintegration tests could not be executed here because the pre-existing matrixone/cgo package requires third-party C headers (roaring.h, usearch.h, xxhash.h) absent on this machine and the review constraints forbid installing dependencies; the identical failure reproduces on base code, so it is an environment limitation not attributable to this PR. All inspection outputs are collected and no background tasks remain running. Conclusion: no blocking or non-blocking findings to report.

@XuPeng-SH

XuPeng-SH commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: c56fd067b9e423849e61fac8fc0f4b9a867fb4bf

New discussion was assessed; the previous review remains unchanged.

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

Independent review of c56fd067b9e423849e61fac8fc0f4b9a867fb4bf against base/merge-base ae40f12a647880a63466de32a9f507c2c72dca0b: one P2 performance finding. Query results remain correct. The earlier selective-IN backfill finding is resolved at this revision; the finding below concerns covering candidate generation and is not a repeat of that issue.

P2 — Let the narrow prefix covering candidate compete with an ordinary range

With a covering index on name, adding the redundant condition name >= 'a' suppresses the narrow lookup for name LIKE 'abc%', in either predicate order.

I independently reproduced this through public SQL on Linux amd64 / Go 1.27.1:

CREATE DATABASE review31940_covering;
USE review31940_covering;
CREATE TABLE t(
  id INT PRIMARY KEY, name VARCHAR(40), payload INT, KEY ix(name)
);
INSERT INTO t
SELECT result,
       concat(if(result % 1000 = 0, 'abc', 'zzz'), lpad(result, 8, '0')),
       result
FROM generate_series(1, 100000) g;

-- Measurements were taken after flushing t and its hidden secondary index.
ANALYZE TABLE t(name) FULLSCAN;

EXPLAIN ANALYZE SELECT count(*) FROM t WHERE name LIKE 'abc%';
EXPLAIN ANALYZE SELECT count(*) FROM t
  WHERE name LIKE 'abc%' AND name >= 'a';
EXPLAIN ANALYZE SELECT count(*) FROM t
  WHERE name >= 'a' AND name LIKE 'abc%';
Predicate Actual scan input rows Input blocks Reported ReadSize
Prefix alone 100 1 124.69 KiB
Prefix + redundant range 100,000 13 1.45 MiB
Reversed predicate order 100,000 13 1.45 MiB

All three count queries returned 100. In this reproduction the slow alternatives still use a covering Index Table Scan, with >= driving access and prefix_eq(serial_extract(...)) left as a residual. The defect is loss of the narrow prefix lookup; it does not necessarily mean a base-table scan.

The cause is candidate admission rather than the scorer: firstFilters unconditionally prefers an ordinary predicate over a logical prefix, the covering matcher constructs only that candidate, and the caller considers only one covering match. The two-class enumeration below it applies only to backfill.

A separate typed planner diagnostic retained the complete filter set and statistics, proved stable evaluation, and asked the matcher to construct each covering alternative independently. The ordinary candidate cost 4,100,000 and was rejected; the legal prefix candidate cost 298,922.98 against a scan cost of 600,000 and was accepted. These are model-work units in that fixture, not measured latency for the SQL above.

Minimal remedy: independently construct the ordinary and logical-prefix covering candidates, pass both through the existing legality/statistics/stable-evaluation gates and common scorer, and prefer ordinary access on a cost tie. Retain the historical choice when prefix admission fails. Add a covering regression for both predicate orders, alongside the existing selective ordinary-access controls. No enumeration of every predicate is necessary.

Design assessment and tradeoffs

The original sargability gap warrants a fix. Deriving typed ranges in the planner, reusing existing index readers, collecting samples during the existing ANALYZE scan, and publishing copied generations are sensible ownership choices. Exact residuals, successor-gap handling, and the whole-filter evaluation guard address meaningful semantic boundaries. I found no additional demonstrated cancellation, resource-lifecycle, or recovery defect in the inspected changes.

The demonstrated finding shows that the shared cost policy is not yet applied consistently: covering candidate generation makes a preference decision before that policy can compare the alternatives.

The following are conservative tradeoffs, not additional defect claims: automatic prefix admission requires a suitable analyzed distribution; collection requires all persisted blocks to be selected; domains and literal/provenance shapes are restricted. Sampling is bounded to 2,048 slots per column, 16,384 per table, and 64 value bytes per slot. With a non-census sample of 2,048 rows, even zero observed hits produces an upper fraction of about 7.19%. That margin and dispersed-backfill costing can reject useful noncovering paths. The change therefore does not promise automatic indexing for every LIKE shape or the fastest plan for every cache/layout state.

Independently checked evidence and limits

Focused planner, analyze, statsinfo and disttae tests passed, including cancellation/generation and remote sample-visibility checks. TestLikePrefixIndex passed for memory/persisted data, prepared reuse, error behavior and writable transactions. Additional binary-domain/NUL/escape/0xFE/0xFF SQL controls and both covering diagnostics passed. Tests used the repository CGo wrapper with validated native artifacts; tracked source remained unchanged.

I did not independently rerun the full repository suite, a fresh race suite, standalone mo-tester BVT, or a base/head latency comparison. ReadSize and input-row observations above are execution evidence, not an end-to-end latency benchmark. Author- or other-reviewer-reported latency/microbenchmark results are not counted as my own measurements.

@XuPeng-SH

XuPeng-SH commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: c56fd067b9e423849e61fac8fc0f4b9a867fb4bf

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

Assessment: request_changes

New review 5724021910 substantiates a covering-candidate omission, changing prior approval 5722791817. The earlier selective-IN backfill issue remains resolved.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

  • P2 pkg/sql/plan/apply_indices.go:3594: On an analyzed table with a covering index, adding redundant name >= 'a' to selective name LIKE 'abc%' suppresses the narrow prefix covering candidate in either predicate order.
    Impact: The supplied same-head SQL probe reports 100,000 scanned rows and 13 blocks instead of 100 rows and one block. Results remain correct; the broader plan still uses covering index access.
    Evidence: firstFilters unconditionally prefers ordinary predicates. matchRegularIndexOnlyScan at line 4455 constructs only that choice, and line 2539 submits one covering match. Two-class enumeration applies only to backfill. Independent source tracing supports review 5724021910's SQL observations and typed cost diagnostic. Construct ordinary and logical-prefix covering alternatives through the existing legality, statistics and stable-evaluation gates, score both, retain ordinary access on ties or failed prefix admission, and add regressions for both predicate orders.

Validation:

  • Reconciled all 16 discussion entries and linked issue 31867; reused supplied prior coverage for unchanged contracts.

  • Traced covering selection, shared costing, safety gates, backfill alternatives and existing tests against frozen source.

  • Source/evidence audit passed with unchanged checkout and exact patch correspondence: checks/1793467444592995146-4.json. Records are retained in validation-summary.json and discussion-assessment.json.

  • Frozen CI contains 20 successful, 14 skipped and 2 neutral checks; skipped and neutral checks were not counted as passes.

Limitations:

  • No fresh product tests or latency benchmarks were run. Public SQL measurements and typed planner execution results are attributed to the supplied review.

  • The evidence establishes increased scan work, not a quantified end-to-end latency regression.

@XuPeng-SH
XuPeng-SH force-pushed the codex/31867-like-range branch from c56fd06 to 3d59100 Compare November 1, 2026 03:59
@XuPeng-SH

XuPeng-SH commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 3d591002f5d1acbef872237dd63fc0bedf5144de

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: 3d591002f5d1acbef872237dd63fc0bedf5144de

Assessment: approve

Completed the 34-file review. The prior selective-IN and covering-candidate findings are resolved. Candidate selection, prefix semantics, statistics ownership, and compatibility contracts are satisfied; no actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a1869d-999c-7481-b340-ae4a63e8cee4 · slot 1 · generation 2

Validation:

  • Full normal tests with vet=all passed for sql/plan, pb/statsinfo, statistics/analyze, and vm/engine/disttae. Receipt: checks/1793506178170625454-2.json; log: owner-tests.jsonl.

  • TestLikePrefixIndex passed through public SQL in memory and persisted phases. Receipt: checks/1793506250293611857-2.json; log: public-sql.jsonl.

  • Focused race tests passed across all five affected packages, including public SQL. Receipt: checks/1793506528189921597-2.json; log: focused-race.jsonl.

  • Full race tests passed for the three statistics owner packages. Receipt: checks/1793506474701398712-2.json; log: stats-owner-race.jsonl.

  • Isolation preflight, qualified native rebuild, formatting, and diff checks passed. Source remains unchanged; all 18 discussion entries are accounted for. Evidence is recorded in validation-audit.json, source-audit.json, and discussion-assessment.json under the assigned diagnostic directory.

Limitations:

  • Standalone BVT and fresh latency benchmarks were not run; incomplete frozen CI results were not counted as passes.

  • Two unrelated planner subtests skipped. Planner race coverage was focused rather than package-wide.

@XuPeng-SH

XuPeng-SH commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: aa6b7c9e331594cae8785e819c4fd953601fb1c8

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

Assessment: approve

Complete review found no actionable defects. Both prior candidate-selection findings are resolved. Prefix admission, ordinary index policy, and sampled-statistics ownership match the documented design.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

Validation:

  • Full planner, analyze, statsinfo, and disttae suites passed with vet enabled.

  • Public SQL tests passed for memory/persisted data, prepared reuse, error behavior, and workspace rollback.

  • Full statistics-owner race suites and focused planner/public SQL race checks passed.

  • Native provenance and protobuf descriptor audits passed.

  • All 20 discussion entries assessed; commands, source fingerprints, exits, and retained logs reconciled in validation-audit.json.

Limitations:

  • Frozen CI was incomplete; repository-wide CI and standalone BVT were not rerun.

  • Author-reported latency measurements were not independently reproduced.

  • Two unrelated planner subtests explicitly skipped; planner race coverage was focused.

This branch was successfully deployed

No deployments
ci — d71f3e0d Deployed Nov 2, 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 size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Performance]: prefix LIKE never uses the index, unlike MySQL range scan

4 participants