Skip to content

A flag group of a regexp is not a capture group - #118361

Merged
alexey-milovidov merged 6 commits into
masterfrom
flag-group-is-not-a-capture-117242
Sep 20, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
flag-group-is-not-a-capture-117242

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

optimize_rewrite_regexp_functions strips a trailing .*$ from the pattern of extract, which is sound only when the pattern has a capture group: extract returns group 1 then, and that group precedes the stripped tail. The analyzer answered that a pattern has a capture group when its only parentheses were flag groups - it counted both a bare (?i) and a scoped (?i:...) - so the strip fired while extract was returning the whole match, and the result was silently truncated:

SELECT extract(materialize('aBcd'), '(?i)b.*$');                             -- 'B', was wrong
SELECT extract(materialize('aBcd'), '(?i)b.*$')
SETTINGS optimize_rewrite_regexp_functions = 0;                              -- 'Bcd'
SELECT regexpExtract(materialize('aBcd'), '(?i)b.*$', 0);                    -- 'Bcd'
SELECT extract(materialize('aBcd'), '(?i:b).*$');                            -- 'B', was wrong

RE2 counts no capture group for either form, so has_capture no longer does either. The rewrite keeps firing for a pattern with a real capture group, which the test pins along with both flag-group forms; the unit test that recorded (?s)bob as having a capture is updated to the answer RE2 gives.

While fixing this, the capture analysis turned out to lose captures in a second way: analyzeImpl replaced the accumulated has_capture with the capture bit of the group it had just descended into, so a capture seen earlier, or nested inside a non-capturing group, was dropped - (?i:(b)).*$ and (a)(?:b).*$ were analyzed as having no capture group even though RE2 exposes group 1 for both, and the sound .*$ strip was skipped for them. The analyzer now accumulates, and the test pins the rewrite with EXPLAIN QUERY TREE, because extract returns the same value for these patterns with and without it.

Closes: #117242

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 to CHANGELOG.md):

Fixed extract returning a truncated result for a pattern that ends with .*$ and whose only parentheses are an inline flag group, such as (?i)b.*$: the pattern has no capture group, so the trailing .*$ must not be stripped.


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

Version info

  • Merged into: 26.10.1.308-master (included in 26.10 and later)

`optimize_rewrite_regexp_functions` strips a trailing `.*$` from the pattern of
`extract`, which is sound only when the pattern has a capture group: `extract`
returns group 1 then, and that group precedes the stripped tail. The analyzer
answered that a pattern has a capture group when its only parentheses were flag
groups - it counted both a bare `(?i)` and a scoped `(?i:...)` - so the strip
fired while `extract` was returning the whole match, and the result was
truncated:

    SELECT extract(materialize('aBcd'), '(?i)b.*$');   -- 'B', wrong
    SELECT regexpExtract(materialize('aBcd'), '(?i)b.*$', 0);  -- 'Bcd'

RE2 counts no capture group for either form, so `has_capture` no longer does
either. The rewrite keeps firing for a pattern with a real capture group, which
the test pins along with both flag-group forms.

Closes: #117242

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5fd771f]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes flag groups being counted as captures and keeps nested or earlier captures from being dropped, but the broader has_capture propagation now also enables the existing ^.* rewrite in handleExtract for patterns that were previously left alone. That rewrite is not semantics-preserving when group 1 can match at more than one offset, so the current patch introduces wrong extract results for some multi-match patterns.

Findings

❌ Blockers

  • [src/Common/OptimizedRegularExpression.cpp:468] has_capture now becomes true for captures nested in (?flags:...) and for captures followed by (?:...), and RegexpFunctionRewritePass::handleExtract uses that bit to strip both trailing .*$ and leading ^.*. The suffix rewrite is the bug this PR fixes, but the prefix rewrite changes which occurrence becomes group 1. For example, extract(materialize('a1a2'), '^.*(?s:(a.))') should capture the last a. (a2), while the rewritten (?s:(a.)) captures the first (a1); ^.*(a.)(?:x) on a1xa2x regresses the same way. Please stop using has_capture as blanket permission for the ^.* optimization, or add a stricter proof that stripping the prefix cannot move group 1, and add a focused regression test.
Final Verdict

Status: ❌ Block

Minimum required actions:

  1. Prevent handleExtract from stripping ^.* in the newly enabled nested-capture / later-noncapturing-group cases unless the rewrite is proven semantics-preserving.
  2. Add a focused regression test such as ^.*(?s:(a.)) or ^.*(a.)(?:x) that distinguishes the last captured occurrence from the first.

LLVM Coverage Report

Measured on commit 5fd771f.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 6, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 5fd771f919b74dd2ca1ded3ea791b7260d9b4cd8 with master failed: RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') AS pr_cou….

See the job log for details.

alexey-milovidov and others added 3 commits September 11, 2026 05:35
`analyzeImpl` overwrote the accumulated `has_capture` with the capture bit of the
group it had just descended into, so a capture seen earlier, or nested inside a
non-capturing group, was lost: `(?i:(b)).*$` and `(a)(?:b).*$` were analyzed as
having no capture group even though RE2 exposes group 1 for both. As a result
`RegexpFunctionRewritePass::handleExtract` skipped the sound `.*$` strip for
them.

Accumulate instead of overwrite, and pin the rewrite with `EXPLAIN QUERY TREE`
cases, because `extract` returns the same value with and without the rewrite for
these patterns.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
has_capture = !is_non_capturing_group;
/// A capture anywhere counts: one seen before this group, one nested inside it,
/// or this group itself when it captures.
has_capture = has_capture || group_has_capture || !is_non_capturing_group;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

result.has_capture feeds both the trailing .*$ rewrite you are fixing and the leading ^.* stripping in RegexpFunctionRewritePass::handleExtract. With this new accumulation, patterns that were previously left alone now start taking the prefix rewrite even though it changes which match becomes group 1.

This is the same last-vs-first capture change already documented by 04492_regexp_pattern_with_nul_byte.sql, just without a NUL byte. For example, extract(materialize('a1a2'), '^.*(?s:(a.))') should capture the last a. (a2), but the pass now rewrites it to (?s:(a.)), which captures the first (a1). The same regression appears for a capture that precedes a later non-capturing group, e.g. ^.*(a.)(?:x) on a1xa2x.

So the new has_capture value is correct for the trailing .*$ case, but it is not a safe blanket permission for stripping ^.*. Please either disable the prefix rewrite for these cases (or entirely), or strengthen the proof so group 1 cannot move, and add a focused regression test around one of the examples above.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Sep 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 20, 2026
Merged via the queue into master with commit 308b1b7 Sep 20, 2026
175 of 177 checks passed
@alexey-milovidov
alexey-milovidov deleted the flag-group-is-not-a-capture-117242 branch September 20, 2026 21:40
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Oct 16, 2026
re2 accepts an empty flag list, `(?)`: a no-op that captures nothing and
pushes nothing, so a quantifier after it applies to the atom before it
(`abcd(?)?e` is `abcd?e`). Two ClickHouse recognizers of inline flag
groups required at least one flag character and missed it:

- `analyzeImpl` (OptimizedRegularExpression.cpp) took `(?)` for a
  capturing group. `RegexpFunctionRewritePass` then stripped the trailing
  `.*$` of an `extract` pattern that has no capture group, so
  `extract('abcd', '(?)b.*$')` returned `b` instead of `bcd`. The same
  misreading kept `abcd` as a required substring of `abcd(?)?e`, so
  `match('abce', 'abcd(?)?e')` returned 0 without asking re2.
- `findEndOfPureFlagGroup` (RegexpUtils.cpp) did not see `(?)` as
  zero-width, so the primary-key prefix of `^ab(?)*c` stayed `ab` and
  `WHERE match(s, '^ab(?)*c')` lost the rows starting with `ac`.

Both recognizers now accept the empty flag list. This completes ClickHouse#118361
(`(?i)` is not a capture group) and the fix for ClickHouse#117256 (`^ab(?i)*c`
primary-key prefix), which handled the non-empty forms only.

Closes ClickHouse#121275

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

2 participants