Repository navigation
Expand url glob patterns lazily - #115680
Conversation
A pattern passed to `url` was expanded into the full direct product before the
query started, so `glob_expansion_max_elements` limited how large a pattern was
allowed to be rather than how much of it a query needed. A query that stops
early paid for the whole address space up front, and was rejected outright when
that space was large:
SELECT * FROM url('https://.../pageviews-20200101-{0..10000}{0..10000}00.gz', LineAsString) LIMIT 3
`RemoteDescriptionGenerator` produces the addresses of a pattern one at a time
instead. Numeric intervals stay symbolic, so `{0..10000}{0..10000}` costs two
factors rather than a hundred million strings, and the odometer over them walks
the same order the materializing code produced - the last factor varies fastest.
`parseRemoteDescription` is now a thin wrapper that checks the arithmetic total
and drains the generator, so there is still one parser of the syntax and
`remote`, `mysql` and `postgresql`, which need every address at once to build a
cluster, behave exactly as before, down to the error message.
Three places on the `url` path stopped materializing:
- `getSampleURI` takes a single address. It only reads hive partitioning and
virtual columns off a path, and used to expand the whole pattern to look at
its first element.
- `StorageURLSource::DisclosedGlobIterator` generates in batches and applies the
`_path` / `_file` filter to each. A pattern that fits into one batch keeps the
exact post-filter size, which is what empty-glob detection and the number of
streams are derived from, so nothing observable changes for it.
- Schema inference pulls addresses through a producer and stops at the first one
it can read.
The limit therefore applies to the addresses a query actually reads. The batch
is `min(1000, glob_expansion_max_elements)` and the default limit is 1000, so
every pattern that works today is still served in a single batch and behaves
bit for bit as it did; only patterns that used to be rejected behave
differently. Groups holding the separator, such as `{a,b}` in `{a,b}{c,d}`, are
still expanded eagerly and bounded by the limit, because the direct product
needs their alternatives up front - a `..` anywhere inside braces makes the
whole group a numeric interval, so those groups can only hold literal text.
Related: #49234
|
Workflow [PR], commit [3c83e62] Summary: ✅
AI ReviewSummaryThis PR replaces eager Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 3c83e62.
Changed lines: Changed C/C++ lines covered: 300/312 (96.15%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes9 object files changed (+35.54 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units35 translation units recompiled, 246 s compile time in total, 35 of them have a recent master baseline. |
The lazy-expansion paragraph was written into the generated
`docs/reference/functions/table-functions/url.mdx` and
`docs/reference/settings/session-settings/other.mdx`, which the next
regeneration would drop again, and which fails the "No direct edits to
generated or read-only docs" subtest of `Docs check (Mintlify)`. Both generated
hunks are reverted; the paragraph now lives in the `Globs in URL` section of the
`url` `FunctionDocumentation` in `src/TableFunctions/TableFunctionURL.cpp`,
next to the `glob_expansion_max_elements` doc string in `src/Core/Settings.cpp`
that was already the source of the settings page.
Both texts now also say what the limit counts: a `_path` or `_file` predicate is
applied to every generated address, so the ones it rejects count against
`glob_expansion_max_elements` as well - only reading the matching ones is
skipped. The addresses have to be generated before they can be pruned, and an
unbounded generator would let a predicate matching nothing walk the whole
address space of `{0..10000}{0..10000}`. Two cases in
`05023_lazy_url_glob_expansion` pin that behaviour.
|
🕵 Triage of the reds on
|
…sion # Conflicts: # src/Common/parseRemoteDescription.cpp
…f the first batch When the pattern does not fit into the first batch, `DisclosedGlobIterator::size` advertised `min(totalCount, glob_expansion_max_elements)`, and `ReadFromURL::createIterator` started that many streams. A sparse `_path` / `_file` predicate can leave fewer survivors in the buffered batch than there are streams, and every extra stream asks the generator for an address as soon as it starts, pushing generation past the limit and raising `too many result addresses` even though everything the query reads was generated within it. Cap the streams by the buffered survivors when a filter pruned a non-exhausted batch. Co-Authored-By: Claude Fable 5 <[email protected]>
… pass `URLReadBufferIterator` ran the filename-based format detection and the `DEFAULT`-mode schema cache lookup only over the addresses known on the first iteration, so the batches `produceMoreURLs` appends went straight to network reads. Scan every appended batch the same way before reading from it, as the materializing iterator did for all addresses at once. Co-Authored-By: Claude Fable 5 <[email protected]>
…treams When a `_path` / `_file` predicate pruned the whole first batch of generated addresses, `DisclosedGlobIterator::size` capped the number of streams at the buffered survivors, serializing multi-batch globs whose matches appear after the first batch. The new `sizeForStreams` prefetches batches until the requested number of survivors is buffered, the pattern is exhausted, or the limit is reached, so those queries keep their parallelism. Rejected addresses still count against `glob_expansion_max_elements`, and nothing is generated past the limit while sizing. The test pins the pipeline shape for survivors of the second batch, and also mentions the lazy generation in the `URL` engine documentation. #115680 Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
`05044_url_glob_schema_cache_after_first_batch` walked its 1000 empty first-batch addresses through full queries against the ClickHouse server itself, which took over 300 seconds on the debug flaky-check runs and timed out. A local Python mock now serves the empty bodies, so the walk takes seconds: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115680&sha=b78db4c7eedfe14331957bf447083ecf07609bc5&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 `05043_url_glob_filtered_parallel_streams` pins the pipeline shape, but `enable_parallel_replicas` replaces the `URL` source with a cluster read, so the run with parallel replicas found no `URL` line. The setting is now disabled in the `EXPLAIN` query: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115680&sha=b78db4c7eedfe14331957bf447083ecf07609bc5&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 #115680 Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Merged
@groeneai, if the |
|
Confirmed from
My own open No stress job has been scheduled on the fresh run yet. If Evidence: |
…with one stream The `Globs in URL` example claimed that `LIMIT 1` reads the first address only. That holds when the plan uses a single stream; in the normal parallel path `ReadFromURL::createIterator` starts several `StorageURLSource`s up front and each of them takes an address from the glob iterator before the `LIMIT` cancels the reading. Pin the example with `max_threads = 1` and spell out the parallel behaviour.
|
🕵 Merged Triage of the single red on
All AI-review threads are answered and resolved; there are no other unresolved threads. |
…sion # Conflicts: # src/Storages/StorageURL.cpp
|
🕵 Merged
Triage of the two reds on
Verified locally against a private server built from this branch: |
…ivors, not the raw batch When the sets of the filter cannot be built while the pipeline is built (a `GLOBAL IN` on `_file` / `_path`), `DisclosedGlobIterator` buffered the first batch unpruned and `sizeForStreams` sized the local parallelism from it. Every stream asks for an address as soon as it starts, so a stream started for an address the filter then rejected walked the rejected tail and asked the generator past `glob_expansion_max_elements` while another stream was already reading the one survivor, failing a query whose surviving addresses were all within the limit - the very case the ready-set path already handles. While the filter is deferred, `sizeForStreams` now returns one stream, and `next` prunes the whole buffered batch in one go when the pipeline runs (the sets are ready by then) and goes back to batch-level pruning for the later batches, instead of filtering each address as it is handed out. Test `05223_url_glob_deferred_filter_single_stream` pins the single stream via `EXPLAIN PIPELINE` and the early stop under `LIMIT`. `05043_url_glob_filtered_parallel_streams` failed on the ParallelReplicas runner, where `url` becomes a cluster read: the initiator hands the addresses to one consumer per replica, and the third replica asking after the two survivors is what makes the generator report that the pattern exceeds the limit, exactly as it always did for that pattern. The early stop under test is a property of the local read, so the query pins `enable_parallel_replicas = 0` like the `EXPLAIN` above it. Addresses the review thread at #115680 (comment) and the failure in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115680&sha=38a01c80bdcf29072976b90b7c98ca8b1dbf7fc7&name_0=PR&name_1=Stateless%20tests%20(amd_llvm_coverage,%20ParallelReplicas,%20s3%20storage,%20parallel) Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 Merged Triage of the two reds on
@groeneai, please confirm the fuzzer red https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115680&sha=38a01c80bdcf29072976b90b7c98ca8b1dbf7fc7&name_0=PR&name_1=AST%20fuzzer%20(amd_release,%20oracle) is covered by #107127; if it is a different collision, provide a fix in a separate PR and link it here. |
|
Not #107127: it is a different collision, and it is already fixed on master. On that run both Measured with the CREATE TABLE v1(a String, b Date, e String) ENGINE MergeTree ORDER BY a;
CREATE TABLE v2(a String, b Date, f String) ENGINE MergeTree ORDER BY a;
INSERT INTO v1 VALUES ('k', '2018-01-01', 'E');
INSERT INTO v2 VALUES ('k', '2018-01-01', 'F');
SELECT DISTINCT * APPLY lambda(tuple(x), toTypeName(x)) FROM v1 AS p ALL INNER JOIN v2 AS q USING (a, b);
SELECT * FROM (SELECT DISTINCT * APPLY lambda(tuple(x), toTypeName(x)) FROM v1 AS p ALL INNER JOIN v2 AS q USING (a, b));That is #118739, fixed by #118825, which landed on master on 2026-09-12, three days after that run. Reverting its three lines on current master reproduces the mismatch verbatim, and with them both queries agree. #107127 fixes a different duplicate-name collision (an explicitly listed column colliding with a starred column of the same name) and does not cover this one: on master with #118825 reverted and #107127 applied, the wrapped query still disagrees with the reference (it returns no rows rather than the swapped one). That combination cannot occur on master, since #118825 is merged. The current head |
…t covers a slow reject test_native_default_session_user_with_password fails only on the amd_llvm_coverage integration shards, with "TimeoutError: timed out" at native_hello's sock.recv(1): 3 failures over 7,621 coverage rows in 30 days, across three unrelated PRs (one of them documentation-only), and 0 master failures in 90 days. A rejected native login is answered only after two symbolized stack traces are rendered. The first comes from the catch in AccessControl::authenticate (src/Access/AccessControl.cpp:629); the second from writeException (src/IO/WriteHelpers.cpp:77-85), reached through TCPHandler::runImpl's sendException (src/Server/TCPHandler.cpp:507, :531) with the server context's calculate_text_stack_trace, and the packet reaches the wire only after it. Since StackTrace::toStringCached keys on the exact frame-pointer triple, the two distinct exceptions each pay a full DWARF symbolization. In the failing job's log (PR ClickHouse#115680 / 4ee5eff, coverage 2/8) those renders took 8.59s and 10.35s, so the client's first byte arrived 18.9s after connect; a second case in the same run took 16.6s. The helper allowed 10s. Nothing here is a server defect: coverage binaries are never shipped, the same renders cost 0.04s once the DWARF is parsed, and the logging is deliberate (AccessControl.cpp:661-663). The server's handshake_timeout_milliseconds is checked only before a read (src/IO/ReadBufferFromPocoSocket.cpp:106), which is why the answer does arrive at 18.9s instead of the connection being dropped. 60s is not an arbitrary pick: 60000ms is the value this repository already uses for a handshake read deadline on a slow lane, in six places. One is 00563_shard_insert_into_remote.sql (SET handshake_timeout_ms = 60000, by Alexey Milovidov, d4fed63); four are my own merged CI fixes (01600, 02040, 03630, 03443), each commented that the default 10s handshake_timeout_ms is not enough on slow lanes; stress_tests.lib:362 uses 30s. Two samples fix the order of magnitude of a first-time symbolization on a loaded runner, not its tail, so a deadline just above the observed maximum would re-flake. The cost is bounded: this is a deadline rather than a sleep, so a passing call pays nothing, native_hello has no retry loop, and pytest.ini's timeout = 900 still catches a genuine hang. The client's own handshake_timeout_ms default is also 10s, but that setting is an SLA for a real connection deciding when to fail over. This read only observes whether a login was rejected and asserts nothing about latency, so a client-realistic deadline adds no assertion value and only decides how often the observation is lost. Alternatives rejected: suppressing either render removes deliberate diagnostics on a security-relevant path; calculate_text_stack_trace=0 in the test profile would leave render #1 at 8.59s, i.e. 86% of a 10s budget, and weaken diagnostics for the module's other tests; skipping the case under coverage deletes reject-path coverage on the flavour whose purpose is measuring it. Two other hand-rolled native Hello sites are deliberately left alone. test_interserver_marker_requires_cluster_secret rethrows in interserver mode at TCPHandler.cpp:521-526 before sendException, so the packet-gating render is structurally absent and its oracle is a closed connection; it has never failed with this signature. In test_tcp_hello_string_limits a client timeout is part of the oracle (a rejection arm returns False on socket.timeout), and that module shortens the server's handshake timeout to 3000ms on purpose. Validation: with the coverage binary from the failing job the module passes 30/30 and the three native_hello callers pass 10 times each. The failure is reproduced deterministically against a stub listener answering after 15s: before this change the helper raises TimeoutError at sock.recv(1) in 10.01s, the exact CI frame; after it, the helper returns the Exception packet at 15.00s. A never-answering stub fails at 10s before and 60.00s after, so the constant is the operative variable, and an arm answering ServerHello instead still reddens the assertion in 0.05s. The 18.9s magnitude is measured in CI and is not reproducible on an idle box, where the same binary answers a reject in 0.105s. Co-Authored-By: Claude Opus 5 <[email protected]>
…pattern fits into the limit
The previous commit (the one titled `wip` just before the `master` merge) makes
`DisclosedGlobIterator::sizeForStreams` fall back to a single stream for a deferred
filter only when the pattern can generate more addresses than
`glob_expansion_max_elements`. When the whole pattern fits into the limit, a stream
that finds nothing left simply finishes, so there is no reason to serialize the read.
A local read builds the sets of its `GLOBAL IN` predicate in `applyFilters`, before plan
optimization moves their subquery plans away, so the deferred path cannot be reached
deterministically from a test. Add the `url_glob_defer_path_filter` failpoint that forces
it, and the test `05243_url_glob_deferred_filter_within_limit_parallel` covering both sides:
`URL × 4` for `{0..1999}` with limit 2000, one `URL` stream for `{0..2000}`, exact survivors,
and the `LIMIT 1` early stop.
Addresses review: #115680 (comment) (thread PRRT_kwDOA5dJV86jVWUi)
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Merged The only red on @groeneai thanks for the fuzzer analysis: the earlier |
# Conflicts: # src/Storages/StorageURL.cpp
|
🕵 Merged Reds on
|
| while (batch.size() - batch_index < requested && !exhausted && generated < max_addresses_upper_bound) | ||
| fillBatch(); | ||
|
|
||
| auto uri = uris[current_index]; | ||
| if (deferred_filter_actions) | ||
| /// Never zero: when everything buffered was pruned and the limit is reached, the one stream | ||
| /// left is the one that asks past the limit and turns that into the error it always was. | ||
| return std::max<size_t>(1, batch.size() - batch_index); |
There was a problem hiding this comment.
sizeForStreams still starts one source per buffered survivor even after DisclosedGlobIterator has already spent the whole glob_expansion_max_elements budget and the pattern continues past it.
A concrete case is url('http://host/prefix_{0..19}.tsv', ...) WHERE _file IN ('prefix_5.tsv', 'prefix_7.tsv') SETTINGS glob_expansion_max_elements = 10, max_threads = 4 with one of the two matching files larger than the other. This path returns 2, so two StorageURLSources start. As soon as the faster source finishes its file it re-enters initialize(), glob_iterator->next() falls through to fillBatch(), and the target == 0 -> 1 probe asks RemoteDescriptionGenerator for the 11th URL. The query then throws too many result addresses even though every file it actually needed was already inside the allowed ten generated URLs.
Unless the iterator starts tracking in-flight assignments, once generated == max_addresses_upper_bound && !exhausted the safe answer here is still a single source (or some equivalent scheme that prevents a finished source from probing past the limit while another source is still reading the last buffered survivor).
alexey-milovidov
left a comment
There was a problem hiding this comment.
The implementation is good.
…ny-addresses Master expands `url` glob patterns lazily now (#115680), which rewrote the same parser. The conflicts are resolved by porting this PR onto `RemoteDescriptionGenerator`: - The generator takes a `RemoteDescriptionCaller` instead of a function name, so every message names the surface that was invoked, and it reports the cardinality of the whole description the user wrote (including the replica stage when its addresses are expanded once more by `|`). - `parseRemoteDescriptionWithFailover` is built on the generator as well, so there is still one parser. - The `url` path keeps the lazy expansion: the limit is not checked up front any more. The total over shards and replicas is enforced as the URLs are consumed, so a query that stops early still pays only for what it reads. `getSampleURI` takes a single address, as on master, so `CREATE TABLE ... ENGINE = URL` no longer rejects a large pattern by itself - the error comes when the table is read. - The `url` documentation keeps both sections; the claim that every address is materialized before the query starts is dropped. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`url`, `ENGINE = URL` and `urlCluster` generate the addresses of a pattern lazily since #115680, so the limit is no longer hit before anything is fetched: a pattern over unreachable `localhost:1` addresses now fails while connecting to the first one. The tests read real addresses from the HTTP interface of the server under test instead, with small limits, so that the limit is what stops the query. A table with the `URL` engine is created successfully and names itself when it is read. Also cover the message of `RemoteDescriptionGenerator`: the invoked surface and the number of addresses of the whole pattern, including its replicas. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A pattern passed to
urlwas expanded into the full direct product before the query started, soglob_expansion_max_elementslimited how large a pattern was allowed to be rather than how much of it a query needed. A query that stops early paid for the whole address space up front, and was rejected outright when that space was large:RemoteDescriptionGeneratorproduces the addresses of a pattern one at a time instead. Numeric intervals stay symbolic, so{0..10000}{0..10000}costs two factors rather than a hundred million strings, and the odometer over them walks the same order the materializing code produced - the last factor varies fastest.parseRemoteDescriptionis now a thin wrapper that checks the arithmetic total and drains the generator, so there is still one parser of the syntax, andremote,mysqlandpostgresql- which need every address at once to build a cluster - behave exactly as before, down to the error messages.Three places on the
urlpath stopped materializing:getSampleURItakes a single address. It only reads hive partitioning and virtual columns off a path, and used to expand the whole pattern to look at its first element.StorageURLSource::DisclosedGlobIteratorgenerates in batches and applies the_path/_filefilter to each. A pattern that fits into one batch keeps the exact post-filter size, which is what empty-glob detection and the number of streams are derived from, so nothing observable changes for it.The limit therefore applies to the addresses a query actually generates. A
_pathor_filepredicate is applied to each address as it is generated, so the ones it rejects are counted as well - an address has to exist before a predicate can prune it, and an unbounded generator would let a predicate matching nothing walk the whole address space. The batch ismin(1000, glob_expansion_max_elements)and the default limit is 1000, so every pattern that works today is still served in a single batch and behaves bit for bit as it did; only patterns that used to be rejected behave differently. Reading a huge pattern in full is still rejected.Groups holding the separator, such as
{a,b}in{a,b}{c,d}, are still expanded eagerly and bounded by the limit, because the direct product needs their alternatives up front. A..anywhere inside braces makes the whole group a numeric interval, so such a group can only hold literal text.Verified against a locally built server: the query above now returns rows;
{1..1000}at the default limit still reads exactly 1000 addresses;_pathfiltering, failover options,remote,mysqland every malformed-pattern error message are byte-identical to an unmodifiedmasterbinary. Theurlover-limit message now namesurlinstead ofremote, which is the only intentional difference.Related: #49234
Related: #115581
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The
urltable function and theURLtable engine now expand glob patterns lazily instead of materializing every address before the query starts.glob_expansion_max_elementsnow limits how many addresses a query actually generates rather than how large the pattern is, so a query that stops early - for example under aLIMIT- can use a pattern that describes far more addresses than the limit.Workflow [PR]
Sync PR [sync-upstream/pr/115680]
Version info
26.10.1.1460-master(included in26.10and later)