Skip to content

Do not materialize constant columns in object storage reads - #132892

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:object-storage-count-drop-const-materialization
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:object-storage-count-drop-const-materialization

Conversation

@groeneai

@groeneai groeneai commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #132859
Related: #95773
Related: #97019
Related: #124174

Changelog category (leave one):

  • Performance Improvement

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

count() and other reads that only need the number of rows (for example sum(1)) over s3, azureBlobStorage, hdfs and data lake tables no longer allocate a column with one value per row of each file. Such a count() over a 100M-row Parquet object now uses about 1 MB of memory instead of about 800 MB.

Description

With optimize_count_from_files, a count-only read takes the row count of each file from its metadata and gets one chunk per file whose columns are constant placeholders. StorageObjectStorageSource::generate converted every constant column of every chunk to a full column (#95773), so that chunk was expanded to all rows of the file.

#95773 added the conversion because INSERT squashing merged the DeltaLake partition constants of different files into one value (#95526). #97019 fixed that in Squashing::squash, which now materializes constants before concatenation, so this PR removes the conversion. A single chunk that squashing passes through unchanged is materialized by the INSERT pre-sink (addMissingDefaults wraps every output column in materialize), so inserting from a partitioned DeltaLake table into file (CSV, TSV, JSONEachRow), s3 (CSV) and Buffer writes the same rows as on master.

Semantic edge: in a data read, DeltaLake partition columns are constant per chunk again (isConstant returns 1), as before #95773. Virtual, hive and Iceberg identity-partition columns and the Iceberg and Paimon schema-evolution defaults were already full and are unchanged. The object-storage condition of #124174 targets the removed block and drops out on rebase.

Validation (debug build, local MinIO): count() over a 100M-row String object 801 MB / 108 ms -> 0.9 MB / 11 ms; a sum(x) data read is unchanged. The new stateless test fails on master with MEMORY_LIMIT_EXCEEDED (76.7 MiB under a 40 MiB limit) and passes 50/50 with random settings. The test_storage_delta partition-column tests, 03918_insert_squashing_const_different_values, and Iceberg (position deletes), hive, s3Cluster and merge() reads return the same results as master. The analysis and the release-build measurements are from #132859.


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

A count-only read (`optimize_count_from_files`) takes the row count of each
file from its metadata and gets one chunk per file whose columns are constant
placeholders. `StorageObjectStorageSource::generate` converted every constant
column of every chunk to a full column, so such a `count()` allocated and
filled one value per row of the file in one thread (about 800 MB for a
100M-row Parquet object).

The conversion was added by ClickHouse#95773 because INSERT squashing merged the
DeltaLake partition constants of different files into one value (ClickHouse#95526).
ClickHouse#97019 fixed that in `Squashing::squash`, which materializes `ColumnConst`
before concatenation, so the conversion in the source is no longer needed.
With ClickHouse#97019's materialization disabled, a DeltaLake `INSERT ... SELECT` hits
the `ColumnConst::insertRangeFrom` assertion; with it, the values are right.
A single chunk that squashing passes through is materialized by the INSERT
pre-sink (`addMissingDefaults` wraps every output column in `materialize`),
and SELECT output by `QueryPipeline::complete`, so format sinks and `Buffer`
still receive full columns.

The new test pins `optimize_trivial_count_query`: with it off, `count()`
requests a column and reads the file instead of taking the count-only path.

Reported in ClickHouse#132859.

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; 3 findings in round 1, 0 in round 2) plus my own review (4 findings).

# Sev Finding Verdict Evidence / action
1 ❌ Without the conversion, DeltaLake partition constants reach INSERT sinks and output formats unmaterialized DISAGREE every INSERT pre-sink wraps each column in materialize (addMissingDefaults.cpp:95), SELECT output goes through MaterializingTransform; DeltaLake rows into file (CSV, TSV, JSONEachRow), s3 and Buffer are identical to master
2 ⚠️ The _file part of the test and the SELECT _file changelog example do not exercise this change AGREE removed
3 ⚠️ The memory-limit test could pass if the count fast path fell back to a normal read DISAGREE it fails on every master run with the two count-path settings pinned; a lost fast path is a different regression
4 ⚠️ No test pins isConstant of a DeltaLake partition column DISAGREE constness is a representation, not a contract; the values are what test_partition_columns_jumbled checks
5 💡 PR body overstated which schema-evolution defaults stay constant AGREE corrected
6 💡 "as before 26.2" ignored the backports of #95773 AGREE corrected
7 💡 After the fix the perf queries take about 10 ms noted the PR comparison is about 10x, outside noise

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

Session id: cron:clickhouse-review-slot-10:20261119-061200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05832_object_storage_count_only_no_materialization fails on every master run (Code: 241 ... would use 76.60 MiB ... maximum: 40.00 MiB) and passes 50/50 with random settings on the fix.
b Root cause explained? A count-only read gets one getChunkForCount(num_rows) chunk per file with constant placeholder columns; the conversion added by #95773 in StorageObjectStorageSource::generate replicated every constant column to all rows of the file, in one thread.
c Fix matches root cause? Yes. The conversion was a workaround for squashing (#95526) that #97019 fixed in Squashing::squash; the PR removes the workaround. No new condition or guard.
d Test intent preserved / new tests added? New stateless test (red on master) and a requires_s3 performance test. The #95526 class stays covered by test_storage_delta::test_partition_columns_3 / _jumbled and 03918_insert_squashing_const_different_values, all passing.
e Both directions demonstrated? Yes: master FAIL on every run, fix 50/50 OK. A 122-case A/B matrix differs only in the 4 memory-limited count rows and in isConstant of a DeltaLake partition column. With #97019's materialization disabled, the DeltaLake INSERT ... SELECT and 03918 hit the ColumnConst::insertRangeFrom assertion, so Squashing keeps them correct.
f Fix is general across code paths? The conversion existed only in this source, which serves s3, Azure, HDFS, local object storage, all data lakes and *Cluster replicas. file() and url() never had it. Checked s3, s3Cluster, hive, merge(), IcebergLocal and deltaLakeLocal.
g Fix generalizes across inputs (params/datatypes/wrappers)? Parquet, CSV, ORC; UInt8, UInt64, String, Nullable structures; _file/_path/_size/_table; DeltaLake partition columns; Iceberg position deletes and identity partitions; max_threads 1/16, max_block_size = 1, optimize_count_from_files and optimize_trivial_count_query 0/1, cached count.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change. DeltaLake partition columns are constant per chunk again in data reads (as before #95773), with the same values.
i Invariants and contracts preserved? Chunk sizes are unchanged (the removed cloneResized was a no-op). Consumers that combine chunks handle constants (Squashing, merging, sorting, joins, sets, window functions, aggregation). Output consumers get full columns: SELECT output through MaterializingTransform, every INSERT through the pre-sink's addMissingDefaults (materialize on each column); DeltaLake rows into file (CSV, TSV, JSONEachRow), s3 and Buffer match master. A debug build asserts on a misused constant, and the matrix plus 151 neighbouring tests ran on one without an assertion.

Session id: cron:clickhouse-impl-slot-7:20261119-054900

@clickhouse-gh

clickhouse-gh Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [09fc2d0]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
05100_autopr_gate_lazy_read FAIL cidb
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
05033_lazy_materialization_column_function_structure_equals NOT_FAILED cidb
01710_projection_with_mixed_pipeline NOT_FAILED cidb
05034_lazy_materialization_column_function_set_capture NOT_FAILED cidb
04353_text_index_explicit_tokenizer_argument NOT_FAILED cidb
Performance Comparison (arm_release, master_head, 2/8) FAIL Performance dashboard
limit_by #0 FAIL dashboard
limit_by #3 FAIL dashboard
multiif #1 unstable query history
Performance Comparison (arm_release, master_head, 5/8) FAIL Performance dashboard
optimize_limit_by_keys #0 FAIL dashboard
optimize_limit_by_keys #1 FAIL dashboard

AI Review

Summary

Reviewed PR #132892 at 09fc2d04838fa6217b88b6d87cc66441cbab6cd7, including the full discussion, diff, current implementation, and downstream consumers. Removing unconditional materialization from StorageObjectStorageSource::generate avoids allocating a placeholder value for every row during metadata-only counts. The existing squashing fix preserves different DeltaLake partition values. No actionable findings remain; the performance category, measurements, and regression coverage support approval.

Because data reads can now expose constant DeltaLake partition columns, the consumer review covered:

  • Squashing::squash: materializes constants before concatenation and reconciles differing column representations.
  • INSERT sinks: InsertDependenciesBuilder::createPreSink uses addMissingDefaults, which materializes every output column, including chunks passed through without concatenation.
  • Sorting and merging: MergeSorter and IMergingAlgorithm::removeConstAndSparse materialize input constants before cursor comparisons and row copying.
  • Aggregation, distinctness, sets, and LIMIT BY: normalize runtime constants before specialized key/argument access, or explicitly handle constant keys.
  • Hash joins: build columns and probe keys are materialized; merge joins also normalize their input chunks.
  • Window functions: materialize partition keys, ordering keys, and function arguments before processing; unrelated payload columns retain their values.
  • Expressions and filtering: scalar constant handling, JIT argument materialization, and column filtering preserve per-chunk values. accumulateExtremes handles constants that differ between chunks.
  • Output and distributed reads: QueryPipeline::complete materializes columns for formats requiring them; NativeWriter also materializes constants before serialization. No wire-format change results.
  • Internal storage paths: lazy rereads exclude DeltaLake; Iceberg identity partitions and schema-evolution defaults, Paimon defaults, hive partitions, and virtual columns already materialize at their producers. Queue readers use createReader directly and do not pass through the removed block.
Missing context / blind spots
  • ⚠️ No runnable local ClickHouse build was available, so runtime validation was not independently repeated. The author reports the new memory-limit regression failing on master and passing 50/50 on the fix, DeltaLake partition/squashing coverage, and before/after benchmarks. The fetched CI reports show the new MinIO regression skipped in Fast test and no targeted-test results yet; a completed stateless run would independently confirm it.
Final Verdict

✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. labels Nov 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 09fc2d048 with master 92fdcb78e (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 09fc2d0

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_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 05829_autopr_skip_index_on_read_in_subquery flaky, not from this PR (the diff does not touch this test or skip-index analysis): red in this job on 14 master commits and 68 PRs since 2026-11-19 00:41 UTC, because plan-based parallel replicas collects no statistics for these queries #132867 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 05100_autopr_gate_lazy_read flaky, not from this PR: red in this job on 6 PRs in 3 days, because plan-based parallel replicas keeps the Top-K read local and collects no statistics for it #132873 (mine, open)
Performance Comparison (arm_release, master_head, 2/8) / limit_by #0, limit_by #3 perf, not from this PR: the reference is master 92fdcb7 and the tested tree is this head merged into it, both queries read numbers_mt only and never reach object storage; the slowed queries are the 1000-key LIMIT BY cases, the 100000-key ones in the same shard are unchanged; other limit_by queries were red on 1 other unrelated PR today a fix task is created (investigating at full effort, fixing-PR link to follow here)
Performance Comparison (arm_release, master_head, 5/8) / optimize_limit_by_keys #0, #1 perf, not from this PR: same reasoning as the row above (numbers_mt with 1000 LIMIT BY keys) a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above #132867, #132873 and the fix task above (the owners above)

Every amd_release Performance Comparison shard passed, including the new count_only_object_storage test. The two early Config Workflow / Pre Hooks reds were the run before the can be tested label; the labelled run's Config Workflow passed. CH Inc sync is green.

Session id: cron:our-pr-ci-monitor:20261119-100025

@groeneai

Copy link
Copy Markdown
Collaborator Author

The four Performance Comparison (arm_release, master_head, 2/8, 5/8) rows (limit_by #0/#3, optimize_limit_by_keys #0/#1) come from where this build places unchanged code; these queries do not run the code this PR changes.

  • All extra CPU samples are in LimitByTransform::consumeImpl for the UInt16 key method (limit_by #0: 132 -> 458, optimize_limit_by_keys #0: 158 -> 643). Its machine code is identical in both binaries (same address-normalized disassembly). Here it starts 704 bytes earlier, which makes the branch that closes its row loop the last instruction of a 4 KiB page (0x1dbffffc; that page also ends on a 2 MiB boundary).
  • I located this loop in the 192 arm binaries of the PR performance runs since 2026-11-18. Only this build places it there, and only this build is slow: in the other 123-138 runs these queries are at 0.93-1.07x, including builds whose loop crosses a page boundary. Another PR's run today hit the same with the UInt32 key method, its loop branch at page offset 0xff4 (limit_by Repair subtree2 #1 +62%, doc: fix typo #4 +30%, report); the builds with that branch at 0xfd4 run at 0.98-1.01x.

@egor-click, this reopens the gate question from #131211 (comment): should the perf job downgrade a confirmed slowdown when the functions the query spends its time in have identical machine code in both binaries (I can send that PR), or should such rows stay blocking for the reviewer to judge?

@egor-click

Copy link
Copy Markdown
Contributor

i feel like that is better for the reviewer to judge

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, so I will not send the gate PR. No fixing PR will follow for the two Performance Comparison (arm_release) rows in the CI ledger above: they are left to the reviewer of this PR, with the evidence in my previous comment.

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-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants