This is an automated email from the ASF dual-hosted git repository.
jacktengg 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 89529eac8c3 [fix](function) Validate regexp replacement strings before
replacing (#71309)
89529eac8c3 is described below
commit 89529eac8c31ef6cbe361148f6c10756ee6a99dd
Author: TengJianPing <[email protected]>
AuthorDate: Thu Dec 3 09:47:00 2026 +0800
[fix](function) Validate regexp replacement strings before replacing
(#71309)
### Background
REGEXP_REPLACE and REGEXP_REPLACE_ONE use RE2 to replace all matches or
the first match. Both accept capture references in the replacement and
an explicit IGNORE_INVALID_ESCAPE option.
### What problem does this PR solve?
Issue Number: None
Related PR: #8307 (introduced global replacement), #13766 (introduced
first-match replacement)
PR Type: Bugfix
Problem Summary:
With one match and replacement `X\xY`, default-mode global replacement
can keep only the prefix while first-match replacement leaves the input
unchanged. Both silently accept an invalid rewrite. Validate strict
rewrites before either operation so both report a meaningful argument
error; legal backreferences, explicit IGNORE_INVALID_ESCAPE and NULL
propagation remain unchanged.
### Details
- **Frequency:** Always for the tested malformed escapes, trailing
backslash and missing capture group in strict mode; real BE baseline
tests returned OK for all 48 calls.
- **Root cause:** RegexpReplaceImpl ignores RE2's replacement failure
semantics and does not validate rewrite syntax. Replace and
GlobalReplace handle a failed rewrite differently.
- **Why existing tests missed it:** FunctionLikeTest covers successful
replacement/backreferences/NULLs; FunctionConstantArgumentTest covers
constant options and block changes. Native test_regexp_replace and
test_regexp_invalid_pattern exercise permissive replacement and pattern
failures, without asserting rejection of invalid strict rewrites.
- **Fix:** Reuse CheckRewriteString in the common replacement path after
NULL skipping and before modifying the source. Skip strict validation
for the existing permissive option. Constant pattern/replacement pairs
validate once per block, preserving lazy-join block boundaries.
- **Other paths and branches:** Three- and four-argument, constant and
column paths for both functions are covered. Extract/match functions
have no replacement argument. Cached branch-3.1/4.0/4.1/4.2 have the
same omission; only master was built and run. External
dialect-conversion services were not exercised.
- **Behavior change:** Invalid strict replacement arguments now fail,
including when the source has no match, instead of silently returning
partial or unchanged text.
### Testing
- Local ASAN baseline:
`FunctionConstantArgumentTest.regexp_replace_invalid_rewrite` fails
because all 48 executions incorrectly return OK.
- Local ASAN candidate: `./run-be-ut.sh --run
--filter='FunctionConstantArgumentTest.regexp*:FunctionLikeTest.regexp*'
-j48` passes all 27 tests.
- `./build.sh --be --fe -j48 --output <isolated-output>` passes. The
first attempt found an obsolete generated FE annotation after switching
branches; moving stale generated annotations and rerunning the standard
build resolved it.
- Generated and independently checked test_regexp_invalid_rewrite.out:
legal captures yield aXbYc, explicit permissive replacements yield
aXxYc, NULL rows remain NULL. BE constant folding is tested both enabled
and disabled.
- `./run-regression-test.sh --run -d
query_p0/sql_functions/string_functions,nereids_syntax_p0 -s
test_regexp_invalid_rewrite,test_regexp_invalid_pattern,test_regexp_replace`
passes all 3 suites with no skips.
- Scoped repository clang-format 16/check-format and clang-tidy pass on
both changed C++ files. `git diff --check` passes.
### Release note
REGEXP_REPLACE and REGEXP_REPLACE_ONE now consistently reject invalid
replacement strings in default mode. IGNORE_INVALID_ESCAPE retains its
existing permissive behavior.
### Check List (For Author)
- Behavior changed: Yes (see Details)
- Does this need documentation: Yes; clarify strict rewrite errors and
unchanged IGNORE_INVALID_ESCAPE behavior in the corresponding
apache/doris-website SQL function pages.
- Pre-submission status: Ready
### AI Disclosure
- Tool: Codex (GPT-6)
- Generated: Implementation, unit/regression tests and this description.
- Human review: Pending author review.
<!-- Recommended: develop the change with the develop-with-evidence
skill and write this description with the doris-pr-description skill,
both from https://github.com/apache/doris-skills (the doris-skills
submodule of this repository). -->
### Background
<!-- How the feature or module this PR touches works today, in two to
four plain sentences, for a reviewer who doesn't know it. Link the user
doc if there is one. Leave the problem and the fix to Problem Summary.
-->
### What problem does this PR solve?
<!-- Issue Number: "close #N" if this PR resolves the issue, "#N" if it
only relates to it, "None" if there is none. A Feature needs an issue.
-->
<!-- Related PR: "#N (relation)" for each PR a reviewer should know
about, such as "#123 (introduced the bug)", separated by commas. Write
"None" if no related PR is known. -->
<!-- PR Type: Bugfix, Performance, Feature, Enhancement, Refactor, Test,
Build/CI/Chore, Revert, Release/Dependency, or Other. -->
Issue Number:
Related PR:
PR Type:
Problem Summary:
<!-- Two to five sentences: the problem or need and who is affected; the
approach in one sentence; when the diff is larger than that suggests,
what else it had to handle, or that most of it is tests; and what
existing users see after an upgrade. -->
### Details
<!--
For a diff of more than about 300 changed lines, start with "- **Change
map:**": how many lines are production code, tests, generated files, and
docs, then the code in parts, each with the problem it handles and its
size.
Then answer each field of your PR type on its own line, as "- **Field:**
answer", in this order:
Bugfix: Frequency, Root cause, Why existing tests missed it, Fix, Other
paths and branches
Performance: Why it was slow, Optimization, Results, Applicability and
cost
Feature: Scope, Design, Usage, Default behavior, Compatibility
Enhancement: Before and after, Configs and defaults, Impact on existing
users
Refactor: Moves vs. logic changes, Behavior change, Compatibility,
Performance impact, Rollback
Test, adding tests: Scenarios, What existing tests miss, Fails when
broken
Test, fixing a test: Failure, Cause, Stability evidence
Build/CI/Chore: Affected, Developer and release impact, License and
third-party, Rollback
Revert: Why not fix forward, Original author notified, Follow-up
Release/Dependency: Versions, Upstream changes, Compatibility, Rollback
Other: Why Other
"None" is a valid answer when it is true. Don't restate the diff.
-->
### Testing
<!-- The tests, suites, or commands that ran, what each shows, and where
it ran (locally or in CI). For a fix, the test that fails before it and
passes after. -->
### Notes for Reviewers
<!-- Optional; delete this section if there is nothing to say. Why each
non-obvious edit was made, what you are unsure about, and where to start
reading if Details has no Change map. -->
### Release note
<!-- One paragraph on what users will notice, or None. -->
### Check List (For Author)
<!-- Behavior changed: "No", or "Yes (see Details)" with a Behavior
change field in Details. -->
<!-- Does this need documentation: "No", or "Yes" with the
apache/doris-website PR or the plan. -->
<!-- Pre-submission status: "Ready"; "Partially verified: " and what is
not verified; or "Not ready: " and why, for a Draft PR. -->
- Behavior changed:
- Does this need documentation:
- Pre-submission status:
### AI Disclosure
<!-- Tool: the agent and model, or None. Generated: the parts it wrote
(code, tests, this description), or None. Human review: what you
reviewed of the generated parts, or "Not applicable" without AI tools.
You may add "- Prompts:" to summarize how you directed the agent. -->
- Tool:
- Generated:
- Human review:
---
be/src/exprs/function/function_regexp.cpp | 21 +++++-
.../function/function_constant_argument_test.cpp | 30 +++++++++
.../test_regexp_invalid_rewrite.out | 19 ++++++
.../test_regexp_invalid_rewrite.groovy | 76 ++++++++++++++++++++++
4 files changed, 144 insertions(+), 2 deletions(-)
diff --git a/be/src/exprs/function/function_regexp.cpp
b/be/src/exprs/function/function_regexp.cpp
index b3005685531..3d64865047f 100644
--- a/be/src/exprs/function/function_regexp.cpp
+++ b/be/src/exprs/function/function_regexp.cpp
@@ -639,6 +639,9 @@ struct RegexpReplaceImpl {
const auto* pattern_col =
check_and_get_column<ColumnString>(argument_columns[1].get());
const auto* replace_col =
check_and_get_column<ColumnString>(argument_columns[2].get());
+ // Pattern and replacement are constant within this block. Skip NULL
rows before
+ // validating, and do not retain validation state across blocks of a
lazy join.
+ bool validate_rewrite = true;
for (size_t i = 0; i < input_rows_count; ++i) {
if constexpr (CheckNull) {
if (null_map[i]) {
@@ -647,7 +650,9 @@ struct RegexpReplaceImpl {
}
}
_execute_inner_loop<true>(context, str_col, pattern_col,
replace_col, source_const,
- options_value, result_data,
result_offset, i);
+ options_value, result_data,
result_offset, i,
+ validate_rewrite);
+ validate_rewrite = false;
}
}
@@ -657,7 +662,8 @@ struct RegexpReplaceImpl {
const ColumnString* replace_col, bool
source_const,
const StringRef& options_value,
ColumnString::Chars& result_data,
- ColumnString::Offsets& result_offset,
const size_t index_now) {
+ ColumnString::Offsets& result_offset,
const size_t index_now,
+ bool validate_rewrite = true) {
auto* re = reinterpret_cast<re2::RE2*>(
context->get_function_state(FunctionContext::FunctionStateScope::THREAD_LOCAL));
std::unique_ptr<re2::RE2> scoped_re; // destroys re if state->re is
nullptr
@@ -676,6 +682,17 @@ struct RegexpReplaceImpl {
re2::StringPiece replace_str = re2::StringPiece(
replace_col->get_data_at(index_check_const(index_now,
Const)).to_string_view());
+ if (validate_rewrite && !re->options().ignore_replace_escape()) {
+ std::string error;
+ // For invalid rewrites such as X\xY, GlobalReplace can consume a
partial
+ // replacement while Replace keeps the original string. Reject
both before
+ // modifying the source, unless the explicit permissive option is
enabled.
+ if (!re->CheckRewriteString(replace_str, &error)) {
+ throw Exception(
+ Status::InvalidArgument("Invalid regexp replacement
string: {}", error));
+ }
+ }
+
std::string result_str(
str_col->get_data_at(index_check_const(index_now,
source_const)).to_string());
if constexpr (ReplaceOne) {
diff --git a/be/test/exprs/function/function_constant_argument_test.cpp
b/be/test/exprs/function/function_constant_argument_test.cpp
index 7e432022336..dd5770bd5e7 100644
--- a/be/test/exprs/function/function_constant_argument_test.cpp
+++ b/be/test/exprs/function/function_constant_argument_test.cpp
@@ -177,6 +177,36 @@ TEST_F(FunctionConstantArgumentTest,
regexp_replace_options) {
EXPECT_EQ(empty_block.get_by_position(4).column->size(), 0);
}
+TEST_F(FunctionConstantArgumentTest, regexp_replace_invalid_rewrite) {
+ auto string_type = std::make_shared<DataTypeString>();
+ auto return_type = make_nullable(string_type);
+ for (const std::string name : {"regexp_replace", "regexp_replace_one"}) {
+ // Invalid escapes, a trailing backslash and a missing capture group
must
+ // fail before RE2 can discard the replacement suffix or keep the
source.
+ for (const std::string rewrite : {"X\\xY", "X\\", "X\\2Y"}) {
+ for (int shape = 0; shape < 8; ++shape) {
+ SCOPED_TRACE(name + ": " + rewrite + ", shape=" +
std::to_string(shape));
+ const std::vector<std::string> values = {"abc", "(b)",
rewrite};
+ Block block;
+ std::vector<std::shared_ptr<ConstantExprResult>> constants(3);
+ for (size_t arg = 0; arg < values.size(); ++arg) {
+ ColumnPtr column = strings({values[arg]});
+ if (shape & (1 << arg)) {
+ column = ColumnConst::create(column, 1);
+ constants[arg] = constant(column);
+ }
+ block.insert({column, string_type, std::to_string(arg)});
+ }
+ Status status = execute(name, block, return_type, constants);
+ EXPECT_TRUE(status.is<ErrorCode::INVALID_ARGUMENT>()) <<
status;
+ EXPECT_NE(status.to_string().find("Invalid regexp replacement
string"),
+ std::string::npos)
+ << status;
+ }
+ }
+ }
+}
+
TEST_F(FunctionConstantArgumentTest,
regexp_replace_pattern_changes_across_blocks) {
// A lazy join can pass a probe-side pattern as a physical ColumnConst for
one block while the
// pattern is not a query-level constant, so FE's constant_cols entry for
it is nullptr here
diff --git
a/regression-test/data/query_p0/sql_functions/string_functions/test_regexp_invalid_rewrite.out
b/regression-test/data/query_p0/sql_functions/string_functions/test_regexp_invalid_rewrite.out
new file mode 100644
index 00000000000..4015c57ef80
--- /dev/null
+++
b/regression-test/data/query_p0/sql_functions/string_functions/test_regexp_invalid_rewrite.out
@@ -0,0 +1,19 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !constants_false --
+aXbYc aXbYc aXxYc aXxYc
+
+-- !constants_true --
+aXbYc aXbYc aXxYc aXxYc
+
+-- !nullable --
+1 aXbYc aXbYc
+3 \N \N
+4 \N \N
+5 \N \N
+
+-- !ignore_invalid_escape --
+1 aXbYc aXbYc
+2 aXxYc aXxYc
+3 \N \N
+4 \N \N
+5 \N \N
diff --git
a/regression-test/suites/query_p0/sql_functions/string_functions/test_regexp_invalid_rewrite.groovy
b/regression-test/suites/query_p0/sql_functions/string_functions/test_regexp_invalid_rewrite.groovy
new file mode 100644
index 00000000000..e6af13b40e6
--- /dev/null
+++
b/regression-test/suites/query_p0/sql_functions/string_functions/test_regexp_invalid_rewrite.groovy
@@ -0,0 +1,76 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Both replacement functions reject invalid rewrites in strict mode, whether
+// the arguments are constants or columns.
+suite("test_regexp_invalid_rewrite", "p0") {
+ def functions = ["regexp_replace", "regexp_replace_one"]
+ def originalFold = sql("select @@enable_fold_constant_by_be")[0][0]
+ try {
+ [false, true].each { fold ->
+ sql "set enable_fold_constant_by_be = ${fold}"
+ functions.each { function ->
+ test {
+ sql "SELECT ${function}('abc', '(b)', CONCAT('X',
CHAR(92), 'xY'))"
+ exception "Invalid regexp replacement string"
+ }
+ test {
+ sql "SELECT ${function}('abc', '(b)', CONCAT('X',
CHAR(92), 'xY'), 'none')"
+ exception "Invalid regexp replacement string"
+ }
+ // Invalid rewrite arguments must not depend on whether the
source matches.
+ test {
+ sql "SELECT ${function}('zzz', '(b)', CONCAT('X',
CHAR(92), 'xY'))"
+ exception "Invalid regexp replacement string"
+ }
+ }
+ "order_qt_constants_${fold}" """SELECT
+ regexp_replace('abc', '(b)', CONCAT('X', CHAR(92), '1Y')),
+ regexp_replace_one('abc', '(b)', CONCAT('X', CHAR(92), '1Y')),
+ regexp_replace('abc', '(b)', CONCAT('X', CHAR(92), 'xY'),
'IGNORE_INVALID_ESCAPE'),
+ regexp_replace_one('abc', '(b)', CONCAT('X', CHAR(92), 'xY'),
'IGNORE_INVALID_ESCAPE')"""
+ }
+ } finally {
+ sql "set enable_fold_constant_by_be = ${originalFold}"
+ }
+
+ sql "DROP TABLE IF EXISTS test_regexp_invalid_rewrite"
+ sql """CREATE TABLE test_regexp_invalid_rewrite (
+ id INT, s STRING, p STRING, r STRING
+ ) DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES("replication_num" = "1")"""
+ sql """INSERT INTO test_regexp_invalid_rewrite VALUES
+ (1, 'abc', '(b)', CONCAT('X', CHAR(92), '1Y')),
+ (2, 'abc', '(b)', CONCAT('X', CHAR(92), 'xY')),
+ (3, NULL, '(b)', CONCAT('X', CHAR(92), 'xY')),
+ (4, 'abc', '(b)', NULL),
+ (5, 'abc', NULL, CONCAT('X', CHAR(92), 'xY'))"""
+ functions.each { function ->
+ ["s, p, r", "s, '(b)', r", "'abc', p, r", "'abc', '(b)', r"].each {
arguments ->
+ test {
+ sql "SELECT ${function}(${arguments}) FROM
test_regexp_invalid_rewrite WHERE id = 2"
+ exception "Invalid regexp replacement string"
+ }
+ }
+ }
+ // NULL rows skip rewrite validation, even when a non-NULL replacement is
invalid.
+ order_qt_nullable """SELECT id, regexp_replace(s, p, r),
regexp_replace_one(s, p, r)
+ FROM test_regexp_invalid_rewrite WHERE id <> 2"""
+ order_qt_ignore_invalid_escape """SELECT id,
+ regexp_replace(s, p, r, 'IGNORE_INVALID_ESCAPE'),
+ regexp_replace_one(s, p, r, 'IGNORE_INVALID_ESCAPE') FROM
test_regexp_invalid_rewrite"""
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]