Skip to content

Fix extract and match results for a regexp with an empty flag group (?) - #126107

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-empty-regexp-flag-group
Oct 16, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-empty-regexp-flag-group

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #121275
Related: #118361

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):

Fix extract returning a truncated match, and match missing matching rows (also through primary-key analysis), for a regular expression with an empty flag group (?). Also fix match missing rows when ?, * or {0,n} applies to a multi-byte character, such as abcdé?x, or comes after a flag group or an empty \Q\E quote, such as (?:abcd)(?s)*x or abcd\Q\E?x. Closes #121275.

Description

On 26.8.18.2, SELECT extract(materialize('abcd'), '(?)b.*$') returns b instead of bcd. The same pattern shape also breaks match: match('abce', 'abcd(?)?e') returns 0 although re2 matches it, and with ORDER BY s, primary-key analysis of WHERE match(s, '^ab(?)*c') can skip granules holding matching rows such as ac. match('x', '(?:abcd)(?s)*x'), match('abcdx', 'abcdé?x') and match('abcx', 'abcd\Q\E?x') also return 0 instead of 1. Also wrong on 26.3.42.3 and master.

re2 accepts an empty flag list, (?): it is zero-width and captures nothing, so a quantifier after it applies to the atom before it (abcd(?)?e is abcd?e). Two recognizers of inline flag groups required at least one flag character:

  • analyzeImpl (OptimizedRegularExpression.cpp) read (?) as a capturing group. RegexpFunctionRewritePass then stripped the .*$ of an extract pattern that has no capture group, and the required-substring analysis kept abcd for abcd(?)?e.
  • findEndOfPureFlagGroup (RegexpUtils.cpp) did not see (?) as zero-width, so the primary-key prefix of ^ab(?)*c stayed ab.

analyzeImpl also applied a quantifier more narrowly than re2: it dropped only the last byte before it (abcdé?x kept abcd plus half of é), did not look through flag groups after a group ((?:abcd)(?s)*x kept abc), and ended the literal at an empty \Q\E quote, which is zero-width too (abcd\Q\E?x kept abcd).

Both recognizers now accept the empty flag list, and analyzeImpl uses the helpers that the primary-key prefix already uses (skipZeroWidthConstructs, isZeroAllowingQuantifier, dropLastLiteral, now exported from RegexpUtils.h). This completes #118361 and the fix for #117256.

New cases in tests 05098 and 05097 fail on the unpatched build and pass with the fix.


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

Version info

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

groeneai and others added 4 commits October 15, 2026 16:31
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]>
Review follow-up. re2 pushes nothing for a pure flag group, so a
quantifier that allows zero occurrences after `(?)` or `(?s)` applies to
the atom before it. The required-substring analysis in `analyzeImpl`
missed two shapes of that atom:

- a group: it looked only at the character right after the group's `)`,
  so for `(?:abcd)(?s)*x` it kept `abcd` in the literal and the `*`
  trimmed one byte, leaving the required substring `abc`;
- a multi-byte character: the quantifier trimmed one byte, so `abcdé?x`
  required `abcd` plus the first byte of `é`.

Both made `match` reject matching rows (`match('x', '(?:abcd)(?s)*x')`
and `match('abcdx', 'abcdé?x')` returned 0). The group check now looks
past a chain of flag groups, as `skipZeroWidthConstructs` does for the
primary-key prefix, and the trim drops the whole UTF-8 character, as
`dropLastLiteral` does.

The `^ab(?)*c` count query now runs with `force_primary_key = 1`, so
the test also fails if the key prefix stops being extracted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-up. The previous commit re-implemented in `analyzeImpl`
three helpers that `RegexpUtils.cpp` already has for the primary-key
prefix (`skipZeroWidthConstructs`, `isZeroAllowingQuantifier`,
`dropLastLiteral`), and the copy left out the empty `\Q\E` quote. re2
pushes nothing for an empty quote, so a quantifier after it applies to
the atom before it, but `analyzeImpl` ended the literal at the escape:
`match('abcx', 'abcd\Q\E?x')`, `match('x', '(?:abcd)\Q\E*x')` and
`match('abcdx', 'abcdé\Q\E?x')` returned 0.

Export the three helpers from `RegexpUtils.h` and call them from
`analyzeImpl` (the group check, the generic quantifier trim, and a new
check in the escape branch for an empty `\Q\E`), so the required-substring
analysis and the primary-key prefix share one definition of zero-width
constructs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Restore master's wording of the ()? group comment; the extra clause restated skipZeroWidthConstructs.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 findings over 3 rounds, the last round clean), plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ A quantifier after (?) trimmed one byte, not the preceding group or multi-byte character: match('x', '(?:abcd)(?)*x') and match('abcdx', 'abcdé(?)?x') returned 0 (OptimizedRegularExpression.cpp) AGREE, fixed the group check looks through zero-width constructs; the trim drops a whole UTF-8 code point
2 ⚠️ The primary-key test also passed if prefix extraction declined (05097) AGREE, fixed SETTINGS force_primary_key = 1 on the count line
3 ❌ An empty \Q\E before a quantifier still kept the atom before it: match('abcx', 'abcd\Q\E?x'), match('x', '(?:abcd)\Q\E*x') returned 0 AGREE, fixed analyzeImpl now calls the RegexpUtils helpers (skipZeroWidthConstructs, isZeroAllowingQuantifier, dropLastLiteral) instead of local copies
4 💡 flags_begin became a plain alias (RegexpUtils.cpp) AGREE, fixed removed
5 💡 findEndOfPureFlagGroup is a static function between the exported helpers; the header and definition name dropLastLiteral's parameter differently noted, not blocking style only; both clang-tidy checks are disabled in .clang-tidy, no behaviour difference

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-11:20261015-191200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. extract(materialize('abcd'), '(?)b.*$') = b, match(materialize('abce'), 'abcd(?)?e') = 0, and count() ... WHERE match(s, '^ab(?)*c') = 1 (rows abc, ac, zz, index_granularity = 1) on every run of the unpatched build, and so are match('x', '(?:abcd)(?s)*x'), match('abcdx', 'abcdé?x') and match('abcx', 'abcd\Q\E?x') = 0; 26.8.18.2 and 26.3.42.3 give the same.
b Root cause explained? re2 accepts an empty flag list (?) (zero-width, no capture). analyzeImpl read it as a capturing group, so the rewrite stripped .*$ and the prefilter required abcd; findEndOfPureFlagGroup did not treat it as zero-width, so the key prefix stayed ab. analyzeImpl also applied a zero-allowing quantifier more narrowly than re2: one byte instead of the whole UTF-8 character, not across flag groups after a group, and not across an empty \Q\E quote.
c Fix matches root cause? Yes. Both recognizers accept the empty flag list, and analyzeImpl now uses the same zero-width and quantifier helpers as the primary-key prefix (skipZeroWidthConstructs, isZeroAllowingQuantifier, dropLastLiteral, exported from RegexpUtils.h); no consumer-side guard. A guard in the rewrite pass instead was tried as a mutation and leaves match wrong.
d Test intent preserved / new tests added? Yes. New cases appended to 05098 and 05097; existing lines unchanged.
e Both directions demonstrated? Yes. Both tests fail on the unpatched build exactly on the new lines and pass with the fix; reverting each change alone reddens only the test cases that pin it, and force_primary_key = 1 pins that the key prefix is used. 50/50 randomized runs each.
f Fix is general across code paths? Yes. The required-substring analysis and the primary-key prefix now share one definition of zero-width constructs, so they cannot drift apart again. Other (? recognizers checked: the rewrite pass's isInlineFlagGroup only declines a rewrite for (?), the regexp JIT falls back to re2, and the multiline/dot-all flag scans see no flags.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The analysis runs on the constant pattern only. Covered positions: leading (?), nested (?:(?)), (?) before a capture group (rewrite still applies), (?) followed by ? and *, a group before (?), (?s) or \Q\E followed by *, a 2-byte character followed by ? directly, after (?) and after \Q\E. Non-empty quotes and other escapes are unchanged (abcd\Qe\E?x, abcd\d?x match re2).
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; only the affected pattern shapes change, from a wrong result to re2's result.
i Invariants and contracts preserved? Yes. has_capture stays true when a real capture exists; required substrings and key prefixes only get shorter, and only before a quantifier that allows zero occurrences.

Session id: cron:clickhouse-impl-slot-40:20261015-183800

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1a25c2e]

Summary: ✅


AI Review

Summary

The PR fixes extract capture detection for (?) and corrects required-substring and primary-key analysis for optional UTF-8 literals and atoms followed by flag groups or empty \Q\E quotes. No actionable findings at 1a25c2e40d830880cba62252880fbbc33992ea76. Both affected stateless tests match their references on the PR binary. An additional 7,200 cases agree with RE2 across constant String, constant FixedString, and varying-pattern execution.

Final Verdict

✅ Approve.

@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 @vitlibar @ahmadov, could you review this? re2 accepts an empty flag group (?) as zero-width, but analyzeImpl read it as a capture group (so extract lost its .*$) and findEndOfPureFlagGroup did not see it as zero-width; analyzeImpl now shares the RegexpUtils zero-width and quantifier helpers. It also needs the can be tested label: I cannot add it, so CI stopped at Config Workflow.

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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.

That's weird. LGTM.

@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 70b72ed Oct 16, 2026
524 of 528 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 #126107 to 26.10: Fix `extract` and `match` results for a regexp with an empty flag group `(?)`
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…gexp with an empty flag group `(?)`
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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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.

extract() truncates result for pattern with empty flag group (?)

5 participants