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

HappenLee 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 4868265f9f0 [fix](string) Avoid truncating strings containing U+FFFF 
(#71317)
4868265f9f0 is described below

commit 4868265f9f0c379a82475b89f813af5356df8cf4
Author: linrrarity <[email protected]>
AuthorDate: Thu Dec 3 14:45:11 2026 +0800

    [fix](string) Avoid truncating strings containing U+FFFF (#71317)
    
    ### Background
    
    `U+FFFF` (`EF BF BF` in UTF-8) is a valid code point inside UTF-8
    strings, but `icu::CharacterIterator::DONE` (`0xFFFF`) in C++ and
    `java.text.CharacterIterator.DONE` (`'\uFFFF'`) in Java use the same
    value as their end-of-iteration sentinel.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: None
    PR Type: Bugfix
    
    Problem Summary:
    
    On `master`, `INITCAP` (BE UTF-8 path) and `FunctionCallExpr.forJSON`
    (FE SQL serialization for `json_*` functions) stop iterating when a
    character equals `DONE`, silently truncating strings at `U+FFFF` and
    dropping all trailing characters. This PR replaces both iterator loops
    with length-based index traversal so `U+FFFF` and all trailing
    characters are preserved, and removes the unused `Text.utf8Length`
    helper that relied on `CharacterIterator.DONE`.
    
    ```text
    1) BE INITCAP: "0a" + U+FFFF + "b" (HEX: 30 61 EFBFBF 62)
       Before: iter != DONE (0xFFFF)  --> stops at U+FFFF --> "0a"              
(HEX: 3061)
       After:  i < length()           --> keeps U+FFFF  --> "0a" + U+FFFF + "B" 
(HEX: 3061EFBFBF42)
    
    2) FE EXPLAIN for json_*: "...'<U+FFFF>tail/end'"
       Before: iter != DONE ('\uFFFF') --> stops at U+FFFF --> "...'"
       After:  i < str.length()        --> keeps U+FFFF  --> 
"...'<U+FFFF>tail\/end'))"
    ```
    
    ### Details
    
    #### 1. BE `INITCAP` UTF-8 path
    
    ```sql
    -- Constructs "0a<U+FFFF>b" and "1a<U+FFFF>b" dynamically via numbers()
    -- so FE constant folding does not bypass the BE INITCAP UTF-8 path.
    SET enable_sql_cache = false;
    SET enable_fold_constant_by_be = false;
    SELECT
        number,
        HEX(CONCAT(CAST(number AS STRING), UNHEX('61EFBFBF62'))) AS input_hex,
        HEX(INITCAP(CONCAT(CAST(number AS STRING), UNHEX('61EFBFBF62')))) AS 
output_hex
    FROM numbers('number'='2')
    ORDER BY number;
    ```
    
    Before:
    ```text
    +--------+--------------+------------+
    | number | input_hex    | output_hex |
    +--------+--------------+------------+
    |      0 | 3061EFBFBF62 | 3061       |
    |      1 | 3161EFBFBF62 | 3161       |
    +--------+--------------+------------+
    ```
    
    After:
    ```text
    +--------+--------------+--------------+
    | number | input_hex    | output_hex   |
    +--------+--------------+--------------+
    |      0 | 3061EFBFBF62 | 3061EFBFBF42 |
    |      1 | 3161EFBFBF62 | 3161EFBFBF42 |
    +--------+--------------+--------------+
    ```
    
    #### 2. FE `FunctionCallExpr.forJSON` (`EXPLAIN` output for `json_*`
    functions)
    
    ```sql
    -- Literal string containing UTF-8 bytes EF BF BF (U+FFFF) followed by 
"tail/end";
    -- run via utf8mb4 client (e.g. python/mysql) so U+FFFF reaches FE 
ExprToSqlVisitor.
    EXPLAIN SELECT json_quote(concat(cast(number AS STRING), 
'<U+FFFF>tail/end')) FROM numbers('number'='1');
    ```
    
    Before (`final projections` drops `U+FFFF`, `tail/end'`, and closing
    `))`):
    ```text
      OUTPUT EXPRS:
        json_quote(concat(cast(number AS STRING), 'tail/end'))[#1]
         final projections: json_quote(concat(CAST(_tvf_numbers.number[#0] AS 
text), '
    ```
    
    After (`U+FFFF` (`EF BF BF`) and escaped `tail\/end` are preserved):
    ```text
      OUTPUT EXPRS:
        json_quote(concat(cast(number AS STRING), 'tail/end'))[#1]
         final projections: json_quote(concat(CAST(_tvf_numbers.number[#0] AS 
text), 'tail\/end'))
    ```
    
    ### Testing
    
    - BE UT (`run-be-ut.sh --run
    --filter="function_string_test.function_initcap*"`), FE UT
    (`run-fe-ut.sh --run org.apache.doris.analysis.ExprToSqlTest`: 119/119
    passed), and Checkstyle (`fe-common`, `fe-catalog`, `fe-core`: 0
    violations) all passed.
    - Regression suite `string_functions_all` (`test_string_all.groovy`)
    passed on a live cluster (`Test 1 suites, failed 0 suites, fatal 0
    scripts, skipped 0 scripts`).
    
    ### Release note
    
    Fixed an issue where `INITCAP` and JSON function SQL serialization
    truncated strings containing `U+FFFF`.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details)
    - Does this need documentation: No
    - Pre-submission status: Ready
    
    ### AI Disclosure
    
    - Tool: Antigravity
    - Generated: Code fix, unit/regression tests, and PR description
    - Human review: Reviewed root cause, scope, cluster verification
    outputs, and test coverage
---
 be/src/exprs/function/function_string.cpp          |  8 +++--
 be/test/exprs/function/function_string_test.cpp    | 41 ++++++++++++++++------
 .../apache/doris/analysis/FunctionCallExpr.java    |  8 ++---
 .../main/java/org/apache/doris/common/io/Text.java | 38 --------------------
 .../org/apache/doris/analysis/ExprToSqlTest.java   | 16 +++++++++
 .../string_functions/test_string_all.out           | 16 +++++++++
 .../string_functions/test_string_all.groovy        |  9 +++++
 7 files changed, 80 insertions(+), 56 deletions(-)

diff --git a/be/src/exprs/function/function_string.cpp 
b/be/src/exprs/function/function_string.cpp
index 5068f3df698..b593cef5d03 100644
--- a/be/src/exprs/function/function_string.cpp
+++ b/be/src/exprs/function/function_string.cpp
@@ -19,10 +19,10 @@
 #include <math.h>
 #include <re2/stringpiece.h>
 #include <unicode/locid.h>
-#include <unicode/schriter.h>
 #include <unicode/uchar.h>
 #include <unicode/unistr.h>
 #include <unicode/ustream.h>
+#include <unicode/utf16.h>
 
 #include <bitset>
 #include <compare>
@@ -769,8 +769,10 @@ struct InitcapImpl {
         unicode_str.toLower(icu::Locale::getRoot());
         icu::UnicodeString output_str;
         bool need_capitalize = true;
-        icu::StringCharacterIterator iter(unicode_str);
-        for (UChar32 ch = iter.first32(); ch != icu::CharacterIterator::DONE; 
ch = iter.next32()) {
+        // Iterate by index; icu::CharacterIterator::DONE is 0xFFFF and 
truncates inputs containing U+FFFF.
+        for (int32_t i = 0; i < unicode_str.length();) {
+            UChar32 ch = unicode_str.char32At(i);
+            i += U16_LENGTH(ch);
             if (!u_isalnum(ch)) {
                 need_capitalize = true;
             } else if (need_capitalize) {
diff --git a/be/test/exprs/function/function_string_test.cpp 
b/be/test/exprs/function/function_string_test.cpp
index 1b4b1806dbb..73f284e2a78 100644
--- a/be/test/exprs/function/function_string_test.cpp
+++ b/be/test/exprs/function/function_string_test.cpp
@@ -3814,16 +3814,37 @@ TEST(function_string_test, function_initcap) {
 
     InputTypeSet input_types = {PrimitiveType::TYPE_VARCHAR};
 
-    DataSet data_set = {{{std::string("SKJ_ASD_SAD _1A")}, 
std::string("Skj_Asd_Sad _1a")},
-                        {{std::string("BC'S aaaaA'' 'S")}, std::string("Bc'S 
Aaaaa'' 'S")},
-                        {{std::string("NULL")}, std::string("Null")},
-                        {{Null()}, Null()},
-                        {{std::string("GROSSE     àstanbul , ÀÇAC123    
ΣΟΦΟΣ")},
-                         std::string("Grosse     Àstanbul , Àçac123    
Σοφος")},
-                        {{std::string("HELLO, WORLD!")}, std::string("Hello, 
World!")},
-                        {{std::string("HHHH+-1; asAAss__!")}, 
std::string("Hhhh+-1; Asaass__!")},
-                        {{std::string("a,B,C,D")}, std::string("A,B,C,D")},
-                        {{std::string("straße")}, std::string("Straße")}};
+    DataSet data_set = {
+            {{std::string("SKJ_ASD_SAD _1A")}, std::string("Skj_Asd_Sad _1a")},
+            {{std::string("BC'S aaaaA'' 'S")}, std::string("Bc'S Aaaaa'' 'S")},
+            {{std::string("NULL")}, std::string("Null")},
+            {{Null()}, Null()},
+            {{std::string("GROSSE     àstanbul , ÀÇAC123    ΣΟΦΟΣ")},
+             std::string("Grosse     Àstanbul , Àçac123    Σοφος")},
+            {{std::string("HELLO, WORLD!")}, std::string("Hello, World!")},
+            {{std::string("HHHH+-1; asAAss__!")}, std::string("Hhhh+-1; 
Asaass__!")},
+            {{std::string("a,B,C,D")}, std::string("A,B,C,D")},
+            {{std::string("straße")}, std::string("Straße")},
+            {{std::string("0a\xef\xbf\xbf"
+                          "b")},
+             std::string("0a\xef\xbf\xbf"
+                         "B")},
+            {{std::string("a\xef\xbf\xbf"
+                          "b")},
+             std::string("A\xef\xbf\xbf"
+                         "B")},
+            {{std::string("\xef\xbf\xbf"
+                          "abc")},
+             std::string("\xef\xbf\xbf"
+                         "Abc")},
+            {{std::string("hello\xef\xbf\xbf")}, 
std::string("Hello\xef\xbf\xbf")},
+            {{std::string("\xef\xbf\xbf\xef\xbf\xbf")}, 
std::string("\xef\xbf\xbf\xef\xbf\xbf")},
+            {{std::string("\xf0\x9f\x98\x80"
+                          "a\xef\xbf\xbf"
+                          "école")},
+             std::string("\xf0\x9f\x98\x80"
+                         "A\xef\xbf\xbf"
+                         "École")}};
 
     check_function_all_arg_comb<DataTypeString, true>(func_name, input_types, 
data_set);
 }
diff --git 
a/fe/fe-catalog/src/main/java/org/apache/doris/analysis/FunctionCallExpr.java 
b/fe/fe-catalog/src/main/java/org/apache/doris/analysis/FunctionCallExpr.java
index 6146293bb1c..4a8294b8cb3 100644
--- 
a/fe/fe-catalog/src/main/java/org/apache/doris/analysis/FunctionCallExpr.java
+++ 
b/fe/fe-catalog/src/main/java/org/apache/doris/analysis/FunctionCallExpr.java
@@ -30,7 +30,6 @@ import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 import com.google.gson.annotations.SerializedName;
 
-import java.text.StringCharacterIterator;
 import java.util.List;
 
 // TODO: for aggregations, we need to unify the code paths for builtins and 
UDAs.
@@ -320,9 +319,9 @@ public class FunctionCallExpr extends Expr {
 
     public String forJSON(String str) {
         final StringBuilder result = new StringBuilder();
-        StringCharacterIterator iterator = new StringCharacterIterator(str);
-        char character = iterator.current();
-        while (character != StringCharacterIterator.DONE) {
+        // Iterate by index; StringCharacterIterator.DONE is '\uFFFF' and 
truncates inputs containing U+FFFF.
+        for (int i = 0; i < str.length(); i++) {
+            char character = str.charAt(i);
             if (character == '\"') {
                 result.append("\\\"");
             } else if (character == '\\') {
@@ -342,7 +341,6 @@ public class FunctionCallExpr extends Expr {
             } else {
                 result.append(character);
             }
-            character = iterator.next();
         }
         return result.toString();
     }
diff --git a/fe/fe-common/src/main/java/org/apache/doris/common/io/Text.java 
b/fe/fe-common/src/main/java/org/apache/doris/common/io/Text.java
index 50efafc55ab..1453cefa941 100644
--- a/fe/fe-common/src/main/java/org/apache/doris/common/io/Text.java
+++ b/fe/fe-common/src/main/java/org/apache/doris/common/io/Text.java
@@ -33,8 +33,6 @@ import java.nio.charset.CharsetEncoder;
 import java.nio.charset.CodingErrorAction;
 import java.nio.charset.MalformedInputException;
 import java.nio.charset.StandardCharsets;
-import java.text.CharacterIterator;
-import java.text.StringCharacterIterator;
 
 /**
  * This class stores text using standard UTF8 encoding. It provides methods to
@@ -630,40 +628,4 @@ public class Text implements Writable {
 
     static final int[] offsetsFromUTF8 = {0x00000000, 0x00003080, 0x000E2080,
             0x03C82080, 0xFA082080, 0x82082080};
-
-    /**
-     * For the given string, returns the number of UTF-8 bytes required to
-     * encode the string.
-     *
-     * @param string text to encode
-     * @return number of UTF-8 bytes required to encode
-     */
-    public static int utf8Length(String string) {
-        CharacterIterator iter = new StringCharacterIterator(string);
-        char ch = iter.first();
-        int size = 0;
-        while (ch != CharacterIterator.DONE) {
-            if ((ch >= 0xD800) && (ch < 0xDC00)) {
-                // surrogate pair?
-                char trail = iter.next();
-                if ((trail > 0xDBFF) && (trail < 0xE000)) {
-                    // valid pair
-                    size += 4;
-                } else {
-                    // invalid pair
-                    size += 3;
-                    iter.previous(); // rewind one
-                }
-            } else if (ch < 0x80) {
-                size++;
-            } else if (ch < 0x800) {
-                size += 2;
-            } else {
-                // ch < 0x10000, that is, the largest char value
-                size += 3;
-            }
-            ch = iter.next();
-        }
-        return size;
-    }
 }
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/analysis/ExprToSqlTest.java 
b/fe/fe-core/src/test/java/org/apache/doris/analysis/ExprToSqlTest.java
index 24fceb2c901..975259fe329 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/analysis/ExprToSqlTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/analysis/ExprToSqlTest.java
@@ -1156,4 +1156,20 @@ public class ExprToSqlTest {
         DateLiteral expr = new DateLiteral(2024, 1, 1, 0, 0, 0, 500000, 
ScalarType.createDatetimeV2Type(1));
         Assertions.assertEquals("'2024-01-01 00:00:00.5'", 
expr.accept(ExprToSqlVisitor.INSTANCE, ToSqlParams.WITH_TABLE));
     }
+
+    @Test
+    public void testFunctionCallExprForJsonPreservesUffff() {
+        FunctionCallExpr expr = new FunctionCallExpr("json_quote", 
Collections.emptyList(), true);
+        Assertions.assertEquals("a\uFFFF\\\"b\\/c\\n", 
expr.forJSON("a\uFFFF\"b/c\n"));
+        Assertions.assertEquals("\uFFFFabc", expr.forJSON("\uFFFFabc"));
+        Assertions.assertEquals("abc\uFFFF", expr.forJSON("abc\uFFFF"));
+    }
+
+    @Test
+    public void testJsonQuoteExprToSqlPreservesUffff() {
+        FunctionCallExpr expr = new FunctionCallExpr(
+                "json_quote", Collections.singletonList(new 
StringLiteral("a\uFFFFb/c")), true);
+        Assertions.assertEquals("json_quote('a\uFFFFb\\/c')",
+                expr.accept(ExprToSqlVisitor.INSTANCE, 
ToSqlParams.WITH_TABLE));
+    }
 }
diff --git 
a/regression-test/data/query_p0/sql_functions/string_functions/test_string_all.out
 
b/regression-test/data/query_p0/sql_functions/string_functions/test_string_all.out
index 2cd0e50a31a..6ccbd6c57c1 100644
--- 
a/regression-test/data/query_p0/sql_functions/string_functions/test_string_all.out
+++ 
b/regression-test/data/query_p0/sql_functions/string_functions/test_string_all.out
@@ -377,6 +377,22 @@ The Quick Brown Fox        Database Management System
 -- !initcap_128 --
 Word1 Word2--Word3     Hello, World! How Are You?
 
+-- !initcap_uffff_1 --
+41EFBFBF42
+
+-- !initcap_uffff_2 --
+EFBFBF416263
+
+-- !initcap_uffff_3 --
+48656C6C6FEFBFBF
+
+-- !initcap_uffff_4 --
+EFBFBFEFBFBF
+
+-- !initcap_uffff_5 --
+0      3061EFBFBF42
+1      3161EFBFBF42
+
 -- !instr_129 --
 2      0
 
diff --git 
a/regression-test/suites/query_p0/sql_functions/string_functions/test_string_all.groovy
 
b/regression-test/suites/query_p0/sql_functions/string_functions/test_string_all.groovy
index 454e7545e0f..a1467f01fed 100644
--- 
a/regression-test/suites/query_p0/sql_functions/string_functions/test_string_all.groovy
+++ 
b/regression-test/suites/query_p0/sql_functions/string_functions/test_string_all.groovy
@@ -316,6 +316,15 @@ suite("string_functions_all") {
     testFoldConst("SELECT INITCAP('the quick brown fox'), INITCAP('DATABASE 
management SYSTEM');")
     qt_initcap_128 "SELECT INITCAP('word1 word2--word3'), INITCAP('hello, 
world! how are you?');"
     testFoldConst("SELECT INITCAP('word1 word2--word3'), INITCAP('hello, 
world! how are you?');")
+    qt_initcap_uffff_1 "SELECT HEX(INITCAP(UNHEX('61EFBFBF62')));"
+    testFoldConst("SELECT HEX(INITCAP(UNHEX('61EFBFBF62')));")
+    qt_initcap_uffff_2 "SELECT HEX(INITCAP(UNHEX('EFBFBF616263')));"
+    testFoldConst("SELECT HEX(INITCAP(UNHEX('EFBFBF616263')));")
+    qt_initcap_uffff_3 "SELECT HEX(INITCAP(UNHEX('68656C6C6FEFBFBF')));"
+    testFoldConst("SELECT HEX(INITCAP(UNHEX('68656C6C6FEFBFBF')));")
+    qt_initcap_uffff_4 "SELECT HEX(INITCAP(UNHEX('EFBFBFEFBFBF')));"
+    testFoldConst("SELECT HEX(INITCAP(UNHEX('EFBFBFEFBFBF')));")
+    qt_initcap_uffff_5 "SELECT number, HEX(INITCAP(CONCAT(CAST(number AS 
STRING), UNHEX('61EFBFBF62')))) FROM numbers('number'='2') ORDER BY number;"
 
     // INSTR tests
     qt_instr_129 "SELECT INSTR('abc', 'b'), INSTR('abc', 'd');"


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

Reply via email to