Skip to content

Fix replaceRegexpAll replacing only the first match when the pattern starts with an optional ^ - #126111

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:regexp-rewrite-quantified-caret
Oct 16, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:regexp-rewrite-quantified-caret

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #121494

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed replaceRegexpAll and regexp_replace replacing only the first match when the pattern starts with an optional ^, such as ^?, ^* or ^{0,3}: replaceRegexpAll('xfx', '^?x', 'Z') returned Zfx instead of ZfZ. Closes #121494.

Description

What breaks. On 26.8.18.2 and 26.3.42.3, replaceRegexpAll(materialize('xfx'), '^?x', 'Z') returns Zfx instead of ZfZ. With optimize_rewrite_regexp_functions = 0 it is correct.

Root cause. RegexpFunctionRewritePass turns replaceRegexpAll into replaceRegexpOne when the pattern starts with ^, because then it can only match at offset 0. It checked only the first byte. A quantifier that allows zero repetitions makes the ^ optional, so the pattern matches anywhere. The quantifier can also bind to the ^ through an empty \Q\E or a flag group (^\Q\E?x, ^(?i)?x).

Change. The ^ side now uses the tokenizer that already decides the trailing $ side: the leading ^ counts as an anchor unless its quantifier allows zero repetitions (?, *, {0,n}). The tokenizer already gives up on a quantifier after \Q\E or a flag group, so those are declined too. The ClickBench pattern ^https?://(?:www\.)?([^/]+)/.*$ keeps the rewrite.

Also declined now, with unchanged results: patterns the tokenizer does not analyze, such as a literal { after ^ (no measurable cost).

Validation. New test 05401_replace_regexp_all_quantified_caret fails on master and passes with the fix, 50/50 randomized runs. Over 36 ^-led patterns the results with the rewrite on now equal the results with it off, and the existing regexp-rewrite tests pass.


Workflow [PR]
Sync PR [sync-upstream/pr/126111]

Version info

  • Merged into: 26.11.1.28-master (included in 26.11 and later)

groeneai and others added 4 commits October 15, 2026 18:07
…fied

RegexpFunctionRewritePass turns `replaceRegexpAll` (and `regexp_replace`)
into `replaceRegexpOne` when the constant pattern starts with `^`, on the
assumption that such a pattern can only match at offset 0. It decided that
from the first byte alone. A quantifier that allows zero repetitions (`^?`,
`^*`, `^{0,n}` and their lazy forms) makes the anchor optional, so the
pattern matches at any offset and every match after the first one was
dropped: `replaceRegexpAll('xfx', '^?x', 'Z')` returned `Zfx` instead of
`ZfZ`. The same happens when the quantifier binds to the `^` through an
empty `\Q\E` or an inline flag group, as in `^\Q\E?x` and `^(?i)?x`.

Decide the caret side with the tokenizer that already decides the trailing
`$` side: `RegexpAtom` gets an `is_caret` flag, set for a bare `^` and
cleared by any quantifier exactly like `is_dollar`, and the tokenizer's
existing give-up on a quantifier after a no-element construct covers the
binding cases. A pattern the tokenizer cannot analyze now declines the
rewrite, which only costs the optimization; the ClickBench pattern
`^https?://(?:www\.)?([^/]+)/.*$` keeps it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t least once

A `^` repeated at least once (`^+`, `^{1,3}`) still anchors the pattern at offset 0,
and re2 does not mark such a program as start-anchored, so declining the rewrite costs
a full rescan per row. Only a quantifier that allows zero repetitions now declines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The comments now say that only a leading `^` whose quantifier allows zero repetitions is optional.
The test pins `enable_analyzer` so it also runs in the old-analyzer jobs of release branches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the example line from the startsWithCaretAnchor comment; the call site already says when a quantified caret stops anchoring.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (rounds 1-3): 1 major and 3 nits agreed and fixed, 1 major declined with measurement; round 3 found nothing
Finding Verdict
⚠️ Any quantifier cleared the caret anchor, so a ^ that must still match (^+x, ^{1,3}x) lost a correct rewrite; re2 does not mark ^+ as start-anchored, so the global replace rescans each row AGREE, fixed: only a quantifier that allows zero repetitions declines
⚠️ A repeated caret followed by a construct the tokenizer does not analyze (^+{, ^{1,3}{) is still declined: results unchanged, 2.3x slower on a synthetic 20M-row benchmark DISAGREE: no test, benchmark or doc pattern repeats a leading ^ (0 of 1732 ^-led patterns in the stateless tests); for a bare ^ the same decline costs nothing because re2 anchors it itself; keeping these would add a second give-up mode to the shared tokenizer
💡 Comments (pass doc, visitor, test header) said every quantified anchor stops anchoring AGREE, fixed
💡 EXPLAIN QUERY TREE in the test needs the analyzer in the old-analyzer jobs of release branches AGREE, fixed: SET enable_analyzer = 1

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: replaceRegexpAll(s, '^?x', 'Z') over ['xfx','xx'] gives Zfx/Zx on master every run, and EXPLAIN QUERY TREE shows replaceRegexpOne.
b Root cause explained? The rewrite decided "anchored at offset 0" from the first byte ^; a zero-repetition quantifier (directly, or through an empty \Q\E / a flag group) makes the ^ optional, so a pattern that matches anywhere was renamed to the single-replace function.
c Fix matches root cause? Yes: the ^ verdict now comes from tokenizeRegexp, like the existing $ verdict: the leading ^ is an anchor unless its quantifier allows zero repetitions, so ^+x / ^{1,3}x keep the rewrite. The functions are untouched.
d Test intent preserved / new tests added? New 05401_replace_regexp_all_quantified_caret: rewrite-on and rewrite-off rows, binding cases, EXPLAIN ^?x = 0, controls ^x, ^+x, ^{1,3}x and the ClickBench pattern = 1; pins enable_analyzer.
e Both directions demonstrated? Runner: [ FAIL ] on master with exactly the bug diff, [ OK ] with the fix; 50/50 randomized runs.
f Fix is general across code paths? This is the only site that claims a single match at offset 0; regexp_replace / REGEXP_REPLACE share it; the $ side was already safe; match, countMatches, extractAll, extract are correct on master.
g Fix generalizes across inputs (params/datatypes/wrappers)? 36 ^-led patterns (all quantifier forms incl. lazy, {0}, {0,}, ^?, ^*): results with the rewrite on equal results with it off. String, FixedString, Nullable(String) fixed; LowCardinality and constant haystacks were not affected.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change; results of previously correct patterns are unchanged. Some correct rewrites are declined (see description).
i Invariants and contracts preserved? The tokenizer stays conservative (give-up declines the rewrite), is_dollar is unchanged, and the multiline and alternation declines still run after the gate.

Session id: cron:clickhouse-impl-slot-41:20261015-184400

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a338323]

Summary: ✅


AI Review

Summary

The PR prevents replaceRegexpAll and regexp_replace from becoming replaceRegexpOne when a leading ^ is optional, while preserving rewrites for mandatory anchors. No actionable findings at commit a33832346c7756b4f0d4fbd2e43a2c140e40683f.

Missing context / blind spots
  • ⚠️ Broader stateless and automated bugfix-validation jobs were dropped. The finish job reports missing bugfix-validation results; rerunning the dropped jobs would close this CI gap. The new regression test passed in Fast test.
Final Verdict

Status: ✅ Approve. No code changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @vdimir, could you review this? RegexpFunctionRewritePass turned replaceRegexpAll into replaceRegexpOne whenever the pattern started with a ^ byte, so ^?x replaced only the first match; the ^ verdict now comes from the same tokenizer as the trailing $ check, and a ^ whose quantifier allows zero repetitions no longer counts as an anchor.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 15, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 15, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Okay.

@alexey-milovidov alexey-milovidov self-assigned this Oct 16, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 16, 2026
Merged via the queue into ClickHouse:master with commit c01c33a Oct 16, 2026
525 of 529 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 16, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #126111 to 26.10: Fix `replaceRegexpAll` replacing only the first match when the pattern starts with an optional `^`
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…first match when the pattern starts with an optional `^`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

replaceRegexpAll drops matches when pattern starts with quantified ^

5 participants