This is an automated email from the ASF dual-hosted git repository.

wyxxxcat pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 979182dcb32 [fix](fe) Preserve Unicode semantics in string constant 
folding (#71251)
979182dcb32 is described below

commit 979182dcb32c98d5cb57c0b0a82e991ee01472a5
Author: linrrarity <[email protected]>
AuthorDate: Fri Dec 4 09:37:54 2026 +0800

    [fix](fe) Preserve Unicode semantics in string constant folding (#71251)
    
    ---
    
    ### Background
    
    Nereids folds string functions during planning when their arguments are
    literals.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: None
    PR Type: Bugfix
    
    FE folding compared individual UTF-16 code units in `ltrim_in`,
    `rtrim_in`, and `trim_in`. A character in the trim set could match and
    remove half of another character. The trim functions now match whole
    Unicode code points using `codePointAt` and `codePointBefore`.
    
    FE folding also accepted full-width digits in URL escapes such as `%οΌ”οΌ‘`.
    `url_decode` now requires ASCII hex digits in `%HH` escapes and folds
    the decoded bytes only if they form valid UTF-8. BE handles malformed
    escapes and decoded byte sequences that an FE string literal cannot
    preserve, such as the byte `FF` from `%FF`.
    
    ### Details
    
    Run this SQL with the MySQL client's `--table` option. For the BE
    comparison, set `debug_skip_fold_constant = true` and rerun the same
    SQL. All three runs used the same BE.
    
    ```sql
    SET enable_fold_constant_by_be = false;
    SET debug_skip_fold_constant = false;
    SELECT HEX(ltrim_in('πŸ˜πŸ˜€x', '😁')) AS ltrim_hex,
           HEX(rtrim_in('xπŸ¨€πŸ˜€', 'πŸ˜€')) AS rtrim_hex,
           HEX(trim_in('πŸ˜πŸ˜€πˆ€', 'πŸ˜πˆ€')) AS trim_hex;
    
    SELECT url_decode('%41') AS ascii_escape,
           url_decode('%E4%B8%AD') AS utf8_escape,
           HEX(url_decode('%FF')) AS raw_byte;
    
    SELECT trim_in('πŸ˜€xπŸ˜€', CAST('πŸ¨€πŸ˜€' AS VARCHAR(3))) AS nested_trim,
           instr(url_decode(CAST('πŸ˜€' AS VARCHAR(1))), '?') AS question_pos;
    
    SELECT url_decode('%οΌ”οΌ‘') AS fullwidth_escape;
    ```
    
    **Before Β· FE folding on the base revision**
    
    ```text
    +-----------+-----------+----------+
    | ltrim_hex | rtrim_hex | trim_hex |
    +-----------+-----------+----------+
    | 3F78      | 783F      |          |
    +-----------+-----------+----------+
    +--------------+-------------+----------+
    | ascii_escape | utf8_escape | raw_byte |
    +--------------+-------------+----------+
    | A            | δΈ­          | FF       |
    +--------------+-------------+----------+
    +-------------+--------------+
    | nested_trim | question_pos |
    +-------------+--------------+
    | x           |            0 |
    +-------------+--------------+
    +------------------+
    | fullwidth_escape |
    +------------------+
    | A                |
    +------------------+
    ```
    
    **After Β· FE folding with this patch**
    
    ```text
    +------------+------------+----------+
    | ltrim_hex  | rtrim_hex  | trim_hex |
    +------------+------------+----------+
    | F09F988078 | 78F09FA880 | F09F9880 |
    +------------+------------+----------+
    +--------------+-------------+----------+
    | ascii_escape | utf8_escape | raw_byte |
    +--------------+-------------+----------+
    | A            | δΈ­          | FF       |
    +--------------+-------------+----------+
    +-------------+--------------+
    | nested_trim | question_pos |
    +-------------+--------------+
    | πŸ˜€xπŸ˜€           |            1 |
    +-------------+--------------+
    ERROR 1105 (HY000) at line 14: errCode = 2, detailMessage = 
(10.26.20.3)[INTERNAL_ERROR]Decode url failed
    ```
    
    **BE execution Β· constant folding disabled**
    
    ```text
    +------------+------------+----------+
    | ltrim_hex  | rtrim_hex  | trim_hex |
    +------------+------------+----------+
    | F09F988078 | 78F09FA880 | F09F9880 |
    +------------+------------+----------+
    +--------------+-------------+----------+
    | ascii_escape | utf8_escape | raw_byte |
    +--------------+-------------+----------+
    | A            | δΈ­          | FF       |
    +--------------+-------------+----------+
    +-------------+--------------+
    | nested_trim | question_pos |
    +-------------+--------------+
    | πŸ˜€xπŸ˜€           |            1 |
    +-------------+--------------+
    ERROR 1105 (HY000) at line 14: errCode = 2, detailMessage = 
(10.26.20.3)[INTERNAL_ERROR]Decode url failed
    ```
    
    ### Testing
    
    - Ran all three variants on an isolated Doris cluster and captured the
    raw `mysql --table` output. The patched FE and BE execution produced
    identical output.
    - `StringArithmeticTest` passed all 17 tests.
    
    ### Release note
    
    FE constant folding preserves whole Unicode characters when trimming and
    follows BE's URL percent-escape rules.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes
    - Does this need documentation: No
    - Pre-submission status: Ready
    
    ### AI Disclosure
    
    - Tool: Codex
    - Generated: Implementation, unit tests, and description
    - Human review: Pending
---
 .../functions/executable/StringArithmetic.java     | 87 ++++++++--------------
 .../functions/executable/StringArithmeticTest.java | 23 ++++++
 2 files changed, 54 insertions(+), 56 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmetic.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmetic.java
index 6875b08ea7d..4f9c3365f99 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmetic.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmetic.java
@@ -47,10 +47,8 @@ import org.apache.doris.nereids.types.ArrayType;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
-import java.io.ByteArrayOutputStream;
 import java.io.UnsupportedEncodingException;
 import java.math.BigInteger;
-import java.net.URLDecoder;
 import java.net.URLEncoder;
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
@@ -62,6 +60,7 @@ import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.HexFormat;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
@@ -183,24 +182,23 @@ public class StringArithmetic {
     }
 
     private static String trimInImpl(String first, String second, boolean 
left, boolean right) {
-        StringBuilder result = new StringBuilder(first);
-
-        if (left) {
-            int start = 0;
-            while (start < result.length() && 
second.indexOf(result.charAt(start)) != -1) {
-                start++;
+        int start = 0;
+        int end = first.length();
+        while (left && start < end) {
+            int codePoint = first.codePointAt(start);
+            if (second.indexOf(codePoint) < 0) {
+                break;
             }
-            result.delete(0, start);
+            start += Character.charCount(codePoint);
         }
-        if (right) {
-            int end = result.length();
-            while (end > 0 && second.indexOf(result.charAt(end - 1)) != -1) {
-                end--;
+        while (right && start < end) {
+            int codePoint = first.codePointBefore(end);
+            if (second.indexOf(codePoint) < 0) {
+                break;
             }
-            result.delete(end, result.length());
+            end -= Character.charCount(codePoint);
         }
-
-        return result.toString();
+        return first.substring(start, end);
     }
 
     /**
@@ -1123,57 +1121,34 @@ public class StringArithmetic {
      */
     @ExecFunction(name = "url_decode")
     public static Expression urlDecode(StringLikeLiteral first) {
-        if (!isValidUtf8AfterUrlDecode(first.getValue())) {
-            // String literals cannot preserve an invalid UTF-8 byte sequence. 
Let BE evaluate it
-            // instead of folding the replacement characters produced by 
java.net.URLDecoder.
-            throw new IllegalArgumentException("URL-decoded value is not valid 
UTF-8");
-        }
-        try {
-            return castStringLikeLiteral(first, 
URLDecoder.decode(first.getValue(), StandardCharsets.UTF_8.name()));
-        } catch (UnsupportedEncodingException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    private static boolean isValidUtf8AfterUrlDecode(String value) {
-        ByteArrayOutputStream decodedBytes = new 
ByteArrayOutputStream(value.length());
-        int index = 0;
-        while (index < value.length()) {
-            char current = value.charAt(index);
+        byte[] bytes = first.getValue().getBytes(StandardCharsets.UTF_8);
+        int decodedLength = 0;
+        for (int index = 0; index < bytes.length; index++) {
+            byte current = bytes[index];
             if (current == '%') {
-                if (index + 2 >= value.length()) {
-                    // Preserve URLDecoder's existing malformed-escape 
handling.
-                    return true;
-                }
-                int high = Character.digit(value.charAt(index + 1), 16);
-                int low = Character.digit(value.charAt(index + 2), 16);
-                if (high < 0 || low < 0) {
-                    // Preserve URLDecoder's existing malformed-escape 
handling.
-                    return true;
+                if (bytes.length - index < 3) {
+                    throw new IllegalArgumentException("Incomplete URL 
escape");
                 }
-                decodedBytes.write((high << 4) + low);
-                index += 3;
+                int high = HexFormat.fromHexDigit(bytes[index + 1]);
+                int low = HexFormat.fromHexDigit(bytes[index + 2]);
+                bytes[decodedLength++] = (byte) ((high << 4) | low);
+                index += 2;
             } else if (current == '+') {
-                decodedBytes.write(' ');
-                index++;
+                bytes[decodedLength++] = ' ';
             } else {
-                int start = index;
-                while (index < value.length() && value.charAt(index) != '%' && 
value.charAt(index) != '+') {
-                    index++;
-                }
-                byte[] originalBytes = value.substring(start, 
index).getBytes(StandardCharsets.UTF_8);
-                decodedBytes.write(originalBytes, 0, originalBytes.length);
+                bytes[decodedLength++] = current;
             }
         }
 
         try {
-            StandardCharsets.UTF_8.newDecoder()
+            String decoded = StandardCharsets.UTF_8.newDecoder()
                     .onMalformedInput(CodingErrorAction.REPORT)
                     .onUnmappableCharacter(CodingErrorAction.REPORT)
-                    .decode(ByteBuffer.wrap(decodedBytes.toByteArray()));
-            return true;
+                    .decode(ByteBuffer.wrap(bytes, 0, 
decodedLength)).toString();
+            return castStringLikeLiteral(first, decoded);
         } catch (CharacterCodingException e) {
-            return false;
+            // BE can return raw bytes that a FE string literal cannot 
preserve.
+            throw new IllegalArgumentException("URL-decoded value is not valid 
UTF-8", e);
         }
     }
 
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmeticTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmeticTest.java
index c3a24eac4f7..38a2b0288f6 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmeticTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/expressions/functions/executable/StringArithmeticTest.java
@@ -21,6 +21,9 @@ import org.apache.doris.nereids.trees.expressions.Expression;
 import org.apache.doris.nereids.trees.expressions.ExpressionEvaluator;
 import org.apache.doris.nereids.trees.expressions.functions.scalar.Decode;
 import org.apache.doris.nereids.trees.expressions.functions.scalar.Encode;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.LtrimIn;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.RtrimIn;
+import org.apache.doris.nereids.trees.expressions.functions.scalar.TrimIn;
 import org.apache.doris.nereids.trees.expressions.functions.scalar.UrlDecode;
 import org.apache.doris.nereids.trees.expressions.literal.DoubleLiteral;
 import org.apache.doris.nereids.trees.expressions.literal.FloatLiteral;
@@ -92,6 +95,25 @@ class StringArithmeticTest {
         Assertions.assertEquals(2, result.getValue());
     }
 
+    @Test
+    void testTrimInMatchesWholeCodePoints() {
+        ExpressionEvaluator evaluator = ExpressionEvaluator.INSTANCE;
+        Assertions.assertEquals(new StringLiteral("πŸ˜€x"),
+                evaluator.eval(new LtrimIn(new StringLiteral("πŸ˜πŸ˜€x"), new 
StringLiteral("😁"))));
+        Assertions.assertEquals(new StringLiteral("xπŸ¨€"),
+                evaluator.eval(new RtrimIn(new StringLiteral("xπŸ¨€πŸ˜€"), new 
StringLiteral("πŸ˜€"))));
+        Assertions.assertEquals(new StringLiteral("πŸ˜€"),
+                evaluator.eval(new TrimIn(new StringLiteral("πŸ˜πŸ˜€πˆ€"), new 
StringLiteral("πŸ˜πˆ€"))));
+    }
+
+    @Test
+    void testUrlDecodeDoesNotFoldInvalidPercentEscapes() {
+        for (String value : new String[] {"%οΌ”οΌ‘", "%+1", "%1g", "%"}) {
+            UrlDecode urlDecode = new UrlDecode(new StringLiteral(value));
+            Assertions.assertSame(urlDecode, 
ExpressionEvaluator.INSTANCE.eval(urlDecode), value);
+        }
+    }
+
     @Test
     void testUrlDecodeDoesNotFoldInvalidUtf8() {
         String[] invalidUtf8Values = {"%80", "%C0%AF", "%E0%80%80", 
"%ED%A0%80", "%FF"};
@@ -105,6 +127,7 @@ class StringArithmeticTest {
     void testUrlDecodeStillFoldsValidUtf8() {
         assertUrlDecodeValue("%E4%B8%AD+text", "δΈ­ text");
         assertUrlDecodeValue("%EF%BF%BD", "οΏ½");
+        assertUrlDecodeValue("δΈ­+%f0%9F%98%80%2B", "δΈ­ πŸ˜€+");
     }
 
     @Test


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to