Skip to content

Return the cached row count of a file as one chunk when only count() reads it - #124174

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:count-from-files-cache-one-chunk
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:count-from-files-cache-one-chunk

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

A repeated count() over file(), url(), s3() and the other file-like table functions and engines, which takes the row count of each file from the cache, now returns it as one block per file instead of one block per max_block_size rows. ClickBench Q1 (SELECT count(*) FROM hits) on a 100M-row Parquet file is more than 6 times faster. Closes #124144.

Description

With optimize_count_from_files and use_cache_for_count_from_files (both on by default), a repeated count() over file(), url() or s3() reads no data: the row count of each file comes from the schema cache. The three cached-count shortcuts (StorageFileSource, StorageURLSource, StorageObjectStorageSource) still emit it through ConstChunkGenerator in max_block_size chunks: 1529 chunks for 100M rows, each going through the pipeline.

The slicing exists because something may materialize the placeholder column of these chunks. That cannot happen when the only aggregate is count() without arguments and the read requests no virtual or hive partition columns, so such a read now gets one chunk per file:

  • the planner records the no-argument property next to optimize_trivial_count (SelectQueryInfo::trivial_count_without_arguments);
  • Merge clears it, because convertAndFilterSourceStream materializes every column of its child reads;
  • object storage skips its const-to-full conversion for that one chunk.

count(x), filtered counts, virtual and hive columns, merge() and first executions are unchanged.

Release builds (x86_64), 99,997,497-row Parquet file, row count cached, 8 paired fresh-server runs, median:

Query Before After
SELECT count(*) FROM hits (File(Parquet)) 18.8 ms 2.8 ms
SELECT count() FROM url(...) 18.9 ms 5.4 ms
SELECT count() FROM s3(...) 22.1 ms 7.1 ms
merge(), count(b), MergeTree controls within noise within noise

The stateless test checks, with a memory limit, that every read which does materialize its columns (count(materialize(x)), s3(), merge(), hive columns) still gets max_block_size chunks; each of those cases fails when its exclusion is removed. A performance test covers the cached count().

The analysis and original patch are from #124144; this version moves the "no arguments" decision into the planner and adds the Merge exclusion. I can switch to a storage-local check instead of the new SelectQueryInfo field if preferred.


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

…lumns

With `optimize_count_from_files` and `use_cache_for_count_from_files`, a
repeated `count()` over `file()`, `url()` or `s3()` takes the row count of each
file from the schema cache, but `ConstChunkGenerator` emitted it in
`max_block_size` chunks (1529 chunks for 100M rows), each going through the
pipeline and the aggregation.

The slicing exists because a consumer may materialize the placeholder column.
That cannot happen when the only aggregate is `count()` without arguments and
the read requests no virtual or hive partition columns, so such a read now gets
one chunk per file. The planner records the no-argument property in
`SelectQueryInfo::trivial_count_without_arguments`; `Merge` clears it because
`convertAndFilterSourceStream` materializes every column of its child reads;
object storage skips its const-to-full conversion for that one chunk.

Issue: ClickHouse#124144

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 6, 2026
@groeneai

groeneai commented Oct 6, 2026

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

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The stateless test does not assert that the cached count() produces one chunk DISAGREE The positive path is covered by tests/performance/count_from_files_cache.xml (14.40 to 3.72 ms, ratio 0.249 [0.210, 0.294]); the stateless test covers the exclusions, each of its four memory-limited queries fails when its exclusion is removed.
2 💡 A shard planning count() only up to FetchColumns would add the row-count marker over one block noted No route found besides Merge over a multi-shard Distributed at FetchColumns; bounded at 1 byte per row. No change.

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

Session id: cron:clickhouse-review-slot-8:20261006-073808

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0186dd2]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 1/6) FAIL Performance dashboard
aggregation_in_order_if_null_map #0 FAIL dashboard
aggregation_in_order_if_null_map #1 slower query history
window_functions_ranking #11 unstable query history

AI Review

Summary

The PR emits cached file row counts in one chunk for a no-argument count, reducing pipeline overhead for File, URL, and object-storage reads. The performance measurements support that improvement, but partial-stage reads violate the assumption that nothing materializes the chunk: a baseline-success/PR-failure reproduction shows memory growing with the entire file. One previously acknowledged concern remains blocking; no duplicate inline thread was posted.

Consumer tracing covered ExtractColumnsTransform and subcolumn extraction (preserve constant columns), no-argument aggregation (uses row counts), virtual/Hive columns and in-order reads (excluded), lazy readers and queue readers (optimization disabled), and Alias/URL dispatch (forward the read). Merge clears the flag locally, but a remote planner can enable it again before NativeWriter materializes its output.

Findings

❌ Blockers

  • src/Planner/PlannerJoinTree.cpp:632, src/Storages/prepareReadingFromFormat.cpp:904: A no-argument aggregate does not guarantee aggregation runs before materialization. The flag is also set when the requested processing stage is FetchColumns; Planner then returns before adding aggregation. The cached source emits a file-sized ColumnConst, and NativeWriter::writeData converts it to a full column. This replaces bounded cached reads with allocations proportional to the file's row count and can exhaust query/server memory. Clearing the flag in Merge does not cover remote shard replanning.

    [dismissed by author -- https://github.com/Return the cached row count of a file as one chunk when only count() reads it #124174#issuecomment-6012243154] The earlier note accepts a one-byte-per-row marker allocation; the current native-output path materializes the physical placeholder itself, demonstrated with a 76 MiB UInt64 allocation.

    Reproduction: write and warm a 10,000,000-row Parquet file with x UInt64, then request SELECT count() FROM file('counts.parquet', Parquet, 'x UInt64') SETTINGS max_memory_usage=33554432 using the native client's --stage fetch_columns, discarding client stdout. Master 1baff789f8493a93cdc87bfaa0440592aa427ed3 succeeds; the PR binary attempts 76.24 MiB and fails with MEMORY_LIMIT_EXCEEDED. A normal Merge over a two-shard Distributed table, with a declared type conversion forcing FetchColumns, also reaches ColumnConst::convertToFullColumn → NativeWriter::writeData → TCPHandler::sendData after cache hits. Its cached count(x) control stays bounded. The normal-query baseline has a separate header error, so only the direct partial-stage case establishes a previously successful query regressing.

    Gate the single-chunk optimization on aggregation actually consuming the read before any materializing boundary, including remote reads requested at FetchColumns.

Tests
  • ⚠️ Add focused coverage for a warmed cached count at FetchColumns with native output and a memory limit; FORMAT Null bypasses the materialization and does not exercise this boundary. Include the Merge/Distributed route where remote replanning bypasses the local exclusion.
  • Runtime comparison used the PR's 45e12795829eeb2adea0ea995b84a1bbb14b11cf build artifact; GitHub's comparison confirms the current head changes only the stateless test and its reference after that commit. The C++ implementation is unchanged. Logs are in tmp/review_124174/build/baseline_wire/, tmp/review_124174/build/pr_wire/, and tmp/review_124174/build/test_merge_distributed_controls.log.
Final Verdict

Status: ❌ Block

Preserve bounded cached chunks when aggregation has not run before a materializing boundary, and add a regression test for partial-stage native output.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). labels Oct 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0186dd287 with master 1baff789f (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

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

Job report

`Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)`
enables parallel replicas in the server profile, so with
`parallel_replicas_for_cluster_engines` the `url()` and `s3()` arms run as
`urlCluster`/`s3Cluster`. The count then happens on the replicas, and the
initiator's `query_log` row has `SchemaInferenceCacheNumRowsHits = 0`, which
failed the cache-hit check 3 out of 3 reruns. The arms test the local read, so
the test pins `parallel_replicas_for_cluster_engines = 0`; `file()` and `merge()`
are not affected by the setting.

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

clickhouse-gh Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 7a1a527d-f21b-4641-88c4-a1a45047c157
  • MIRAI run: 5c50b809-37a5-4764-8b4f-eca324f48152
  • PR check IDs:
    • clickbench_27377_1791300661
    • clickbench_27383_1791300662
    • clickbench_27389_1791300661
    • tpch_adapted_1_official_27400_1791300661
    • tpch_adapted_1_official_27413_1791300661
    • tpch_adapted_1_official_27450_1791300661

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7b466d3

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
Stateless tests (arm_asan_ubsan, azure, sequential) / job timeout the job hit its 9000 s wall-clock cap at test 1152 of 1168 (Timeout exceeded [9000], SIGTERM, exit code -15). All 1061 tests that ran before the kill passed, so CIDB has only the job-level row. The same job-level error hit 41 other PRs and 11 master runs in 14 days, and this PR's new test does not run in this job #123849 (mine, open): splits this job into 2 batches
PR rollup, red only because of the row above #123849
Sync - CH Inc sync (private, not actionable by me)

All 146 check runs completed and Finish Workflow is green. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261006-193218

…che-one-chunk

# Conflicts:
#	src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp
#	src/Storages/ObjectStorage/StorageObjectStorageSource.cpp
#	src/Storages/ObjectStorage/StorageObjectStorageSource.h
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 93e564d

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
Stateless tests (amd_debug, sequential) / 05339_iceberg_top_k_query_condition_cache master breakage, not from this PR (it changes how a cached row count is emitted): the test failed on all master commits from the #126987 merge 41d5f3406f9d until its revert, and the tested merge tree 0f7e50cb5b53 contains #126987 but not the revert #127378 (external, merged revert)
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_asan_ubsan, azure, sequential, 2/2) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Mergeable Check, PR praktika rollups of the rows above #127378 (the owner of the rows above)

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

Session id: cron:our-pr-ci-monitor:20261022-170010

…che-one-chunk

Conflicts in StorageObjectStorageSource.{cpp,h} (createReader parameter
list: master added prefetch_input_format, this branch count_in_one_chunk;
both kept) and StorageFile.cpp (ReadFromFile::initializePipeline: master's
query_condition_cache_table_id block and this branch's count_in_one_chunk
line; both kept).

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

Copy link
Copy Markdown

Since ClickBench bbc2118 (2026-11-08), clickhouse-parquet and clickhouse-parquet-partitioned run queries through clickhouse-server, restarted before each query, so the hot runs repeat SELECT COUNT(*) on a running server with the row count already cached. I merged this PR's head into master b8c902a: it applied cleanly except for two one-line conflicts in StorageFile.cpp and ReadFromObjectStorageStep.cpp, where I kept master's lines and added the PR's count_in_one_chunk line.

Release builds (clang-21, no LTO), r6i.8xlarge (Xeon 8375C) with the server pinned to 16 cores, ClickBench config.yaml, warm server, clickhouse benchmark -c1 -i300 mean latency, two alternating passes per build; results identical:

Query master master + this PR
SELECT COUNT(*) FROM hits, single hits.parquet 12.95 / 13.04 ms 2.22 / 2.22 ms
SELECT COUNT(*) FROM hits, 100 partitioned files 3.58 / 3.64 ms 2.58 / 2.59 ms
SELECT COUNT(*) FROM hits WHERE AdvEngineID <> 0, both tables 10.1–10.3 ms 10.2–10.3 ms
SELECT count(), max(EventDate) FROM hits, both tables 9.6–10.1 ms 9.6–10.1 ms

…che-one-chunk

Conflicts: StorageFile.cpp (ReadFromFile::initializePipeline, master's
single-file split block next to count_in_one_chunk; trySplitSingleFile
returns nullptr when need_only_count, so the two never meet) and
prepareReadingFromFormat.h (both forward declarations kept).

Also pass count_in_one_chunk_ = false from the new
ReadFromObjectStorageStep::buildInOrderPipe: it calls the source
constructor positionally, and the read-in-order merge materializes the
sorting key of the columns it reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 21, 2026
@stresshouse

stresshouse Bot commented Nov 21, 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=25 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 5a743a7f-d71e-4dde-a87e-90d81c280873
  • MIRAI run: c78648cd-3be8-4c19-8c2a-9ad358a81fa3
  • PR check IDs:
    • clickbench_685918_1795283132
    • clickbench_685924_1795283132
    • tpch_adapted_1_official_685931_1795283132
    • tpch_adapted_1_official_685945_1795283132

The randomized Parquet writer settings (ClickHouse#132712) made the four 10M-row
fixtures of the test take up to 460 s in the tsan and msan flaky checks.
Write 1M rows and lower the memory limits from 40 MiB to 3 MiB. With
`max_block_size = 8192` and `max_untracked_memory = 0` a read in
`max_block_size` chunks peaks below 0.5 MiB, while one chunk of 1M UInt64
rows needs 7.63 MiB, so every case still fails when its exclusion is
removed.

Since ClickHouse#131185 an aggregation without GROUP BY copies at most 1 MiB of a
constant argument, so `count(x)` no longer materializes a one-chunk read.
The case counts `materialize(x)` instead, which still does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 21, 2026 17:11

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0186dd2

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
Performance Comparison (amd_release, master_head, 1/6) / aggregation_in_order_if_null_map #0 perf noise, not from this PR (it changes only the trivial count() paths of file/url/S3/Merge): the query is a MergeTree GROUP BY in order with sumIfOrDefault. Queries #0/#1 of this test were also slower on a master run on 2026-11-13, and #3/#4 failed on another PR on 2026-11-20 a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the same task as the row above)

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

Session id: cron:our-pr-ci-monitor:20261121-193028

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Performance Comparison (amd_release, master_head, 1/6) red in the ledger above (aggregation_in_order_if_null_map #0, with #1 slower next to it) is a property of this build, not of this PR's code, so no fixing PR follows.

  • Same work at a lower speed: in the job's prewarm query_log the PR server ran #0 with 1639.0M instructions against 1638.4M on the reference and equal branch misses (0.9M and 1.0M), but in 522M cycles against 436M (+20%); Repair subtree2 #1 is the same. Rows, marks and arena bytes are equal, and the job's restart check reproduced it at all three stack placements.
  • Every function on the query's path (AggregatingInOrderTransform::work, the Aggregator interval functions, AggregateFunctionNullVariadic::addBatchSinglePlace, the -OrDefault/-If/sum batch functions, CurrentMemoryTracker, jemalloc) has identical machine code in both binaries (address-normalized disassembly). work sits 1216 bytes, the Aggregator functions 704 bytes and jemalloc 4096 bytes later in this build; the rest is at the same address.
  • The speed follows the binary: of 2584 amd binaries measured since 2026-10-27, 27 run #0 18-33% slower than the rest (measured against Repair subtree2 #2 and doc: fix typo #4 of the same server), master builds included (14f22279602d in both of its runs, report), and none of the 1229 binaries measured in two or more server processes was fast in one and slow in another. On arm_release #0 moved by more than 10% in 2 of 6500 runs.

As ruled in #132892 (comment), a row like this stays for the reviewer to judge, so I am not changing the test or the perf job for it.

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-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

count() over file/url/S3 re-emits a cached row count as max_block_size chunks; one chunk per file makes ClickBench q1 on Parquet 13x faster

2 participants