Skip to content

Auto-enable uncompressed cache for MergeTree reads - #99639

Open
paf91 wants to merge 82 commits into
ClickHouse:masterfrom
paf91:pr/auto-uncompressed-cache
Open

paf91 wants to merge 82 commits into
ClickHouse:masterfrom
paf91:pr/auto-uncompressed-cache

Conversation

@paf91

@paf91 paf91 commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

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

Add the setting enable_automatic_use_uncompressed_cache (disabled by default) that automatically enables the uncompressed cache for eligible local reads from tables in the MergeTree family when use_uncompressed_cache is not explicitly set.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

This change improves the MergeTree read path by allowing the uncompressed cache to be enabled automatically for small eligible local reads, while keeping the old behavior for remote storage and explicit user settings. The automatic mode is opt-in (enable_automatic_use_uncompressed_cache = 1).

The automatic mode is not enabled by default because the server cannot distinguish an explicit use_uncompressed_cache=0 passed as an HTTP query parameter or a command-line client option from an unset one (SettingsConstraints::checkOrClamp erases settings changes whose value equals the current value), so a default-on automatic mode would silently override an explicit user opt-out on those paths. Only SETTINGS use_uncompressed_cache = 0 in the query text or a settings profile takes precedence reliably. Defaulting the automatic mode to on would additionally need performance evidence, since the uncompressed cache is not universally beneficial.


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

@paf91
paf91 marked this pull request as draft March 16, 2026 17:12
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 16, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Interesting - in my experience, uncompressed cache can lower performance sometimes: https://presentations.clickhouse.com/2021-meetup53/optimizations/

@clickhouse-gh

clickhouse-gh Bot commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1da7684]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
05865_join_shard_by_pk_ranges_above_right_full_join FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 16, 2026
@paf91

paf91 commented Mar 16, 2026

Copy link
Copy Markdown
Contributor Author

Interesting - in my experience, uncompressed cache can lower performance sometimes: https://presentations.clickhouse.com/2021-meetup53/optimizations/

Yeah, uncompressed cache is not universally beneficial and can hurt some workloads for sure.

This PR is intentionally much narrower than enabling it by default everywhere. It still respects the existing max_marks_to_use_cache threshold, so this is only about eligible small local reads.
Also:

  • explicit use_uncompressed_cache = 0/1 still works as before
  • it stays off for remote and mixed local+remote reads
  • it also stays off when uncompressed_cache_size = 0

@paf91
paf91 marked this pull request as ready for review March 16, 2026 23:42
@paf91

paf91 commented Mar 20, 2026

Copy link
Copy Markdown
Contributor Author

at this point issue in tests is that in s3 storage / azure jobs, the test table lands on remote storage and enable_automatic_use_uncompressed_cache doesn't use remote for caching (tests assumed local). thinking about fix

@paf91
paf91 force-pushed the pr/auto-uncompressed-cache branch from 8795dd5 to a76fe91 Compare March 20, 2026 07:07
alexey-milovidov and others added 2 commits October 19, 2026 20:18
…` into the `ON CLUSTER` entry settings

The settings of a `DDLLogEntry` are reapplied on the worker via `makeQueryContext` without the
fallback for unknown settings, so a worker of an older version would reject every `ON CLUSTER`
task issued in a session with an explicit `use_uncompressed_cache = 0` with `UNKNOWN_SETTING`
during a rolling upgrade. The opt-out matters only for DDL that reads (`CREATE ... AS SELECT`),
and `executeDDLQueryOnCluster` already bakes `SETTINGS use_uncompressed_cache = 0` into the
queued query text, which older workers understand. Drop the settings carrier; the existing
`05241` cases (including the one where the automatic mode comes only from the entry settings)
still pass through the query-text carrier.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cache` to 26.11

The master branch is now 26.11, and the setting has not been released in 26.10.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99639&sha=114393b0cf6&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel) (05210_lightweight_update_materialized_cte_in_ignore: Unknown table expression identifier '_materialized_cte_c_...' under parallel replicas; it fails in many unrelated PRs since 2026-10-13) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is #123121 (merged 2026-10-13). This branch already contains it through the master merge in 0eb561c, so no separate PR is needed.

The failing run on 114393b was built without it: its workflow was created on 2026-10-11, before the merge. Since the merge, master has 0 failures of 05210_lightweight_update_materialized_cte_in_ignore in 276 ParallelReplicas runs (37 failures in 332 runs in the six days before). The 30 PR heads that still failed it afterwards were all running workflows created before the merge.

alexey-milovidov and others added 2 commits October 27, 2026 06:02
# Conflicts:
#	src/Interpreters/executeDDLQueryOnCluster.cpp
…tRangesReadInfo`

The new lazy-materialization read on master (`19ee3397248e`) constructs `PartRangesReadInfo`
with the old signature, which this pull request extended with `has_uncompressed_cache`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99639&sha=e5c5db79273448efc3fe62ee3613030df07c5479&name_0=PR&name_1=Fast%20test
PR: ClickHouse#99639

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

Copy link
Copy Markdown
Member

🕵 Merged current master and pushed efa3bb648be3.

  • Conflict: src/Interpreters/executeDDLQueryOnCluster.cpp. On master, stripInitiatorOnlySettingsFromQuery was renamed to stripInitiatorOnlySettingsFromDDLQuery for the DDL path. I kept the new name and this PR's resolveAutomaticUncompressedCacheOptOutInQuery call after it.
  • CI failure (ours): Fast test and Build (arm_tidy) failed with no matching constructor for initialization of 'PartRangesReadInfo'. The new lazy-materialization read on master (19ee3397248e) still uses the old constructor. This PR added the has_uncompressed_cache argument to that constructor, so I passed it there too. The binary now builds locally.
  • Ran this PR's stateless tests against a local server: 8 pass. 04649_...mixed_storage needs S3 and 05241_...on_cluster_create_as_select needs Keeper; neither is available locally, so CI has to cover them.

@groeneai, thanks for confirming that 05210_lightweight_update_materialized_cte_in_ignore is fixed by #123121. That fix is in this branch, so nothing more is needed.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 4 commits November 4, 2026 06:14
…uiring hits

The control runs of `04612`, `04842` and `05076` expected `UncompressedCacheHits > 0` on the second (warm) run.
The stateless tests run with a small uncompressed cache (`small_caches.xml`, 128 MiB) that is shared with
concurrent tests, and the `query_log` of the failed runs shows `UncompressedCacheWeightLost` on the first run
and only `UncompressedCacheMisses` on the second: the entries were evicted in between. Whether the automatic
mode enabled the cache is shown equally well by hits and misses together, so check their sum instead.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99639&sha=efa3bb648be3178be5eddcc0df8df9f2fd673403&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
PR: ClickHouse#99639

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…`CREATE` in its outer `SETTINGS` clause

The opt-out was written into the `SETTINGS` clause of the last plain `SELECT` of the source query. That missed
a source query whose last element is a set operation (`EXCEPT`, `INTERSECT`, a nested `UNION`), and for
`CREATE VIEW` it turned the session opt-out of the creator into a permanent setting of the stored view body.

Use the trailing query-level `SETTINGS` clause of the `CREATE` itself instead. `applySettingsFromQuery` applies
it before the settings of the source query, whatever its shape, and `InterpreterCreateQuery` resets it
(`resetOutputASTIfExist`) before the definition is stored. The formatter wraps the source query in parentheses
when this clause is present, so it is re-parsed on the worker as the outer clause.

`05241` is extended with an `EXCEPT ALL` source and with a view created under the session opt-out, whose stored
definition must not mention `use_uncompressed_cache`. The control runs there also check hits and misses together,
because the small test cache shared with concurrent tests can evict the entries of the first run.

PR: ClickHouse#99639

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…GS` clauses

A `use_uncompressed_cache = 0` in the `SETTINGS` clause of a subquery or of the stored query of a view must win
over `enable_automatic_use_uncompressed_cache = 1`. On current master `applyQueryLevelSettings` clamps nested
clauses with `CLAMP_ON_VIOLATION_THROW_ON_INVALID`, which keeps changes equal to the current value, so the
`changed` flag survives and the opt-out is honored. Add a regression test with a cache-using control.

PR: ClickHouse#99639

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits November 12, 2026 01:54
…oss `SQL SECURITY DEFINER` and `EXECUTE AS` context rebuilds

The rebuild clamps the caller's settings changes to the new user's constraints, which drops
the default-valued opt-out, while `enable_automatic_use_uncompressed_cache = 1` survives.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…R` views and `EXECUTE AS`

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99639&sha=00b62ef53d2811d1f363572394dbf8b9bb9ab2d7&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. The server was OOM-killed (OOM in dmesg, 44 GB RSS) on a fuzzed SELECT DISTINCT ... COUNTOrDefaultDistinct(toFixedString('', 1048577)) ... FROM merge(currentDatabase(), ...). That looks like the memory-limit bypass tracked in #117916 (and maybe #130682). The same OOM in dmesg failure has hit 8 PRs and master in the last 30 days.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating this OOM in dmesg; I'll follow up here with a PR (or my findings) shortly. #130682 does not cover it: it changes only the FixedString single-value states (min, max, any, argMax and the -ArgMin/-ArgMax combinators), and this query uses none of them.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #131185.

The 64 GiB request is the constant argument copied to the size of the block: without GROUP BY, Aggregator::prepareAggregateInstructions materializes every constant argument, so toFixedString('', 1048577) with max_block_size = 65409 becomes a 64 GiB allocation in each of the 16 AggregatingTransform threads. The run's jemalloc heap profiles hold one such live block, allocated by ColumnConst::convertToFullColumn from prepareAggregateInstructions. The PR adds a constant argument once for the functions that ignore repeated values, -Distinct included; the query from the run, on the same 4M-row table, now uses 14.5 MiB.

It is not #117916: this allocation goes through Allocator, which checks the limit, and the same query without the trailing IGNORE NULLS, just before, was refused with attempt to allocate chunk of 64.00 GiB. It is not #130682 either: the query has no min/max/any/argMax state.

Why one of these checked requests got past max_server_memory_usage in CI is a separate MemoryTracker problem that this PR does not change. I could not reproduce that part locally: 20 of 20 runs with the CI's jemalloc profiler settings were refused, with memory_worker_correct_memory_tracker on and off.

perfloop-agent pushed a commit to perfloop-oss/ClickHouse that referenced this pull request Nov 20, 2026
Without keys, `Aggregator::prepareAggregateInstructions` materialized every
constant argument to the size of the block. For
`COUNTOrDefaultDistinct(toFixedString('', 1048577))` with
`max_block_size = 65409` that is a 64 GiB request in each
`AggregatingTransform` thread: the AST fuzzer run on PR ClickHouse#99639 had 16 of
them, and the server was OOM-killed at 44 GB RSS.

A function whose state ignores repeated values (`ignoresRepeatedValues()`,
added by ClickHouse#127940) gets the same state from one row as from every row of a
constant. So, without keys, a single constant argument of such a function is
now passed as its one-row data column and added once per block, the way
ClickHouse#127940 adds the used values of a `LowCardinality` argument and the radix
partitioned `uniqExact` routes a constant once per block.

`-Distinct` forwards to the nested function only the values it has not seen,
so it ignores repeated values whatever the nested function is. It now reports
it, which also gives it the `LowCardinality` path without keys.

The JIT branch of `executeWithoutKeyImpl` is not affected: its only caller
passes `use_compiled_functions = false`.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99639&sha=00b62ef53d2811d1f363572394dbf8b9bb9ab2d7&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 20, 2026 22:04
…d-cache

Conflicts:
- `src/Interpreters/DDLTask.cpp`: `master` made the settings of a DDL entry unconditional
  (entry format versions below 3 are rejected). Kept that, with this PR's use of
  `ClusterProxy::getInitiatorOnlySettingNames` and its comment about the opt-out.
- `src/Processors/Sources/LazyReadFromMergeTreeSource.cpp`: `master` builds one read pool
  per storage snapshot (projection parts). The automatic uncompressed cache decision is
  still resolved once for the whole second-phase read set and is passed to every pool.
- `src/Processors/Transforms/LazyMaterializingTransform.h`: kept both sets of members.
- `src/Storages/StorageInMemoryMetadata.cpp`: kept both sets of includes.

Semantic adaptation: on `master` the parts of `LazyMaterializingRows` are added by
`addPartsOfMainRead` instead of the constructor, so `any_source_parts_on_remote_disk`
is now updated there as well.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The final query selected `system.query_log` rows with `log_comment LIKE '05621\_%'`.
The test runner sets the default `log_comment` of the test's other queries to the name
of the test file, which matches this pattern too, so in CI the result had an extra row
`05621_uncompressed_cache_auto_enable_sql_security_opt_out.sh-default`. Select the six
comments of the test by their exact names instead.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=99639&sha=0fa94ada96c159452344163cc1ca1af1c6e8c7dd&name_0=PR&name_1=Fast%20test
ClickHouse#99639

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

Copy link
Copy Markdown
Member

🕵 Merged current master and pushed 2d270946024a.

  • Conflicts (4 files):
    • src/Interpreters/DDLTask.cpp: master now always writes the settings of a DDL entry (entry format versions below 3 are rejected). I kept that, with this PR's ClusterProxy::getInitiatorOnlySettingNames and its comment about the opt-out.
    • src/Processors/Sources/LazyReadFromMergeTreeSource.cpp: master builds one read pool per storage snapshot (for projection parts). The automatic uncompressed cache decision is still resolved once for the whole second-phase read set and is passed to every pool.
    • src/Processors/Transforms/LazyMaterializingTransform.h and src/Storages/StorageInMemoryMetadata.cpp: kept both sides.
  • Semantic adaptation: on master the parts of LazyMaterializingRows are added by addPartsOfMainRead, not by the constructor, so any_source_parts_on_remote_disk is now updated there too. Without it, a lazy read after a first phase that touched remote parts would have been treated as local.
  • CI failure (ours): 05621_uncompressed_cache_auto_enable_sql_security_opt_out failed in Fast test with an extra row 05621_..._opt_out.sh-default. Its final query used log_comment LIKE '05621\_%', which also matches the default log_comment the test runner sets (the test file name). It now selects the six comments by exact name.
  • Review thread on the SQL SECURITY DEFINER / EXECUTE AS opt-out: fixed earlier in f3bb22b, and its regression test passes now, so I resolved the thread.

Local checks on the merged build: 10 of this PR's 11 stateless tests pass, including the ON CLUSTER and Distributed ones, plus 02703_max_local_read_bandwidth. 04649_uncompressed_cache_auto_enable_mixed_storage needs the S3 storage policy, which my local server does not have, so CI has to cover it. Of the existing lazy_materializ* / lazy_final* tests, 98 pass; the 18 that fail need S3, graphite_rollup or other CI-only configuration. The gtest and the integration test were not run locally.

@groeneai, thanks for #131185. It is merged and this branch now contains it.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (no conflicts) and fixed the only red check, pushed as 1da768401f52.

  • Style check / settings_changes_history (ours): the version on master is now 26.12, so the history record of enable_automatic_use_uncompressed_cache moved from 26.11 to 26.12. python3 -m ci.jobs.scripts.settings_history --base origin/master passes locally.
  • All 16 translation units this pull request touches compile on the merged tree. No tests were re-run locally; CI has to cover them.
  • There are no unresolved review threads.

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization pr-improvement Pull request with some product improvements pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants