Repository navigation
fix(sql): align ORD, BIT_COUNT and REGEXP UTF-8 semantics - #28267
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? |
1ceaed7 to
d24a034
Compare
cbb1a5c to
3276e32
Compare
|
Systematic fixes pushed in Closed the remaining review gaps without broadening semantics: prepared Final evidence: all owning CGo packages pass, |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Blocking findings on b2eebbda2ac14eb5e701d83c373058d558601214 (self-review cannot submit GitHub REQUEST_CHANGES):
[P1] Validate prepared REGEXP domains after runtime values are known
The dynamic-domain mask is correct while the statement is initially prepared, but bindPreparedFuncExprImplByPlanExpr derives the same mask from originalArgs during execute-time rebinding. regexpStringDomainFixedTypeMatchN then skips those operands even though boundArgs now carry their concrete runtime domains. As a result, an illegal text/binary mix is accepted and the executor silently selects byte mode.
The checked-in BVT currently demonstrates the wrong behavior:
PREPARE p FROM
'SELECT REGEXP_INSTR(?, CAST(_binary''中'' AS BINARY(3)), 2)';
SET @s = '中中';
EXECUTE p USING @s;Current expected result: 4. MySQL 8.4.10 returns:
ERROR 3995 (HY000): Character set 'utf8mb4_0900_ai_ci' cannot be used
in conjunction with 'binary' in call to regexp_instr.
Please separate “unresolved at PREPARE” from “runtime-owned but resolved for this EXECUTE”. Defer compatibility only in the initial prepared plan; when rebuilding the execution plan, validate all concrete effective domains. Keep result-domain propagation as separate metadata rather than using the compatibility-skip mask for both purposes.
Please cover SQL PREPARE and COM_STMT transitions on one cached statement: binary/binary succeeds, binary/text and text/binary return 3995, text/text succeeds, and a later binary/binary execution still succeeds. Include a nested REGEXP_SUBSTR result consumed by another REGEXP function, and correct the middle text execution in func_regular_instr.test.
[P1] Honor explicit i/c for binary REGEXP_LIKE
getPureMatchType currently drops i whenever binary is true. Binary operands are case-sensitive by default, but an explicit match_type still overrides that default. MySQL 8.4.10 returns:
SELECT REGEXP_LIKE(_binary'A', _binary'a', 'i'),
REGEXP_LIKE(_binary'A', _binary'a', 'ci'),
REGEXP_LIKE(_binary'A', _binary'a', 'ic');
-- 1, 1, 0The current head returns 0, 0, 0. This also means the previous self-review conclusion and the new BVT oracle for binary_i are incorrect.
Please preserve binary's case-sensitive default for the two-argument form, but process explicit i/c normally with the rightmost flag winning. Add ASCII binary controls and a high-byte control (for example binary é versus É, which remains nonmatching under i in MySQL's byte domain), plus binary -> text -> binary prepared reuse.
[P2] Make empty-pattern and empty-subject position handling consistent with MySQL
Only REGEXP/REGEXP_LIKE currently reject an empty pattern. REGEXP_SUBSTR turns it into NULL, while INSTR/REPLACE compile it as a zero-width pattern. MySQL 8.4.10 returns error 3685 for all of these:
SELECT REGEXP_INSTR('abc', '');
SELECT REGEXP_SUBSTR('abc', '');
SELECT REGEXP_REPLACE('abc', '', 'X');Please route all REGEXP entry points through the same nonempty-pattern validation and remove the SUBSTR len(pattern) == 0 NULL shortcut.
There is also one INSTR-specific bounds exception that the shared regexpSearchStartByte loses: for an empty subject, MySQL permits any positive pos; REGEXP_INSTR('', '^$', 5) returns 5, while REGEXP_INSTR('', '.', 5) returns 0. SUBSTR and REPLACE still reject pos > 1. Keep that exception local to INSTR and add positive/zero-width/no-match coverage rather than weakening the shared bounds rule.
The cache/lifecycle shape itself looks bounded (100 regexp entries and BIT_COUNT state bounded by parameter count), and I did not find a goroutine, wait-cycle, or cleanup blocker. The findings above are deterministic semantic mismatches and should be fixed before merge.
|
Systematic review closure pushed in This supersedes the earlier review-stage conclusion that binary Closed the remaining gaps:
Final exact-head evidence:
The PR body now records the root causes, invariants, performance/resource bounds, unhappy paths, counterexamples, rollback, and residual RE2/ICU boundary. I found no remaining correctness, performance, lifecycle, hang, or unbounded-growth blocker in the final diff. New CI is running on the pushed head; this conclusion does not depend on waiting for it. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review on exact head 95aa6e084fbae404344fe1d58e673ca22c614f0c.
Decision: BLOCKED — [P1] keep the replacement operand out of REGEXP_REPLACE matcher and result-domain selection.
This is my own PR, so GitHub does not permit a REQUEST_CHANGES event; this COMMENT review is the equivalent blocking verdict.
At func_builtin_regexp.go:831-839, stringOperands=3 makes a BLOB-typed replacement parameter alone switch a text subject/pattern to byte mode and mark the result binary. The exact-head test locks this in: subject "中", pattern ".", replacement BLOB "X" expects "XXX" and binary output (test).
Those are two different contracts. MySQL aggregates the regexp collation from subject and pattern only (args, 2), then REGEXP_REPLACE separately validates replacement compatibility (base resolve_type, replace resolve_type). Its facade also evaluates replacement separately after resetting the matcher from the subject (Replace). A direct BLOB replacement marker may participate in compatibility validation, but it must not turn text subject/pattern matching into byte matching or own the output collation. This case should replace one Unicode character and return "X" in the subject/pattern domain.
Please split compatibility arity (3 operands) from matcher/result-domain arity (subject + pattern), fix all REGEXP_REPLACE arities and planner return-type derivation, update the design invariant, and replace the wrong-oracle test with controls covering replacement-only BLOB, binary subject/pattern with either replacement domain, and the static incompatible-domain error.
Review scope: design, binder/type-domain checks, prepared-parameter provenance, vectorized executors, result metadata, regexp cache/lifecycle and positional semantics, plus ORD and BIT_COUNT. The previous REGEXP findings are addressed; no additional blocker was found in those areas. All current CI checks are green. The exact focused prepared-execution test passes, confirming that the current wrong oracle and implementation agree.
|
Addressed the latest deep-review blocker in
Validation on the pushed tree:
|
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review on exact head a5f142445a268d59f96b14bb955c0a2a631e4ebf.
Decision: BLOCKED — [P1] transcode a binary replacement before producing a text-domain REGEXP_REPLACE result.
The previous blocker is correctly split now: only subject/pattern select matching and result domain, while replacement still participates in compatibility. But the executor passes replacement bytes unchanged into the text matcher/result path at func_builtin_regexp.go:835, then marks the output as text. That is only valid for ASCII.
Counterexample: prepare SELECT HEX(REGEXP_REPLACE("a", "a", ?)) and bind the direct marker as LONG_BLOB containing byte 0xff. This PR accepts that combination and correctly keeps text matching/result domain, but it returns raw FF; the result vector is nonbinary while containing invalid UTF-8. MySQL evaluates replacement separately and converts its binary charset through the regexp charset before replacement, so byte 0xff becomes U+00FF and the utf8mb4 result is C3BF (MySQL EvalExprToCharset, Replace).
I reproduced this deterministically on the exact head with a temporary unit test: the existing function reports a text-domain result, and utf8.ValidString(result) fails. The checked-in replacement-only test uses ASCII X, so it cannot detect the missing conversion.
Please keep compatibility-domain and matcher-domain selection separate, but add an explicit replacement-to-effective-result-domain conversion before matching/replacement. Cover 3/4/5 arities and COM_STMT/prepared reuse with at least a high byte or invalid UTF-8 BLOB control; binary subject/pattern must continue preserving replacement bytes in the binary result.
This is my own PR, so GitHub cannot record REQUEST_CHANGES; this COMMENT review is the equivalent blocking verdict. The focused exact-head tests for the new domain split pass, and the regexp cache/prepared-state ownership remains bounded with no lifecycle blocker.
|
Closed the latest deep-review blocker in
The PR body now has the corrected matcher/result-domain invariant and the final QA plan/evidence. I found no remaining blocker in this review scope; new CI may run independently and was not awaited. |
|
Review-feedback closure is pushed in cb8dc36; current head 32d4301 also includes the latest main. The four reported blockers are addressed systematically:
CI diagnosis: the failed UT was TestIssue27666CDCWatermarkWriteSerializesWithDrop/writer_wins. It is the known unrelated flaky tracked by #28282 and fixed on main by #28283; this head contains that main fix, so no duplicate issue was created. Final validation on the merged head:
No CI wait is required for this update. |
|
Systematic review-feedback closure is pushed in aaf4152. The four reported areas remain covered on the updated head: CP-1252 high-byte folding under an effective binary i mode, the VARBINARY-only 3995 trigger boundary, prepared scalar-subquery runtime-domain propagation, and expansion-aware REGEXP_REPLACE result width. The counterexample pass found and fixed one additional P1-shaped gap in the scalar-subquery work: a scalar result projected directly from a parameter retained its runtime domain, but the same value projected through a derived table or CTE became a ColRef and lost the parameter lineage. A prepared binary execution then rebound the outer REGEXP operand as TEXT. The fix follows ColRef binding tags to the producer ProjectList during PREPARE and stores only the domain-producing expression in the existing sparse metadata. Explicit CAST remains an authoritative boundary; EXECUTE still does not walk the plan graph or mutate the cached plan. Coverage includes direct, derived-table, and CTE scalar projections; binary -> incompatible mixed -> text -> binary reuse; explicit-cast termination; and cached-plan immutability. Validation on the pushed tree:
The new work is PREPARE-only and limited to REGEXP string operands. Ordinary execution and non-REGEXP plans gain no scan or allocation. Full CI may run independently and was not awaited. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep review of aaf415236c1ce2e9d59f2ed98536a1e712d78e9e (current head).
Assessment: no blocking finding. The implementation now closes the previously identified correctness gaps and is reasonable to merge from correctness, performance, and unhappy-path perspectives. This is a self-authored PR, so GitHub does not permit me to record an APPROVE event; this COMMENT records a clean self-review.
What I verified:
ORDkeeps text inputs code-point aware while preserving first-octet semantics for binary inputs.BIT_COUNTdistinguishes text numeric-prefix conversion from binary byte-popcount semantics, including prepared-statement category reuse and the MySQL-compatible transition to sticky numeric semantics after a numeric execution.- regexp matching is start-aware instead of filtering a precomputed non-overlapping sequence, so matches crossing
pos, anchors, and zero-width progress are handled consistently. - regexp subject/pattern select the matching domain; replacement affects compatibility/result conversion but cannot accidentally select the matcher domain. Text positions remain code-point based and binary positions remain byte based.
- prepared regexp domain provenance survives scalar subqueries, projected/derived columns, plan copying, parameter remapping, and execute-time rebinding. Repeated references to the same projected expression retain independent metadata.
- dynamic pattern caching is bounded, matcher iteration does not retain an unbounded match-index slice, and the execution hot path does not add goroutines, waits, logging loops, or new lock dependencies.
- invalid mixed text/binary operands, NULL/runtime domain changes, empty patterns, malformed binary bytes, occurrence/position bounds, and zero-width replacement paths are covered by production tests or focused source-level counterexample review.
Independent oracle checks against MySQL 8.4.10 matched the implemented behavior for:
- text/binary
ORDandBIT_COUNT; - prepared
BIT_COUNT(?)executions across binary, text, and numeric values; - regexp positional range errors;
- the window-expression parameter case, which MySQL also rejects with error 3995 at PREPARE time.
Local exact-head validation:
make -j8 cgo.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=240s ./pkg/sql/plan/function ./pkg/sql/plan ./pkg/frontend- focused
-raceruns for regexp/ORD/BIT_COUNT and prepared regexp lineage git diff --check origin/main...HEAD
All passed. Current required CI checks are green.
Non-blocking documentation nit: the PR body says no wire-format field is added, but PreparedNumericMetadata.string_domain_source = 11 is a new protobuf field. Please describe it instead as a backward-compatible plan-metadata field (with no persisted catalog-format change), so the compatibility statement matches the actual diff.
Summary
Fixes #28207, #28219, #28202, #25299, and #27217.
ORD()combines the bytes of the first UTF-8 code point in network order. BINARY/VARBINARY/BLOB values remain byte-oriented and return the first octet.BIT_COUNT()applies MySQL-compatible numeric-prefix coercion to nonbinary strings, while preparedBIT_COUNT(?)distinguishes numeric runtime domains from text/BLOB byte semantics.EXECUTE USINGvariables and COM_STMT parameters.REGEXP_REPLACEreplacement roles.MatrixOne still uses Go RE2. Full MySQL ICU grammar compatibility is explicitly outside this PR; this change owns string-domain, position, occurrence, error-precedence, and prepared-execution semantics that are independent of the regexp engine.
Root causes and systematic fixes
1. String syntax, transport type, and SQL domain were conflated
A cached parameter marker is text-shaped at PREPARE, while the current execution may provide BLOB/VARBINARY.
Literal.IsBin, COM_STMT wire type, SQL user-variableSourceType, and numericRuntimeTypeare different axes and cannot substitute for one another.The execution metadata now carries
IsBinaryStringindependently. The prepared specialization cache includes that domain. SQL EXECUTE records user-variable source type, and plan-copy materialization preserves a non-NULL binary type for every marker, even when a different sibling expression triggered specialization. This closes a real cross-expression failure where:returned text-style
ORD(?) = 14989485for a VARBINARY parameter solely because the regexp sibling caused all markers to be materialized. It now returns228, 4, 228.Numeric
RuntimeTyperemains authoritative for numeric overload specialization. SQL source types do not replace comparison domains, pagination types, or DML assignment contracts.2. PREPARE deferral leaked into EXECUTE validation
Parameter-owned regexp domains must be deferred while unknown at PREPARE, but the old rebind path derived the same defer mask from cached ParamRefs after concrete values were available. Illegal text/binary executions were therefore accepted and silently ran in byte mode.
PREPARE-time uncertainty and EXECUTE-time resolution are now separate. Every execution computes the effective type/domain of direct and nested parameter-dependent expressions and validates all concrete semantic operands. Explicit casts terminate domain propagation. Fixed-output functions such as
HEXown their text domain; domain-preserving functions resolve from current child domains.NULL rules are explicit:
NULLcontributes no regexp domain;Failed execution-time validation does not mutate the cached plan, so a binary -> invalid text -> binary sequence remains reusable.
3. Matching was filtered after committing to the wrong occurrence sequence
Computing all non-overlapping matches from byte zero and then discarding matches before
posloses valid matches that overlap the boundary. For example, MySQL returnsaXfor both:Matching now starts at the requested boundary and streams occurrences. INSTR searches a suffix, so anchors are relative to that suffix. SUBSTR and REPLACE retain the complete original subject and pass a start offset, preserving original-subject anchor and word-boundary behavior.
An empty match advances by exactly one text code point or binary byte, guaranteeing termination. The iterator retains the ICU/MySQL empty match immediately after a nonempty match instead of relying on Go
FindAll, which suppresses it.INSTR keeps MySQL's local empty-subject exception: every positive
posis accepted; a zero-width anchor returns that position, while a consuming pattern or later occurrence returns zero. SUBSTR/REPLACE retain normal bounds checks.4. Binary regexp execution needed a bounded representation
RE2 has no byte mode. Each non-ASCII input byte is mapped to a distinct private-use rune while ASCII and regexp grammar stay intact. Raw high bytes, hexadecimal/octal escapes, ranges, and negated ranges address the same byte alphabet. Unicode properties and code-point escapes above
0xffare rejected in binary mode so users cannot address the internal private-use encoding.Binary matching is case-sensitive by default, but explicit
iandcflags override that default and the rightmost flag wins, matching MySQL 8.4. ASCII bytes can fold underi; encoded high bytes remain distinct and are not Unicode-folded.5. Empty-pattern and NULL/error precedence differed by function
All REGEXP predicate, INSTR, SUBSTR, and REPLACE variants reject a non-NULL empty pattern with error 3685, including when subject, replacement, position, or occurrence is NULL/invalid.
REGEXP_LIKEstill returns NULL first whenmatch_typeitself is NULL. This removes the previous split where SUBSTR returned NULL and INSTR/REPLACE treated an empty pattern as a valid zero-width regexp.6. Prepared
BIT_COUNT(?)needs asymmetric type evolutionAn unresolved marker begins in binary-string semantics. Text/BLOB inputs remain byte-oriented; only an actual numeric SQL/protocol domain triggers numeric specialization. Numeric executions record the canonical signed/unsigned integer, DOUBLE, or DECIMAL parameter category. NULL neither changes nor clears that category, and explicit casts remain authoritative. State is bounded by parameter count and cleared with the prepared-plan generation.
Correctness and ownership invariants
REGEXP_SUBSTRandREGEXP_REPLACEpropagate the effective text/binary result domain.The detailed design and compatibility boundary are documented in
docs/design/regexp_string_domain_and_position_semantics.md.Performance and resource bounds
ReplaceAllLiteralStringpath. Only nullable syntax uses the compatibility iterator.pos; SUBSTR/REPLACE keep the complete subject only because their anchor contract requires it.Three-run focused benchmarks on the final regexp implementation:
Prior fresh-host stress also covered 1M-row uniform text/binary predicates, 100K distinct dynamic patterns, and the 1,000,000th dense match without cache growth or a hang.
Unhappy-path / counterexample coverage
posboundary-overlapping matches, anchors, multiline anchors, word boundaries, and zero-width matches;i/c,m/n, invalid flags, ASCII folding, and non-ASCII binary non-folding;selectListbehavior;Validation on
cdb01b74e8go test ./pkg/sql/plan/function -count=1— pass (13.926s).go test ./pkg/sql/plan -count=1— pass (3.636s).go test ./pkg/frontend -count=1— pass (28.558s).go vetfor all three package trees — pass.make -j8 buildwith exact-worktree native artifacts — pass.func_regular_instr.test: 150/150;func_regular_like.test: 80/80;func_regular_replace.test: 53/53;func_regular_substr.test: 58/58;ORD(?),REGEXP_INSTR, nestedORD(REGEXP_SUBSTR(...))returned228, 4, 228.git diff --check— pass.MySQL 8.4.10 was used as the public oracle for boundary overlap, function-specific anchors, empty patterns, empty-subject INSTR, explicit binary
i/c, text/binary mismatch 3995, prepared NULL domains, and binaryORD.New exact-head CI was triggered by this commit and is intentionally not required for the manual validation above.
Latest review closure on
36b35b34d30xffnow yields UTF-8C3BF,0x80yieldsE282AC, and binary bytesE4B8ADare decoded bytewise toC3A4C2B8C2AD; text replacement remainsE4B8AD. Binary subject/pattern matching continues to preserve raw replacement bytes.newRegexpReplacementDomainConverter,forMatchDomain,regexpBinaryReplacementToText, andregexpWindows1252Rune) are each 100% covered.pkg/sql/plan/functionandpkg/frontendpass; exact final function package rerun passes. Targeted molint completes with no new finding and golangci-lint reports 0 issues.10.222.1.55: isolatedmake clean && make -j12passes; the exact final source is rebuilt, started from a fresh data directory, satisfies SQL plus task-service readiness, andfunc_regular_replace.testpasses 63/63. The test-owned process, ports, data, and worktree are removed afterward.git diff --checkpasses. No persisted state, goroutine, wait, or unbounded cache was added.Rollback and residual risk
Rollback is code-only: there is no migration or persisted-state dependency. Mixed-version execution continues to use existing prepared-parameter transport; binary provenance is local execution metadata.
RE2/ICU grammar differences remain. Unsupported ICU-only constructs are not fixed by this PR. Binary high-byte subjects pay the documented linear encoding cost, while ASCII and ordinary replace-all paths retain their fast paths. These are explicit compatibility boundaries rather than hidden fallbacks.