Skip to content

Parallelize listing of globbed s3 table function paths - #107567

Open
alexey-milovidov wants to merge 149 commits into
masterfrom
s3-list-object-parallelism
Open

alexey-milovidov wants to merge 149 commits into
masterfrom
s3-list-object-parallelism

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 15, 2026 •

Copy link
Copy Markdown
Member

Speeds up listing files over globbed paths on S3-compatible object storage (the s3 and s3Cluster table functions, the S3 table engine, and their gcs, cosn, oss aliases), in two complementary ways. The listing was a single serial stream of ListObjectsV2 requests paginated by a continuation token, bound by the per-request latency of S3 (~75 ms measured against clickhouse-public-datasets); this dominates queries over buckets with many objects. An earlier attempt (#66504) used speculative keyspace splitting with fixed split points assuming a uniform key distribution and a fixed character set, and was closed as fragile.

Controlled by the new setting s3_list_object_parallelism (default 1 = the previous serial behavior).

1. Hierarchical layouts — walk the "directory" tree formed by the / delimiter with several worker threads in parallel, pruning subtrees that cannot contain a matching key (so for partitioned layouts like year=*/month=*/ fewer objects are fetched, not merely listed in parallel). Recursive globs (**) keep serial listing.

2. Big flat directories (e.g. files named by hash/UUID — musicbrainz/mlhdplus-complete/<uuid>.txt.zst, ~600k files in one prefix) — when a listed prefix is truncated but has no sub-directories, split it by keyspace: tile the remaining range into contiguous (start_after, end] sub-ranges listed concurrently, with boundaries derived from the byte alphabet observed in the listed page. Because the sub-ranges are contiguous they tile the interval with no gaps — a key whose byte is absent from the sampled alphabet still falls into the range that brackets it — so the split is complete regardless of the key distribution or character set. The split is a single level and is probe-gated: before splitting, one cheap ListObjectsV2 checks whether any key exists beyond the current bucket; if not (keys share a common prefix, e.g. pageviews-YYYYMMDD-HH), the directory is paginated serially instead of issuing a fan of empty boundary probes. This is the robust counterpart to #66504 — it never regresses for clustered keys. On S3 Express / directory buckets — which reject StartAfter and only allow the / delimiter — keyspace splitting is disabled automatically (detected via isS3ExpressBucket), so flat ranges are paginated serially while hierarchical layouts are still listed in parallel. Directory buckets also return listings in no particular order (IObjectStorage::listsKeysInLexicographicOrder), so every order-dependent shortcut (the end bound of a widened walk, the budget-trim resume, the single-page directory-marker stop) is disabled for them and ranges are paginated by continuation tokens only.

Correctness of glob matching is guaranteed by the existing per-file RE2::FullMatch, so the directory pruning only needs to be conservative.

Measured against real S3 (clickhouse-public-datasets, ~75 ms/list-request) across ~16 datasets — all return identical results (same count, no duplicates, identical path checksum), serial vs parallel:

  • Big flat, uniform keys — musicbrainz/mlhdplus-complete (594415 files): 37s → 3.7s (~10x).
  • Big flat, clustered keys — wikistat (97529) / gharchive (100091): probe sends them serial; parallel matches serial (no regression).
  • Hierarchical — web/store: ~2.5x (bounded by its small directory count; scales toward the parallelism factor for larger trees).
  • Small/medium directories (nyc-taxi, ontime, hits/native, sensors, tranco, youtube, adsblol, bluesky, …): correct, no regression.

A unit test (gtest_object_storage_parallel_listing) asserts every key is produced exactly once across parallelism 1–64, including adversarial cases (bytes outside the sampled alphabet, shared long prefixes, boundary keys, mixed hierarchical+flat). Stateless tests (04339_s3_parallel_glob_listing, 04340_s3_parallel_flat_listing) verify parallel and serial listing return identical results.

Closes: #65572
Related: #66504

Changelog category (leave one):

  • Improvement

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

Added a setting s3_list_object_parallelism to list globbed paths on S3-compatible object storage in parallel. It applies to reads through the s3 and s3Cluster table functions, the S3 table engine, and their gcs, cosn, oss aliases. Hierarchically partitioned layouts are listed by walking the tree of common prefixes concurrently; a single big flat directory is listed by splitting its keyspace into contiguous sub-ranges. This speeds up queries over buckets with many objects (e.g. ~10x for a directory of 600k files).


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

Listing files for the `s3` table function with a glob was a single serial
stream of `ListObjectsV2` requests paginated by a continuation token, bound by
the per-request latency of S3 (~0.1-0.3s). This dominates queries over buckets
with many objects (issue #65572; an earlier attempt was #66504).

List the matching files in parallel by walking the "directory" tree formed by
the `/` delimiter: worker threads list different common prefixes concurrently,
and subtrees that cannot contain a matching key are pruned during the walk, so
for hierarchically partitioned layouts fewer objects are fetched, not merely
listed in parallel. Controlled by the new setting `s3_list_object_parallelism`
(default `1`, the previous serial behavior). Recursive globs (`**`) keep serial
listing. Correctness is guaranteed by the existing per-file `RE2::FullMatch`, so
the directory pruning only needs to be conservative.

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

clickhouse-gh Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6b93d30]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds opt-in parallel listing for globbed S3 paths, using delimiter traversal and keyspace splitting, with adaptive recursive listing for sparse directories. One correctness blocker remains: parallel listing uses current-version metadata when reading an explicitly selected historical object version, which can silently omit rows.

Listing output was traced through local reads and their full-key filtering, archive expansion, cluster task distribution, and the three sampling/inference consumers that explicitly retain serial ordering. The version mismatch affects metadata consumers before the historical object is read.

Missing context / blind spots
  • ⚠️ A current-head binary was unavailable from CI artifacts. An HTTP-mock run against the PR's 68e18a39633 ARM CI binary reproduced [1] with size 2 and the current ETag for the 4-byte historical object. That binary predates the serial-path fix, so the serial/parallel distinction was verified from current source; its parallel metadata construction differs only by explicit string conversions. A current-head regression run would close this runtime-validation gap.
Findings

❌ Blockers

  • src/Disks/DiskObjectStorage/ObjectStorages/S3/S3ObjectStorage.cpp:511–520: listObjectsSingleLevel attaches current-version size, timestamp, ETag, and tags even for a URL containing versionId. Unlike S3IteratorAsync, it does not leave metadata unset to obtain a version-specific HEAD. StorageObjectStorageSource::createReader consequently bypasses that request and uses the current size for empty-file skipping and read bounds. If the current object is 9\n and the selected historical version is 1\n2\n, prefetch can return only [1]; an empty current version causes the historical file to be skipped entirely with s3_skip_empty_files=1. Return keys without metadata for explicit-version reads, matching the serial iterator. Inline finding.
Tests
  • ⚠️ Add a focused stateless regression comparing s3_list_object_parallelism=1 and 8 for explicit historical versions whose sizes differ from the current version, including an empty current version and metadata virtual columns. Existing 05814_s3_explicit_version_size_from_version_metadata.sh covers versioned wildcard reads only at the default serial setting.
Final Verdict

Status: ❌ Block

Preserve version-specific metadata on the parallel path and add regression coverage proving historical reads remain independent of listing parallelism.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 15, 2026
@alexey-milovidov alexey-milovidov changed the title Parallelize listing of globbed s3() table function paths Parallelize listing of globbed s3 table function paths Jun 15, 2026
The previous commit parallelizes hierarchical globs by walking the '/' tree, but
a single big flat directory still lists serially (S3 pagination within a prefix
is sequential). Such directories are common when files are named by hash/UUID,
e.g. `musicbrainz/mlhdplus-complete/<uuid>.txt.zst` (~600k files in one prefix).

When a listed prefix is truncated but has no sub-directories, split it by
keyspace: tile its remaining range into contiguous `(start_after, end]`
sub-ranges and list them concurrently. Boundaries are derived from the byte
alphabet observed in the listed page (so the split adapts to the actual keys,
e.g. hex for UUIDs). Because the sub-ranges are contiguous they tile the
interval with no gaps — a key whose byte is absent from the sampled alphabet
still falls into the range that brackets it — so the split is complete
regardless of the key distribution or character set. This avoids the fragility
of the earlier attempt #66504, which used fixed split points assuming a uniform
distribution and a fixed character set.

Measured on `musicbrainz/mlhdplus-complete` (594415 flat files, real S3,
~75ms/list-request): listing drops from 37.6s to 3.7s (~10x) with identical
results (same count, no duplicates, identical path checksum).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…sions

Testing the flat-directory keyspace split across many public datasets revealed
two cases where parallel listing was slower than serial:

- Keys that share a long common prefix (e.g. `gharchive/original/2015-..`,
  `wikistat/original/pageviews-..`): the byte alphabet cannot divide them, so the
  split produced one full bucket plus a fan of empty boundary probes (pure
  overhead). Now a single cheap probe (one `ListObjectsV2` after the current
  bucket) checks whether any key exists beyond it; if not, the range is paginated
  serially with no wasted probes.
- Multi-level splitting compounded the empty-probe overhead with no benefit for
  such keys. The split is now a single level (the recursion gave nothing for
  uniformly distributed keys — they are already balanced after one fan-out — and
  only hurt clustered keys). The number of boundaries is also capped.

Uniformly distributed keys (hashes/UUIDs) still get the full speedup
(`musicbrainz/mlhdplus-complete`, 594415 files: ~9-10x), while clustered keys now
match serial instead of regressing.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The probe that decides whether a flat directory can be usefully split was
evaluated on every page of a serially-paginated range, not once. For a directory
whose keys share a common prefix (which is paginated serially), this issued one
wasted probe request per page — roughly doubling the number of requests and
making parallel listing ~50% slower than serial on `gharchive`/`wikistat`
(~100k files each). Probe only on the first flat page; once a range is decided to
be unsplittable, paginate it serially without probing again.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Performance comparison

Measured against real S3 (clickhouse-public-datasets, list round-trip ~75 ms) with clickhouse local, listing only — SELECT count() FROM s3('…', NOSIGN, 'One'). The One input format yields one row per object without reading file bodies, so the wall time is dominated by ListObjectsV2. Every run was checked for correctness: identical count, uniqExact(_path) (no duplicates) and sum(sipHash64(_path)) (identical set) between serial and parallel — this held for all datasets and parallelism levels below.

Big flat directory, uniformly distributed keys — the target case (issue #65572)

musicbrainz/mlhdplus-complete/*.txt.zst — 594,415 files named by UUID in a single flat prefix:

s3_list_object_parallelism wall time speedup
1 (serial, previous behavior) 38.0 s 1.0×
4 10.8 s 3.5×
8 5.1 s 7.5×
16 3.6 s 10.4×
32 3.7 s 10.3×

(Plateaus at ~16 because the keyspace is split one level by the hex alphabet → ~16 concurrent sub-ranges.)

Other shapes (serial vs. parallelism = 16)

Dataset Files Shape serial parallel(16)
musicbrainz/mlhdplus-complete 594,415 flat, uniform (UUID) 38.0 s 3.6 s
gharchive/original 100,092 flat, clustered (2015-…) 6.1 s 6.5 s
wikistat/original 97,530 flat, clustered (pageviews-…) 7.8 s 7.0 s
web/store/*/*/*/* 2,040 hierarchical 0.34 s 0.27 s

Clustered keys (a long shared prefix) cannot be divided by keyspace; the one-shot probe detects this and paginates serially, so parallel matches serial rather than regressing (the small differences here are within run-to-run S3 noise, which I measured at ±10–20%).

Correctness sweep

In addition, parallel vs. serial were checked to be byte-identical (count + path checksum) on a range of small/medium datasets — adsblol, bluesky, cisco-umbrella, github_events, hits/native, nyc-taxi, ontime, scansio, sensors, tranco, us_buildings, youtube — all match, none regress.

Caveats

  • Real-S3 list latency is noisy (±10–20% run-to-run), so the small-dataset and clustered numbers are indicative, not precise; the order-of-magnitude win on big uniform directories and the correctness results are solid.
  • The setting defaults to 1 (serial) — this is opt-in.

alexey-milovidov and others added 2 commits June 17, 2026 16:02
…mbers

Adding the `list_object_parallelism = 1` default member initializer made the
implicit default constructor of `StorageObjectStorageQuerySettings` non-trivial,
so `clang-tidy`'s `cppcoreguidelines-pro-type-member-init` began requiring every
member to be initialized and failed the `Build (arm_tidy)` job. Give all members
explicit default initializers; every call site uses designated aggregate
initialization, so behavior is unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ng-slash globs

The parallel glob listing walk pruned every `CommonPrefixes` entry whose component
depth equalled the glob's. But an object whose key itself ends with `/` (a directory
marker such as `root/dir/`, as created by some S3 tools) is returned by
`ListObjectsV2` only as a `CommonPrefixes` entry when its parent is listed, and as a
`Contents` entry when its own prefix is listed. For a glob like `root/*/` such a
marker is accepted by `RE2::FullMatch`, so serial listing returned it while the
parallel walk dropped it, making `s3_list_object_parallelism > 1` produce an
incomplete result set.

`makeShouldDescendPredicate` now descends one extra level into a fully-matching
common prefix when the glob ends with `/`, so the marker object is surfaced from
`Contents`. Behavior is unchanged for globs that do not end with `/`.

Move `splitPathComponents` and `makeShouldDescendPredicate` into a dedicated
`ParallelListingGlobPredicate` translation unit next to the
`ObjectStorageParallelListingIterator` they serve, so the predicate can be
unit-tested, and add a `gtest` regression case `DirectoryMarkerMatchesTrailingSlashGlob`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 6 commits June 18, 2026 18:03
…ry buckets

Flat keyspace splitting lists a big flat "directory" by resuming strictly after
an arbitrary key (`StartAfter`) with an empty `Delimiter`. S3 Express / directory
buckets reject `StartAfter` and only allow the `/` delimiter, so with
`s3_list_object_parallelism > 1` an otherwise serial glob listing could turn into
a `ListObjectsV2` error as soon as a flat range was probed or split.

Gate keyspace splitting on a new `IObjectStorage::supportsListingKeyspaceSplit`
capability (false by default; `S3ObjectStorage` returns
`!client->isS3ExpressBucket`). When disabled, a flat directory is paginated
serially while the hierarchical delimiter walk — which uses only the `/`
delimiter and continuation tokens, both supported by directory buckets — stays
parallel.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`clang-tidy` flagged `compare`-based prefix/suffix checks
(`modernize-use-starts-ends-with`) and disregarded `snprintf` return values
(`cert-err33-c`) in `gtest_object_storage_parallel_listing`; switch to
`starts_with`/`ends_with` and `fmt::format`.

Add a test that a big flat directory listed with keyspace splitting disabled is
still complete yet never issues a `StartAfter` request or an empty `Delimiter`,
at parallelism 1/4/16 (and that, with splitting enabled, the same directory is
indeed split — so the gate is meaningful).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107567&sha=8d2e9128969499945fbc99a6107e44c5754ebaca&name_0=PR&name_1=Build%20%28arm_tidy%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The flat-directory tests derived hex names as `hex[x & 0xf]` from an LCG, but the
low nibble of an LCG cycles with a period of at most 16 independent of the seed's
high bits, so every `i` sharing `i mod 16` produced the same name. Each "big flat
directory" therefore collapsed to ~16 distinct keys and the keyspace-split path
was never taken (completeness still held, but only trivially). Add a `splitmix64`
`hexName` helper that yields well-distributed unique names with a uniform first
byte, so a flat directory is genuinely split — verified by the new gate test,
whose `requests_with_start_after`/`requests_with_empty_delimiter` counters are now
positive when splitting is enabled.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…uzzer

The Stress test reported `S3_ERROR No such key thrown` attributed to
`04340_s3_parallel_flat_listing.sh`. The failing read was of a key
`test_<db>/04340/data\xef\xbf\xbd.csv` — the UTF-8 replacement character
where `_NN` should be — i.e. a mutation of this test's own path literal
`http://localhost:11111/test/<db>/04340/data_NN.csv`, which the stress query
fuzzer harvests and replays into the shared bucket. The test's `*.csv` glob
then lists that corrupt sibling and the read of its body fails with
`No such key`.

This is unrelated to the parallel-listing feature: it reproduces identically
with `s3_list_object_parallelism = 1` (the pre-existing serial code path), and
in the failing run the only two `No such key` occurrences in the whole stress
session were this test's serial and parallel queries.

Anchor the read glob to `data_??.csv` instead of `*.csv`. This narrows both
the S3 listing prefix (to `.../04340/data_`) and the matching regexp to the
exact file shape, so a fuzzer-injected sibling with a mutated name is never
listed or read. In a clean environment it lists the same 40 files, so the
reference is unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107567&sha=1db36fa35a05e948591fbc96d1039427e0a25839&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-merged master + hardened 04340 against the stress query fuzzer

The branch was 461 commits behind master and red, so I merged master (clean, no conflicts; the s3_list_object_parallelism entry in SettingsChangesHistory.cpp is correctly in the 26.6 block) and pushed 1db36fa..607899a.

Investigation of the S3_ERROR No such key thrown stress reds (arm_tsan / arm_msan / arm_ubsan). These are not caused by the parallel-listing feature:

  • The failing read was of key test_<db>/04340/data\xef\xbf\xbd.csv — the UTF-8 replacement character (�) where _NN should be. That is a mutation of this test's own path literal .../04340/data_NN.csv, which the stress query fuzzer harvests and replays into the shared bucket (the query log shows the same literal replayed across unrelated databases, e.g. data%14.csv, paths with \0, etc.).
  • It reproduces identically with s3_list_object_parallelism = 1 (the pre-existing serial code path), and in the failing run the only two No such key occurrences in the entire stress session were 04340's serial and parallel queries — i.e. the test's *.csv glob simply lists the fuzzer-injected corrupt sibling and the read of its body fails.

Fix: anchor 04340's read glob to data_??.csv instead of *.csv, narrowing both the S3 listing prefix (.../04340/data_) and the matching regexp to the exact file shape, so a fuzzer artifact is never listed or read. In a clean environment it lists the same 40 files, so the reference is unchanged. (04339 did not trip the check and its globs are mostly anchored on data.csv.)

Other reds are unrelated, widespread AST-fuzzer / stress flakes (present on master and many PRs):

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107567&sha=1db36fa35a05e948591fbc96d1039427e0a25839&name_0=PR

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Hung check reds are a real hang in the parallel listing, not the generic flake

CI auto-links both Hung check failed, possible deadlock found failures (commit 607899a8, Stress test (arm_ubsan) and Stress test (arm_asan_ubsan, s3)) to #107941. That issue is an auto-generated matcher keyed on the test name only, so the link is a false negative: the hung-thread stack on this PR is specific to the new code and cannot occur on master.

Evidence (hung_check.log, both jobs): one query stuck with is_cancelled: 1 and elapsed ~3273 s / ~3143 s, the only thread in the dump being the query's main thread:

SELECT … FROM s3('…/04339/year=*/month=*/data.csv', …) SETTINGS s3_list_object_parallelism = 8

std::condition_variable::wait
DB::ObjectStorageParallelListingIterator::popBatch
DB::ObjectStorageParallelListingIterator::advanceLocked
DB::ObjectStorageParallelListingIterator::getCurrentBatchAndScheduleNext   (line 430)
DB::StorageObjectStorageSource::GlobIterator::nextUnlocked
DB::StorageObjectStorageSource::GlobIterator::next
DB::StorageObjectStorage::getPathSample
DB::StorageObjectStorage::StorageObjectStorage   (constructor)

Mechanism. getPathSample lists synchronously on the query's main thread inside the StorageObjectStorage constructor. The consumer is blocked in the prefetch popBatch that getCurrentBatchAndScheduleNext issues after handing back a batch. The iterator's blocking waits (result_available, space_available, work_available) and the workers' list_level calls only unblock on finished (all ranges listed) or stop (set in the destructor). Nothing observes query cancellation, so when the query is cancelled at max_execution_time = 60 the wait is not interrupted; the wait ends only if the producers either publish another batch or finish the whole walk. Contrast the serial path IObjectStorageIteratorAsync, which waits on a single std::future per ListObjectsV2 call — bounded by the S3 request timeout, with the exception propagated through future::get.

Why the producers stall under stress. The query fuzzer mutates the credentials/arguments (the err log shows InvalidAccessKeyId, XMinioIAMNotInitialized, MissingFields thrown out of listObjectsSingleLevel), and the stress harness kills/restarts the server and minio. A single listObjectsSingleLevel call is bounded (it reuses the same client and request timeouts as the serial path), but with eight workers hammering the S3 client and credential provider concurrently, the walk can reach a state where no further batch is produced and finished is never set, while the consumer waits unbounded. The destructor cannot rescue it either, because the constructor frame is still parked in popBatch, and even once it unwinds ~ObjectStorageParallelListingIterator does pool.wait(), which would block on any worker still stuck in list_level.

Production implication. A real S3 slowdown or outage during listing would hang a s3_list_object_parallelism > 1 query, ignoring max_execution_time and KILL QUERY — exactly what the Hung check is designed to catch.

Fix direction (not yet pushed). Make the parallel listing cancellation-aware rather than only stop/finished-aware: thread a cancellation predicate from the query context into the popBatch / worker-loop wait predicates, attach the listing-pool threads to the query's thread group so the in-flight S3 calls observe cancellation, and ensure ~ObjectStorageParallelListingIterator cannot block on a worker stuck inside list_level. I have not pushed a change for this yet — it is a concurrency/cancellation design decision, and a partial fix risks merely relocating the hang (e.g. into the destructor's pool.wait()); the repro is stress + fuzzer only and is not reproducible locally with confidence.

Reports:

alexey-milovidov and others added 2 commits June 22, 2026 03:38
The `Hung check` reds on this PR are a real, PR-specific deadlock in the new
`ObjectStorageParallelListingIterator`, not the generic flake (CI mis-links them
to a name-only matcher issue). The consumer (e.g. the query's main thread inside
`getPathSample`, called from the `StorageObjectStorage` constructor during query
analysis) blocks in `popBatch` waiting on `result_available`, whose predicate only
becomes true on `finished` or `stop`. Nothing observed query cancellation: when the
query is killed (the hung dump shows `is_cancelled = 1`, which is `QueryStatus::isKilled`)
the wait was never interrupted, and the destructor — the only place that sets `stop` —
could not run because the constructor frame was parked in `popBatch`. The result was an
unbounded hang ignoring `max_execution_time` and `KILL QUERY`.

Make the parallel listing cancellation-aware, mirroring the serial path which is
bounded by per-request timeouts:

- `popBatch` now waits in bounded slices (`wait_for`) instead of indefinitely, and on
  each timeout calls a `check_cancellation` hook. Query cancellation does not notify our
  condition variables, so polling is required to observe it. On cancellation the hook
  throws the proper exception (`TIMEOUT_EXCEEDED` / `QUERY_WAS_CANCELLED`); `popBatch`
  sets `stop` and wakes the workers before propagating, so the exception unwinds the
  consumer and the iterator is destroyed.
- `GlobIterator` builds the hook from `Context::getProcessListElementSafe` →
  `QueryStatus::throwIfKilled`. It is empty in non-query contexts (e.g. unit tests).
- Worker threads now attach to the owning query's thread group via `ThreadGroupSwitcher`,
  so listing memory is accounted to the query and in-flight listing requests observe its
  cancellation (the same as the serial listing path).
- With the consumer unblocked and `stop` set promptly, `~ObjectStorageParallelListingIterator`'s
  `pool.wait()` is bounded by a single (already bounded) listing request rather than hanging.

Adds a deterministic `gtest` (`CancellationUnblocksBlockedConsumer`) that reproduces the
consumer-blocked-on-a-stalled-producer state and asserts that cancellation interrupts the
wait and the iterator destructs without blocking.

Reports:
- https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107567&sha=607899a8a70ded0637ea3dd950b8ad7d401a42ee&name_0=PR&name_1=Stress%20test%20%28arm_ubsan%29
- https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107567&sha=607899a8a70ded0637ea3dd950b8ad7d401a42ee&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed the cancellation-aware fix for the Hung check deadlock

Commit 09a6c0a (on a fresh master merge) makes the parallel listing observe query cancellation, so it can no longer hang ignoring max_execution_time / KILL QUERY as described above.

  • ObjectStorageParallelListingIterator::popBatch now waits in bounded slices (wait_for) and, on each timeout, calls a check_cancellation hook — query cancellation does not notify our condition variables, so polling is required to observe it. On cancellation it sets stop, wakes the workers, and the hook throws the proper exception. (The hung dump's is_cancelled = 1 is exactly QueryStatus::isKilled, so the fix keys off the real signal.)
  • StorageObjectStorageSource::GlobIterator builds the hook from Context::getProcessListElementSafe → QueryStatus::throwIfKilled; it is empty in non-query contexts (the iterator stays storage/query-agnostic — only the callback couples it).
  • Worker threads now attach to the owning query's thread group via ThreadGroupSwitcher, so listing memory is accounted to the query and in-flight requests observe its cancellation, mirroring the serial path.
  • With the consumer unblocked and stop set promptly, ~ObjectStorageParallelListingIterator's pool.wait() is bounded by a single (already bounded) listing request instead of hanging.

Added a deterministic unit test ObjectStorageParallelListing.CancellationUnblocksBlockedConsumer that reproduces the consumer-blocked-on-a-stalled-producer state and asserts cancellation interrupts the wait and the iterator destructs without blocking (a stateless repro isn't feasible — it needs a stalled producer plus cancellation, which is stress + fuzzer only). Locally: unit_tests_dbms builds clean and all 13 ObjectStorageParallelListing.* tests pass (the new one 30/30 repeats).

alexey-milovidov and others added 3 commits October 30, 2026 00:47
`ListObjectsV2` may return an empty page with `IsTruncated` set, which does
not prove the directory marker is absent. Keep paginating such a range until
an entry settles the question, and add a regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch at d9fd5fd2ccc (no conflicts; the PR diff is unchanged). The touched translation units and gtest_object_storage_parallel_listing compile on the merged tree.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107567&sha=5934381d8e1ea5914cf0d207a08e0bbc14cfe647&name_0=PR&name_1=Stress%20test%20%28amd_msan%29 (Logical error: Cannot write to canceled buffer (STID: 4158-2b4c), raised from ClientBase::processQueryText in the embedded client) and provide a fix in a separate PR. If the fix is already in progress, link it here. This failure is not related to this PR. In the last 5 days it was seen on master and on dozens of other PRs, and it is still happening after #127834 was merged.

@groeneai

Copy link
Copy Markdown
Collaborator

The failing build predates #127834. Workflow run 40983708219 was created at 01:05Z, about 7 hours before #127834 was merged (08:05Z). It tested a48a51a5, which is the merge of 5934381d into master b1eff66e (2026-10-29 22:44Z). That base is 25 commits before the merge commit 553f2289. The stack is the exact site #127834 guards: ProgressIndication::writeProgress (ProgressIndication.cpp:175) <- ClientBase::onProgress (:2192) <- receiveEndOfQueryForInsert (:3005) <- processInsertQuery <- processQueryText <- ClientEmbedded::run.

On "still happening after the merge": CIDB has three Cannot write to canceled buffer (STID: 4158-*) hits timestamped after 08:05Z (PRs 127090, 117814, 116257; the last one at 10:09Z). All three come from workflow runs created between 06:34Z and 07:41Z, so their builds do not contain the fix. Since 10:10Z there are 0 hits in 967 Stress runs (302 of them on master). In the 24 hours before that, there were 30 hits in 1841 Stress runs.

The new head d9fd5fd2 contains 553f2289, so the next CI run here tests a fixed tree. The only other embedded-client write site of this error I know of is resetOutput -> IOutputFormat::finalize (STIDs 4158-307c/-351e). My open #126142 covers it.

…ce split valid UTF-8

`splitWouldHelp` incremented the byte at the split position and `splitFlatRange`
appended arbitrary sampled bytes to build slice boundaries. Both are sent as
`StartAfter`, so a key with a multi-byte character at the split position (e.g.
`p/é.csv`) produced an incomplete sequence (`p/\xC4`) or a lone continuation byte,
which S3-compatible storages such as OpenStack Swift reject with `InvalidArgument`.

Split only at ASCII bytes: probe only when the byte at the split position is
below `0x7F` (so its successor is ASCII and the prefix ends on a character
boundary), and form slice boundaries only from ASCII bytes. Keys with non-ASCII
bytes at the split position are still covered by the last slice, which inherits
the range's own upper bound. Add a unit test that validates every outgoing
`StartAfter` for names beginning with non-ASCII characters and ASCII-leading
names with a non-ASCII suffix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Oct 31, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch at 43cb5742e25 (no conflicts; the PR diff is unchanged). The branch was 9 days behind. All translation units touched by the PR, plus gtest_object_storage_parallel_listing, compile on the merged tree. CI on the previous head 6acbac9d634 was green, and there are no unresolved review threads.

alexey-milovidov and others added 3 commits November 10, 2026 21:57
The delimited walk issues at least one request per descended sub-directory.
For a sparse layout such as `root/p=*/data.csv` with one file per `p=...`,
that is up to `page_size` times more requests than the serial recursive
listing (10010 instead of 10 for 10000 directories), which no parallelism
can compensate.

When the first page of a fresh hierarchical range descends into at least 16
sub-directories and prunes none of them, `probeRecursiveListing` lists one
recursive (delimiter-free) page over the same interval. If that page spans at
least 8 sub-directories (or covers the whole range), the range is listed
recursively from there on; otherwise the delimited walk goes on, having spent
one extra request. This covers ordinary file globs and trailing-slash globs
alike. It is disabled for a `_tags` scan, which fetches tags for every listed
object, and for unordered storages.

Added request-count regressions for both sparse layouts, and checks that
dense and pruned layouts keep the delimited walk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…llelism

Resolved conflicts with the new `s3_skip_hidden_files` setting: keep both
`list_object_parallelism` and `skip_hidden_files` (with default member
initializers), and keep `hidden_check_prefix_size` while the listing iterator is
still created later in `GlobIterator` (serial or parallel).
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch at 68e18a39633 (no conflicts; the PR diff is unchanged). All translation units touched by the PR, plus gtest_object_storage_parallel_listing, pass -fsyntax-only on the merged tree.

On the previous head 9aae2b46630 the only red items were:

  • CH Inc sync (conflicts): I overlaid the current PR files onto private master (3-way, no conflicts; the per-file delta equals the public PR diff) and pushed it to the sync branch, which is now MERGEABLE.
  • Stress test (amd_tsan): a heap-use-after-free in DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat, which this PR does not touch. It is fixed on master by Fix use-after-free on renaming Delta Lake columns to their physical names #131029, which this merge pulls in.

There are no unresolved review threads.

alexey-milovidov and others added 3 commits November 20, 2026 23:59
…llelism

Conflict in `IObjectStorage.h`: keep both the `ObjectStorageListResult` struct from this branch and the `RemoteHostFilter` forward declaration from master.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The 26.11 release branch was cut without this setting, and master is now 26.12, so the settings changes history entry in the declaration must name 26.12.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
After merging master, `Aws::String` is no longer `std::string`, so the values taken from the `ListObjectsV2` result (`GetKey`, `GetETag`, `GetPrefix`, `GetNextContinuationToken`) need an explicit conversion to `String`, the same way the other listing code in `S3ObjectStorage.cpp` does it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (d528ae28ef39) and resolved the conflict in IObjectStorage.h by keeping both the ObjectStorageListResult struct from this PR and the RemoteHostFilter forward declaration from master.

Two follow-up commits were needed for the merged tree:

  • d351da9243cf: Aws::String now has a custom allocator on master, so S3ObjectStorage::listObjectsSingleLevel no longer compiled; added explicit conversions to String, as the other listing code in S3ObjectStorage.cpp does.
  • 1dd85c996253: the settings changes history entry of s3_list_object_parallelism now says 26.12, because the 26.11 release branch was cut without this setting.

Verified locally on the merged tree: clickhouse and unit_tests_dbms build; all 45 ObjectStorageParallelListing unit tests pass; 04339_s3_parallel_glob_listing and 04340_s3_parallel_flat_listing match their references against a local MinIO. 04498_s3_parallel_listing_inference_invariant matches except for its s3Cluster part, which I could not run locally (no server with the test cluster configuration), so that part is left to CI. The PR diff against master is unchanged in scope (same 23 files).

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 21, 2026
@snelheidai

Copy link
Copy Markdown

I measured s3_list_object_parallelism on public Hive-partitioned buckets over real S3. When the partition levels have few values, the parallel walk is no faster than serial listing at any setting I tried, and up to 9x slower. Those levels never reach the recursive-listing probe. With MIN_CHILDREN_FOR_RECURSIVE_PROBE = 2 instead of 16, most of the extra requests go away.

Setup: this PR's CI build of 68e18a39 (the listing code is unchanged at head d351da92), run with clickhouse local on a 4-vCPU ARM VM in AWS us-east-2. Query: SELECT count(), uniqExact(_path), sum(sipHash64(_path)) FROM s3(url, NOSIGN, 'One'). Each run used a fresh process; times are medians of 5 runs, with the order rotated each round. All runs, including the threshold-2 runs below, returned identical results.

glob (files) LIST requests, p=1 → p>1 p=1 p=2 p=4 p=8 p=16 p=32
OpenAQ locationid=2178/year=*/month=*/*.csv.gz (3,446) 7 → 142 0.87 s 2.48 s 1.49 s 1.01 s 0.87 s 0.90 s
Ookla type=*/year=*/quarter=*/*.parquet (62) 2 → 82 0.34 s 3.02 s 1.83 s 1.19 s 0.98 s 0.86 s
NOAA GHCN by_year/YEAR=*/ELEMENT=*/*.parquet (14,176) 18 → 52 / 63 1.84 s 2.48 s 2.30 s 2.22 s 2.27 s 2.23 s
web/store/*/*/*/* (2,040) 6 → 27 1.77 s 3.04 s 2.47 s 2.37 s 2.39 s 2.41 s
OpenAQ locationid=2178/year=*/month=01/*.csv.gz (287) 7 → 25 0.64 s 0.73 s 0.62 s 0.56 s 0.54 s 0.51 s

Only the last glob gets faster; there the walk prunes 11 of every 12 months.

OpenAQ and Ookla. probeRecursiveListing runs only when a page has at least MIN_CHILDREN_FOR_RECURSIVE_PROBE = 16 unpruned sub-directories. These levels have fewer values: OpenAQ has 11 years and up to 12 months, and Ookla has 2 types, 8 years and 4 quarters. So the walk never checks the density and lists every leaf directory separately: 127 month directories for OpenAQ's 3,446 keys.

The next table uses the same binary with only that comparison changed to children >= 2. The runs are paired, from a separate session; each cell shows the PR as-is → threshold 2, in seconds:

glob LIST p=2 p=4 p=8 p=16 p=32 serial
OpenAQ, all months 142 → 27 2.46 → 0.98 1.47 → 0.82 1.01 → 0.77 0.77 → 0.80 0.73 → 0.78 0.74
Ookla 82 → 3 2.98 → 0.40 1.85 → 0.43 1.20 → 0.44 0.95 → 0.41 0.87 → 0.43 0.32
OpenAQ, month=01 25 → 26 0.75 → 0.80 0.63 → 0.69 0.54 → 0.61 0.51 → 0.64 0.51 → 0.59 0.64

Each OpenAQ year then fits in one recursive page, so the walk runs at about serial speed instead of up to 3.3x slower. The cost is one more round trip wherever the probe fails. For the month=01 glob the root probe is wasted, and that removes most of its gain at p ≥ 8. Starting the probe together with the first delimited page, for levels above the glob's last directory segment, would avoid that wait. NOAA is unchanged, because its root already has 265 sub-directories.

NOAA. After the switch to recursive listing, splitFlatRange takes its boundaries from every byte that appears at or after split_pos in the sampled keys (YEAR=1863/ELEMENT=TMAX/<hex>_0.snappy.parquet). Here split_pos is the first digit of the year, so only the YEAR=1… and YEAR=2… sub-ranges hold keys. The other 30–40 sub-ranges are empty, but each still costs a request: 52 requests at p ≤ 8 and 63 at p ≥ 16, against 18 for serial listing. Splitting at the common prefixes from the range's delimited first page would avoid the empty ranges.

web/store loses here, unlike in your run, because each parallel worker opens its own connection. From this VM, a new connection to eu-central-1 takes about 200 ms. At p=16 the query opened 16 connections (3.2 s in total), while serial listing opened 1.

For reference, the flat case is faster here too: musicbrainz (594,415 files) takes about 98 s serially and 42 s at p=16. The VM is CPU-bound at p=16 (3.7 of 4 cores busy), which limits the gain to 2.3x rather than your 10x.

I did not rebuild from source or run the gtests. Request-count assertions for small trees may need updating along with the constant.

How the threshold-2 binary was made, and the runs
  • Binary: https://clickhouse-builds.s3.amazonaws.com/PRs/107567/68e18a39633bba4777fd7c9efe7221ae4cc57b2a/pr/build_arm_release/clickhouse. In DB::ObjectStorageParallelListingIterator::listRange, the inlined probe check compiles to cmp x22, #0xf; b.hi at listRange+0x4a4. I changed the immediate to #0x1 (one byte), so any page with at least 2 unpruned sub-directories is probed. MIN_DIRECTORIES_PER_RECURSIVE_PAGE is unchanged.
  • Each run: clickhouse local --time --multiquery -q "SELECT count(), uniqExact(_path), sum(sipHash64(_path)) FROM s3('<url>', NOSIGN, 'One') SETTINGS s3_list_object_parallelism = <p>; SELECT sumIf(value, event = 'S3ListObjects') FROM system.events". The time is the query's elapsed time.
  • Buckets: openaq-data-archive (us-east-1, prefix records/csv.gz/), ookla-open-data (us-west-2, prefix parquet/performance/), noaa-ghcn-pds (us-east-1, prefix parquet/), clickhouse-public-datasets (eu-central-1).
  • First table: 5 rounds, with the order of p rotated each round. Threshold table: 5 rounds; for each p, both binaries ran back to back, in alternating order.
  • Connection counts are from StorageConnectionsCreated and StorageConnectionsElapsedMicroseconds. The CPU figure for musicbrainz is from time: 34.8 s wall, 64 s user, 64 s system.

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

Sophisticated, but well-contained. LGTM.

alexey-milovidov and others added 3 commits November 22, 2026 23:39
…llelism

Resolved the conflict in `StorageObjectStorageSource.cpp`: keep both the `config.h` include from `master` and the `<algorithm>` include from this branch.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
`clang-tidy` now enforces `modernize-use-nodiscard`, and the `arm_tidy` builds failed on the listing methods this branch adds to `IObjectStorage` and on `ListRange::isPastEnd`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107567&sha=d351da9243cfeb249b2b2f9910d806a02a158616&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29
#107567

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Address review: `probeRecursiveListing` ran only for a page with at least 16 unpruned sub-directories, so partitioned layouts with few values per level (e.g. `type=*/year=*/quarter=*/`) never reached it and were listed with one request per leaf directory. Measured on real S3, that was up to 9 times slower than the serial listing. Lower `MIN_CHILDREN_FOR_RECURSIVE_PROBE` to 2 and add unit tests for such layouts.

#107567 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @snelheidai, thanks for the measurements. Applied in 6b93d302be6a:

  • MIN_CHILDREN_FOR_RECURSIVE_PROBE is now 2, so a page with at least two unpruned sub-directories is probed. A range with a single sub-directory is still just descended into.
  • Two unit tests cover the layouts you measured: FewValuesPerPartitionLevelAreListedRecursively (2 types, 8 years, 4 quarters, one file each: 2 requests instead of 83) and SmallSubtreesBelowFewValuesAreListedRecursively (11 years of 12 months of 26 files: at most 24 requests instead of 144). The existing 45 ObjectStorageParallelListing tests pass unchanged, so no request-count assertion needed updating.

Not changed in this pass:

  • Starting the probe together with the first delimited page (the wasted round trip for month=01).
  • Splitting a recursive range at the common prefixes instead of the sampled byte alphabet (the empty sub-ranges for NOAA).
  • One connection per listing worker (the web/store result from a distant region).

These three cost extra requests or connections but do not affect the results, and the setting is off by default (s3_list_object_parallelism = 1), so I left them for a follow-up.

Also in this push: merged master (one include conflict in StorageObjectStorageSource.cpp), and bd03b9632f55 marks the new listing methods as [[nodiscard]], which is what failed the arm_tidy builds on the previous head.

for (const auto & object : result.GetContents())
{
ObjectMetadata metadata{
.size_bytes = static_cast<uint64_t>(object.GetSize()),

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.

[Blocker] Preserve the selected object's version when attaching listing metadata

Unlike S3IteratorAsync, this path always attaches the current version's ListObjectsV2 metadata, even when uri.version_id selects an older version. That bypasses the version-aware HEAD in StorageObjectStorageSource::createReader and uses the current size to bound the historical read.

For example, let the current data.csv contain 9\n (2 bytes), and version old contain 1\n2\n (4 bytes). Reading s3('.../data*.csv?versionId=old', ..., 'CSV', 'x UInt64') with s3_list_object_parallelism=8 and prefetch enabled bounds the old-version read to 2 bytes, silently returning [1] instead of [1,2]. If the current version is empty, s3_skip_empty_files=1 skips the non-empty historical version entirely. _size, _etag, and _tags also describe the wrong version.

Mirror the serial iterator's reads_explicit_version branch: return the key with metadata unset when uri.version_id is non-empty, allowing the existing version-aware metadata request to run. Add a focused stateless regression comparing parallelism 1 and 8 for historical versions with different sizes; the HTTP mock in 05814_s3_explicit_version_size_from_version_metadata.sh can be reused.

@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 23, 2026 00:57

AI review of a later commit does not approve the PR, see the AI Review comment.

@stresshouse

stresshouse Bot commented Nov 23, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — inconclusive across 29 queries analysed

This PR has no regressions or improvements in this comparison. Only clickbench Q31 was flagged, at +10.6% (240 ms vs 217 ms), and it stays not_sure: master's timings for this query changed character after 2026-11-23 (Q10 and Q30 are affected too), and its history is noisy. The PR adds an opt-in parallel listing path for globbed S3 reads, behind the new setting s3_list_object_parallelism, which defaults to 1 and keeps the old serial listing. Q31 reads a local table and never calls that code, so the shift is not plausibly caused by this change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 31 not_sure 217 240 +10.6% 0.0025 aggregation: Q31 runs a GROUP BY over the local hits table and never reaches S3 glob listing. The +10.6% shift falls in a master era that recently became unstable, and this query's history is noisy.

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
  • StressHouse run: 7f5ecd25-cb4d-4f92-8c02-9ef49fb89423
  • MIRAI run: 026b7083-dcb6-4c01-8984-a2bc81cef27f
  • PR check IDs:
    • clickbench_916096_1795406656
    • clickbench_916210_1795406682
    • tpch_adapted_1_official_916236_1795406684
    • tpch_adapted_1_official_916654_1795406924

This branch has not been deployed

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

Labels

comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parallelize listing of files on S3

5 participants