Repository navigation
perf(sql): cost literal LIKE prefix ranges with analyzed distributions - #31940
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
mo-bot review · Commit: "interrupted" |
|
mo-bot review · Commit: "interrupted" |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
|
mo-bot review · Commit: New discussion was assessed; the previous review remains unchanged. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
c56fd06 to
3d59100
Compare
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
What type of PR is this?
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:
mainat2e2b814ae3. 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 incrementalgo vet, pinnedmolint, andgolangci-lintpass across the five affected packages, with affected-package rechecks after the last test changes.