Skip to content

Read a character class of a regexp the way RE2 does - #118342

Merged
alexey-milovidov merged 6 commits into
masterfrom
regexp-character-class-literals-117254
Sep 11, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
regexp-character-class-literals-117254

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

The analyzer that extracts a required substring for the match prefilter tracks character classes, and it read two of RE2's rules wrong.

A ] written first in a class - right after [ or [^ - is a literal member of it, so []a] is the class of ] and a. The analyzer closed the class at that ] instead and analyzed the rest of the body as a top-level literal run, so the prefilter required a substring the pattern does not:

SELECT match(materialize('ab'), '[]a]b');                  -- 0, was wrong
SELECT match(materialize('xb'), '[^]a]b');                 -- 0, was wrong
SELECT replaceRegexpOne(materialize('ab'), '[]a]b', 'X');  -- 'X': RE2 matches

A [ inside an already-open class is a literal member as well. The analyzer opened another class for it and never got back to depth zero, so a top-level | after [[] was not recognized as an alternative and the literal run before the class stayed a required substring:

SELECT match(materialize('zb'), 'abc[[]|b');  -- 0, was wrong: RE2 reads this as 'abc[' | 'b'
SELECT match(materialize('x'), 'abc[[]|');    -- 0, was wrong: the right alternative is empty

The same hidden alternation also let optimize_rewrite_regexp_functions turn replaceRegexpAll into replaceRegexpOne, which replaced only the first match:

SELECT replaceRegexpAll(materialize('[[a'), '[[]|a$', 'Z');  -- 'Z[a', was wrong; 'ZZZ' now

extract, extractAll and the replaceRegexp* family run RE2 without the prefilter and answered correctly all along, which is what makes the wrong answer of match and countMatches visible side by side. Both the constant-pattern and the non-constant-pattern paths are affected, and no setting is involved.

The one [ inside a class that is not a literal is the opening one of a POSIX named class such as [[:alpha:]] or [[:^digit:]]: RE2 consumes [:name:] as a part of the enclosing class, and reads the [ as a literal only when there is no closing :] anywhere in the rest of the pattern. The analyzer follows that rule too, so [[:alpha:]]b keeps requiring b and not ]b.

Closes: #117254
Closes: #117255
Closes: #117243

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 match and countMatches returning wrong results for a pattern whose character class starts with a literal ] ([]a]b) or contains a literal [ next to an alternation (abc[[]|b): the required-substring prefilter demanded a substring the pattern does not require. The same defect made optimize_rewrite_regexp_functions turn such a replaceRegexpAll into replaceRegexpOne.


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

Version info

  • Merged into: 26.9.1.1194 (included in 26.9 and later)

The analyzer that extracts a required substring for the `match` prefilter tracks
character classes, and it read two of RE2's rules wrong.

A `]` written first in a class - right after `[` or `[^` - is a literal member
of it, so `[]a]` is the class of `]` and `a`. The analyzer closed the class at
that `]` instead and analyzed the rest of the body as a top-level literal run,
so `match(materialize('ab'), '[]a]b')` required the substring `a]b` and answered
0 for a haystack RE2 matches.

A `[` inside an already-open class is a literal member as well. The analyzer
opened another class for it and never got back to depth zero, so a top-level
`|` after `[[]` was not recognized as an alternative and the literal run before
the class stayed a required substring: `match(materialize('zb'), 'abc[[]|b')`
answered 0, and so did `match(materialize('x'), 'abc[[]|')`, whose right
alternative is empty and matches everything.

`extract`, `extractAll` and the `replaceRegexp*` family run RE2 without the
prefilter and answered correctly all along, which is what makes the wrong answer
of `match` and `countMatches` visible side by side.

Closes: #117254
Closes: #117255

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

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e4932ee]

Summary: ✅


AI Review

Summary

This PR fixes the required-substring analyzer so RE2 character classes with a leading literal ], a literal [ inside the class, and POSIX named classes are read the same way as RE2, and it adds stateless coverage for the reported wrong-result cases. The parser change itself looks sound, but one user-visible surface the PR explicitly mentions, text-index pruning via RegexpAnalysisResult::alternatives, is still not directly proven by the new tests.

Missing context / blind spots
  • ⚠️ As of 2026-09-11, the only Praktika report visible on the PR is Build profile diff; I did not have runtime CI results for the new stateless test file.
Tests
  • ⚠️ [tests/queries/0_stateless/05096_regexp_character_class_literals.sql:49] The new foo|[[:alpha:]]x case runs plain match, but match does not consume RegexpAnalysisResult::alternatives; once the required substring is empty it falls back to RE2. So this query stays green even if the analyzer still extracts the right branch as ]x instead of x, and the regression would only show up under text-index pruning. Please add either a focused gtest_optimize_re expectation for foo|[[:alpha:]]x -> {"foo", "x"} or a text-index match(... SETTINGS use_skip_indexes = 1) / multiMatchAny case on this exact POSIX-class shape.
Final Verdict

Needs one more focused regression test for the alternatives / text-index path before I would consider this fully covered.

LLVM Coverage Report

Measured on commit e4932ee.

Metric Baseline Current Δ
Lines 89.00% 88.90% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 31/31 (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 5, 2026
@zlareb1

zlareb1 commented Sep 5, 2026

Copy link
Copy Markdown
Member

TL;DR: the two reported shapes are fixed correctly, but the new [-inside-class rule introduces a fresh over-claim on POSIX named classes: after this change, match(materialize('Qxyz'), '[[:alpha:]]xyz') returns 0 while extract('Qxyz', '[[:alpha:]]xyz') returns Qxyz — the same fault class this PR fixes, one shape over. Master currently analyzes these patterns correctly.

  1. The mechanism. The in-class branch of case '[' treats every [ inside an open class as a one-byte literal member. RE2 (parse.cc, ParseCharClass + ParseCCName) treats [ followed by : with a closing :] and a valid name as a POSIX named class consumed as a unit, so the class stays open past the inner :]. With the literal-skip, the analyzer closes the class at the ] of :] (it is not at square_braces_body_begin), and the real class-closing ] plus everything after it becomes a top-level literal run: [[:alpha:]]xyz yields required substring ]xyz instead of xyz. The prefilter then rejects any haystack without a literal ], before RE2 runs.

  2. Extracted-analyzer trace (this branch vs master), verified against RE2 on a real server:

    • [[:alpha:]]xyz — master required xyz (correct), branch ]xyz (wrong: Qxyz matches with no ] in the data).
    • [a[:digit:]z]xyz — master xyz, branch z]xyz (wrong: 7xyz matches).
    • foo|[[:alpha:]]x — master alternatives {foo, x}, branch {foo, ]x}; the alternatives feed both the match prefilter and text-index multiMatchAny pruning, so this shape is silent row loss under use_skip_indexes = 1 as well.
    • Near-miss worth knowing: [[:alpha:]]*xyz escapes, because the quantifier truncates the spurious trailing ] from the literal run — only unquantified POSIX classes are hit.
  3. The cases the branch handles correctly (traced): []], [^]], [a]], [\]], [a-], [(], (a|[b|c]), [[]|bar, [ at end of pattern (RE2 refuses to compile, loud), and abc[[:]]xyz where there is no valid closing :] (RE2 also takes [ as a literal there, so agreeing is right). It also fixes [^]]xyz, which over-claims ]xyz on master today.

  4. Fix shape. In the in-class case '[' branch, mirror RE2: if the next character is : and a closing :] exists before the class ends, skip through the :] and keep the class open; otherwise skip the [ as a literal, as the branch does now. (A minimal conservative alternative: keep the old nesting behavior just for [:.)

  5. Test gap. No stateless test and no gtest_optimize_re case anywhere covers [[: together with match, so CI stays green on this regression. A one-line addition to the new test — match with [[:alpha:]]xyz over a row without ] — pins it.

@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 e4932ee0d with master c108e273b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 6 s compile time in total, 7 of them have a recent master baseline.

Job report

alexey-milovidov and others added 5 commits September 6, 2026 02:01
The tracker that reads a `[` inside an open class also decides whether
`optimize_rewrite_regexp_functions` may turn `replaceRegexpAll` into
`replaceRegexpOne`: the rewrite declines for a pattern with a top-level
alternation, and with the alternation hidden it replaced only the first match.

    SELECT replaceRegexpAll(materialize('[[a'), '[[]|a$', 'Z');   -- 'Z[a', now 'ZZZ'

Closes: #117243

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… literal `[`

Reading every `[` inside an open character class as a literal member of it was
broader than RE2's grammar: RE2 first looks for a POSIX named class such as
`[:alpha:]` and consumes it as a part of the enclosing class. For `[[:alpha:]]b`
the analyzer therefore closed the class at the `:]`, took the trailing `]b` as a
top-level literal run, and the prefilter demanded a substring the pattern does
not - dropping rows that RE2 matches.

Consume the named class as a whole, following RE2's rule that the `[` is a
literal only when there is no closing `:]` anywhere in the rest of the regexp.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A control binary built without the fix answers 0 for
`match('zabcdefg', 'z[[:alpha:]]bcdefg')`, because the required substring is
taken as `]bcdefg`; the case without a closing `:]`, where the `[` really is a
literal member, is covered too.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A named class next to ordinary members, one inside an alternative (the
alternatives also drive text-index pruning), and `[[:]]`, which has no closing
`:]` and is a literal `[` for RE2 too.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
-- A named class next to other members, and one inside an alternative, where the analyzer also
-- feeds the alternatives to the text-index pruning.
SELECT match(materialize('7xyz'), '[a[:digit:]z]xyz'), match(materialize('qxyz'), '[a[:digit:]z]xyz');
SELECT match(materialize('Qx'), 'foo|[[:alpha:]]x'), match(materialize('foo'), 'foo|[[:alpha:]]x'), match(materialize('bar'), 'foo|[[:alpha:]]x');

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.

This still does not exercise the path that consumes RegexpAnalysisResult::alternatives. match never reads that vector: OptimizedRegularExpression::getAnalyzeResult exposes only required_substring, and MatchImpl::matchOneRow falls straight back to RE2 when that required substring is empty. So this query stays green even if analyze('foo|[[:alpha:]]x') still extracts the right branch as ]x instead of x, and the regression would only show up under text-index pruning.

Please add either a focused gtest_optimize_re expectation for foo|[[:alpha:]]x -> {"foo", "x"} or a text-index match(... SETTINGS use_skip_indexes = 1) / multiMatchAny case on this exact POSIX-class shape.

@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.

LGTM

@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment