Skip to content

fix(sql): align ORD, BIT_COUNT and REGEXP UTF-8 semantics - #28267

Merged
XuPeng-SH merged 25 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-sql-function-semantics
Sep 6, 2026
Merged

XuPeng-SH merged 25 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-sql-function-semantics

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

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 prepared BIT_COUNT(?) distinguishes numeric runtime domains from text/BLOB byte semantics.
  • REGEXP operators/functions count UTF-8 code points for text and bytes for binary values, including SQL EXECUTE USING variables and COM_STMT parameters.
  • REGEXP rejects statically or execute-time-resolved mixed text/binary operands with MySQL error 3995, including subject, pattern, and REGEXP_REPLACE replacement roles.
  • Positional matching is start-aware, preserves each function's anchor contract, handles ICU-compatible zero-width occurrence sequences without hanging, and rejects empty patterns consistently with error 3685.

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-variable SourceType, and numeric RuntimeType are different axes and cannot substitute for one another.

The execution metadata now carries IsBinaryString independently. 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:

SELECT ORD(?), REGEXP_INSTR(?, _binary'中', 2),
       ORD(REGEXP_SUBSTR(?, _binary'中', 2));

returned text-style ORD(?) = 14989485 for a VARBINARY parameter solely because the regexp sibling caused all markers to be materialized. It now returns 228, 4, 228.

Numeric RuntimeType remains 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 HEX own their text domain; domain-preserving functions resolve from current child domains.

NULL rules are explicit:

  • a bare untyped NULL contributes no regexp domain;
  • a prepared marker whose current value is NULL retains its PREPARE-time domain;
  • a NULL-valued function result retains its declared result domain;
  • typed NULL and explicit CAST remain fixed domain boundaries.

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 pos loses valid matches that overlap the boundary. For example, MySQL returns aX for both:

SELECT REGEXP_REPLACE('aaa', 'aa', 'X', 2, 1);
SELECT REGEXP_REPLACE('aaa', 'aa', 'X', 2, 0);

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 pos is 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 0xff are rejected in binary mode so users cannot address the internal private-use encoding.

Binary matching is case-sensitive by default, but explicit i and c flags override that default and the rightmost flag wins, matching MySQL 8.4. ASCII bytes can fold under i; 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_LIKE still returns NULL first when match_type itself 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 evolution

An 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

  • Static known regexp domains are checked during binding; current dynamic domains are checked on every EXECUTE.
  • REGEXP matching and result domains are derived only from subject and pattern; REGEXP_REPLACE validates replacement compatibility separately and converts binary replacement bytes into the selected text domain.
  • REGEXP_SUBSTR and REGEXP_REPLACE propagate the effective text/binary result domain.
  • Execute-time work mutates only a copied plan; the cached prepared plan is byte-for-byte stable after successful and failed rebinds.
  • COM_STMT and SQL EXECUTE rebuild metadata for each execution; no stale binary/text domain crosses executions.
  • Explicit casts own their target domain and are never silently bypassed.
  • No persisted catalog field or wire-format field is added.
  • No goroutine, lock, channel, wait, retry, log loop, or external resource owner is added.

The detailed design and compatibility boundary are documented in docs/design/regexp_string_domain_and_position_semantics.md.

Performance and resource bounds

  • ASCII binary subjects stay zero-copy.
  • Non-ASCII binary encoding is linear and emits at most three UTF-8 bytes per source byte.
  • Positional occurrence iteration retains constant match-index memory; it does not materialize discarded matches.
  • Replace-all patterns that cannot match empty input stay on RE2's native ReplaceAllLiteralString path. Only nullable syntax uses the compatibility iterator.
  • Replacement conversion is bypassed for ordinary text and binary-match paths. A constant binary replacement in a text match is converted lazily at most once per vector call and reused across rows.
  • INSTR encodes/searches only the suffix at pos; SUBSTR/REPLACE keep the complete subject only because their anchor contract requires it.
  • The uniform non-NULL predicate path remains vectorized and allocation-free. A row-aware path is used only when NULL/error precedence requires it.
  • Matcher and zero-width metadata share one 100-entry operator-owned cache and are evicted together. Prepared metadata is bounded by statement parameter count; runtime specializations use the existing bounded cache and now include binary domain in its key.

Three-run focused benchmarks on the final regexp implementation:

  • 3 KiB text replace: about 175-184 us/op, 16.7 KiB, 14 allocs;
  • binary ASCII replace: about 165-180 us/op;
  • binary high-byte replace: about 445-453 us/op, 43 KiB, 17 allocs;
  • 3 KiB zero-width text stress: about 399-400 us/op and deterministic termination;
  • near-end 1 MiB INSTR: text about 515-521 us/op, binary ASCII about 72-73 ns/op, binary high-byte about 128 ns/op.

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

  • mixed text/binary subject, pattern, and replacement at bind and EXECUTE;
  • binary -> text -> binary reuse, including an intervening 3995 failure;
  • direct and nested parameter-dependent results;
  • bare NULL, typed NULL, prepared NULL, and NULL-valued function results;
  • invalid/empty patterns with NULL subjects/replacements and invalid positions;
  • pos boundary-overlapping matches, anchors, multiline anchors, word boundaries, and zero-width matches;
  • empty subjects at large positive INSTR positions;
  • raw NUL/high bytes, every byte inside valid multibyte UTF-8, invalid UTF-8, byte escapes/ranges, and private-use/property-escape controls;
  • contradictory i/c, m/n, invalid flags, ASCII folding, and non-ASCII binary non-folding;
  • masked invalid rows and selectList behavior;
  • packet-level COM_STMT BLOB/VAR_STRING transitions and SQL user-variable BINARY/VARBINARY/BLOB values;
  • cached-plan immutability after success and failure;
  • BIT_COUNT string/numeric/decimal/BLOB/NULL transitions and overflow/no-prefix inputs.

Validation on cdb01b74e8

  • go 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 vet for all three package trees — pass.
  • make -j8 build with exact-worktree native artifacts — pass.
  • Fresh standalone BVT, exact binary/source:
    • func_regular_instr.test: 150/150;
    • func_regular_like.test: 80/80;
    • func_regular_replace.test: 53/53;
    • func_regular_substr.test: 58/58;
    • combined: 341/341, 100%.
  • SQL socket check for the cross-expression prepared VARBINARY case: ORD(?), REGEXP_INSTR, nested ORD(REGEXP_SUBSTR(...)) returned 228, 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 binary ORD.

New exact-head CI was triggered by this commit and is intentionally not required for the manual validation above.

Latest review closure on 36b35b34d3

  • Fixed the direct BLOB replacement counterexample: 0xff now yields UTF-8 C3BF, 0x80 yields E282AC, and binary bytes E4B8AD are decoded bytewise to C3A4C2B8C2AD; text replacement remains E4B8AD. Binary subject/pattern matching continues to preserve raw replacement bytes.
  • Covered 3/4/5-argument execution, complete Windows-1252 high-byte mapping, undefined C1 bytes, ASCII/high-byte mixtures, UTF-8-looking binary input, COM_STMT BLOB rebinding, text controls, mixed row domains, and constant conversion reuse.
  • Final focused production functions (newRegexpReplacementDomainConverter, forMatchDomain, regexpBinaryReplacementToText, and regexpWindows1252Rune) are each 100% covered.
  • Final CGo package tests: pkg/sql/plan/function and pkg/frontend pass; exact final function package rerun passes. Targeted molint completes with no new finding and golangci-lint reports 0 issues.
  • 10.222.1.55: isolated make clean && make -j12 passes; the exact final source is rebuilt, started from a fresh data directory, satisfies SQL plus task-service readiness, and func_regular_replace.test passes 63/63. The test-owned process, ports, data, and worktree are removed afterward.
  • git diff --check passes. 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.

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

@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Sep 5, 2026
@XuPeng-SH
XuPeng-SH force-pushed the codex/fix-sql-function-semantics branch from 1ceaed7 to d24a034 Compare September 5, 2026 15:02
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Sep 5, 2026
@XuPeng-SH
XuPeng-SH force-pushed the codex/fix-sql-function-semantics branch from cbb1a5c to 3276e32 Compare September 5, 2026 17:26
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Systematic fixes pushed in 4ac6126752.

Closed the remaining review gaps without broadening semantics: prepared BIT_COUNT(?) now distinguishes actual numeric protocol/runtime domains from string/BLOB bytes; explicit casts remain authoritative; mixed row-level binary provenance is honored; and regexp zero-width iteration now follows the MySQL/ICU sequence while guaranteeing one-unit progress. Ordinary non-nullable replace-all stays on the native RE2 fast path, and all new metadata is bounded.

Final evidence: all owning CGo packages pass, make -j8 build passes, packet-level COM_STMT domain tests pass, and standalone func_bit_count.test (80/80) plus func_regular_replace.test (51/51) each passed twice on the same fresh instance. The PR body now records the root causes, counterexamples, performance rationale, unhappy-path guarantees, and residual risk.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, 0

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

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Systematic review closure pushed in cdb01b74e8.

This supersedes the earlier review-stage conclusion that binary REGEXP_LIKE should ignore i/c: MySQL 8.4 keeps binary case-sensitive by default, but explicit i/c overrides the default and the rightmost flag wins. The implementation and BVT now use that oracle.

Closed the remaining gaps:

  • PREPARE-only regexp domain deferral can no longer bypass concrete EXECUTE-time 3995 validation, including nested results and prepared NULL values.
  • COM_STMT binary domain is part of parameter metadata and runtime cache identity.
  • SQL EXECUTE/COM_STMT parameter materialization preserves binary type across statement-wide specialization. The BVT-discovered direct ORD(?) failure is fixed: the prepared VARBINARY case now returns 228, 4, 228, not text-style 14989485, 4, 228.
  • Binary REGEXP_LIKE honors explicit i/c; high bytes remain byte-oriented and are not Unicode-folded.
  • INSTR/SUBSTR/REPLACE consistently reject empty patterns with MySQL error 3685 and preserve the required NULL/error precedence.
  • Empty-subject INSTR accepts any positive pos without weakening SUBSTR/REPLACE bounds.
  • Boundary-overlapping and zero-width matching retains function-specific anchor semantics and guaranteed progress.

Final exact-head evidence:

  • complete pkg/sql/plan/function, pkg/sql/plan, and pkg/frontend tests pass;
  • go vet for all three package trees passes;
  • make -j8 build passes;
  • fresh standalone regexp BVT: 341/341 (INSTR 150, LIKE 80, REPLACE 53, SUBSTR 58);
  • git diff --check passes.

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 XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Addressed the latest deep-review blocker in a5f142445a.

  • Split REGEXP_REPLACE domain ownership: subject/pattern select matcher and result domain; replacement remains part of the three-operand 3995 compatibility check only.
  • Removed caller-supplied operand counts from matcher/result helpers, preventing future arity-specific drift.
  • Resolve the row match domain once and reuse it for validation, execution, and result metadata.
  • Corrected the replacement-only BLOB oracle and added subject-only, pattern-only, subject+pattern, 3/4/5-arity, Unicode-pattern validation, return-type, and static-mismatch controls.
  • Updated the design invariant and validation matrix.

Validation on the pushed tree:

  • Test_BuiltIn_RegexpUsesMatchOperandDomain, TestRegexpFunctionsHonorStringDomainCheckModes, and the exhaustive mode matrix: PASS.
  • TestCOMStmtRegexpRebindExecutesWithWireStringDomain: PASS.
  • Full ./pkg/sql/plan/function: PASS.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Closed the latest deep-review blocker in 36b35b34d3.

  • A direct BLOB replacement no longer leaks raw bytes into a text-domain result. It is converted with the MySQL binary-regexp Windows-1252 facade: FF -> C3BF, 80 -> E282AC; UTF-8-looking binary bytes are decoded independently. Binary matching still preserves the original bytes.
  • The fix covers every REGEXP_REPLACE arity and COM_STMT/prepared text/BLOB reuse. The complete 0x80..0xff mapping, undefined C1 bytes, ASCII/high-byte mixtures, text controls, binary-result controls, and mixed row domains are covered.
  • The performance review removed per-row amplification for constant BLOB replacements: conversion is lazy and cached once per vector call. Ordinary text and binary-match paths do no conversion-stage scan or allocation.
  • Focused production conversion functions are each 100% covered. Full CGo tests for pkg/sql/plan/function and pkg/frontend pass; targeted molint completed with no new finding and golangci-lint reports 0 issues.
  • On 10.222.1.55, isolated clean build passed. The exact final source was rebuilt, started with a fresh data directory, met SQL/task readiness, and func_regular_replace.test passed 63/63. The owned process, ports, data, and worktree were removed.

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.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Review-feedback closure is pushed in cb8dc36; current head 32d4301 also includes the latest main.

The four reported blockers are addressed systematically:

  1. Binary high-byte case folding: binary REGEXP_LIKE with an effective explicit i mode now uses Windows-1252 semantics, including C9/E9 and 8A/9A pairs. Byte-exact regexp paths keep the existing PUA encoding, and ASCII remains on the zero-copy fast path. Tests cover high bytes, unrelated bytes, escaped byte patterns, UTF-8-looking binary input, and rightmost i/c precedence.
  2. Error 3995 trigger: only the VARBINARY string family participates in MySQL dynamic text/binary incompatibility. Fixed BINARY and BLOB remain byte-domain inputs but no longer falsely trigger 3995. Direct parameter markers continue not to trigger it.
  3. Prepared scalar-subquery runtime domain: flattening now preserves a sparse source expression only where runtime parameter provenance is required. Parameter-order reset recursively remaps that metadata, explicit casts terminate propagation, and cached plans remain immutable. Ordinary prepared statements do not gain a full-plan execution scan or a per-expression pointer-size cost.
  4. REGEXP_REPLACE width: all 3/4/5-argument overloads now use the safe S + (S + 1) * R bound, covering maximum zero-width insertion at every boundary. Real CTAS validation produced VARCHAR(11) and XYZbXYZbXYZ for a VARCHAR(2) subject with VARCHAR(3) replacement.

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:

  • CGo tests pass for pkg/sql/plan/function, pkg/sql/plan, and pkg/frontend.
  • make build passes.
  • Targeted golangci-lint reports 0 issues; molint adds no new finding.
  • Fresh SQL validation passes for CP-1252 high-byte folding, UTF-8-looking binary non-folding, BINARY/BLOB mixed-domain behavior, prepared VARBINARY/text/BLOB rebinding, and REGEXP_REPLACE value/type width.
  • git diff --check passes; no debug logging remains.

No CI wait is required for this update.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

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:

  • full pkg/sql/plan CGo test package: PASS;
  • focused pkg/frontend and pkg/sql/plan/function domain/rebind suites: PASS;
  • make -j8 build: PASS;
  • func_regular_instr.test twice on one fresh instance: 183/183 both runs;
  • func_regular_like.test twice on the same instance: 83/83 both runs, including prepared CP-1252 high-byte folding;
  • targeted golangci-lint: 0 issues; git diff --check: PASS.

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 XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • ORD keeps text inputs code-point aware while preserving first-octet semantics for binary inputs.
  • BIT_COUNT distinguishes 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 ORD and BIT_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 -race runs 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.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: ORD reverses the byte order of multibyte characters

2 participants