Repository navigation
Add an experimental regex-free glob parser - #91062
thevar1able wants to merge 104 commits into
Conversation
|
Workflow [PR], commit [efc0652] Summary: ❌
AI ReviewSummaryThis PR adds the experimental Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 1097/1152 (95.23%) · Uncovered code |
54b3bc7 to
a786ab7
Compare
e4a3696 to
61c735d
Compare
Handle unmatched and empty braces gracefully instead of crashing:
- Fix inverted condition for double-brace '{{' literal escape (was dead code)
- Treat '{' as literal when no closing '}' is found (prevents SIGABRT)
- Treat '{}' as literal '{' when braces are empty (length <= 2)
The parser previously passed empty/short string_views from consumeMatcher
to tryParseRangeMatcher/tryParseEnumMatcher which have assert(length > 2),
causing the server to abort on filenames like 'b}{r?{ces'.
Assisted-by: Claude Opus 4.6 via GitHub Copilot
The '{{' sequence should emit a literal '{' and advance by 1 (not 2),
so the second '{' is re-processed as a potential matcher start. This
makes '{{a,b,c,d}}' parse as: literal '{' + enum {a,b,c,d} + literal '}'.
Enable the previously commented-out test case for this pattern.
Assisted-by: Claude Opus 4.6 via GitHub Copilot
…onGlob
Add expand() method to BetterGlob::GlobString that performs cartesian product
expansion of enum globs with a configurable max_expansion guard (default 1000)
to prevent combinatorial explosion. Single-element enums like {test} are treated
as literals (matching bash behavior). Non-enum expressions (wildcards, ranges,
constants) are passed through as literal text.
Migrate the two production callers in StorageFile and StorageObjectStorageSource
from the old expandSelectionGlob to the new BetterGlob::expand().
Assisted-by: Claude Opus 4.6 via GitHub Copilot
…ate regex in StorageFile
Replace re2::RE2 compilation and FullMatch calls in listFilesWithRegexpMatchingImpl
and getArchiveInfo with GlobString::matches(), which walks the parsed expression
list directly. This avoids O(N) regex alternations for range patterns (e.g.
{1..1000} generated '(1|2|...|1000)') in favor of O(1) numeric bounds checks,
and removes the need for a mutex on the archive filter lambda since matches()
is const/thread-safe. Removes re2.h include from StorageFile.cpp entirely.
Assisted-by: Claude Opus 4.6 via GitHub Copilot
Fix greedy digit consumption in matchesImpl() that prevented consecutive
non-padded ranges like {0..9}{0..9}{0..9} from matching correctly.
The first range would consume all available digits, leaving none for
subsequent ranges.
For padded ranges, consume exactly pad_width digits (deterministic).
For non-padded ranges, try each possible digit count with backtracking,
similar to how wildcard '*' matching works.
Also extend expand() with expand_ranges parameter for expanding range
expressions into concrete values (with zero-padding support), and add
isFullyExpandable() for detecting globs that can be fully enumerated.
Assisted-by: Claude Opus 4.6 via GitHub Copilot
…hes() Replace all re2::RE2 usage in StorageObjectStorageSource and ObjectStorageQueueSource with BetterGlob::GlobString::matches() for direct AST-based matching. Expand the KeysIterator optimization path: globs with only constants, enums, and ranges (no wildcards) are now fully expanded via expand() with expand_ranges=true, enabling direct key lookups instead of LIST + filtering. Assisted-by: Claude Opus 4.6 via GitHub Copilot
Wire the existing glob_expansion_max_elements user-facing setting into both production callers of BetterGlob::expand() (StorageFile and StorageObjectStorageSource) so users can control the maximum glob expansion cardinality. Previously both callers used a hardcoded DEFAULT_MAX_EXPANSION of 1 billion, ignoring the setting entirely. Reduce DEFAULT_MAX_EXPANSION from 1 billion to 1000 to match the setting default. Update the setting description to reflect its broader scope beyond just address expansion. Assisted-by: Claude Opus 4.6 via GitHub Copilot
GlobString stores string_views pointing into its input_data member. The compiler-generated copy constructor would copy input_data to a new address while string_views still reference the old buffer, causing dangling references. Move could also break due to SSO. Delete copy constructor/assignment and define move constructor/assignment that re-parse after moving input_data so string_views always point into the owning object's string. Assisted-by: Claude Opus 4.6 via GitHub Copilot
Rename BetterGlob namespace to GlobAST. Introduce GlobMatcher wrapper class that delegates to either GlobAST::GlobString (new) or re2::RE2 (legacy) based on the use_glob_ast_parser setting (default true). All call sites in StorageFile, StorageObjectStorageSource, and ObjectStorageQueueSource now gate between new and legacy code paths. Remove re2.h include from parseGlobs.h (use forward declaration). Add use_glob_ast_parser to SettingsChangesHistory for 26.2. Assisted-by: Claude Opus 4.6 via GitHub Copilot
The error code was declared but never used in this file, causing a style check failure. Assisted-by: Claude Opus 4.6 via GitHub Copilot
When the AST glob parser's enum expansion exceeds `glob_expansion_max_elements`,
`listFilesWithRegexpMatching` traverses the unexpanded pattern once instead of
throwing. That traversal splits the pattern at every raw `/`, so an enum whose
alternatives span path segments (e.g. `{a/b,c/d}.csv`) is cut apart: the first
segment becomes the impossible `{a`, and the query silently returns no rows for
`file`, `fileCluster`, and `INFILE`. Lowering `glob_expansion_max_elements` thus
dropped valid local-file matches without any error.
Fail closed instead: the new `GlobAST::GlobString::hasSlashInsideEnums` detects
such patterns and the fallback throws `BAD_ARGUMENTS` naming the setting, so the
wrong file set is never returned. Enums that stay inside one path segment keep
using the unexpanded traversal as before.
Tests: gtest `GlobASTSlashInsideEnums` and stateless
`04839_glob_ast_expansion_cap_slash_enum` (verified that the over-cap query
returns 0 rows without the guard and `BAD_ARGUMENTS` with it).
|
🕵 Triage of the two CI reds on
This push also merges master (459 commits, no conflicts) and fixes the sole blocking AI-review Major — the over-cap glob expansion fallback now fails closed for enums that span path segments (see the review thread on |
The test wrote a new logger config, slept a fixed 3 seconds and expected the asynchronous config reloader to have already applied the `trace` level, so on slow runs (e.g. MSan) the final assertion saw zero `<Trace>` lines: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=91062&sha=5bd33a1f41d843f69d93cb75e2192bb668e61368&name_0=PR&name_1=Integration%20tests%20%28amd_msan%2C%204%2F8%29 Related: ClickHouse#91062 Poll for up to a minute until trace logging becomes active instead. (cherry picked from commit 0b51ec0)
…listing paths The description said the setting applies to per-query table-function paths such as `s3` wholesale, but object-storage writes (`StorageObjectStorage::write`/`truncate`) and `partition_strategy` validation (`initPartitionStrategy`) always classify the path with the legacy parser, even for table functions. Call these exceptions out explicitly. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Triage of the CI failures on c0c0f92 (all unrelated to this PR — the
@groeneai, investigate these failures and provide fixes in separate PRs if none are in progress yet; if a fix is already in progress, link it here. Also pushed: the review fix narrowing the |
|
Both are already owned.
Hung |
|
Fixing PR for the hung |
clang-tidy 22 on master introduced `bugprone-random-generator-seed` and now flags the deterministic fuzzer seed despite the existing `cert-msc32-c`/ `cert-msc51-cpp` suppressions - add the new check to the NOLINT list. Also use `contains` instead of `find != npos` per `readability-container-contains`. Fixes Build (arm_tidy): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=91062&sha=ee29a6d477a48eb0c6f35948dce6edc09d035891&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: #91062 Co-Authored-By: Claude Fable 5 <[email protected]>
The inner-archive matcher and the `file` engine split
(`splitToArchivePathAndPathInArchive`) were already setting-aware, but the
outer archive-vs-plain split for object-storage paths in
`getURIAndArchivePattern` still raw-scanned the left side of `::` for `*?{`,
so with `allow_archive_path_syntax = 1` and `use_glob_ast_parser = 1` a
per-query path like `data_{x}::foo.csv` (literal text to the AST parser) was
still torn into archive `data_{x}` plus inner path `foo.csv` before
`ArchiveIterator` ran, and `s3` / `url` reads could open the wrong object.
`getURIAndArchivePattern` now takes the parser choice and uses
`GlobAST::GlobString::hasGlobs` for the glob-capability check under the AST
parser; `S3::URI` forwards it, and the `s3` / `url` per-query paths and the
cluster `ReadTaskIterator` re-split pass the session setting. Stored tables,
`S3Queue` tables and data-lake catalog tables keep the legacy classification
of their persisted/catalog paths: `contextWithPinnedGlobParser` moved from
`StorageObjectStorage.cpp` to `Storages/ObjectStorage/Utils.h` and is applied
at configuration parsing in `registerStorageObjectStorage`,
`registerQueueStorage`, `DatabaseDataLake` and `GlueCatalog`.
Tests: gtest `GlobASTArchiveURISplit`, stateless
`04840_glob_ast_object_storage_archive_split` (minio).
Addresses the AI review Major on `StorageObjectStorageSource.cpp`.
PR: #91062
Co-Authored-By: Claude Fable 5 <[email protected]>
| file_source = StorageFile::FileSource::parse( | ||
| literal->value.safeGet<String>(), | ||
| factory_args.getLocalContext(), | ||
| /* allow_archive_path_syntax = */ {}, |
There was a problem hiding this comment.
This still leaves the persisted ENGINE = File path dependent on the session allow_archive_path_syntax setting. registerStorageFile now pins use_glob_ast_parser, but it passes no override for allow_archive_path_syntax, so FileSource::parse re-reads that setting on every ATTACH / startup through lines 1148-1155.
Concrete trace: create ENGINE = File(..., 'archive.zip::data.csv') under allow_archive_path_syntax = 1, then DETACH and ATTACH it under allow_archive_path_syntax = 0. The same stored DDL now stops splitting archive.zip::data.csv into archive + inner path and instead looks for a literal filename with :: in it. The reverse flip is possible too.
That breaks the metadata-stability invariant this PR is trying to establish for stored paths. Could we persist the archive-syntax choice (or reject ambiguous stored :: paths) instead of letting ATTACH / restart re-interpret them from the current session setting?
There was a problem hiding this comment.
🕵 This is a real gap, but it is pre-existing master behavior, independent of this PR: FileSource::parse reads allow_archive_path_syntax from the current context whenever no explicit override is passed, and registerStorageFile passes none — on master exactly as on this branch. The ATTACH flip in your trace reproduces on master without any of this PR's code. This PR neither introduced the setting nor changed how it is (not) persisted; it only pins the choice its own new experimental setting makes.
Persisting the archive-syntax choice (or rejecting ambiguous stored :: paths at CREATE time) is a metadata/compatibility design decision that deserves its own change, not a rider on an experimental glob parser. I have filed #114491 to track it for all affected engines (File, S3, URL, S3Queue, data lakes).
| StorageObjectStorageConfiguration::initialize(*configuration, args.engine_args, context, false, &args.table_id); | ||
| /// Stored tables classify their persisted path with the legacy glob parser regardless of | ||
| /// the session `use_glob_ast_parser` (see `contextWithPinnedGlobParser`). | ||
| StorageObjectStorageConfiguration::initialize( |
There was a problem hiding this comment.
This does not make the stored object-storage path fully stable across ATTACH / restart yet. contextWithPinnedGlobParser only forces use_glob_ast_parser = 0, but StorageObjectStorageConfiguration::initialize still reaches S3StorageParsedArguments::fromAST / StorageWebConfiguration::setNamespaceFromURL, which take the archive :: split from the current allow_archive_path_syntax setting.
Concrete trace: create ENGINE = S3 (or ENGINE = URL) on archive.zip::data.csv with allow_archive_path_syntax = 1, then load the same stored definition under allow_archive_path_syntax = 0. The re-parse no longer splits the path into archive + inner pattern and instead reads the literal key archive.zip::data.csv; if the settings are flipped the other way, a literal :: key starts being treated as archive syntax. S3Queue and the catalog-backed data-lake paths that now reuse this helper have the same problem.
So the persisted archive-syntax semantics are still session-dependent even though the glob parser choice is pinned. Could we persist the archive-syntax choice for stored metadata (or reject ambiguous stored :: paths) instead of only pinning use_glob_ast_parser?
There was a problem hiding this comment.
🕵 Same class as the StorageFile thread, and likewise pre-existing master behavior rather than a gap this PR introduced: on master, S3StorageParsedArguments::fromAST already passes settings[Setting::allow_archive_path_syntax] into S3::URI, and StorageWebConfiguration::setNamespaceFromURL gates the split on the same session setting — the ATTACH flip reproduces without any of this PR's code. contextWithPinnedGlobParser pins only the setting this PR adds, because that is the invariant this PR can establish without changing GA semantics: pinning allow_archive_path_syntax to any fixed value would change behavior for existing stored tables (the setting is precisely the compat escape hatch for literal :: keys), and persisting it is a metadata design decision.
Tracked separately for all affected engines in #114491.
…b to an exact key
The test asserted that the legacy parser returns 0 rows for
`data_{x}::foo.csv` (archive glob matching nothing), but the legacy path
takes the exact-key expansion shortcut: `hasExactlyOneBracketsExpansion`
accepts the single brace group, `expandSelectionGlob` turns the archive
part into the exact key `data_x`, and the strict `KeysIterator` read
throws `S3_ERROR` on the missing object. This is master behavior,
unchanged by this PR; the expectation was wrong.
The discriminating pattern is now `data_{x}_{y}`: with two brace groups
the legacy parser cannot expand (it lists and matches nothing, 0 rows),
while the AST parser still sees pure constant text (no split, exact-key
read fails). The genuine-glob case similarly moves from `data_{a,b}`
(which both parsers expand to exact keys) to `data_{a,b}_{c,d}` (which
both parsers list). The single-brace case stays as an error pin for
both parsers.
Failed in CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=91062&sha=1673e1f67c5dcca7a6ceec4a42bc6faed55f9f5b&name_0=PR
PR: #91062
Co-Authored-By: Claude Fable 5 <[email protected]>
| archive_pattern.reset(); | ||
| if (context->getSettingsRef()[Setting::allow_archive_path_syntax]) | ||
| std::tie(url, archive_pattern) = getURIAndArchivePattern(raw_url); | ||
| std::tie(url, archive_pattern) = getURIAndArchivePattern(raw_url, context->getSettingsRef()[Setting::use_glob_ast_parser]); |
There was a problem hiding this comment.
StorageWebConfiguration::setNamespaceFromURL is now keyed off use_glob_ast_parser, but stored ENGINE = URL tables still build this configuration from the raw session context in StorageURL.cpp:2618-2619 instead of contextWithPinnedGlobParser().
Concrete trace:
SET allow_experimental_url_wildcard_from_index_pages = 1, allow_archive_path_syntax = 1, use_glob_ast_parser = 1;CREATE TABLE t ENGINE = URL('http://host/data_{x}::foo*.csv', CSV, 'c1 Int32').- Here
getURIAndArchivePattern(..., true)leavesdata_{x}::foo*.csvunsplit because{x}is literal toGlobAST, soarchive_patternstays empty. ATTACH TABLE tunderuse_glob_ast_parser = 0reparses the same stored URL throughStorageURL.cppand now splits it into archivedata_{x}plus inner globfoo*.csv.
At that point the same persisted DDL flips between plain-path and archive semantics, so the table can read a different object set or fail on a non-archive key. The later read-time pin in StorageObjectStorage cannot repair this because isArchive() was already fixed during configuration parsing. URL needs the same create/attach-time pinning as registerStorageObjectStorage / registerQueueStorage, plus a DETACH / ATTACH regression.
There was a problem hiding this comment.
Confirmed by measurement, using this PR's own Build (amd_debug) artifact at efc06520 (v26.8.1.1, build id 581f7504). One session, same persisted DDL:
SET allow_experimental_url_wildcard_from_index_pages=1, allow_archive_path_syntax=1, use_glob_ast_parser=1;
CREATE TABLE t (c1 Int32) ENGINE = URL('http://127.0.0.1:PORT/data_{x}::foo*.csv', CSV);
SELECT groupArray(c1) FROM t; -- [] (plain-path semantics)
DETACH TABLE t; SET use_glob_ast_parser = 0; ATTACH TABLE t;
SELECT groupArray(c1) FROM t; -- Code: 643 CANNOT_UNPACK_ARCHIVE "Cannot determine the type of archive data_{x}"create_table_query is byte-identical before and after the ATTACH, and it flips in both directions (create=0/attach=1 gives the mirror image). Fixture: data_{x} is a real zip whose member foo1.csv holds 11,12, plus a plain object literally named data_{x}::foo1.csv holding 77.
Two things that are easy to get wrong when writing the regression:
-
The archive name must have no supported extension.
getURIAndArchivePatternORshasSupportedArchiveExtension(left)before the glob check, so adata_{x}.zipleft side splits under both parsers. I first built the fixture that way and all four create/attach arms returned[11,12]identically, i.e. the test passes while pinning nothing. The extensionless name is the only shape where thepath_to_archive_has_globsterm decides the outcome: legacy matchesfind_first_of("*?{"),GlobAST::GlobString("data_{x}").hasGlobs()is false. -
An in-session
SETdoes not exercise the ATTACH path inclickhouse local, since the startup ATTACH runs before the file's first statement. TheDETACH/SET/ATTACHform above does work; for a process-level arm,--use_glob_ast_parser=Nhas to be passed at startup.
Scope, for whoever picks this up: the URL engine only reaches StorageWebConfiguration when urlPathHasListableGlobs sees a * in the path and http_method is empty, so the plain StorageURL path does not diverge (measured [77] in both directions across DETACH/ATTACH). Of the stored-table registrars, StorageURL.cpp:2619 is the only remaining unpinned Configuration::initialize; TableFunctionURL being unpinned looks correct, since table functions are per-query by design and is_table_function already guards the read-time pins. use_glob_ast_parser does not exist on master (0 occurrences in Settings.cpp there, this PR declares it), so this is pre-merge only, with nothing released or backportable.
|
Dear @alexey-milovidov, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Introduces
GlobAST, a regex-free glob parser, and wires it into the file and object-storage listing paths. It is off by default (the experimentaluse_glob_ast_parsersetting), somasterbehavior is unchanged — the goal is to land the parser and all the wiring now so that enabling it later is a one-setting switch.The legacy engine builds a regex (
makeRegexpPatternFromGlobs+re2::RE2), which has noticeable downsides:s3[Cluster]('s3://bucket/prefix/{a.json,b.json}')S3 list request count #73333)file/s3/...with numeric ranges in globs #43456){a}/{-}).GlobASTparses a pattern once into typed expressions (constant,?/*/**,{M..N}range,{a,b,…}enum) and matches/expands directly — ranges by numeric bounds checks, enum-only globs by expanding to concrete keys. AGlobMatcherfront-end selects the new or legacy backend per the setting, so call sites are unchanged; the grammar is documented inparseGlobs.h.Tested by unit tests, a differential fuzzer against the legacy matcher (
GlobASTLegacyMatchFuzz), and a stateless parity test.Related: #73333
Related: #43456
Related: #80950
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added an experimental setting
use_glob_ast_parser(defaultfalse) that switches glob matching for thefile/s3/object-storage listing paths to a new regex-free parser (GlobAST), avoiding regex blow-up on large numeric ranges and listing fewer keys for brace-enumeration globs.