Skip to content

Do not wait for unused Parquet reads after LIMIT or a cancellation when reading from object storage - #127624

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:parquet-s3-no-wait-for-unused-reads
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:parquet-s3-no-wait-for-unused-reads

Conversation

@groeneai

@groeneai groeneai commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #127592
Related: #131938

Changelog category (leave one):

  • Performance Improvement

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

Queries that read Parquet from object storage no longer wait for the background reads of row groups they do not need once a LIMIT is satisfied or the query is cancelled (max_execution_time, KILL QUERY, client cancel): these reads are now stopped. For example, SELECT * FROM s3(...) LIMIT 2 through a throttled connection finishes in under a second instead of several seconds.

Description

SELECT * FROM s3(<file>, 'Parquet') LIMIT 2 over a throttled connection took 7.1 s against 33 ms with one parsing thread, and a read stopped by max_execution_time = 2 ended about 6 s after the deadline (#127592; KILL QUERY and Ctrl+C likewise).

The reader teardown (ReadManager::shutdownTasks) waited for the decode tasks before stopping the prefetcher, whose reads passed no progress callback to readBigAt, so the 16 MiB reads of unused row groups ran to the end. And a cancellation did not reach the nested reader of StorageObjectStorageSource while its pull waited for data.

Changes:

  • Prefetcher reads stop once its shutdown is requested, and unstarted reads fail at once; shutdownTasks requests it before waiting for the decode tasks.
  • ReadManager::cancel makes read return the end of data instead of throwing, so the query reports its own error (159, 394, 735 unchanged), and stops the prefetcher's data reads, which read itself waits for with max_parsing_threads = 1. It no longer builds an Exception(QUERY_WAS_CANCELLED) with a stack trace for every file, also one read to the end (proposal 4 of Overview: per-file overhead when reading many small cached Parquet files of Iceberg tables (reader setup, IN set probes, query-level format settings) #131938).
  • StorageObjectStorageSource::onCancel cancels the current file's format when it supports that (IInputFormat::supportsCancellationDuringRead: Parquet and the aggregate_function_input_format wrapper), and a cancelled read caches nothing about the file.

Validation: the issue's script on release builds, base vs fix: A1 7130-7135 vs 17-633 ms, A3 end_ms - 2000 6031-6139 vs 493-599 ms; one parsing thread at 2 MiB/s (debug): 5.4 s without stopping the reads in cancel, 0.4-0.5 s with it. Over 4,000 small cached files (debug), ReadManager::cancel is in 1.3-1.8% of the CPU samples on master and in none of 2,150 here. The new test fails on master and passes 32/32 randomized runs.

Not covered: in-flight reads through the userspace page cache, Azure, HDFS or a non-positional buffer and footer reads still complete.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 23, 2026 17:15
Reading Parquet from object storage, the reader starts reads of the row
groups beyond the first one. After a satisfied `LIMIT`, the reader
teardown (`ReadManager::shutdownTasks`) waited for those reads: it
drained the decode tasks first, which waited for the reads, and the
reads passed no progress callback to `readBigAt`, so nothing stopped
them. Through a throttled connection that is seconds (7.1 s against
33 ms for the same rows read with one parsing thread, ClickHouse#127592).

A cancellation (`max_execution_time`, `KILL QUERY`, a client cancel) did
not reach the nested reader of `StorageObjectStorageSource` while its
`pull` waited for a decoded chunk, so the query ended only after a whole
read had completed, and then waited in the teardown as well.

- Prefetcher reads pass a progress callback that stops them once the
  prefetcher's shutdown is requested, and reads that have not started
  fail at once. `ReadManager::shutdownTasks` requests it before waiting
  for the decode tasks; the waits keep their order, so no task reads
  through the buffer after `shutdownTasks` returns.
- `ReadManager::cancel` makes `read` return the end of data instead of
  an exception, so a forwarded cancellation never becomes an error of
  its own and the query reports its own reason (159, 394, 735).
- `IInputFormat::supportsCancellationDuringRead` (Parquet, and the
  `AggregateFunctionStatesFromValuesInputFormat` decorator in front of
  it) lets `StorageObjectStorageSource::onCancel` cancel the format of
  the current file from another thread. A read that was cancelled may
  have ended early, so the source caches nothing about the file then
  (row count, query condition cache).
- `ParquetV3BlockInputFormat::initializeIfNeeded` holds `reader_mutex`
  only around the emplace, and applies a cancellation that came before
  it, so a cancel is neither lost nor kept waiting by the footer read.

Not covered: an in-flight read through the userspace page cache, Azure,
HDFS or a buffer without positional reads completes as before, and the
footer reads are not interrupted.

Closes ClickHouse#127592

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Write method names as `f` instead of `f()` in the added comments, drop a redundant line on `ReadManager::shutdownTasks`.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ The S3Queue/AzureQueue source does not forward a cancellation into its blocked nested read DISAGREE (out of scope: separate PR) ObjectStorageQueueSource never pulls after a cancel and its teardown uses the same ReadManager::shutdownTasks, so the unused-read wait is gone there too; forwarding first needs a cancelled-read path in its file state machine (pull returning false marks the file Processed).
2 ⚠️ The timing bounds (+3000 ms, +2500 ms) are looser than one 16 MiB read DISAGREE Each check reddens when its part of the fix is reverted (base: 7.1 s); the fix measured up to 825 ms and 2905 ms over 91 randomized debug runs, so a 1 s bound would be flaky on sanitizer builds.
3 ⚠️ The test does not cover the aggregate_function_input_format wrapper DISAGREE One-line forward next to the wrapper's other forwards; measured with aggregate_function_input_format = 'value': the next query starts 7149 ms after the start on base, 2400 ms with the fix.
4 💡 New comments write f() instead of f AGREE Comment-only, fixed before push.
5 💡 (own) A cancellation that arrives while the reader drains at the end of a file waits for reader_mutex of ParquetV3BlockInputFormat Noted, not blocking Narrow window; the drain is short for S3 now.
6 💡 (own) readBigAt of Azure and HDFS ignores the progress callback Noted, not blocking Stated in the description: in-flight reads there complete as before, queued ones are skipped.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261023-172100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: the issue's script and 05446_parquet_s3_no_wait_for_unused_reads reproduce on every run on base (about 7.1 s, bound by the 8 MiB/s throttle).
b Root cause explained? Teardown waited for the decode tasks before stopping the prefetcher, and its reads had no progress callback, so the unused 16 MiB reads ran to the end; a cancellation did not reach the nested reader of StorageObjectStorageSource while pull waited for data.
c Fix matches root cause? Yes: the reads get a stop signal and are told to stop before the drain; the cancellation is forwarded to the blocked reader. No bound, admission, coalescing or setting change.
d Test intent preserved / new tests added? New test: a premise (the LIMIT query started reads the one-thread control did not) and three checks; reverting each part of the fix reddens its check.
e Both directions demonstrated? Yes, base vs fix on debug and release builds, with the issue's script and with the test (fails on base on its two timing checks only).
f Fix is general across code paths? Every reader shutdown goes through ReadManager::shutdownTasks; S3 and HTTP reads honor the callback; the aggregate_function_input_format wrapper forwards the capability. Azure, HDFS, page-cache and non-positional reads complete as before (queued ones are skipped).
g Fix generalizes across inputs (params/datatypes/wrappers)? No type-dependent logic. Checked with 24 and 1 parsing threads, throttled and unthrottled, top-K, the wrapper path, a corrupted row group, and 91 randomized runs.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change; error codes unchanged (159, 394, 735 measured).
i Invariants and contracts preserved? The waits keep their order, so no task reads through the buffer after shutdownTasks returns (#114668). The reader is replaced only under the new mutex and destroyed outside it. Row count and query condition cache entries are written only for a read that was not cancelled.

Session id: cron:clickhouse-impl-slot-5:20261023-144400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @scanhex12, could you review this and add the can be tested label so CI runs? The Parquet prefetcher's reads now stop (a progress callback for readBigAt, an early-out for queued reads) before ReadManager::shutdownTasks waits for the decode tasks, and StorageObjectStorageSource::onCancel forwards a cancellation to the blocked reader, so a satisfied LIMIT or max_execution_time no longer waits seconds for unused row-group reads.

@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [68b6629]

Summary: ✅


AI Review

Summary

Reviewed #127624 at 68b66296a67cc1b546f8325ee41f032390008cf8, including all prior discussion and the current implementation. The change stops unused Parquet prefetches before draining decode tasks, forwards cancellation to the active object-storage reader, and prevents incomplete reads from populating row-count and query-condition caches. The earlier finding about cancellation with max_parsing_threads = 1 is fixed. No unresolved actionable findings remain; approve.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available, and latest-head functional CI was still pending. Runtime evidence includes the author's before/after measurements and the preceding revision's MSan regression runs: 49 passed, with one fixture-generation timeout using brotli. The latest commit pins the codec to zstd; completion of its functional jobs will close this remaining validation gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-parquet-reader-v3 Issues related to the native Parquet reader. labels Oct 23, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 23, 2026
groeneai and others added 2 commits October 23, 2026 20:25
…thread

With `max_parsing_threads = 1` the manual executor runs the decode tasks
inside `ReadManager::read`, in the query thread. A decode task waiting in
`Prefetcher::getRangeData` for a remote read could not be woken up by
`ReadManager::cancel`, which only set `cancelled` and notified
`delivery_cv`; the prefetcher's reads were stopped only by `shutdownTasks`,
after the inline task had returned. So a timed out or killed query still
waited for the whole range read in progress: 5.4 s after a
`max_execution_time = 2` deadline for a 16 MiB row group at 2 MiB/s.

`cancel` now also stops the prefetcher's reads, once `init` has read the
file metadata (reading the metadata is still not interrupted, as documented
in `IInputFormat::supportsCancellationDuringRead`). The tasks failed by the
stopped reads record an exception, so `read` checks `cancelled` before
`exception` and still returns end of data: the query keeps its own error
(159 instead of 394 from the stopped read).

The test gets the same timed out query with one parsing thread through a
2 MiB/s connection; it fails without this change (next statement 7.4 s
after the start instead of at most 4.5 s). Its `s3` call now names the
structure, so the request-count premise does not depend on schema inference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fixes the `Build (arm_tidy)` failure `cppcoreguidelines-init-variables`
on `ReadManager.cpp:195`. The variable was always assigned under
`delivery_mutex` before use, so the behavior does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 68b66296a with master 49d9f8fdc (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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ea071f2

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Cannot start clickhouse-server, Server failed to start, Check failed not from this PR: the check runs the stateless tests of v26.9.25.15-stable on that release, then starts this PR's binary, which since #125817 refuses to attach a table those tests leave with a small SLRU cache disk (max_file_segment_size (33554432) must not exceed the size of each SLRU queue). The test fix is merged on the release branches and reaches this check with the next 26.9 stable tag #127566 (external, merged), #127567 (external, merged)
Mergeable Check, PR praktika rollups of the row above #127566 / #127567 (the owners of the row above)
CH Inc sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261024-013003

…for-unused-reads

# Conflicts:
#	src/Processors/Formats/Impl/Parquet/ReadManager.h
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
#	src/Storages/ObjectStorage/StorageObjectStorageSource.cpp
@arsenmuk

Copy link
Copy Markdown
Member

@groeneai this PR also removes the Exception(QUERY_WAS_CANCELLED) that ReadManager::cancel builds for every file after a normal finish (proposal 4 of #131938: 1.2–1.4% of CPU when reading 8,400 small cached files). Please:

  1. Mention it in the description and add Related: #131938.
  2. Check that cancel after a file was read to the end stays cheap: it now calls prefetcher.cancelReads() for every file.

@arsenmuk

Copy link
Copy Markdown
Member

@groeneai also merge latest master, and resolve conflicts

groeneai and others added 2 commits November 22, 2026 15:18
…for-unused-reads

# Conflicts:
#	src/Processors/Formats/Impl/Parquet/ReadManager.cpp
#	src/Processors/Formats/Impl/Parquet/ReadManager.h
#	src/Storages/ObjectStorage/StorageObjectStorageSource.cpp
#	src/Storages/ObjectStorage/StorageObjectStorageSource.h
Master now randomizes the Parquet reader and writer settings in stateless
tests. Under some of the values the test's premise does not hold:
- `input_format_parquet_max_block_size` 1000 or 8192,
  `input_format_parquet_prefer_block_bytes` 65536 and
  `input_format_parquet_memory_low_watermark` 64 MiB make the one-thread
  control read all row groups before its first block (3-7 s, also on master);
- `input_format_parquet_memory_high_watermark` 1 MiB or less leaves no
  background reads to stop;
- a smaller `output_format_parquet_row_group_size_bytes` splits the row
  groups, and without a dictionary and compression row group 0 is 16 MiB
  like the others instead of 5 KiB.

Clamp them with a `Random settings limits:` line. Before: 1 of 1 and 5 of 24
randomized runs failed; after: 32 of 32 pass, and the test still fails on master.

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

Copy link
Copy Markdown
Collaborator Author

Done: master is merged in 4497880 (conflicts in ReadManager.{h,cpp} and StorageObjectStorageSource.{h,cpp}; the new fields use master's TSA_GUARDED_BY(delivery_mutex)), and the head is now c69595d.

  1. The description now says that ReadManager::cancel no longer builds Exception(QUERY_WAS_CANCELLED) for every file, with Related: #131938.
  2. cancel after a file was read to the end stays cheap. Prefetcher::cancelReads is ShutdownHelper::begin_shutdown: with no read in flight, two atomic adds, an uncontended lock/unlock and a notify_all without waiters. On master ~ReadManager already calls it for every file (through Prefetcher::shutdownTasks); after cancel the calls in ~ReadManager take the already-requested path (two atomics each). Measured on 4,000 small files with the footers and columns cached (use_parquet_metadata_cache = 1, use_columns_cache = 1, no misses), debug builds, 3 runs each, CPU profiler at 1 ms:
    • master (903285f): ReadManager::cancel in 34 of 2,259 samples (1.3-1.8% per run), 32 of them building the exception (Exception constructor, StackTrace);
    • this PR: in 0 of 2,150 samples.

One more change: master now randomizes the Parquet reader and writer settings in tests, and some values broke the premise of the test. For example, with input_format_parquet_max_block_size = 1000 the one-thread control reads all row groups before its first block and takes 3-7 s, on master too. c69595d clamps them with a Random settings limits: line: 32/32 randomized runs pass, and the test still fails on master.

@stresshouse

stresshouse Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

no significant changes detected. K_source=4 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 46c40991-7ba0-400f-8e43-7aa239d920e9
  • MIRAI run: 027bcefb-65c9-4dc8-b940-9f9a38e762f3
  • PR check IDs:
    • clickbench_839823_1795375688
    • clickbench_839839_1795375687
    • tpch_adapted_1_official_839868_1795375688
    • tpch_adapted_1_official_839889_1795375688

The test writes 10M UInt64 values, 8M of them random hashes, into one Parquet
file. With the randomized writer settings, 1 run in 8 compresses them with
brotli. In `Stateless tests (amd_msan, flaky check)` the 8 slowest of 50 runs
were exactly the brotli runs (CI query_log): their INSERT took 26-205 s, and one
run took 218 s in total, over the 180 s limit. Every other codec, data page size
and batch size kept a run under 36 s.

Measured on this PR's msan binary, one copy: the INSERT costs 3.9 s CPU with
zstd, 17.7 s with brotli, and 56.2 s with brotli plus 1-byte data pages and
100-row batches (the failed run's draw).

The codec does not affect what the test checks, so it is pinned to the default
`zstd`.

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

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

can be tested Allows running workflows for external contributors comp-parquet-reader-v3 Issues related to the native Parquet reader. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parquet queries on S3 take seconds to finish after LIMIT or a hard cancellation

3 participants