Skip to content

fix: honor the effective collation in LIKE, REGEXP and FIND_IN_SET - #32357

Merged
XuPeng-SH merged 10 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-31175-main-434dd98f
Nov 9, 2026
Merged

XuPeng-SH merged 10 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-31175-main-434dd98f

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Nov 7, 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 #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 fix(sql): honor DESC column filters and ordinary table partitions #32197 replan-refilter assertions are unchanged). pkg/tests/sqlintegration/like_prefix_index_test.go pins its perf(sql): cost literal LIKE prefix ranges with analyzed distributions #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.

@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Nov 7, 2026
@mergify mergify Bot added the kind/bug Something isn't working label Nov 7, 2026
@gouhongshen
gouhongshen force-pushed the agent/issue-31175-main-434dd98f branch from 2a8c6b5 to 5613473 Compare November 7, 2026 23:46
@gouhongshen
gouhongshen force-pushed the agent/issue-31175-main-434dd98f branch from 5613473 to b554558 Compare November 8, 2026 00:51
@gouhongshen
gouhongshen marked this pull request as ready for review November 8, 2026 03:25
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Design revision updated to r5 (docs/design/20261108-pattern-matching-effective-collation.md, SHA256 c37413e83c10d49cd71153d22b2066733d3ecc1f2a543b14b50b830c9ecbba42, docs-only commit 597aaf838f), addressing the mo-bot design-gate review (CHANGES_REQUESTED).

Why r5: the independent design-only review of r4 recorded a PASS (with one non-blocking P3, carried as an in-place erratum). During the post-approval implementation, measurement proved one r4 validation-map expectation physically unachievable on the regexp2 route, so the design is corrected before the implementation lands:

  • 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). Measured on the implementation: a 40-rune s fold run expands to 17,918 bytes and compiles at 1,439 tracks (admitted); a single 80-rune run compiles past 4,096 tracks and is rejected.
  • r4 planned that the 328-byte four-alternative comment-bearing shape would fold fully after deduplication (forty ß matching eighty s under i). Even after deduplication to two distinct branches, its 80-rune fold runs exceed the track bound, so the shape raises the bounded resource-limit error under i — inside the error contract r4 already approved. The translated-size bound (1 MiB) is not the binding constraint for that shape (the deduplicated expansion is 137,917 bytes); for many-branch shapes the rewrite's own per-pattern emission budget (also 1 MiB) fires first.
  • The RE2 route has no compiled-state bound: the same four-alternative shape without the comment deduplicates to one branch and folds fully (44,502-byte expansion admitted), so the forty-ß oracle outcome is proved there; the regexp2 route proves fold-fully equivalence below its bound (four identical 12-s alternatives plus the comment; six ß match twelve s).

What r5 changes: the validation-map invariant-5 row splits the equivalence proof by engine route; the resource-boundary BVT row updates round-14 (comment-bearing 'i' statements become the bounded resource-limit error, 'c' controls unchanged, fold-fully BVT proofs relocated) and names the backtracking-state bound with the measured values in invariant 7 and the compatibility bullet. No invariant, ownership decision, budget value, error family, or approved r4 semantic changes. Alternatives considered and rejected: raising the 4,096-track bound (weakens an existing resource guard owned by the ICU design), post-expansion branch deduplication (a single 80-rune branch alone exceeds the bound), and subject-side folding (breaks the position mapping REGEXP_INSTR/REPLACE/SUBSTR rely on).

The focused UT evidence for the corrected contract is green locally (TestRegexp2CaseFoldIdenticalAlternativesDedup — the 328-byte shape errors with the bound named, 'c' control and below-bound fold proofs pass; TestRE2CaseFoldIdenticalAlternativesDedup — forty ß match eighty s on the RE2 route). Implementation review remains blocked until the independent design review of r5 records a decision.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Disposition for the mo-bot design-gate review (PRR_kwDOFEPiGM8AAAABWrZxXQ, CHANGES_REQUESTED on commit b554558f):

The required design-first gate is now satisfied and the implementation has landed.

  1. Design authored and independently reviewed. docs/design/20261108-pattern-matching-effective-collation.md records the versioned design the review required. The independent design-first reviewer approved revision r4, and — after a post-approval measurement corrected one validation-map expectation — approved the exact current revision r5 (SHA256 c37413e83c10d49cd71153d22b2066733d3ecc1f2a543b14b50b830c9ecbba42, committed in 597aaf838f). r5 covers the full-fold translation stage the review cited: grammar-aware parsing, recursive fold expansion, the resource budgets (per-pattern emission budget, RE2 nesting admission, regexp2 4,096-track compiled backtracking-state bound) and the budget-dependent semantic fallbacks, each with invariants, ownership, alternatives, and a validation map. The design explicitly extends the existing docs/design/regexp-icu-compatibility.md (issue [Compatibility]: REGEXP lacks MySQL ICU constructs and capture-group replacement #28305), whose admission/cache/budget layer this change threads case folding through, so the new stage is traceable into the previously reviewed design lineage.

  2. Implementation on the approved design. Head 5c628ab92f implements exactly the approved r5 revision: eligibility-checked identical-alternative deduplication with equal effective option state, exact per-part translated-size enforcement in the regexp2 translation stage, the resource-limit error contract naming the violated bound, and the LIKE shared search budget with the total-work bound and cancellation accounting.

  3. Validation. Focused UT batches pass (pkg/sql/plan/function — TestRegexp2CaseFoldIdenticalAlternativesDedup, TestRE2CaseFoldIdenticalAlternativesDedup, fold/routing/dedup-eligibility suites; full pkg/common/collation batch including the LIKE budget UTs). mo-tester BVT: genrs regeneration + independent row-by-row review of every expected result, then two normal-comparison passes of include=issue_31175_pattern on one clean instance — each 431/431 green (416 statements in issue_31175_pattern_collation, 15 in the new issue_31175_pattern_resource_limits pair pinning the bounded error contract at every bound with below-bound positive and negative fold controls). The r5 review's one non-blocking P3 (the below-bound REGEXP positive control) is corrected in that pair: the suffixed subject CONCAT(REPEAT('ß',20),'a') matches the forty-s-then-a branch (1) and the unsuffixed subject is the negative control (0).

The review's underlying concern — no reviewed design for the materially expanded pattern execution — is resolved: no unapproved implementation is published, and implementation review can now proceed against the approved r5 design.

@gouhongshen

gouhongshen commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Unrelated CI blockers on this PR, from two tracked classes: the known shared-runner tool-download transport class (#27066) and a flaky TN-side disttae round-24 control test (#25590):

Run 42566409967 (head c8a615913c, attempt 1, completed as failure): five lanes failed in their tool-download setup steps before any PR code was compiled or tested —

  • UT Test on Ubuntu/x86 (job 128993812841): setup-java Adoptium JDK8 tarball Unexpected HTTP response: 504 ×3 (05:19:05–05:19:31 UTC);
  • UT Coverage on Ubuntu/x86 (job 128993842093): setup-cmake CMake/ninja download Unexpected HTTP response: 504 ×3 → install-cmake failed (05:19:40–05:20:09 UTC);
  • SCA Test on Linux/arm64 (job 128993812273): setup-go go-1.27.1-linux-arm64.tar.gz from actions/go-versions Unexpected HTTP response: 504 ×3, then go.dev fallback timeout (05:18:27–05:22:15 UTC);
  • multi cn e2e bvt test docker compose(PROXY) (job 128996713471): setup-java Adoptium JDK8 504 ×3 (05:27:41–05:28:15 UTC), all BVT steps skipped;
  • multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC) (job 128996713546): setup-java Adoptium JDK8 504 ×3 (05:28:05–05:28:46 UTC), all BVT steps skipped.

The Coverage (job 128997347104) and CI Required (job 128997388132) gates failed only because those producer lanes never published results ("coverage merge blocked: a required producer did not publish a complete coverage profile"). Same-head CI preflight, Matrixone Shared Build, pr-size-label, Check coverage eligibility, and Iceberg Connector E2E lanes passed. After the run completed, the single permitted attempt-1 gh run rerun 42566409967 --failed was triggered (2026-11-09 05:35 UTC). Occurrence records: issuecomment-6732933452, issuecomment-6733091681.

Run 42566409967 attempt 2 (the rerun above, same head c8a615913c): the same transport class persisted across the rerun — both e2e BVT lanes failed again in tool-download setup before any PR code was compiled or tested:

  • multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC) (job 128999349851): setup-java Adoptium JDK8 Unexpected HTTP response: 504 ×3 (05:37:05–05:37:35 UTC), every BVT step skipped (setup-go also hit one 504 at 05:36:20 UTC but recovered on retry);
  • multi cn e2e bvt test docker compose(PROXY) (job 128999350038): setup-cmake ninja-build download Unexpected HTTP response: 504 ×3 (05:37:11–05:37:43 UTC) → install-cmake failed, all downstream steps skipped.

Of the run's remaining lanes on this attempt: UT Coverage on Ubuntu/x86 (job 128999349689) succeeded at 06:08:05 UTC and published its profile; the Coverage merge gate (job 129008771487) then failed at 06:08:17 UTC with prerequisites_ready: false ("coverage merge blocked: a required producer did not publish a complete coverage profile; no coverage verdict was calculated") — the aggregation cascade of the two 504-killed BVT producers above, with no coverage measurement of PR code attempted. Both previously pending lanes finished green: UT Test on Ubuntu/x86 (job 128999349559) and SCA Test on Linux/arm64 (job 128999349465) succeeded at 06:49:50/06:27:03 UTC, and matrixone-ut-coverage reported coverage_status: passed. The CI Required gate (job 129022073679) then failed at 06:49:55 UTC in 5 s without evaluating code: its verifyResults step (.github/ci/change-scope.cjs:113) raised Error: matrixone-compose-ci: failure on the three failed constituents (matrixone-compose-ci, matrixone-standalone-ci, matrixone-coverage-merge). Every lane that compiled or tested PR code on this attempt passed; only the two 504-killed setup lanes and their two downstream aggregation gates failed. No further rerun of this run is permitted (attempt 2). Occurrence records: issuecomment-6733148313, issuecomment-6733612732, issuecomment-6734143108.

Earlier run 42464723468 (head 5c628ab9): same class on attempt 1 (five lanes: UT Test on Ubuntu/x86, SCA Test on Linux/arm64, UT Coverage on Ubuntu/x86, multi cn e2e bvt test docker compose(PROXY), multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)) and on attempt 2 (the one permitted gh run rerun --failed), again all in setup tool downloads; the Coverage/CI Required aggregation gates failed only because those producer lanes never published results. Occurrence records: issuecomment-6719547729, issuecomment-6719631426, issuecomment-6719722413, issuecomment-6719730493.

Run 42623360322 (head 07943b3040, attempt 1, still in progress at inspection): a different, non-#27066 class — UT Coverage on Ubuntu/x86 (job 129180985863) failed at 13:41:46 UTC on exactly one test, TestIssue25590CloneBorrowedNeverHandedOffToQueueR24ControlC in pkg/vm/engine/disttae (require.ElementsMatch saw an empty unpublishedPending queue where the txn-local and fresh names were expected; 0.01s). All tool-download setup lanes on this run succeeded, so #27066 did not recur here. Root cause by code read: the handoff under test schedules an async gcPool drain of the very queue the assertion then reads with no synchronization (txn.go:1376 scheduleUnpublishedPendingDrain), so a loaded coverage runner can drain both moved names before the assert — a flaky round-24 control test, not PR code. The PR diff and the 6 rebased-in base commits contain zero pkg/vm/engine/disttae files, and the failing path evaluates no LIKE/REGEXP/collation code. Local verification on the exact failed head with the repo mo-cgo-test wrapper: the single test passes (1.6s) and the full ./pkg/vm/engine/disttae package passes (ok, 50.7s, zero failures). Unrelated to this PR and TN-side (protected scope for a fix); occurrence recorded on the matching existing issue (issuecomment-6741878936 on #25590). No rerun triggered: the workflow run is still in progress, and the rerun rule forbids rerunning a pending run.

No PR code was compiled or tested on any failing lane on either of the two earlier runs, and the current run's single failed test passes locally on the exact head; these failures are unrelated to this PR's changes. Resolution requires the shared runner/tool-download infrastructure class in #27066 and the flaky round-24 control test tracked in #25590 to be fixed by their owners, or the affected lanes to be retried by a maintainer.

@XuPeng-SH

XuPeng-SH commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: bd80b57137855d7e4535198c1cb086c94c6f3fde

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

Assessment: request_changes

The r5 design resolves the earlier design-gate concern and reuses existing collation and regexp owners. One implementation blocker remains: the deduplication prepass performs quadratic work outside the resource safeguards.

Model: gpt-6.1-sol / max

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

  • P1 pkg/sql/plan/function/regexp_casefold.go:290: A case-insensitive REGEXP/REGEXP_LIKE pattern contains many identical alternatives or deeply nested capturing groups.
    Impact: The new prepass performs quadratic work before rewrite budgets, engine admission and match timeouts apply. Large or concurrent patterns can monopolize CN CPU during compilation, including patterns the engine would promptly reject.
    Evidence: Line 290 rescans intervening branches for every duplicate, giving (N-1)(N-2)/2 checks. An exact-source helper probe took 1.32 s for 65,536 alternatives (196,607 bytes; 2.15 billion derived checks), versus 27 ms for the same-pattern RE2 parse control. Ancestor marking at lines 254-268 also scales quadratically: 32,768 captures took 0.73 s versus 5 ms for engine rejection. Both paths precede budget initialization at line 195. Replace repeated scans with incremental summaries preserving capture/reference/option eligibility, bound this prepass, and add duplicate/depth regression coverage. Evidence: dedup-growth-internal.log, dedup-nested-growth.log and dedup-probe-manifest.json.

Validation:

  • Reviewed all 42 changed paths, all 11 discussion entries, relevant linked requirements and SQL result oracles; coverage and discussion assessments retained.

  • Isolation preflight and exact-source helper probes passed: receipts 1794198851435562899-2, 1794198923017277512-2 and 1794199704062966994-2, with matching logs.

  • Static audit passed, including formatting of all 25 changed Go files and source integrity: receipt 1794200091769385212-2. Four intentional multiline result-header whitespace diagnostics were retained.

  • Frozen-head CI reports successful UT, SCA, coverage, proxy/pessimistic BVT and CI Required. Evidence reconciled in validation-ledger.json.

Limitations:

  • Full local package/SQL tests were not rerun: installed Go 1.26.6 is below required Go 1.27.1. Successful probes use stdlib-only extracted helpers with module mode disabled; timings are internal controls, not query benchmarks.

  • Historical author and MySQL/ICU validation reports were not independently reproduced.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Disposition for the mo-bot implementation review (PRR_kwDOFEPiGM8AAAABWwHQ1A, CHANGES_REQUESTED on bd80b571):

The P1 blocker is resolved in head c8a615913c. The deduplication prepass is now linear and carries its own charged bound, with the capture/reference/option eligibility verdicts preserved exactly.

  1. Identical-sibling rescans eliminated. closeAlternation now makes a single pass per alternation: kept maps each branch text to its first occurrence and lastSetter tracks the most recent branch carrying an unscoped setter at that level, so the intervening-setter check is O(1) per duplicate (lastSetter <= i) instead of a rescan of the branches between the kept occurrence and the duplicate. The review's exact-source probe shape (65,536 alternatives, 196,607 bytes) drops from 2.19 s to 4.8 ms locally — linear, and below the 27 ms RE2-parse control the review cited.

  2. Ancestor walks eliminated. Capture, reference, and option-setter marks now land on the innermost frame's current branch in O(1); when a group closes, its branches' flags fold into the enclosing branch in one pass (setterTop stays level-local, since an unscoped setter applies only to its own alternation's siblings). A construct's flags reach exactly the branches whose text contains it — the same eligibility verdicts as the ancestor walk, pinned by new table rows (nested capture/reference/unscoped-setter duplicates retained, nested scoped setter exempt, nested setter blocking its own level only). 32,768 nested captures drop from 0.94 s to 4.7 ms.

  3. The prepass is bounded. regexpCaseFoldMaxDedupWorkBytes (4 MiB) charges the pattern length once for the scan, one unit per branch for the close-time folding, and the branch-text bytes each closure hashes — so deeply nested alternations cannot multiply the pattern length by the nesting depth either (the depth-2000 shape that would hash ~410 MB abandons). Exhaustion abandons the prepass and returns the source pattern byte for byte, discarding recorded deletions: deduplication only shrinks the later emission, so the engines keep their own verdicts and the approved expansion budgets still guard the rewrite. No new SQL-visible outcome, and no BVT result changes (every BVT pattern is orders of magnitude below the bound; in-budget dedup outputs are unchanged).

Regression coverage (pkg/sql/plan/function/regexp_casefold_internal_test.go): exact-budget straddle pins of the charged-work model (a|a charges exactly 5, (?:a|a) exactly 11; one unit below abandons), both review probe shapes completing far below the production bound (327,679 and 98,310 charged), the depth-scaling nested-alternation shape abandoning byte-identically while a shallow control still dedups its core pair, and the nested flag-propagation eligibility rows above.

Validation on c8a615913c: focused dedup/work-bound/eligibility suites pass; the broad CaseFold|Dedup|Regexp|RE2 selection passes 135/135 top-level tests (917 runs including subtests, 0 failures) via mo-cgo-test; gofmt and go vet clean. The design record is revised to r6 documenting the prepass bound inside invariant 7's bounded-work contract.

Pattern matchers compared byte-wise and ignored the effective collation,
so under utf8mb4_general_ci/utf8mb4_unicode_ci 'a' LIKE 'A' was 0 and
case-insensitive columns missed folded prefix matches, disagreeing with
=, IN and LOCATE/INSTR/POSITION on the same data.

Resolve the operands' collation for LIKE/ILIKE/REGEXP/REGEXP_LIKE and
FIND_IN_SET (columns, explicit COLLATE, session default, _binary/CAST
domains), match LIKE through collation weights and REGEXP through an
exact bounded full-fold rewrite, keep the LIKE predicate for ci columns
instead of byte-ordered prefix_eq rewrites, preserve folded binary-CAST
values and domains, and keep MySQL's binary-wins-tie admission for
implicit ci-column vs CAST(x AS BINARY) predicates.

Related to matrixorigin#31175
Record the versioned design for the LIKE/ILIKE/REGEXP/FIND_IN_SET
effective-collation change: problem evidence, invariants, MySQL/ICU/UCA
precedent and alternatives, ownership and data flow, resource budgets and
fallbacks, compatibility and rollout, and the validation map. The design
gate was raised by the mo-bot implementation review; implementation review
stays blocked until this revision's design decision is recorded.

Design revision r1, SHA256 215a86b250e88a8a6f3f1bfc1ccc6024d09c5c501a745a9ce609e4d6504ce574.
)

Resolve the independent design review's two P2 findings on r1:
- fold rewrite: match-set-preserving alternative deduplication plus a
  bounded resource-limit error for residual over-budget faithful
  expansions, replacing the silent per-character fallback
- LIKE anchor fallback: one shared per-call search budget (cancellation
  every 1024 shared steps across all token kinds) and a deterministic
  total verification-work bound

Design-only change; the preserved implementation head b554558 predates
these resolutions, which land after design approval.
)

Resolve the independent design review's two P2 findings on r2:
- deduplication is now eligibility-checked: only byte-identical sibling
  alternatives free of captures, backreferences and unscoped option
  setters are dropped (first occurrence kept); capture/reference/option-
  bearing branches are retained and the resource-limit contract applies,
  with planned capture/backreference/replacement/inline-option
  counterexample tests
- the resource-limit error gains a defined contract (internal-error
  family, stable bound-naming message prefixes) and planned public-path
  BVT proof: flipped round-14/15 statements updated, a new resource-limits
  BVT file with both engines' exhaustion errors, LIKE work-bound
  exhaustion, below-bound controls and source-pattern errors, expected
  results independently reviewed before comparison execution

Design-only change; the preserved implementation head b554558 predates
these resolutions, which land after design approval.
Require equal effective inline-option state at both occurrences before
deduplicating sibling alternatives: an intervening unscoped option
setter changes the duplicate's ambient state (^(?:ss|(?i)a|ss)$ keeps
both ss branches), so any unscoped setter between the occurrences in
the enclosing group now makes the duplicate ineligible. Validation plan
gains intervening-option counterexamples on both engine routes and a
public REGEXP_LIKE match_type 'c' BVT case.

Resolves the r3 independent design review's P2 finding.
…rigin#31175)

Correct 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), so the round-14 four-alternative comment-bearing shape
raises the bounded resource-limit error under 'i' even after
deduplication. Fold-fully proofs relocate to below-bound regexp2 shapes
(four identical 12-s alternatives plus the comment; six sharp-s match
twelve s) and to the RE2 route at the original scale (four identical
80-s alternatives deduplicate to one branch; forty sharp-s match
eighty s). No invariant, ownership decision, budget value, or error
family changes; r4's independent design-only PASS remains the base.
…trixorigin#31175)

LIKE, ILIKE, REGEXP/REGEXP_LIKE and FIND_IN_SET compared byte-wise and
never consulted the operands' resolved collation, while =/IN and
LOCATE/INSTR/POSITION already did. Under utf8mb4_general_ci and
utf8mb4_unicode_ci the pattern operators therefore diverged from both
their sibling predicates and MySQL (issues matrixorigin#31175, matrixorigin#31179).

Implement the reviewed design
docs/design/20261108-pattern-matching-effective-collation.md revision r5
(SHA256 c37413e83c10d49cd71153d22b2066733d3ecc1f2a543b14b50b830c9ecbba42):

- pkg/common/collation: weighted LIKE/ILIKE matching under the resolved
  collation with a shared per-call search budget bounding total work
  (max(1<<20, 4*patternWords*subjectChars) comparisons), charged across
  fragmented patterns and honored for cancellation.
- pkg/sql/plan/function: grammar-aware Unicode full case folding for
  REGEXP/REGEXP_LIKE under ci collations on both the RE2 and regexp2
  routes, with eligibility-checked identical-alternative deduplication,
  exact per-part translated-size enforcement, and a bounded
  resource-limit error family naming the violated bound (per-pattern
  emission budget, RE2 nesting bound, regexp2 4,096-track compiled
  backtracking-state bound). Also covers the LIKE-prefix planner
  rewrite keeping its folded residual predicate and the find_in_set
  domain/collation handling recorded in the design history.

Validation: focused UT batches for pkg/sql/plan/function and
pkg/common/collation green; mo-tester BVT
issue_31175_pattern_collation.sql (416 statements) and new
issue_31175_pattern_resource_limits.sql (15 statements) regenerated and
run twice on one clean instance, 431/431 green both passes.
…31175)

Resolve the implementation review P1 on the r5 head: the
alternative-deduplication prepass performed quadratic work before the
rewrite budgets were initialized.

- closeAlternation now makes a single pass per alternation, tracking the
  most recent unscoped-setter branch incrementally instead of rescanning
  the intervening branches for every duplicate ((N-1)(N-2)/2 checks for
  N identical siblings: 65,536 alternatives took 2.19 s in an
  exact-source probe, now 4.8 ms).
- capture/reference/option-setter marks land on the innermost branch in
  O(1); a closing group folds its branches' flags into the enclosing
  branch in one pass, preserving the eligibility verdicts exactly
  (32,768 nested captures took 0.94 s, now 4.7 ms).
- a charged work bound (4 MiB) abandons the prepass and returns the
  source pattern unchanged on exhaustion, so deeply nested alternations
  cannot multiply the pattern length by the nesting depth; the expansion
  budgets still guard the rewrite.

Regression coverage: exact-budget straddle pins of the charged-work
model, both probe shapes completing below the production bound, the
depth-scaling shape abandoning byte-identically, and nested
flag-propagation eligibility rows. Design doc revised to r6.
@XuPeng-SH

XuPeng-SH commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 07943b30408b74fc8656f18b6254aad3f15f3749

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: 07943b30408b74fc8656f18b6254aad3f15f3749

Assessment: approve

The prior design concern and quadratic-prepass P1 are resolved. The bounded r6 deduplication preserves capture and option semantics. Weighted LIKE and grammar-aware REGEXP require distinct adaptations and reuse existing collation tables, engines and caches. No actionable finding remains.

Model: gpt-6.1-sol / max

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

Validation:

  • Reviewed all 42 changed files, relevant owners/consumers and all 14 discussion entries; recorded review-plan.md, discussion-assessment.json and oracle-assessment.md.

  • Isolation preflight passed. Native provenance matched 196 current inputs, 7 artifacts and 27 headers; retained receipts and native-evidence.json.

  • All four affected Go package suites passed with -vet=all -count=1 and the supplied test-exec; 10 unrelated skips. See packages-normal.jsonl and checks/1794237518065618426-2.json.

  • Both selected LIKE prefix SQL integration tests passed, including in-memory/persisted controls and case-insensitive scan/index/computed-predicate equivalence: 33 test/subtest passes, no skips. See prefix-integration.jsonl and checks/1794237911237693395-2.json.

  • Final audit passed: frozen patch/head, clean source, 25-file gofmt, discussion coverage and receipt/log correlation. See validation-audit.json and checks/1794238537324923031-2.json. Four git diff --check diagnostics are intentional multiline result-header whitespace.

  • Frozen CI metadata shows required build, UT, coverage and BVT checks successful; historical failure reports are superseded.

Limitations:

  • Distributed BVT, multi-CN, MySQL/ICU differential and performance reports were assessed from supplied evidence; no new local runs of those campaigns are claimed.

  • Documented ICU dialect/full-fold corner cases and existing general-ci equality/IN gaps remain within the accepted scope.

@mergify

mergify Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue · pull request dequeued

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

So far

  • ✅ Entered the queue Mon 9 Nov, 15:37 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 16:07 · cf95e34

Reason

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

This branch had an error being deployed

1 failed deployment
ci — cf95e34e 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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants