Repository navigation
Bound the {a,b,c} glob expansion in paths - #118467
Conversation
The `{a,b,c}` selector globs of a path are not compiled into a regexp; they
are enumerated into separate paths by `expandSelectionGlob`. The enumeration
is a Cartesian product of the groups and had no bound in either time or
memory, so `SELECT * FROM file(repeat('{a,b}', 100))` asks for 2^100 paths
and eats all the memory of the server without ever returning. It cannot be
interrupted: the expansion runs while the table function is being resolved,
where `max_execution_time` cancellation does not reach it, and it is not
stopped by `max_memory_usage` either.
The AST fuzzer found it as `SELECT * FROM file(file('data.jsonl'),
'data.jsonl')`: the `file` function reads the file into a string, the `file`
table function takes that string as a path, and every `{...}` of a
`JSONEachRow` file is a glob group. The server went from 1 GiB to 45 GiB of
RSS in 25 seconds and was OOM-killed.
Refuse a pattern that asks for more than 100000 paths, for more than 64 MiB
of paths, or that has more than 1000 groups. The limits are constants, not
settings, because `Common/parseGlobs.cpp` has no access to a `Context`, and
because they guard against a pathological pattern rather than being a knob:
the smallest of them is two orders of magnitude above any plausible glob.
Also split the pattern into its groups once instead of once per produced
path. Which text is a group does not depend on the alternatives picked for
the groups before it, so the recursion was re-scanning and re-copying the
whole pattern at every level of every branch - quadratic in the pattern
size, and the reason `repeat('{a,b}', 100)` still needed 22 seconds of CPU
to reach the path limit. It is now rejected without generating anything.
The rewrite is behavior-preserving: a differential check against the
previous implementation over 700000 random patterns reports identical
output, and identical throw/no-throw, on every one of them.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=7a5d669906cc37af41a4260c942417d72d880bfe&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_debug%29
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [6f5fe0e] Summary: ✅
AI ReviewSummaryThis PR bounds selector-glob expansion and range-glob regexp generation, and it now keeps hive-partition sample-path inference aligned with the actual object-storage reader across the pure-brace, regexp, and refusal paths. I re-checked the current diff and every prior inline thread against the current code; the earlier analysis/execution mismatches appear addressed, and the added gtests plus stateless coverage are proportionate to the touched invariants. Final Verdict
LLVM Coverage ReportMeasured on commit 6f5fe0e.
Changed lines: Changed C/C++ lines covered: 193/195 (98.97%) · Uncovered code |
Build profile diff (arm_release)Commit See the job log for details. |
`MAX_EXPANDED_PATHS` was checked only after a group had been parsed, so one selector with an enormous number of alternatives - which is what a whole file passed as a path by `file(file(...))` looks like - still cost one offset and one `string_view` per alternative before the limit was reached. The memory `expandSelectionGlob` took therefore still grew with the size of its input, even though nothing was ever expanded. Check the running Cartesian product against the number of commas seen so far, at the comma: after `k` commas the group has at least `k + 1` alternatives, so the scan stops at the comma that makes the group exceed the limit and the parsing state stays bounded by the limit rather than by the input. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Passing the pattern through a file read it back as a 2 MiB CSV line of a
million columns, and the 21 seconds the test took were all spent in schema
inference for that file, not in the glob expansion the case is about. Fold the
pattern in the query instead: a two-megabyte argument does not fit on a command
line anyway (`MAX_ARG_STRLEN` is 128 KiB), while `file('{' || repeat('a,',
1000000) || 'a}')` is a constant expression and reaches `expandSelectionGlob`
with the same million-alternative group. The test now takes a second.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`expandSelectionGlob` charged `MAX_EXPANDED_BYTES` the length of each
produced path but allocated the length of the whole pattern for it, so a
group with one long alternative among many short ones defeated the
bound. A group of 100000 alternatives whose first one is 1 MiB is
charged ~1 MiB and holds ~120 GiB:
SELECT * FROM file('{' || repeat('A', 1000000) || ','
|| repeat('a,', 99998) || 'a}');
Charge and reserve the length the path actually has, and throw before
allocating rather than after. The pattern above now costs what any other
100000-path expansion costs.
Looking for the next glob ran both regexps over the whole remaining
pattern once per glob, so the scan alone cost their product, and the
pattern is not bounded. Neither answer has to be recomputed that often.
A `{N..M}` range glob cannot appear in a tail without appearing in the
pattern, so it is looked for once. The leftmost `{a,b,c}` match is still
the leftmost match of every tail that starts at or before it, so it is
searched for again only once the enumeration has consumed past it, and
successive searches then cover disjoint parts of the pattern. On
`repeat('{a*}', 999)` followed by a 100 MB literal this is 8131 ms ->
129 ms, and 1000 regexp calls -> 2. A differential check over 700000
random patterns reports the same answer as the previous predicate on
every tail the enumeration visits.
While there, `makeRegexpPatternFromGlobs` turns a `{N..M}` range glob
into a regexp alternation of every number of the range, with no bound at
all - the same unbounded, uncancellable, unaccounted growth, reached
from the same table functions:
SELECT * FROM file('{1..60000000}.csv');
-- 4.2 GiB RSS and 22.7 s, then CANNOT_ALLOCATE_MEMORY
Refuse a range covering more than 100000 values, which is already a
regexp of hundreds of kilobytes.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`getPathSample` needs one path to infer hive partition columns from, and
got it by expanding the whole `{a,b,c}` Cartesian product and taking the
first element. The reader does not work that way: `createFileIterator`
enumerates a pattern only when it has exactly one brace group, and
matches anything with more as a regexp. Bounding the expansion therefore
made `s3('.../{a,b}{c,d}.../x.parquet')` throw during analysis, in both
`StorageObjectStorage::getPathSample` and the cluster variant, for a
pattern the reader would have read. Neither call site catches, so the
query fails rather than losing partitioning.
Add `expandSelectionGlobFirst`, which picks the first alternative of
every group and keeps nothing else. It cannot be refused: one pass over
the pattern and a result no longer than it, whatever the groups multiply
out to. The brace scan is shared with the full expansion, so both refuse
a malformed glob identically.
`createFileIterator` and `StorageFile` keep the full expansion: they need
every path, and the former is gated on a single brace group, so its limit
matches what it has to enumerate.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`MAX_RANGE_GLOB_VALUES` caps one range, and nothing capped how many
ranges a path may hold, so the invariant it was meant to establish did
not hold. Every range of `repeat('{1..100000}', 128)` is within the
per-range cap, yet 1408 bytes of path emitted 75 MB of alternations
before RE2 saw any of it - the same uncancellable, unaccounted growth,
reached the same way.
Cap the total as well, at `MAX_REGEXP_BYTES`. RE2's own default memory
budget is 8 MiB, so a larger regexp is not one it could compile, and the
overshoot is one range's worth because a single range is still capped.
The per-range cap could also be stepped around: for the single value
2^64-1 the difference is zero, so it passed the cap, and `range_begin +
1` then wrapped and the loop enumerated from zero. Count the iterations
instead of comparing against `range_end`, so the increment cannot wrap.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Address review: `getPathSample` took every pure-brace path through `expandSelectionGlobFirst`, but `StorageObjectStorageSource::createFileIterator` still materializes a pattern with exactly one brace group through `expandSelectionGlob`. With `use_hive_partitioning = 1` analysis could then infer hive partition columns - and persist them in a table definition - from a path that the reader always rejects on `MAX_EXPANDED_PATHS` / `MAX_EXPANDED_BYTES`. Mirror the reader's split instead: keep the limit-enforcing expansion for `hasExactlyOneBracketsExpansion`, and reserve the first-alternative fast path for the shapes the reader matches as a regexp (multiple groups, or web object storage, which always goes through `GlobIterator`). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Both picked up, with the measurements on each: #120202 and #121048. Neither is waiting on a review, and the order matters:
New here since your comment: I cannot request reviewers on pull requests I do not own, so that part stays with you. |
…e status Address review: `status >= 500` is not "the cluster never answered". The server reports several of its own verdicts on a query as a 500 - 164 for a setting change on a readonly profile, 158 for `max_rows_to_read`, 241 for the memory limit, 395 for a `throwIf` after the result started - so a real defect in one of the `Build profile diff` reads would have reported the check green. `X-ClickHouse-Exception-Code` is the exact discriminator: it is present on every answer the server produced and absent when the answer did not come from it, whatever the status. `LogCluster._classify` keys on it - absent means a gateway, a proxy or a closed connection (`LogClusterUnavailable`); a code in `TRANSIENT_EXCEPTION_CODES` (159, 202, 209, 241) is the shared cluster talking about its own load (`LogClusterUnavailable`); anything else is its verdict on this very query (`LogClusterQueryError`, fail closed, and the same verdict on every retry so it is not retried). 241 in the transient set also closes azat's ask on #118708 in its general form, by the exception code rather than by the coincidence that the status happens to be 500. `raise` on that verdict has to escape the loop, so `except LogClusterError: raise` precedes the generic transport handler; without it the handler catches the verdict and retries it eight times. An endpoint that never became ready is now its own `LogClusterNotReady`, a sibling of `LogClusterError` that `main` does not catch: a readiness probe that never answers is indistinguishable from a rotated password or a deleted SSM parameter, and completing green on that would blank the check fleet-wide for as long as the condition lasts. Neither change affects the outage this pull request is about: those failures never get a response at all (`ReadTimeout`), so they end at "every POST attempt failed with an exception". Related: #118708 Related: #118467 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Merged @groeneai, thank you for the two write-ups — both decisions are made and both are acted on, so neither is waiting on me any more. #121048 ( #120202 (NATS The third red, Requesting reviewers on #121048 and #120202 is on me; I will do that. |
|
Harness sent to the fork's own suite: ClickHouse/nats.c#10, test only on top of On #121048 I posted one dissent from the patch you adopted, in favour of the AI Review's new finding: 159 and 209 should come out of Neither PR needs anything from me now. #120202 needs a re-run of |
|
📊 Cloud Performance Report ✅ AI verdict: This PR bounds path-glob expansion ( clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…le path instead of swallowing it
`StorageObjectStorage` caught every exception from `getPathSample` as a listing failure and only
dropped hive partition inference. Since `expandSelectionGlob` refuses an unbounded `{a,b,c}` group
with `BAD_ARGUMENTS`, that left analysis and execution disagreeing: with `use_hive_partitioning = 1`,
`SELECT date FROM s3('.../{a,a,...}.tsv')` reported `UNKNOWN_IDENTIFIER`, while reading the same
path and `s3Cluster` rejected it with `BAD_ARGUMENTS`.
Rethrow `BAD_ARGUMENTS` from both fallback catches (the constructor and the deferred resolution,
where `throw_on_hive_partitioning_resolution_failure = 0` tolerates only endpoint failures): a
refused path fails the same way on every read, so it is not something the next query might not hit.
Test `05230` now expects `BAD_ARGUMENTS` from the plain table function as well as from `s3Cluster`,
so the `parallel_replicas_for_cluster_engines` pin is gone, and probes the deferred path with the
setting disabled.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 Pushed c54fa82: adopted the AI Review Major - The only red on the previous head was |
|
🕵 Merged master into the branch (531cbd0, clean; the four touched translation units compile against the merged tree). The only red on c54fa82, |
|
#119387 is unblocked. It had drifted into a merge conflict in One decision is still open from your 2026-09-12 comment there. After you called the predicate ugly I replaced it with |
… the hive sample path
A glob that is not a pure `{a,b,c}` selection is listed through `GlobIterator`, which refuses
a regexp RE2 cannot compile with `CANNOT_COMPILE_REGEXP` before anything is listed. Both
fallback catches of `StorageObjectStorage` (the constructor and
`resolveHivePartitioningSamplePathIfDeferred`) downgraded that to a listing failure, so the
plain `s3` table function reported `UNKNOWN_IDENTIFIER` for a hive column while `s3Cluster` and
the reader reported the real refusal. Both catches now rethrow it, like `BAD_ARGUMENTS`.
New test `05237_s3_glob_uncompilable_regexp_sample_path`; the plain `s3` probe gives code 47
with the previous binary and 427 with this one.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The reader lists everything under the prefix before the first brace group, which was the bucket root. With the s3 storage that root holds the data of the server's own disks, so the listing was slow (396 s locally) and in the private flaky check MinIO answered `500 Internal Server Error`, failing the test on the `AWSClient` error in stderr (18 of 200 runs). ClickHouse/clickhouse-private#73005 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Pushed 4868d64:
@groeneai thanks, the #119387 design question is for that PR, nothing is needed here. |
…matches it
Address review: for a pattern with several `{a,b,c}` groups the reader matches the path as the
regexp `makeRegexpPatternFromGlobs` builds, and a selector glob does not always agree with it.
An empty alternative (`{,a}`), an empty group or a one-character group is literal text for the
regexp, and RE2 refuses an alternation too large to compile. `getPathSample` in both
`StorageObjectStorage` and `StorageObjectStorageCluster` took the first alternative of every group
anyway, so hive partition columns were resolved - and persisted for a table definition - from a
path the reader never reads.
The new `tryExpandSelectionGlobFirstMatchedByRegexp` returns the first alternative only when that
regexp compiles and matches it; otherwise the path is listed the same way the reader lists it, so
an uncompilable regexp is reported as `CANNOT_COMPILE_REGEXP` and a literal-brace path resolves no
hive columns when nothing matches. Test `05241` is control-proved: the binary without this change
resolves `date` for `date={2020-01-01,2020-01-02}/{,x}{a,b}.tsv`.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The flaky check under TSan reported `Test runs too long (> 180s)`: most of the time is spent in
`makeRegexpPatternFromGlobs` and in RE2 on a 3.4 MB pattern, five times. RE2 gives up from about
50000 alternatives of 16 characters, so 100000 are enough; the `s3Cluster` probe (a plain listing,
no code of this PR) and the `SELECT` repeating the `DESC` of the same deferred table are dropped.
Adds a case for two `{a,b,c}` groups, where the sample path must not be taken from the first
alternatives when the reader's regexp does not compile (control-proved: `DESC` succeeded before).
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118467&sha=4868d64915a62c6adc207d4113ddb4cb7e94e7a7&name_0=PR
Related: #118467
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The
{a,b,c}selector globs of a path are not compiled into a regexp; they are enumerated into separate paths byexpandSelectionGlob. The enumeration is a Cartesian product of the groups and had no bound at all, in either time or memory:It is reached from
file, froms3/azure/hdfs(StorageObjectStorage::getPathSample) and fromStorageObjectStorageSource::createFileIterator. Nothing on the way bounds it: the expansion runs while the table function is being resolved, somax_execution_timecancellation does not reach it (the server log below showsCancellationChecker: Cancelling the task because of the timeouthaving no effect), and it is not stopped bymax_memory_usageeither. The server grows until it is OOM-killed.The AST fuzzer found it as
SELECT * FROM file(file('data.jsonl'), 'data.jsonl'): thefilefunction reads the file into a string, thefiletable function takes that string as a path, and every{...}of aJSONEachRowfile is a glob group. On the failure below the file had 130818 of them, and the server went from 1 GiB to 45 GiB of RSS in 25 seconds:The expansion now refuses a pattern that asks for more than 100000 paths, for more than 64 MiB of paths, or that has more than 1000 groups. The limits are constants rather than settings because
Common/parseGlobs.cpphas no access to aContext, and because they are a guard against a pathological pattern rather than a knob: the smallest of them is two orders of magnitude above any plausible glob.The byte limit is charged the length each path actually has, and not the length of the pattern it comes from. A group with one long alternative among many short ones makes the two differ without bound, so reserving the pattern for every path would hold
number of paths * pattern sizewhile the charged amount stays small: a group of 100000 alternatives whose first one is 1 MiB is charged about 1 MiB and would hold about 120 GiB. The refusal also happens before the path is allocated rather than after it.While there, the enumeration itself is rewritten to split the pattern into its groups once instead of once per produced path. Which text is a group does not depend on the alternatives picked for the groups before it, so the recursion was re-scanning and re-copying the whole pattern at every level of every branch — quadratic in the pattern size, and the reason
repeat('{a,b}', 100)still needed 22 seconds of CPU to reach the 100000-path limit. It is now rejected without generating anything.Looking for the next group ran both regexps over the whole remaining pattern once per group, so the scan alone cost their product, and the pattern is not bounded either —
file(file(...))makes it as long as a file. Neither answer has to be recomputed that often. A{N..M}range glob cannot appear in a tail of the pattern without appearing in the pattern, so it is looked for once; and the leftmost{a,b,c}match is still the leftmost match of every tail that starts at or before it, so it is searched for again only once the enumeration has consumed past it, and successive searches then cover disjoint parts of the pattern. Onrepeat('{a*}', 999)followed by a 100 MB literal that is 8131 ms -> 129 ms, and 1000 regexp calls -> 2.{N..M}is the other half of the same problem. A range glob is not enumerated into separate paths —makeRegexpPatternFromGlobsturns it into a regexp alternation of every number of the range — and that had no bound at all, reached from the same table functions and just as uncancellable and unaccounted:A range covering more than 100000 values is refused, and so is a pattern whose ranges emit more than 8 MiB of regexp in total: capping one range does not cap how many of them a path may hold, and every range of
repeat('{1..100000}', 128)is within the per-range cap while those 1408 bytes of path emit 75 MB of alternations. RE2's own default memory budget is 8 MiB, so a larger regexp is not one it could compile. The enumeration is also counted rather than compared against the end of the range, because for the single value 2^64-1 the difference is zero - the per-range cap passes - and the increment then wrapped and the loop ran from zero.One caller must not be bounded this way.
getPathSampleneeds a single path to infer hive partition columns from, and got it by expanding the whole Cartesian product and taking the first element, while the reader enumerates a pattern only when it has exactly one brace group and matches anything with more as a regexp. Bounding the expansion therefore faileds3('.../{a,b}{c,d}.../x.parquet')during analysis, in bothStorageObjectStorage::getPathSampleand the cluster variant, for a pattern the reader would have read.expandSelectionGlobFirstpicks the first alternative of every group and keeps nothing else, so it cannot be refused: one pass over the pattern, and a result no longer than it.createFileIteratorandStorageFilekeep the full expansion, since they need every path.The rewrite is behavior-preserving: a differential check against the previous implementation over 700000 random patterns (comma-rich short patterns, and long patterns with deeply nested groups) reports identical output, and identical throw/no-throw, on every one of them. The regexp caching is checked the same way: over 700000 random patterns it gives the same answer as the uncached predicate on every tail the enumeration visits.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=7a5d669906cc37af41a4260c942417d72d880bfe&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_debug%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed unbounded memory and CPU usage when a path passed to
file,s3,azureBlobStorageorhdfscontains many{a,b,c}glob groups or long{N..M}ranges. A path with several{a,b,c}groups expands to the Cartesian product of the groups, and a{N..M}range expands to a regexp listing every number of the range, so a pattern of a few hundred bytes could exhaust the memory of the server; the expansion was neither cancellable nor accounted bymax_memory_usage. Such a path is now rejected with an error. The limits are 100000 expanded paths, 64 MiB of expanded paths, 1000{a,b,c}groups, 100000 values in a single{N..M}range, and 8 MiB of regexp for all the ranges of a path together.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/118467]
Version info
26.10.1.552-master(included in26.10and later)