Skip to content

fix(plan): retain bounded REPLACE primary-key runtime filters - #32401

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
ck89119:issue-27403-pruning-main
Nov 9, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
ck89119:issue-27403-pruning-main

Conversation

@ck89119

@ck89119 ck89119 commented Nov 9, 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 #27403.

What this PR does / why we need it:

REPLACE conflict lookup already compares the serialized composite primary key as a single key. Unlike the multi-column JOIN path addressed by #27501, it can still lose its runtime filter at the generic NDV selectivity gate.

In a current-main reproduction, a session retained NDV=64 and TableCnt=64 while flushed L0 objects accumulated. A batch of 16 new keys therefore exceeded the 10% admission threshold, and the DEDUP target scan read every historical block despite there being no conflicts.

Allow a bounded DEDUP lookup on the leading, complete physical primary key to bypass that NDV ratio gate. Retain the existing exact-IN budget, encoding checks, join-direction restrictions, scan limits, and large-build guards. Actual over-budget builds still fall back to PASS. Ordinary joins, partial composite keys, and nonleading keys retain their existing cost gates; no reader, storage-format, or protocol changes are introduced.

Regression evidence

The independent single-CN SQL fixture disables table auto-merge, verifies the L0 object layout, and waits for logtail application rather than sleeping. With a fixed 16-key input:

Persisted layout Before: scan blocks / input rows After: scan blocks / input rows After: scan ReadSize
8 objects / 512 rows 8 / 512 0 / 0 0 bytes
16 objects / 1,024 rows 16 / 1,024 0 / 0 0 bytes

The regression also checks exact result rows and table cardinality for existing keys, mixed keys, two matching objects, different run IDs, duplicate input with last-value semantics, and transaction-local conflicts. Workspace batches are counted separately from persisted reads. Planner tests cover stale/unknown NDV, single and serialized PKs, budget boundaries, and the nearest rejected candidates. The new positive planner cases and the original read-work regression fail without the fix.

Validation

Local validation used Go 1.27.1 with matching worktree-native libraries and the repository CGo test wrapper:

  • Focused planner regressions and existing REPLACE planning controls: passed.
  • TestReplaceCompositeKeyPrunesFlushedObjects, -count=2: all 14 scenarios passed in each run.
  • Full pkg/sql/plan, pkg/sql/colexec/hashbuild, and pkg/sql/colexec/runtimefilter packages: passed.
  • Changed production statements: 100% coverage; planner package: 86.0%.
  • Changed-package go vet, incremental golangci-lint 2.14.0, gofmt, and git diff --check: passed.
  • Built a separate local mo-service and ran the existing test/distributed/cases/dml/replace suite through mo-tester: 783/783 SQL statements passed, with no failures, skips, or abnormal results.

This is a local mechanism fix on main, not a claim that the MNL2 deployment or long-running workload has been validated. It does not promise constant-time object metadata work and does not include a 4.2-dev backport.

@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 Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 009351022e27efda73f8102c246b6e5e2b1a34e7

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: 009351022e27efda73f8102c246b6e5e2b1a34e7

Assessment: approve

The bounded DEDUP exception fixes stale-NDV admission while retaining the existing encoding, budget, join-direction and PASS safeguards. It reuses the planner/filter owners and shared SQL fixture; the added tests distinguish pruning from SQL correctness. No actionable findings remain.

Model: gpt-6.1-sol / max

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

Validation:

  • Reviewed all four changed files, linked issue #27403 and all discussion entries; traced admission through exact-key publication and SQL fixture cleanup.

  • Reused frozen exact-head successful build, Ubuntu UT/coverage, arm64 SCA and PROXY/pessimistic compose BVT evidence; the repository UT scope includes the affected owners and integration package.

  • Author reports full plan/hashbuild/runtimefilter tests, pruning integration -count=2 (14 scenarios each), unfixed controls, vet/lint and 783/783 REPLACE BVT statements passing; retained as attributed evidence in review-notes.md.

  • Local git diff --check and frozen-source verification passed; checks/*.json, diff-check.log, source-check.log and source-ledger.json reconcile commands, head and exits.

Limitations:

  • No local Go or SQL suite was rerun; CI per-test logs and author raw execution artifacts were not supplied.

  • The managed long-running workload, release backport and constant-time object metadata work are outside this fix's demonstrated scope.

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

mergify Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue · pull request dequeued

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

So far

  • ✅ Entered the queue Mon 9 Nov, 11:17 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 12:39 · 693175e

Reason

Pull request #32401 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 da867c9 into matrixorigin:main Nov 9, 2026
@mergify mergify Bot added dequeued and removed queued labels Nov 9, 2026
@ck89119
ck89119 deleted the issue-27403-pruning-main branch November 9, 2026 13:33
XuPeng-SH pushed a commit that referenced this pull request Nov 9, 2026
…32357)

## 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 #31175
Related to #31179

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


**Design.**
`docs/design/20261108-pattern-matching-effective-collation.md` (revision
r5, SHA256
`c37413e83c10d49cd71153d22b2066733d3ecc1f2a543b14b50b830c9ecbba42`,
revised in `b9d08296ef` after the rebase onto `c99234dcf4`) records the
problem evidence, invariants, MySQL/ICU/UCA precedent and alternatives,
ownership and data flow, resource budgets and boundaries,
compatibility/rollout, and the validation map for the complete change.
r5 corrects r4's validation-map fold-fully expectation with engine
bounds measured during the post-approval implementation: exact fold
emission grows quadratically with run length, and the regexp2 route's
binding engine bound for long fold runs is its compiled
backtracking-state limit (4,096 tracks — a 40-rune fold run compiles at
1,439 tracks and is admitted; an 80-rune run compiles past the bound),
so the round-14 four-alternative comment-bearing shape raises the
bounded resource-limit error under `i` even after deduplication, and
fold-fully proofs relocate to below-bound regexp2 shapes and to the RE2
route at the original scale. No invariant, ownership decision, budget
value, or error family changes; r4's independent design-only PASS
(SHA256
`c31aef6c201f712c72aca88c59149d6805f1b99fddad9d2a0cde724021edc098`)
remains the base. r4 had resolved the r3 finding (equal effective
inline-option state before deduplication; an intervening unscoped setter
makes a duplicate ineligible, so `^(?:ss|(?i)a|ss)$` keeps both `ss`
branches) and carried forward the r3 resolutions of the two r2 findings
(capture/backreference/option-aware dedup eligibility; the
resource-limit error contract with planned public-path BVT proof).
Design r5 passed the independent design-first review, and the production
deltas are implemented in head `bd80b57137` on top of the r5 design
commit. Revision r6 (2026-11-09) records the resolution of the
implementation review's P1 on the r5 head: the alternative-deduplication
prepass is linear and carries its own charged work bound (4 MiB) —
construct marks land on the innermost branch in O(1) with close-time
flag folding into the enclosing branch, and each alternation closure
tracks its most recent unscoped-setter branch incrementally — so many
identical siblings and deeply nested groups cannot perform quadratic
work before the rewrite budgets are initialized; abandoning the prepass
returns the source pattern unchanged, deferring to the approved
expansion budgets with no new SQL-visible outcome. It extends
`docs/design/regexp-icu-compatibility.md` (issue #28305), whose
admission/cache/budget layer this change threads case folding through.

**Problem.** `LIKE`, `ILIKE`, `REGEXP`/`REGEXP_LIKE` and `FIND_IN_SET`
ignored the effective collation and compared byte-wise. Under the
default `utf8mb4_general_ci` (and under an explicit `utf8mb4_unicode_ci`
column) `'a' LIKE 'A'` returned 0 and `WHERE name LIKE 'alice%'` missed
`'Alice'`, while MySQL returns 1 for both — and while `=`/`IN` and
`LOCATE`/`INSTR`/`POSITION` on the same data already honored the
collation. Pattern operators therefore disagreed with their sibling
operators, and `LIKE 'prefix%'` index range scans could return different
rows than folded scans.

**Root causes closed by this PR.**

1. The LIKE executor and FIND_IN_SET ran byte-wise matchers and the
regexp engine ran case-sensitively; none of the pattern operators
consulted the operands' resolved collation (column COLLATE, expression
COLLATE, session default, `_binary` introducer, `CAST(x AS BINARY)`).
2. Collation-correct matching needs more than per-character caseless
flags: `utf8mb4_general_ci` folds by MySQL's weight table,
`utf8mb4_unicode_ci` compares UCA 4.0.0 primary weights per character,
and ci REGEXP needs Unicode full case folding (`ß`↔`ss`) that
per-character orbits cannot express.
3. The planner rewrote `col LIKE 'prefix%'` into byte-ordered
`prefix_eq`/`=` filters, which return different rows than
collation-folded LIKE.
4. Constant folding truncated planner-built binary→text conversions
whose target width is `-1` (every non-empty constant folded to `''`) and
re-marked folded `CAST(x AS BINARY)` literals as binary-introducer
domains, losing a winning case-insensitive collation.
5. Aggregating the matchers into collation resolution exposed implicit
ci-column vs `CAST(x AS BINARY)` ties (equal coercibility 2) to the
resolver's version check, raising error 1267 where base behavior and
MySQL compare byte-wise; `find_in_set`'s overload registration also cast
binary operands to utf8 `varchar`, erasing the binary string domain for
non-constant operands.
6. Constant `CAST(x AS BINARY)`, `BINARY 'x'` and `binary(x)` presented
a coercible literal's coercibility (4) instead of MySQL's IMPLICIT
coercibility (2) for cast results: folding replaces the cast with a
literal that keeps only its type, and the `binary()` function fell
through to the default rank. A case-insensitive column then strictly
outranked the binary operand and the planner converted it to
case-insensitive text, flipping `vc LIKE BINARY 'a%'` / `vc LIKE
CAST('a%' AS BINARY)` / `BINARY vc LIKE 'a%'` to case-insensitive
(surfaced by `operator/mysql_compat_string_binary_comparison`).

**What changes.**

- `pkg/common/collation/wildcard.go` (new): collation-aware LIKE matcher
— general_ci weight folding, UCA per-character weights, `_`/`%`/ESCAPE
handling, bounded multi-`%` segment matching with cancellation.
- `pkg/sql/plan/function/func_builtin_regexp.go`,
`regexp_casefold.go`/`regexp_casefold_tables.go` (new), `regexp_icu.go`:
LIKE/ILIKE/REGEXP/REGEXP_LIKE resolve the operands' collation (including
the ESCAPE argument; `REGEXP_LIKE` resolves from subject and pattern);
ci collations route LIKE through the weighted matcher and REGEXP through
an exact, bounded full-fold pattern rewrite (byte-identical below its
budgets; per-character caseless orbit above them); the binary/ci mix
keeps MySQL's error 3995 in both operand orders, and malformed-pattern
verdicts are always taken from the source pattern as written.
- `pkg/sql/plan/function/func_binary.go`: FIND_IN_SET honors the
resolved collation (weighted whole-key membership, unpadded comparison;
trailing spaces stay significant).
- `pkg/sql/plan/collation_expression.go`: expression-level collation
resolution covers the pattern matchers; a scoped pairwise tie rule
(`patternBinaryCollationAdmission` + `pairwiseBinaryTieWinner`) restores
the base behavior for implicit ci-column vs binary-CAST predicates only
— the binary operand wins the equal-implicit-rank tie,
LIKE/ILIKE/FIND_IN_SET compare byte-wise, REGEXP keeps 3995, and
text-text conflicts still raise 1267. Binary-domain cast results are
stamped with MySQL's IMPLICIT coercibility (2) so the tie rule, not a
rank-4 literal default, decides them.
- `pkg/sql/plan/base_binder.go`: `CAST(x AS BINARY)`/`BINARY 'x'` carry
IMPLICIT coercibility from creation; the stamp rides the expression
type, so constant folding (which preserves the type wholesale) cannot
drop it.
- `pkg/sql/plan/opt_misc.go`: for case-insensitive columns the planner
keeps the LIKE predicate instead of rewriting it to byte-ordered
`prefix_eq`/`=` filters, so scan and index paths return the same rows.
- `pkg/sql/plan/function/func_cast.go`,
`pkg/sql/plan/rule/constant_fold.go`: negative-width conversion targets
no longer truncate folded constants, and a folded binary-CAST literal
keeps the selected text domain when an explicit ci collation won the
resolution.
- `pkg/sql/plan/function/list_builtIn.go`: `find_in_set` uses the
domain-preserving overload registration.

**Issue-to-test proof.** Every reproduction row from #31175 and the
preserved #31179 report is pinned: `'a' LIKE 'A'`/`'ABC' LIKE
'abc'`/`'abc' REGEXP 'ABC'`/`'abc' REGEXP '[A-Z]+'` now return 1; the
`ci1`/`uci2` table rows match folded `LIKE 'alice%'` and `REGEXP
'^alice'`; `FIND_IN_SET('A','a,b')` = 1; explicit `utf8mb4_unicode_ci`
column and literal COLLATE cases agree across `=`/IN/LIKE/REGEXP;
binary/case-sensitive controls (`_bin` collations, `_binary` domains)
stay byte-wise; `LOCATE`/`INSTR`/`POSITION`/`FIND_IN_SET` neighbors keep
their behavior.

- UT: `pkg/common/collation` (weights, segments, boundaries),
`pkg/sql/plan` (resolution/admission matrix incl. CAST and prepared
shapes, executor routing over real typed batches, fold/cast
preservation, folded-`CAST(x AS BINARY)`/`BINARY 'x'`/`binary()`
coercibility regression test) and `pkg/sql/plan/function` (fold rewrite
tables/orbits, matcher routing, error shapes).
`pkg/sql/plan/build_show_desc_oracle_test.go` fixture spellings now
differ beyond letter case, because the DESCRIBE/SHOW COLUMNS filter LIKE
honors the effective case-insensitive collation (the #32197
replan-refilter assertions are unchanged).
`pkg/tests/sqlintegration/like_prefix_index_test.go` pins its #31940
prefix-plan fixtures to `utf8mb4_bin`, the byte-ordered domain the
prefix rewrite requires, and the new
`TestLikePrefixCaseInsensitiveKeepsFoldedPredicate` proves that under
`utf8mb4_general_ci` the analyzed planner keeps the folding LIKE
predicate (no `prefix_in_range`/`prefix_eq`) while scan, forced-index
and computed-subject paths all return the folded rows
(`'abc'`/`'ABC'`/`'Abc'` for `LIKE 'abc%'`).
- BVT: new
`test/distributed/cases/charset_collation/issue_31175_pattern_collation.sql`
— 416 statements covering literals, columns, explicit COLLATE in both
operand orders, `_binary`/HEX/BIT/CAST domains, prepared `CAST(?)`
parameters, user variables, VARBINARY columns, index-vs-scan plans,
NULL/empty/escape boundaries and error texts; every expected value
probed against a MySQL 8.0.44 oracle. Its resource-boundary rows pin the
r5 contract: the 328-byte four-alternative comment-bearing shape raises
the bounded resource-limit error naming the regexp2 4,096-track
backtracking-state bound under `i` while the `c` control returns 1,
below-bound shapes fold fully on the regexp2 route (six `ß` match twelve
`s`), and the RE2 route folds fully at the original scale (forty `ß`
match eighty `s`). New
`test/distributed/cases/charset_collation/issue_31175_pattern_resource_limits.sql`
(15 statements) pins the bounded error contract at every bound —
per-pattern emission budget exhaustion, RE2 nesting admission, the
4,096-track bound, and below-bound positive/negative fold controls
(`CONCAT(REPEAT('ß',20),'a')` matches the forty-`s`-then-`a` branch = 1;
the unsuffixed subject = 0). Existing expectations updated only where
folding intentionally changes results (`operator/like_operator`,
`optimizer/like` plans, `function/func_regular_like` CRLF-multiline
rows), plus the same intentional case-folding flips surfaced by CI in
`charset_collation/charset_collation_advanced` (`code LIKE 'abc%'`),
`charset_collation/charset_collation_basic` (`name LIKE 'app%'/'APP%'`
on the `general_ci` table; the `utf8mb4_bin` controls are unchanged),
`operator/operator.test` (`username LIKE '%Frau'`),
`operator/regexp_operator` and `operator/not_regexp_operator` (`'Acorn'
[NOT] REGEXP 'Corn'`), and `fulltext2/fulltext2_covered` (`tag LIKE
'Act%'`). `operator/mysql_compat_string_binary_comparison` keeps its
committed expectations: its CI failure was root cause 6, fixed in code.

Local validation: `mo-cgo-test -count=1 ./pkg/sql/plan
./pkg/sql/plan/rule ./pkg/sql/plan/function ./pkg/common/collation` (all
packages pass), `go vet` clean, gofmt clean, `go test -count=1 -run
'TestLikePrefixIndex$|TestLikePrefixCaseInsensitiveKeepsFoldedPredicate$'
./pkg/tests/sqlintegration` (both pass, memory+persisted phases; the
unadapted fixture failed the line-105 plan assertion in CI coverage UT
on this head), and mo-tester `run` of the new BVT passes 410/410 on the
fixed binary while the pre-fix binary fails exactly the new
discriminator statements. At the pre-rebase r5 head `5c628ab92f` (same
diff, now rebased): focused UT batches pass (`pkg/sql/plan/function`
dedup/fold/routing suites incl.
`TestRegexp2CaseFoldIdenticalAlternativesDedup` and
`TestRE2CaseFoldIdenticalAlternativesDedup`; full `pkg/common/collation`
batch incl. the LIKE budget UTs), and mo-tester `genrs` + independent
row review + two normal-comparison `run` passes of
`include=issue_31175_pattern` on one clean instance each pass 431/431
(416 collation + 15 resource-limits). After the root-cause-6 fix,
mo-tester `run` additionally passes
`operator/mysql_compat_string_binary_comparison` (57/57), the six
refreshed files above, `function/func_regular_like`, `optimizer/like`
and `optimizer/like_prefix_range` on the rebuilt binary
(`operator/like_operator` passes 190/190 in CI; one `rpad`+cast INSERT
at row 230 fails only under the local prepared-statement runner, before
and after this change); live probes confirm `vc LIKE BINARY 'a%'` / `vc
LIKE CAST('a%' AS BINARY)` / `BINARY vc LIKE 'a%'` / `vc LIKE BINARY vb`
compare byte-wise while `_binary 'a%'` and plain literals keep folding
case-insensitively.



**Rebase note (2026-11-09).** Rebased onto main `c99234dcf4` to clear
the merge conflict: #32341's `BuildPlan`/`CompilerContext.Resolve`
signature migration overlapped this PR's `n_NAME`→`n_PAME` expectation
update in `pkg/sql/plan/build_show_desc_oracle_test.go` (kept the PR's
case-beyond-letter-case fixture with the new 4-argument call and
`TableResolution` output), and one PR-added `BuildPlan` call in
`pkg/sql/plan/collation_expression_test.go` was migrated to the new
signature. The post-rebase PR diff is byte-identical to the pre-rebase
diff outside those two resolutions. Post-rebase validation on
`bd80b57137`: all five touched Go packages (`pkg/sql/plan`,
`pkg/sql/plan/function`, `pkg/common/collation`, `pkg/sql/plan/rule`,
`pkg/tests/sqlintegration`) compile clean via `mo-cgo-test`; the 26
DESC-oracle/LIKE-prefix/binary-tie tests and the 20 collation-expression
tests (incl. the migrated `TestPatternBinaryColumnCastTieRestored`)
pass; the full `pkg/sql/plan/rule` suite passes.

**Review-resolution note (2026-11-09, head `c8a615913c`).** Resolved the
mo-bot implementation review's P1 on `bd80b57137` (the deduplication
prepass performed quadratic work before the rewrite budgets):
identical-sibling dedup now makes one pass per alternation (65,536
alternatives: 2.19 s -> 4.8 ms in an exact-source probe) and
capture/reference/setter marks fold upward at group close instead of
walking the ancestor stack per construct (32,768 nested captures: 0.94 s
-> 4.7 ms), with eligibility verdicts preserved exactly; a charged 4 MiB
prepass bound abandons dedup byte-identically on exhaustion (the
depth-2000 nested-alternation shape that would hash ~410 MB is capped).
Validation on `c8a615913c`: focused dedup/work-bound/eligibility suites
pass (incl. exact-budget straddle pins and nested flag-propagation
rows), the broad `CaseFold|Dedup|Regexp|RE2` selection passes 135/135
top-level tests (917 runs incl. subtests, 0 failures), gofmt and `go
vet` clean. No BVT result changes: abandonment is unreachable below the
bound (every BVT pattern is orders of magnitude smaller), and dedup
outputs are unchanged for all in-budget patterns.

**Base refresh (2026-11-09, head `07943b3040`).** Rebased onto main
`da867c90df` (6 commits: #32401, #32399, #31419, #32353, #32380, #32251)
under the scheduled ci_base_refresh after run 42566409967's four
failures were verified as the unrelated #27066 tool-download transport
class. Zero file overlap with this PR's diff; no conflict resolutions
needed and the post-rebase PR diff is byte-identical to the pre-rebase
diff. Post-rebase validation on `07943b3040`: `go test -count=1` passes
for all three affected packages — `pkg/common/collation` (17.2s),
`pkg/sql/plan/function` (38.9s), `pkg/sql/plan` (131.1s). No code
change; design r5/r6 record and all review dispositions carry over
unchanged.

**Residual limits** (pinned by tests and documented in the issue): LIKE
stays a per-character weight comparison (no multi-character expansion
spanning; `ß LIKE 'ss'` = 0); three ICU-only regexp corners diverge
(character-class string closure, caseless backreference matching,
quantified-atom image spanning); equality/IN over pure literals under
explicit `utf8mb4_general_ci` keep a pre-existing parity gap that a
follow-up issue owns; `REGEXP_INSTR`/`REGEXP_SUBSTR`/`REGEXP_REPLACE`
keep their default case behavior unless `match_type` requests `i`; PAD
SPACE, sort weights and key uniqueness under ci collations are out of
scope per the issue's acceptance checklist.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
XuPeng-SH added a commit that referenced this pull request Nov 9, 2026
…-pick #32401) (#32432)

## 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 #27403 (backport of #32401 to `4.2-dev`).

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

Cherry-pick #32401 (`da867c90dfaf1c5102ace1a192b358fcc5adbb9c`) to
`4.2-dev`.

Keep a bounded DEDUP lookup on the leading, complete physical primary
key from losing its runtime filter at the NDV ratio gate. This includes
REPLACE's already-serialized composite primary key. Preserve the
exact-IN budget, encoding checks, join-direction restrictions, scan
limits, large-build guards, and runtime PASS fallback.

This backport is independent of #32400: it uses the existing single-key
DEDUP path, not the new multi-column JOIN filter construction.

### Backport adaptations

- Use `4.2-dev`'s existing `HashmapSize` and singleton admission logic;
do not import main's point-filter/tree refactoring.
- Adapt all 13 planner scenarios to the target branch's builder and
scoped configuration APIs.
- Preserve all 14 REPLACE regression scenarios in
`pkg/tests/issues/isolated`, using an owned single-CN cluster and
explicit cleanup instead of importing main's SQL-integration harness.
- Omit only the four `multi_insert.result` expectation lines: the target
branch has neither that fixture nor the multi-table INSERT feature. No
unrelated feature or dependency PR is imported.

### Validation

Go 1.26.4, macOS arm64, worktree-built native libraries, repository CGo
test wrapper:

- Before the fix, the five positive planner cases fail, while the eight
rejection controls pass. The SQL regression also fails for the intended
missing-filter condition.
- After the fix, all 13 planner cases pass; all 14 SQL scenarios pass in
each of two runs (`-count=2`). Exact rows, cardinality, duplicate-input
semantics, and transaction-local conflicts are checked separately from
read work.
- With 16 new keys, persisted reads change from **8 blocks / 512 rows**
and **16 blocks / 1,024 rows** to **0 blocks / 0 rows / 0 bytes** for
both layouts.
- Full `pkg/sql/plan` tests pass: 76.0% statement coverage; changed
production statements are fully covered.
- Changed-package `go vet`, incremental golangci-lint 2.6.2, Go 1.26.4
formatting, and whitespace checks pass.

Full BVT, the full isolated integration-test package, multi-CN, and CI
validation were not run locally. This is a local mechanism backport, not
a claim that the long-running deployment workload in #27403 has been
validated.

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

This branch was previously deployed

1 inactive deployment
ci — 693175e8 Deployed Nov 9, 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/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants