Skip to content

Query result cache on disk - #79393

Closed
nbarannik wants to merge 53 commits into
ClickHouse:masterfrom
nbarannik:query-result-cache-on-disk
Closed

nbarannik wants to merge 53 commits into
ClickHouse:masterfrom
nbarannik:query-result-cache-on-disk

Conversation

@nbarannik

@nbarannik nbarannik commented Apr 22, 2025 •

Copy link
Copy Markdown
Contributor

On-disk configuration for query result cache is provided in addition to the already existing in-memory configuration. When data is written to the cache, it will be written to both of them (write-through). When data is searched inside the cache, it is searched in memory first, then on disk. If the data is found on disk, it will be also put in memory.

On-disk cache has independent configurations of max size, max elements and max element size.

<query_cache>
        <max_size_in_bytes>1073741824</max_size_in_bytes>
        <max_entries>1024</max_entries>
        <max_entry_size_in_bytes>1048576</max_entry_size_in_bytes>
        <max_entry_size_in_rows>30000000</max_entry_size_in_rows>

        <on_disk>
                 <max_size_in_bytes>2147483648</max_size_in_bytes>
                 <max_entries>2048</max_entries>
                 <max_entry_size_in_bytes>2097152</max_entry_size_in_bytes>
                 <max_entry_size_in_rows>60000000</max_entry_size_in_rows>
        </on_disk>
</query_cache>

The data is stored in subdirectory query_cache/ relative to the base directory (<path>...</path> in the server configuration).

For each query result, a file is created, with the AST tree hash as file name.

To support future changes of the persistence format, a file query_cache/format_version.txt stores the version of the data, e.g. 1.

Changelog category (leave one):

  • New Feature

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

Added an optional on-disk tier for the query result cache. Query results are written through to disk (under the query_cache/ directory) in addition to memory, so they survive server restarts. The on-disk cache has its own max_size_in_bytes, max_entries, max_entry_size_in_bytes, and max_entry_size_in_rows limits, configured under <query_cache><on_disk> in the server configuration.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 22, 2025
@clickhouse-gh

clickhouse-gh Bot commented Apr 22, 2025

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [df24a75]

@rschu1ze rschu1ze self-assigned this Apr 22, 2025
@alexey-milovidov

Copy link
Copy Markdown
Member

@rschu1ze, don't forget that we also need query cache inside the filesystem cache.

@alexey-milovidov

Copy link
Copy Markdown
Member

And the on-disk cache should allow arbitrary object storage.

@clickhouse-gh

clickhouse-gh Bot commented May 27, 2025

Copy link
Copy Markdown
Contributor

Dear @rschu1ze, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

# Conflicts:
#	CHANGELOG.md
#	README.md
#	ci/jobs/build_clickhouse.py
#	ci/jobs/fast_test.py
#	ci/jobs/functional_stateless_tests.py
#	ci/jobs/performance_tests.py
#	ci/praktika/info.py
#	ci/praktika/json.html
#	ci/praktika/native_jobs.py
#	ci/praktika/result.py
#	ci/praktika/settings.py
#	ci/praktika/yaml_generator.py
#	ci/settings/settings.py
#	ci/workflows/pull_request.py
#	contrib/CMakeLists.txt
#	docker/docs/builder/Dockerfile
#	docker/keeper/Dockerfile
#	docker/server/Dockerfile.alpine
#	docker/server/Dockerfile.ubuntu
#	docs/en/engines/table-engines/mergetree-family/annindexes.md
#	docs/en/engines/table-engines/mergetree-family/collapsingmergetree.md
#	docs/en/engines/table-engines/mergetree-family/invertedindexes.md
#	docs/en/engines/table-engines/mergetree-family/mergetree.md
#	docs/en/engines/table-engines/mergetree-family/versionedcollapsingmergetree.md
#	docs/en/interfaces/cli.md
#	docs/en/interfaces/formats.md
#	docs/en/interfaces/prometheus.md
#	docs/en/interfaces/ssh.md
#	docs/en/interfaces/third-party/client-libraries.md
#	docs/en/operations/analyzer.md
#	docs/en/operations/caches.md
#	docs/en/operations/server-configuration-parameters/settings.md
#	docs/en/operations/system-tables/events.md
#	docs/en/operations/system-tables/mutations.md
#	docs/en/sql-reference/aggregate-functions/reference/anyheavy.md
#	docs/en/sql-reference/aggregate-functions/reference/grouparraysorted.md
#	docs/en/sql-reference/aggregate-functions/reference/quantileexact.md
#	docs/en/sql-reference/aggregate-functions/reference/quantileexactweighted.md
#	docs/en/sql-reference/aggregate-functions/reference/quantiletdigest.md
#	docs/en/sql-reference/data-types/float.md
#	docs/en/sql-reference/data-types/int-uint.md
#	docs/en/sql-reference/data-types/newjson.md
#	docs/en/sql-reference/dictionaries/index.md
#	docs/en/sql-reference/functions/array-functions.md
#	docs/en/sql-reference/functions/comparison-functions.md
#	docs/en/sql-reference/functions/geo/h3.md
#	docs/en/sql-reference/functions/nlp-functions.md
#	docs/en/sql-reference/functions/other-functions.md
#	docs/en/sql-reference/functions/time-window-functions.md
#	docs/en/sql-reference/functions/type-conversion-functions.md
#	docs/en/sql-reference/functions/udf.md
#	docs/en/sql-reference/statements/alter/index.md
#	docs/en/sql-reference/statements/alter/role.md
#	docs/en/sql-reference/statements/alter/settings-profile.md
#	docs/en/sql-reference/statements/alter/statistics.md
#	docs/en/sql-reference/statements/create/table.md
#	docs/en/sql-reference/statements/create/view.md
#	docs/en/sql-reference/statements/grant.md
#	docs/en/sql-reference/statements/parallel_with.md
#	docs/en/sql-reference/syntax.md
#	docs/en/sql-reference/table-functions/azureBlobStorage.md
#	docs/en/sql-reference/table-functions/file.md
#	docs/en/sql-reference/table-functions/hdfs.md
#	docs/en/sql-reference/table-functions/s3.md
#	docs/en/sql-reference/table-functions/url.md
#	programs/client/Client.cpp
#	programs/client/Client.h
#	programs/client/FuzzLoop.cpp
#	programs/local/LocalServer.cpp
#	programs/server/Server.cpp
#	programs/server/play.html
#	src/Access/Common/AccessType.h
#	src/Access/Credentials.h
#	src/Analyzer/ConstantNode.cpp
#	src/Analyzer/ConstantNode.h
#	src/Analyzer/ConstantValue.h
#	src/Analyzer/Resolve/QueryAnalyzer.cpp
#	src/Analyzer/SetUtils.cpp
#	src/CMakeLists.txt
#	src/Client/BuzzHouse/AST/SQLProtoStr.cpp
#	src/Client/BuzzHouse/Generator/ExternalIntegrations.cpp
#	src/Client/BuzzHouse/Generator/ExternalIntegrations.h
#	src/Client/BuzzHouse/Generator/FuzzConfig.h
#	src/Client/BuzzHouse/Generator/QueryOracle.cpp
#	src/Client/BuzzHouse/Generator/QueryOracle.h
#	src/Client/BuzzHouse/Generator/RandomGenerator.h
#	src/Client/BuzzHouse/Generator/RandomSettings.h
#	src/Client/BuzzHouse/Generator/SQLCatalog.h
#	src/Client/BuzzHouse/Generator/SQLExpression.cpp
#	src/Client/BuzzHouse/Generator/SQLFuncs.h
#	src/Client/BuzzHouse/Generator/SQLQuery.cpp
#	src/Client/BuzzHouse/Generator/SQLTable.cpp
#	src/Client/BuzzHouse/Generator/SQLTypes.cpp
#	src/Client/BuzzHouse/Generator/SQLTypes.h
#	src/Client/BuzzHouse/Generator/StatementGenerator.cpp
#	src/Client/BuzzHouse/Generator/StatementGenerator.h
#	src/Client/BuzzHouse/Proto/CMakeLists.txt
#	src/Client/BuzzHouse/Proto/SQLGrammar.proto
#	src/Client/ClientBase.cpp
#	src/Client/ClientBase.h
#	src/Client/ConnectionParameters.cpp
#	src/Columns/ColumnAggregateFunction.cpp
#	src/Columns/ColumnAggregateFunction.h
#	src/Columns/ColumnArray.cpp
#	src/Columns/ColumnArray.h
#	src/Columns/ColumnCompressed.h
#	src/Columns/ColumnConst.h
#	src/Columns/ColumnDecimal.h
#	src/Columns/ColumnDynamic.cpp
#	src/Columns/ColumnDynamic.h
#	src/Columns/ColumnFixedString.h
#	src/Columns/ColumnFunction.cpp
#	src/Columns/ColumnFunction.h
#	src/Columns/ColumnLowCardinality.h
#	src/Columns/ColumnMap.cpp
#	src/Columns/ColumnMap.h
#	src/Columns/ColumnNullable.cpp
#	src/Columns/ColumnNullable.h
#	src/Columns/ColumnObject.cpp
#	src/Columns/ColumnObject.h
#	src/Columns/ColumnObjectDeprecated.cpp
#	src/Columns/ColumnObjectDeprecated.h
#	src/Columns/ColumnSparse.cpp
#	src/Columns/ColumnSparse.h
#	src/Columns/ColumnString.h
#	src/Columns/ColumnTuple.cpp
#	src/Columns/ColumnTuple.h
#	src/Columns/ColumnUnique.h
#	src/Columns/ColumnVariant.cpp
#	src/Columns/ColumnVariant.h
#	src/Columns/ColumnVector.h
#	src/Columns/IColumn.h
#	src/Columns/IColumnDummy.cpp
#	src/Columns/IColumnDummy.h
#	src/Columns/tests/gtest_column_object.cpp
#	src/Common/CacheBase.h
#	src/Common/CurrentMetrics.cpp
#	src/Common/ErrorCodes.cpp
#	src/Common/FailPoint.cpp
#	src/Common/FunctionDocumentation.cpp
#	src/Common/LRUCachePolicy.h
#	src/Common/config.h.in
#	src/Common/threadPoolCallbackRunner.h
#	src/Core/Defines.h
#	src/Core/FormatFactorySettings.h
#	src/Core/ServerSettings.cpp
#	src/Core/Settings.cpp
#	src/DataTypes/DataTypeDynamic.cpp
#	src/DataTypes/Serializations/ISerialization.cpp
#	src/DataTypes/Serializations/ISerialization.h
#	src/Databases/enableAllExperimentalSettings.cpp
#	src/Disks/ObjectStorages/MetadataStorageFromPlainRewritableObjectStorage.cpp
#	src/Formats/FormatFactory.cpp
#	src/Functions/FunctionsComparison.h
#	src/Functions/FunctionsStringHashFixedString.cpp
#	src/Functions/generateSerialID.cpp
#	src/IO/S3/copyS3File.cpp
#	src/Interpreters/ActionsVisitor.cpp
#	src/Interpreters/Aggregator.cpp
#	src/Interpreters/Cache/QueryResultCache.cpp
#	src/Interpreters/Cache/QueryResultCache.h
#	src/Interpreters/ConcurrentHashJoin.cpp
#	src/Interpreters/ConcurrentHashJoin.h
#	src/Interpreters/Context.cpp
#	src/Interpreters/Context.h
#	src/Interpreters/ExpressionAnalyzer.cpp
#	src/Interpreters/InterpreterExplainQuery.cpp
#	src/Interpreters/InterpreterInsertQuery.cpp
#	src/Interpreters/InterpreterParallelWithQuery.cpp
#	src/Interpreters/InterpreterParallelWithQuery.h
#	src/Interpreters/InterpreterSystemQuery.cpp
#	src/Interpreters/JIT/CHJIT.cpp
#	src/Interpreters/Session.cpp
#	src/Interpreters/SystemLog.h
#	src/Interpreters/TraceLog.cpp
#	src/Interpreters/executeQuery.cpp
#	src/Parsers/ASTSystemQuery.cpp
#	src/Parsers/ASTSystemQuery.h
#	src/Planner/PlannerActionsVisitor.cpp
#	src/Planner/PlannerActionsVisitor.h
#	src/Planner/PlannerJoins.cpp
#	src/Processors/Formats/IOutputFormat.cpp
#	src/Processors/Formats/Impl/Parquet/ParquetDataBuffer.h
#	src/Processors/Formats/Impl/Parquet/ParquetRecordReader.cpp
#	src/Processors/Formats/Impl/PrettyBlockOutputFormat.cpp
#	src/Processors/QueryPlan/AggregatingStep.cpp
#	src/Processors/QueryPlan/CreatingSetsStep.cpp
#	src/Processors/QueryPlan/IQueryPlanStep.h
#	src/Processors/QueryPlan/JoinStep.cpp
#	src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h
#	src/Processors/QueryPlan/Optimizations/filterPushDown.cpp
#	src/Processors/QueryPlan/Optimizations/optimizeUseNormalProjection.cpp
#	src/Processors/QueryPlan/Optimizations/splitFilter.cpp
#	src/Processors/QueryPlan/SortingStep.cpp
#	src/Processors/Transforms/AddingDefaultsTransform.cpp
#	src/Server/ClientEmbedded/ClientEmbedded.cpp
#	src/Server/HTTPHandler.cpp
#	src/Server/SSH/SSHEvent.cpp
#	src/Server/SSH/SSHPtyHandler.cpp
#	src/Server/TCPHandler.cpp
#	src/Storages/AlterCommands.cpp
#	src/Storages/MergeTree/Compaction/CompactionStatistics.cpp
#	src/Storages/MergeTree/Compaction/ConstructFuturePart.cpp
#	src/Storages/MergeTree/Compaction/MergeSelectors/TTLMergeSelector.cpp
#	src/Storages/MergeTree/Compaction/MergeSelectors/TrivialMergeSelector.cpp
#	src/Storages/MergeTree/Compaction/PartProperties.cpp
#	src/Storages/MergeTree/MergeFromLogEntryTask.cpp
#	src/Storages/MergeTree/MergeTreeData.cpp
#	src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.h
#	src/Storages/MergeTree/MergeTreeDataWriter.cpp
#	src/Storages/MergeTree/MergeTreeIndexGin.cpp
#	src/Storages/MergeTree/MergeTreeIndexReader.cpp
#	src/Storages/MergeTree/MergeTreeIndexReader.h
#	src/Storages/MergeTree/MergeTreeIndices.h
#	src/Storages/MergeTree/MergeTreeRangeReader.cpp
#	src/Storages/MergeTree/MergeTreeRangeReader.h
#	src/Storages/MergeTree/MergeTreeSettings.cpp
#	src/Storages/MergeTree/MergeTreeSink.cpp
#	src/Storages/MergeTree/MutateFromLogEntryTask.cpp
#	src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp
#	src/Storages/MergeTree/registerStorageMergeTree.cpp
#	src/Storages/ObjectStorageQueue/ObjectStorageQueueIFileMetadata.cpp
#	src/Storages/ObjectStorageQueue/ObjectStorageQueueIFileMetadata.h
#	src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp
#	src/Storages/ObjectStorageQueue/ObjectStorageQueueOrderedFileMetadata.h
#	src/Storages/ObjectStorageQueue/ObjectStorageQueueSource.cpp
#	src/Storages/ObjectStorageQueue/ObjectStorageQueueSource.h
#	src/Storages/ObjectStorageQueue/ObjectStorageQueueUnorderedFileMetadata.h
#	src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.cpp
#	src/Storages/ObjectStorageQueue/StorageObjectStorageQueue.h
#	src/Storages/StorageMerge.cpp
#	src/Storages/StorageMerge.h
#	src/Storages/StorageReplicatedMergeTree.cpp
#	src/Storages/tests/gtest_transform_query_for_external_database.cpp
#	src/configure_config.cmake
#	tests/ci/ci.py
#	tests/ci/ci_cache.py
#	tests/ci/ci_config.py
#	tests/ci/ci_definitions.py
#	tests/ci/stress_check.py
#	tests/ci/test_ci_options.py
#	tests/clickhouse-test
#	tests/config/install.sh
#	tests/docker_scripts/stateless_runner.sh
#	tests/integration/helpers/cluster.py
#	tests/integration/helpers/keeper_utils.py
#	tests/integration/test_mask_sensitive_info/test.py
#	tests/integration/test_non_default_compression/test.py
#	tests/integration/test_storage_iceberg/test.py
#	tests/integration/test_storage_kafka/test_batch_slow_0.py
#	tests/integration/test_table_functions_access_rights/test.py
#	tests/parallel_replicas_blacklist.txt
#	tests/queries/0_stateless/00111_shard_external_sort_distributed.sql
#	tests/queries/0_stateless/00416_pocopatch_progress_in_http_headers.reference
#	tests/queries/0_stateless/00501_http_head.reference
#	tests/queries/0_stateless/01271_show_privileges.reference
#	tests/queries/0_stateless/01625_constraints_index_append.reference
#	tests/queries/0_stateless/01825_json_type_order_by.sql
#	tests/queries/0_stateless/01881_join_on_conditions_hash.reference.j2
#	tests/queries/0_stateless/01881_join_on_conditions_merge.reference.j2
#	tests/queries/0_stateless/02136_scalar_progress.reference
#	tests/queries/0_stateless/02221_parallel_replicas_bug.sh
#	tests/queries/0_stateless/02350_views_max_insert_threads.sql
#	tests/queries/0_stateless/02373_progress_contain_result.reference
#	tests/queries/0_stateless/02423_insert_summary_behaviour.reference
#	tests/queries/0_stateless/02884_create_view_with_sql_security_option.sh
#	tests/queries/0_stateless/02911_join_on_nullsafe_optimization.sql
#	tests/queries/0_stateless/02933_group_by_memory_usage.sh
#	tests/queries/0_stateless/02993_lazy_index_loading.reference
#	tests/queries/0_stateless/03305_parallel_with_query_log.sh
#	tests/queries/0_stateless/03310_create_database_with_settings.sql
#	tests/queries/0_stateless/transactions.lib
#	utils/list-versions/version_date.tsv
Workflow files in this branch were stale or had been deleted as a
workaround for GitHub's workflow-scope check. Restoring them to match
`master` so the PR diff no longer contains those unrelated changes.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label May 23, 2026
@@ -4991,12 +4995,23 @@ void Context::updateQueryResultCacheConfiguration(const Poco::Util::AbstractConf
size_t max_entries = config.getUInt64("query_cache.max_entries", DEFAULT_QUERY_RESULT_CACHE_MAX_ENTRIES);
size_t max_entry_size_in_bytes = config.getUInt64("query_cache.max_entry_size_in_bytes", DEFAULT_QUERY_RESULT_CACHE_MAX_ENTRY_SIZE_IN_BYTES);
size_t max_entry_size_in_rows = config.getUInt64("query_cache.max_entry_rows_in_rows", DEFAULT_QUERY_RESULT_CACHE_MAX_ENTRY_SIZE_IN_ROWS);

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.

SYSTEM RELOAD CONFIG still ignores the configured row limit because this reads query_cache.max_entry_rows_in_rows, but the declared server setting and the documented XML key are query_cache.max_entry_size_in_rows. Any non-default query_cache.max_entry_size_in_rows therefore falls back to the default 30000000 on reload until the server is restarted. Please use the declared key here so the reload path matches startup.

@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Jul 10, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Picked this up via /continue-pr (routine maintenance pass).

Merged current master — the branch was ~1 week / ~2604 commits behind (last merge was on 2026-07-03). The criss-cross with master has since resolved to a single merge base, so git merge origin/master was clean (0 conflicts). Verified afterwards that the diff vs master is still exactly the 11 in-scope feature files, and that master's ASTCreateFunctionWithDriverQuery UDF carve-out in QueryResultCache.cpp is preserved. Compile-checked all 5 feature translation units (QueryResultCache.cpp, Context.cpp, Server.cpp, LocalServer.cpp, CurrentMetrics.cpp) against the newer master headers — all clean, no warnings.

Pushed 250775de39e and re-triggered CI (the fork head had a stale can be tested label with 0 check-runs, so removing and re-adding it kicked off the pipeline).

Previous CI reds are both known master-wide flakes, unrelated to this PR (confirmed against master history on play.clickhouse.com, pull_request_number = 0):

No code changes in this pass. The PR remains blocked only on the reserved design decisions in the open clickhouse-gh threads (persist-by-default vs opt-in, on-disk size accounting, eviction atomicity, per-user disk quota, SYSTEM RELOAD CONFIG semantics, metadata-only vs full-payload startup) plus human approve/merge.


if (entry_size_in_bytes < max_entry_size_in_bytes && entry_size_in_rows < max_entry_size_in_rows && !QueryResultCache::IsStale()(entry->key))
{
cache_.set(entry->key, entry->mapped); /// Add entry to in-memory cache

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.

This repopulates the in-memory cache on a disk hit before any quota has been registered for entry->key.user_id in the current process. TTLCachePolicy treats a user with no configured quota as unbounded (approveWrite falls back to max() when quotas.find(user_id) == end()), and createReader never calls cache.setQuotaForUser.

After a restart, the first disk hit for a quota-limited user can therefore insert an oversized entry into the memory cache even though the same user's writes would be rejected. Because the insert also records the entry in actual, the over-quota resident can remain until some later write happens to refresh that user's quota. Please load the user's query_cache_max_size_in_bytes / query_cache_max_entries quota on the read path too, or skip the memory repopulation unless a quota is already registered.

}
catch (const Exception& e)
{
LOG_TRACE(logger, "Exception on writing entry to disk cache {}", e.what());

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.

writeCacheEntry swallows every filesystem / serialization failure, but the metadata for this key was already inserted into cache_policy above. After a transient WriteBufferFromFile/finalize() failure, future lookups still see the non-stale metadata, readCacheEntry returns nullopt, and the next set of the same key returns early at the existing-entry check instead of repairing the file.

That leaves the on-disk cache stuck with an unreadable entry until TTL expiry or eviction. Please either propagate the error back to set so it can roll the metadata back out, or write to a temporary file first and publish the metadata only after the file is durable.

…on-disk

# Conflicts:
#	tests/queries/0_stateless/00830_join_overwrite.sql
@alexey-milovidov

Copy link
Copy Markdown
Member

Routine maintenance: merged master (branch was ~3900 commits / 9 days behind) — new head 05ef38b. The branch had returned to a criss-cross state (two spurious merge bases), so the merge was done with -s resolve; the resulting diff against master is exactly the 11 feature files, and master's recent QueryResultCache.cpp change (excluding eval from the cache) is preserved. All affected translation units compile cleanly against the merged master.

The two CI reds on the previous head are both known master issues, unrelated to this PR:

The 12 unresolved review threads remain the design/format/policy decisions previously reserved for the maintainer; no code changes were made for them in this pass.

@alexey-milovidov

Copy link
Copy Markdown
Member

Weekly maintenance pass: the branch was ~3200 commits (8 days) behind, so I merged master into it (head is now `c56def40105`). The branch was criss-crossed with master again (3 merge bases), so git merge -s resolve was used; the result is conflict-free and the diff against master is still exactly the 11 feature files. Master's own recent QueryResultCache guards (the eval exclusion and the ASTCreateFunctionWithDriverQuery UDF carve-out) are preserved. All five feature translation units (QueryResultCache.cpp, Context.cpp, Server.cpp, LocalServer.cpp, CurrentMetrics.cpp) compile clean against the new base.

The only red on the previous head was test_replicated_database/test.py::test_replicated_table_structure_alter, which is the known flake tracked in #110036 (marked retry_ok) — unrelated to this PR.

No new review feedback since the last pass; the 11 unresolved clickhouse-gh threads and the AI review's "Minimum required actions" still map 1:1 to the design/policy decisions reserved for you (persist-by-default vs opt-in plus docs, max_size_in_bytes = 0 semantics, per-user quota on the disk write and disk-hit repopulation paths, on-disk byte accounting, file/metadata atomicity, SYSTEM RELOAD CONFIG handling of persist_cache and max_entry_size_in_rows, metadata-only startup, and the throwing std::filesystem::remove in the eviction callback), so I did not touch them.

…nit__.py`

The previous master merge on this branch was done with `git merge -s resolve`
(the `resolve` strategy was needed to work around a criss-cross history that
made the recursive strategy report a hundred spurious conflicts). That strategy
detected the newly added, empty `tests/integration/test_query_result_cache_on_disk/__init__.py`
as a *rename* of the equally empty `tests/integration/test_storage_nats/__init__.py`
that master had just added, and therefore deleted the latter.

Style check caught it:
`./tests/integration/test_storage_nats/__init__.py should exist for every integration test`.
@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Jul 28, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Follow-up to yesterday's maintenance pass: the Style check red on c56def40 was my own merge artifact, now fixed.

Yesterday's master merge had to use git merge -s resolve, because the branch was criss-crossed with master and the recursive strategy reported a hundred spurious conflicts. That strategy did rename detection across the merge and mistook this PR's newly added, empty tests/integration/test_query_result_cache_on_disk/__init__.py for a rename of the equally empty tests/integration/test_storage_nats/__init__.py that master had just added in the same window — so it deleted the latter. Style check caught it precisely:

./tests/integration/test_storage_nats/__init__.py should exist for every integration test

The file is restored, so that is the whole of the fix. The same red on the CH Inc sync mirror ran against the same SHA and has the same single cause; the mirror's earlier Config Workflow failure already went green on its own re-run.

The other red on the old head, Build (arm_tidy), never got as far as compiling anything — it died in setup_build_caches_env because the AWS SSM GetParameter call returned 502 Bad Gateway, i.e. pure CI infrastructure, unrelated to the code.

This pass also merged today's master. The criss-cross has resolved back to a single merge base, so a plain git merge was clean (0 conflicts) and no -s resolve was needed this time. Verified afterwards that the diff against master is still exactly the 11 feature files and that master's QueryResultCache guards (the eval exclusion and the ASTCreateFunctionWithDriverQuery UDF carve-out) are preserved. All five feature translation units — QueryResultCache.cpp, Context.cpp, Server.cpp, LocalServer.cpp, CurrentMetrics.cpp — compile clean against the new base. New head is 8bad5c98489; Style check is green on it and no check has failed, with Build (arm_tidy) now well past the stage where it previously broke.

For future passes on this branch: when the criss-cross forces -s resolve, its rename detection is the thing to check afterwards — identical empty files across unrelated directories are exactly what trips it.

No new review feedback. The 11 unresolved clickhouse-gh threads and the AI review's "Minimum required actions" are unchanged and still map 1:1 to the design and policy decisions reserved for you (persist-by-default vs opt-in plus docs, max_size_in_bytes = 0 semantics, per-user quota on both the disk-write and disk-hit repopulation paths, on-disk byte accounting, file/metadata atomicity, SYSTEM RELOAD CONFIG handling of persist_cache and max_entry_size_in_rows, metadata-only startup, and the throwing std::filesystem::remove in the eviction callback), so I did not touch them.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.50% 78.40% -0.10%

Changed lines: Changed C/C++ lines covered: 415/443 (93.68%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Weekly maintenance pass: merged master (the branch was ~4255 commits / 7 days behind) — new head 526d254a8c7. The merge was clean (single merge base this time, no criss-cross), the diff against master is still exactly the 11 feature files, and master's recent QueryResultCache.cpp changes (the eval exclusion and the driver-created UDF carve-out) are preserved. All affected translation units compile cleanly against the merged master.

The only red on the previous head (8bad5c9) was Stress test (arm_debug): a logical error Cannot create part with type Compact and storage type Full because table does not support polymorphic parts during part loading at server startup, which then caused the consequent "Cannot start clickhouse-server" failure. This is a chronic master-wide stress flake (STID 3286-403e, seen on dozens of unrelated PRs over the last three weeks) in MergeTreeDataPartBuilder, unrelated to the query result cache; a fix is in flight in #111626.

The 11 unresolved review threads are unchanged — all are the reserved design decisions (persist-by-default, disk-tier size accounting, per-user quota on the disk path, file/metadata atomicity, SYSTEM RELOAD CONFIG semantics, etc.) left for a human decision.

@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9a4106e30 with master 809fc9a43 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of a63b5b574; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.03 MiB 689.12 MiB -2.92 MiB (-0.42%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

92 object files changed (+200.72 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Cache/QueryResultCache.cpp.o 303.57 KiB 489.08 KiB +185.52 KiB (+61.11%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

3869 translation units recompiled, 22050 s compile time in total, 3836 of them have a recent master baseline.

Job report

…on check

Address review feedback on the query result cache:

- `squashChunks` and the totals/extremes path in `QueryResultCacheWriter::buffer`
  used `convertToFullIfSparse`, while `master` uses `removeSpecialColumnRepresentations`
  there. The difference is `convertToFullColumnIfReplicated`: without it, a result with
  lazily replicated columns (from `JOIN`, `ARRAY JOIN` or lambda captures) is stored in
  the in-memory tier as a `ColumnReplicated`. Restore `removeSpecialColumnRepresentations`
  at both call sites, so the in-memory tier again behaves exactly as on `master` and the
  on-disk tier gets materialized columns from `squashChunks` as well.

- The repopulation of the in-memory tier from a disk hit rejected entries whose size is
  exactly `max_entry_size_in_bytes` / `max_entry_size_in_rows`, whereas both write paths
  reject only entries strictly greater than the limits. An entry sized exactly at the
  boundary was therefore persisted on disk but never promoted back into memory. Use the
  same boundary as the write paths.

Add a test for caching a result with lazily replicated columns, with and without
`query_cache_compress_entries`.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Weekly maintenance pass, plus two review fixes.

Merged master (the branch was ~3453 commits / 8 days behind) — the merge was clean (single merge base, no criss-cross), the diff against master is still exactly the 11 feature files with no rename/delete artifacts, and master's QueryResultCache.cpp guards (the eval exclusion and the driver-created UDF carve-out) are preserved. All five affected translation units compile cleanly against the merged master.

Addressed two of the AI review blockers in 9a4106e — both are plain divergences rather than the reserved design questions:

  • QueryResultCache.cpp:715 (reopened thread): squashChunks and the totals/extremes branch of QueryResultCacheWriter::buffer used convertToFullIfSparse, whereas master uses removeSpecialColumnRepresentations at exactly those two places. The difference is convertToFullColumnIfReplicated, so a result with lazily replicated columns was stored in the in-memory tier as a ColumnReplicated. Both call sites now use removeSpecialColumnRepresentations again, which also means squashChunks materializes the columns on the on-disk path (the explicit de-replication loop in OnDiskCache::set is kept as a belt-and-braces guard).
  • QueryResultCache.cpp:914: the in-memory repopulation on a disk hit used strict <, while both write paths reject only entries strictly greater than the limits, so an entry sized exactly at max_entry_size_in_bytes / max_entry_size_in_rows was persisted on disk but never promoted back into memory. It now uses <=.

Added 04869_query_cache_replicated_columns, which caches a result with lazily replicated columns (ARRAY JOIN) with and without query_cache_compress_entries and asserts that the second execution is served from the cache.

The remaining AI blockers — on-disk size accounting from EntryWeight on the in-memory representation, and the non-atomic metadata/file lifecycle — are the design decisions left for you, together with the other reserved threads (persist-by-default, max_size_in_bytes = 0 semantics, per-user quota on the disk path, SYSTEM RELOAD CONFIG).

The only red on the previous head (526d254a) was Stress test (amd_tsan): Hung check failed, possible deadlock found. This is a chronic master-wide flake, not related to the query result cache — on 2026-08-05 alone it failed on 49 distinct pull requests with master as the base, and it has been failing continuously since (with a large fleet-wide storm on 2026-08-10 and 2026-08-11).

Comment on lines +1634 to +1658
if (tag)
{
/// Remove only the entries matching the tag, deleting their files as a side effect of the predicate.
auto predicate = [&tag](const Key & key, const CachePolicy::MappedPtr & mapped) -> bool
{
if (key.tag == tag.value())
{
fs::remove(mapped->path);
return true;
}
return false;
};
cache_policy->remove(predicate);
}
else
{
/// `cache_policy->clear()` does not invoke the eviction callback, so remove the persisted files explicitly.
cache_policy->clear();

fs::path format_version_path = query_cache_path / FormatTokens::format_version_txt;
for (const auto & entry_file_it : fs::directory_iterator(query_cache_path))
{
if (entry_file_it.path() == format_version_path)
continue; /// keep format_version.txt
fs::remove(entry_file_it.path());

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.

OnDiskCache::clear still lets filesystem exceptions break the cache's bookkeeping. In the tagged branch, this fs::remove runs inside LRUCachePolicy::remove(predicate): if the second or third unlink throws, earlier entries have already been erased from cells / queue and current_size_in_bytes, but the final CurrentMetrics::sub(...) never runs, so QueryCacheOnDiskBytes / QueryCacheOnDiskEntries stay stale and SYSTEM DROP QUERY CACHE TAG becomes partially applied.

The no-tag branch has the same problem in a different shape: cache_policy->clear() drops all metadata first, then a later fs::remove(entry_file_it.path()) can throw and leave orphaned persisted files that come back on the next restart.

Please make the filesystem deletions non-throwing here (for example the std::error_code overload plus logging) or separate the metadata mutation from the best-effort unlink pass so a single unlink failure cannot leave the cache half-cleared.

@rschu1ze rschu1ze added the hold Skip for auto-updating. label Aug 12, 2026
@rschu1ze

Copy link
Copy Markdown
Member

Discussed with @thevar1able today. He will take over. Adding hold for now to save CI resources. We will also need some mechanism to save/load cache entries in distributed setups, i.e. we need to store data in Keeper.

@rschu1ze

Copy link
Copy Markdown
Member

There is a new RFC and a new implementation for that.

@rschu1ze rschu1ze closed this Aug 19, 2026
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 hold Skip for auto-updating. pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants