Skip to content

Expand url glob patterns lazily - #115680

Merged
alexey-milovidov merged 20 commits into
masterfrom
lazy-url-glob-expansion
Oct 3, 2026
Merged

alexey-milovidov merged 20 commits into
masterfrom
lazy-url-glob-expansion

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

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://clickhouse-public-datasets.s3.amazonaws.com/wikistat/original/pageviews-20200101-{0..10000}{0..10000}00.gz', LineAsString) LIMIT 3
-- Code: 36. DB::Exception: first argument generates too many result addresses. (BAD_ARGUMENTS)

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

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 generates. A _path or _file predicate 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 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. 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; _path filtering, failover options, remote, mysql and every malformed-pattern error message are byte-identical to an unmodified master binary. The url over-limit message now names url instead of remote, which is the only intentional difference.

Related: #49234
Related: #115581

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

The url table function and the URL table engine now expand glob patterns lazily instead of materializing every address before the query starts. glob_expansion_max_elements now limits how many addresses a query actually generates rather than how large the pattern is, so a query that stops early - for example under a LIMIT - can use a pattern that describes far more addresses than the limit.


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

Version info

  • Merged into: 26.10.1.1460-master (included in 26.10 and later)

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
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3c83e62]

Summary: ✅


AI Review

Summary

This PR replaces eager url glob materialization with RemoteDescriptionGenerator, threads the url / URL read path and schema inference through lazy batches, and adds good coverage around early-stop and deferred _file / _path filters. The earlier local deferred-filter regressions are fixed, but one correctness edge remains in the ready-filter path: once a filtered query has already generated exactly glob_expansion_max_elements URLs, more than one active consumer can still make a finished source probe the 1-past-limit URL and raise a spurious too many result addresses exception. The same accounting gap is still exposed through urlCluster, even though the new docs now advertise the lazy contract there too.

Findings
  • ⚠️ Majors
    • [src/Storages/StorageURL.cpp:430] sizeForStreams still turns the current survivor count into the number of local sources even after DisclosedGlobIterator has already spent the whole glob_expansion_max_elements budget and the pattern continues past it. With two matches inside the first allowed prefix, this returns 2; once the faster StorageURLSource finishes its file, initialize() asks glob_iterator->next() again, fillBatch() performs the 1-past-limit probe, and the query throws even though every file it needed was already inside the allowed prefix.
      Suggested fix: if generated == max_addresses_upper_bound && !exhausted, either keep a single local source or track leased/in-flight buffered URLs so a finished source cannot be the one that performs the 1-past-limit probe while another source is still reading the last buffered survivor.
    • [src/Storages/StorageURLCluster.cpp:147] [dismissed by author -- https://github.com/Expand url glob patterns lazily #115680#discussion_r3969469688] urlCluster still hands out the next task with bare iter->next() and has no equivalent of sizeForStreams, so one replica can hit the same 1-past-limit probe while another replica is still reading the last matching URL already inside the allowed prefix. That still contradicts the new urlCluster docs at src/TableFunctions/TableFunctionURLCluster.cpp:122, which now say the limit is on generated/dispatched addresses rather than raw pattern size.
      Suggested fix: either apply the same in-flight accounting to cluster task handout or narrow the urlCluster docs/contract back to the pre-PR behavior explicitly.
Tests
  • ⚠️ Add a focused stateless regression where a pattern larger than glob_expansion_max_elements has two matching files inside the allowed prefix and one file is made much larger (or otherwise kept busy) so another source/replica definitely asks for the next URL/task first. The existing tests cover LIMIT 1, deferred filters, and within-limit patterns, but not the multi-survivor full-read path that still trips the iterator.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Fix the multi-survivor over-limit path in the local url / URL read iterator.
    • Reconcile urlCluster with the same invariant or narrow its docs to the old eager-limit contract.
    • Add the focused regression above.

LLVM Coverage Report

Measured on commit 3c83e62.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.40% 79.50% +0.10%

Changed lines: Changed C/C++ lines covered: 300/312 (96.15%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 20, 2026
Comment thread src/Storages/StorageURL.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3c83e62c6 with master d046101ce (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.

Object file sizes

9 object files changed (+35.54 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageURL.cpp.o 1.21 MiB 1.22 MiB +17.14 KiB (+1.39%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

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

Copy link
Copy Markdown
Member Author

🕵 Triage of the reds on 308401c3, and what changed in 7e1220c9a326:

master is merged, and the two clickhouse-gh threads are answered and resolved.

Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
alexey-milovidov and others added 3 commits August 25, 2026 04:45
…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]>
Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/TableFunctions/TableFunctionURL.cpp Resolved
alexey-milovidov and others added 5 commits August 27, 2026 12:49
…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]>
`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]>
@alexey-milovidov

alexey-milovidov commented Aug 29, 2026 •

Copy link
Copy Markdown
Member Author

🕵 Merged master to get a fresh CI run. Both reds on 89542e0 are AST-fuzzer-induced logical errors in the stress tests, unrelated to this PR:

@groeneai, if the Not-ready Set failure reappears on the fresh run, please investigate and provide a fix in a separate PR; if a fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed from fatal.log: both Not-ready Set reds on this PR are the object storage _path route, i.e. the one #112968 fixes, so there is nothing further for me to link for it.

arm_asan_ubsan on 89542e0e: in.cpp:128 under filterBlockWithExpression <- getFilterByPathAndFileIndexes <- filterByPathOrFile <- StorageObjectStorageSource::createFileIterator, for SELECT count() FROM azureBlobStorage(..., '/slashed.csv', ...) WHERE _path GLOBAL NOT IN (SELECT _path FROM azureBlobStorage(...) LIMIT 553), so a glob-free key taking the pruning branch. The older arm_debug red on 308401c3 (2026-08-21) has the identical frame chain over test_s3_race, the same carrier your description cites.

My own open Not-ready Set PR #115868 is a different 0250-4e52 route and cannot affect this one: ReadFromObjectStorageStep::applyFilters builds sets through buildSetsForDAGExcludingGlobalIn, which skips globalNotIn sets by construction, so buildOrderedSetInplace, the function #115868 changes, is never reached here. Worth stating because the two routes share one CIDB bucket.

No stress job has been scheduled on the fresh run yet. If Not-ready Set reappears there I will check the frames against this seam and open a separate PR only if it lands outside it.

Evidence: fatal.log

Comment thread src/TableFunctions/TableFunctionURL.cpp Resolved
…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (clean) and addressed the AI-review Nit in dab448e615af.

Triage of the single red on b4a77d77:

  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) — job-level ERROR: command failed after 1/1 attempt(s), exit code: -9 after 7370 s, with no failed test: the runner killed the job with SIGKILL (the job carries the ram-pressure/cpu-bound/io-bound labels). The last lines are all PASSED, and none of the tests in that shard touch url globs. Infrastructure, unrelated to this PR; the fresh run on the merge commit should clear it.

All AI-review threads are answered and resolved; there are no other unresolved threads.

@clickhouse-gh clickhouse-gh Bot added the comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). label Sep 4, 2026
…sion

# Conflicts:
#	src/Storages/StorageURL.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was ~4465 commits behind and CONFLICTING) and reconciled the lazy iterator with two changes that landed on master in the meantime, both in StorageURLSource::DisclosedGlobIterator::Impl:

  • 47f18ac7a3b2 "Fix url commas and archive path filtering" added the split_uris flag: a URI without globs is taken as is, because it can hold commas of its own. The generator is now std::optional and is only created when split_uris is set; otherwise the single URI is the whole (immediately exhausted) first batch, and it still goes through the iterator so the _path / _file filter is applied to it.
  • a6cf117f7fbd (fix-object-storage-global-in-set, Fix _path / _file filtering for object storage, file and url #112968) made buildSetsForDAG report whether every set could be built, and defers the pruning to read time when a set is only created while the pipeline runs. The lazy iterator keeps building the sets on first use (an empty glob must still not run the subqueries of a _path IN (...) predicate); when they cannot be built, filter_deferred is set and the filter is applied to each address as next hands it out instead of to the batch. The charge-before-prune property is unchanged: an address is still counted as generated before any predicate can look at it.

Triage of the two reds on dab448e6:

  • Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) — 03707_autopr_unsupported_cases, unrelated to this PR (automatic projections, supported_aggregation/supported_join flipping to 0 under the old analyzer). Already fixed on master by 054e61604430 "Force the analyzer in 03707_autopr_unsupported_cases", which this merge pulls in.
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) — job-level Container memory budget exceeded (/docker) with no failing test; the harness itself classifies it as an infrastructure/resource failure. Same runner-pressure class as the exit code: -9 on the previous head.

Verified locally against a private server built from this branch: 05023_lazy_url_glob_expansion, 05043_url_glob_filtered_parallel_streams, 05044_url_glob_schema_cache_after_first_batch, 05045_url_glob_filtered_multibatch_streams, 05029_remote_description_deep_braces, 05043_selected_rows_file_url_double_count, 05043_file_archive_member_path_filter, 04145_url_glob_parallelize_output, 02044_url_glob_parallel, 02044_url_glob_parallel_connection_refused all pass. master's 04907_file_url_path_filter_global_in and 05048_url_cluster_path_filter_prune are only red locally because they address the default ports / the test_cluster_one_shard_three_replicas_localhost cluster, which a private server on custom ports does not have; every one of their arms was re-run by hand against this server and behaves correctly, including a globbed URL with a deferred GLOBAL IN filter, which never opens a connection. Style check is green locally.

Comment thread src/Storages/StorageURL.cpp Resolved
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was ~4385 commits behind; clean merge) and fixed the deferred-filter stream sizing from the review thread in 4ee5eff0aca0 (see the reply there).

Triage of the two reds on 38a01c80:

  • Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel), 05043_url_glob_filtered_parallel_streams - the PR's own. On that runner url becomes a cluster read, which hands the addresses to one consumer per replica; the third replica asking after the two survivors of {0..19} under glob_expansion_max_elements = 10 makes the generator report that the pattern exceeds the limit, which is the right answer for a pattern larger than the limit when no LIMIT stops the initiator. The early stop the test pins is a property of the local read, so its LIMIT 1 probe now pins enable_parallel_replicas = 0 like the EXPLAIN before it. Fixed in 4ee5eff0aca0.
  • AST fuzzer (amd_release, oracle) - unrelated: Subquery wrap oracle mismatch for SELECT DISTINCT * REPLACE (...) ... FROM table1 AS t1 STREAM BOUNDED UNORDERED ALL INNER JOIN (...) AS t2 USING (a, b) ORDER BY t1.a ..., i.e. a JOIN ... USING query whose values change when wrapped in a subquery. That is the class of Wrapping a JOIN ... USING query in a subquery changes the value of the qualified join column #118986, with the fix in progress in Fix wrong result for duplicate-named subquery columns wrapped in SELECT * #107127. No url involved.

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

Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Not #107127: it is a different collision, and it is already fixed on master.

On that run both USING keys were named after the lambda parameter, so the projection carried two columns called toTypeName(x); the outer SELECT * resolved the duplicate by name and returned the second key's value in the first position:

reference: String  Date  String  String  Date
wrapped:   Date    Date  String  String  Date

Measured with the amd_release binary from 38a01c80, the 01671_merge_join_and_constants tables and the settings recorded in the report. Minimal form:

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 4ee5eff0 already contains #118825, so no separate PR is needed for this red.

pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Sep 19, 2026
…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]>
alexey-milovidov and others added 3 commits September 23, 2026 19:08
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (clean) and addressed the open review thread (deferred-filter streams keep their parallelism when the pattern fits into the limit; new failpoint url_glob_defer_path_filter + test 05243), head f7c83558dd55.

The only red on 4ee5eff0 was Integration tests (amd_llvm_coverage, 2/8): test_default_session_user::test_native_default_session_user_with_password timed out in native_hello. That is unrelated to url, and it is fixed on master by #120753 (merged 2026-09-18), which this merge pulls in.

@groeneai thanks for the fuzzer analysis: the earlier Subquery wrap oracle mismatch is #118739 / #118825, which is already on the branch.

# Conflicts:
#	src/Storages/StorageURL.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (one trivial conflict in the FailPoints declarations of src/Storages/StorageURL.cpp: kept url_glob_defer_path_filter next to the new storage_url_pause_* ones), head 3c83e62c6db. Built and sanity-checked locally: {0..10000}{0..10000} with LIMIT 3 returns rows, {1..1000} still reads 1000 addresses, and {1..1001} read in full is still rejected.

Reds on f7c83558, all unrelated:

  • Fast test (arm_darwin): the runner ran out of disk space (No space left on device).
  • Integration tests (amd_llvm_coverage, 3/8): test_replicated_database_active_node_taken. That test was removed from master on 2026-10-01 (4cbdcbc1c9d), so the merge drops it.
  • Performance Comparison (arm_release, master_head, 4/6): index_bulk_filtering. That test does not touch url.

Comment on lines +425 to +430
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);

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.

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

The implementation is good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 3, 2026
Merged via the queue into master with commit 308921d Oct 3, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the lazy-url-glob-expansion branch October 3, 2026 23:32
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 3, 2026
alexey-milovidov added a commit that referenced this pull request Oct 4, 2026
…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]>
alexey-milovidov added a commit that referenced this pull request Oct 4, 2026
`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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants