Skip to content

Add borrow_from_cache object storage and memory metadata types - #100371

Open
alexey-milovidov wants to merge 287 commits into
masterfrom
borrow-from-cache-object-storage
Open

alexey-milovidov wants to merge 287 commits into
masterfrom
borrow-from-cache-object-storage

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 22, 2026 •

Copy link
Copy Markdown
Member

Add a new object storage type borrow_from_cache that allocates space in a named filesystem cache using ephemeral FileSegments. Each stored object is backed by a cache segment held alive via FileSegmentsHolder; when released, the cache reclaims the space.

Add a new metadata type memory that keeps all file-to-blob mappings and directory structure entirely in memory with no persistence. On server restart all data is lost, which is acceptable for the intended use case of temporary tables.

Configuration example:

  disk(type=object_storage,
       object_storage_type='borrow_from_cache',
       metadata_type='memory',
       cache_name='some_cache')

Changelog category (leave one):

  • New Feature

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

A new object storage type and metadata type suitable for temporary tables. Add a new object storage type borrow_from_cache that allocates space in a named filesystem cache and holds it from eviction. Add a new metadata storage type memory that keeps the mapping in memory. For example, this could allow creating temporary tables with custom engines in the Cloud without using S3. Closes #75551.


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

@clickhouse-gh

clickhouse-gh Bot commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [af620e0]

Summary: ❌

job_name test_name status info comment
Style check FAIL
functional_tests_check 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-feature Pull request with new product feature label Mar 22, 2026
alexey-milovidov added a commit that referenced this pull request Mar 22, 2026
…dicate

- Remove unused `DIRECTORY_DOESNT_EXIST` error code from `MetadataStorageInMemory.cpp`
  (style check failure)
- Remove default argument values from override declarations in
  `BorrowFromCacheObjectStorage` to fix `google-default-arguments` clang-tidy error
- Guard `removeRecursive` against null `should_remove_objects` predicate and
  pass relative paths to match the predicate contract

#100371

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread docs/en/operations/storing-data.md Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The flaky check failure is fixed in #102148, let's update the branch.

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review April 25, 2026 12:36
@kssenii kssenii self-assigned this Apr 26, 2026
alexey-milovidov added a commit that referenced this pull request Apr 28, 2026
…set explicitly

The previous check relied on `compatibility_type_hint == "memory"`, but the
hint is only populated when `metadata_type` is absent from the config. With
`metadata_type = 'local'` set explicitly, the hint stays empty and the check
was bypassed, allowing a misconfiguration the test
`04141_borrow_from_cache_metadata_check` exists to reject.

Use the actual `ObjectStorageType` of the local location instead, so the
enforcement triggers regardless of whether `metadata_type` is set explicitly.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100371&sha=b9bc6622d4fc456f6196c00d34ebd5ad505638fa
PR: #100371

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits October 31, 2026 07:24
… `mutate_mutex`

`INSERT INTO j SELECT ... FROM j` holds the read lock of its source. A concurrent persistent
insert that holds `mutate_mutex` while publishing its backup waits for the write lock, so
waiting on `mutate_mutex` in `StorageJoin::write` was a lock cycle. Check that the insert is
possible before taking `mutate_mutex`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… a cached disk

A lost invalidation can leave stale cache entries for reused blob paths on cached `plain` and
`plain_rewritable` disks. The bookkeeping only allocates a few small nodes, so do not let the
memory limits of the query or the user make it fail.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master (no conflicts) and pushed 9ea5a9791417..f9e834d3a52d. clickhouse builds on the merged tree.

  • All flaky-check failures were 05458_borrow_from_cache_temporary_table_drop_releases_segments: concurrent runs shared the server-wide cache and disk names and counted each other's segments. Converted it to a .sh test that names the cache and the disk after the test database; 40 parallel runs pass locally.
  • Review (self-reading Join insert lock cycle): StorageJoin::write now rejects a self-reading insert before waiting on mutate_mutex; new test 05459_storage_join_self_read_insert_no_lock_cycle.
  • Review (cache coherence after a failed post-commit bookkeeping): the bookkeeping now runs with memory limits lifted; the remaining design choice is described in the thread and left for a human reviewer.

`DiskObjectStorageOverInMemoryMetadataTest.AppendToInlinedFileIsRejected` required the
append to an inline-backed file to throw. The private build moves the inline content to a
blob before the append instead, which is equally correct. The test now checks the actual
invariant: the file never carries the stale inline payload next to a blob, and its content is
either the original one (rejected append) or the whole appended one.

`05453_borrow_from_cache_wrapper_rollback_reclaims_segments` exceeded the time limit of the
flaky check with the default disk on S3: every background write of the server commits through
the one-shot failpoint and consumes it, so the retries take too long. Tag it `no-object-storage`.

Sync PR: ClickHouse/clickhouse-private#53277
Related: #100371

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

Copy link
Copy Markdown
Member Author

🕵 Pushed f9e834d3a52d..99a7e2285164 to fix the CH Inc sync (tests failed) in https://github.com/ClickHouse/clickhouse-private/pull/53277. All public CI checks were green.

  • DiskObjectStorageOverInMemoryMetadataTest.AppendToInlinedFileIsRejected failed in all private unit-test jobs. In the private repository, DiskObjectStorageTransaction::writeFile moves inline content to a blob before an append instead of rejecting the append, so the file became tiny-more. Both behaviours are correct, so the test (now AppendToInlinedFileKeepsConsistentContent) checks the invariant instead: the stale inline payload never sits next to a blob, and the content is either the original one or the whole appended one. It passes locally.
  • 05453_borrow_from_cache_wrapper_rollback_reclaims_segments exceeded 180 s in the private flaky check (s3 storage, meta in keeper). With the default disk on object storage, every background write of the server commits through the one-shot disk_object_storage_fail_commit_metadata_transaction failpoint and consumes it, so the retry loop runs too long. The test is now tagged no-object-storage.
  • The other private failures (03100_lwu_48_bytes_limit_merge, 00753_alter_attach, test_storage_iceberg_with_spark/test_compaction_file_size.py) are in areas this PR does not touch.

The two open review threads (the replay cost of a persistent Set insert, and cache coherence when the post-commit bookkeeping fails) are still waiting for a human design decision, as explained in the replies there.

…k through a `cache` disk

`DiskObjectStorageTransaction::undo` called `removeObjectsOfFailedTransaction` for every disk, and
`CachedObjectStorage` forwards it to the storage it wraps. On a cached `plain_rewritable` disk an
ordinary file overwritten in place reuses the key of its existing blob, so a failed copy or write
whose commit is rolled back would physically remove a blob that the committed metadata still
references. Forward the physical removal only when the metadata storage generates random blob paths
(as `memory` metadata over `borrow_from_cache` does), so every written blob is owned by the failed
transaction; otherwise keep the previous behaviour of `removeObjectsIfExist`, which for a `cache`
disk only drops the cache entries.

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

Copy link
Copy Markdown
Member Author

🕵 Pushed 99a7e2285164..f915272e4f8c:

  • Review (a failed cached copy removes an existing destination object): DiskObjectStorageTransaction::undo now removes the wrapped objects physically only when the blob paths are random. Metadata with reusable keys, such as cached plain_rewritable, gets the master behaviour back. Details are in the thread.
  • CH Inc sync: the previous sync (https://github.com/ClickHouse/clickhouse-private/pull/53277) failed on a Logical error: 'false' in DistributedCacheTCPHandler::processReadRequest, which is tracked as the already closed private issue 67397, and on private-only integration tests (test_e2e_paimon, test_e2e_databricks_rest_catalog, test_shared_merge_tree_lightweight_snapshot) that do not touch this change. This push starts a new sync.
  • Two older threads are still waiting for a human design decision: the O(total_rows) replay of persistent Set inserts, and cache coherence when the post-commit bookkeeping fails.

alexey-milovidov and others added 3 commits November 4, 2026 12:01
# Conflicts:
#	src/Storages/StorageJoin.cpp
…_insert`

The test, added on `master`, checks that a `Join` insert which throws
partway through a block keeps the keys inserted before the throw. This PR
makes persistent `Join` inserts atomic: they stage their blocks in a backup
file and are rolled back as a whole on failure, so the table stays empty
and the `scan > 0` check failed in the Fast test. Only a non-persistent
table still inserts blocks directly into the live state, so use
`persistent = 0` to keep testing the partial-insert path.

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

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

Copy link
Copy Markdown
Member Author

🕵 Merged master (no conflicts) and pushed e04848b9c337..1a1661676485.

  • Fast test failed on 05395_storage_join_count_after_partial_insert, a test added on master. It checks that a Join insert which throws partway through a block keeps the keys inserted before the throw. This PR makes persistent Join inserts atomic (rolled back as a whole on failure), so the table stayed empty and scan > 0 returned 0. The test now uses persistent = 0, where blocks still go directly into the live state, so it keeps covering the partial-insert path. Verified locally: the old test gives 1 0, the new one matches the reference, and the insert still throws MEMORY_LIMIT_EXCEEDED.
  • The two unresolved review threads (O(total_rows) replay in persistent Set inserts, cache coherence after failed post-commit bookkeeping) are still waiting on a human design decision; see the replies there.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CH Inc sync failed because the sync PR (https://github.com/ClickHouse/clickhouse-private/pull/53277) conflicted in src/Storages/StorageJoin.cpp. Private master has its own getJoin/setJoin accessors there, and they clashed with the HashJoin::create changes the PR got from the latest master merge. I resolved it on the sync branch (cb61d039f859..8b137447116e), keeping the private accessors and the PR's changes. The sync PR is MERGEABLE again. Every public CI check is green, so this branch did not need any change. The two open review threads (the StorageSet replay cost and the post-commit cache invalidation in MetadataStorageFromCacheObjectStorage) already have replies and are waiting on a human design decision.

alexey-milovidov and others added 2 commits November 13, 2026 11:04
…bject-storage

Conflict in `DiskObjectStorageTransaction::undo`: master now removes the blobs of
an undone transaction through every layer (`getUnderlying`) down to the base object
storage. This subsumes the PR's `removeObjectsOfFailedTransaction`, which is removed.
The PR's guard is kept: the blobs are removed below the outermost layer only when
the blob paths are random (`areBlobPathsRandom`), so an in-place overwrite of a
`plain_rewritable` file under a cache does not delete the committed object.

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

The style check requires queries to `system.text_log` to be bounded by
`event_time`, since a full scan exceeds `max_rows_to_read` on CI.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100371&sha=2600974e83b033594cea65469e9ec59d89e39dc7&name_0=PR&name_1=Style%20check
Related: #100371

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageJoin.cpp Resolved
alexey-milovidov and others added 3 commits November 18, 2026 14:39
…bject-storage

Resolve the conflict in `StorageSet.cpp` by keeping both `onException` of this PR and
`onPipelineFinished` from master; guard `onPipelineFinished` with `insert_finished` so that a
pipeline cancelled after a successful `onFinish` does not publish the backup twice.
…type analysis

`StorageJoin::joinGetCheckAndGetReturnType` read `join` without `rwlock`, while a failed
persistent `INSERT` (and its lost-state recovery), a mutation or `TRUNCATE` replace it under
the write lock and may destroy the old `HashJoin`. `JoinGetOverloadResolver::buildImpl` calls
it before taking any table lock, so a concurrent `joinGet` analysis could use a destroyed
object. Take the read lock with the query context, like `joinGet` itself does.

Add a test running `joinGet` analyses concurrently with persistent inserts that exceed
`max_rows_in_join` and are rolled back.

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

`master` enabled the `modernize-use-nodiscard` clang-tidy check; the functions this PR adds to
`IMetadataStorage` and `MetadataStorageInMemory` would fail the clang-tidy build.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed 6fe129a2c500..90cfba513f93:

  • Conflicts: StorageSet.cpp (master added SetOrJoinSink::onPipelineFinished for timeout_overflow_mode = 'break'; kept it next to this PR's onException and guarded it with insert_finished, so a pipeline cancelled after a successful onFinish does not publish the backup twice; 05627_set_join_insert_persisted_on_break passes locally), plus [[nodiscard]] / signature / docs conflicts in MetadataStorageFromIndexPages.h, MetadataStorageWithPathWrapper.h, ObjectStorageFactory.cpp and storing-data.mdx.
  • Review (joinGet type analysis reads HashJoin without the lock): fixed, with a new test 05829_storage_join_joinget_analysis_during_failed_insert.
  • master enabled modernize-use-nodiscard; added [[nodiscard]] to the four new const functions it flags. The full clang-tidy config is clean on all changed translation units.
  • The only red check was the review-threads gate (the full suite was skipped). Two threads remain open because they need a human decision: the O(total_rows) replay cost of a persistent Set insert, and the stale-cache risk when the post-commit bookkeeping of a cached plain_rewritable disk fails (details in each thread).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (no conflicts) and pushed 90cfba513f93..7208460c0dd3:

  • Style check: renamed 05829_storage_join_joinget_analysis_during_failed_insert to 05829_storage_join_joinget_analysis_during_rejected_insert, because test names must not contain fail.
  • Build (arm_tidy, 1/4): added [[nodiscard]] to countBlobs and readThroughDisk in gtest_metadata_in_memory.cpp (modernize-use-nodiscard). The other three tidy shards were green.
  • All 33 changed translation units compile against the merged tree.
  • CH Inc sync: the sync PR (https://github.com/ClickHouse/clickhouse-private/pull/53277) was CONFLICTING again in src/Storages/StorageJoin.cpp (private getJoin/setJoin accessors against the new joinGetCheckAndGetReturnType and the HashJoinTable changes from master). Resolved on the sync branch (8b137447116e..1cd845997cfa); it is MERGEABLE now and the private CI has restarted.
  • The Review Threads gate is still red, so the full CI suite is skipped: two threads stay open because they need a human design decision (the O(total_rows) replay cost of a persistent Set insert, and the stale-cache risk when the post-commit bookkeeping of a cached plain_rewritable disk fails). Both have replies with the trade-offs.

@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=24 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: b3e8650f-895e-4e73-9d78-f098ced07051
  • MIRAI run: aa93433c-8d66-4f6e-a157-9d88d848a939
  • PR check IDs:
    • clickbench_658534_1795268710
    • clickbench_658540_1795268710
    • tpch_adapted_1_official_658575_1795268710
    • tpch_adapted_1_official_658597_1795268710

alexey-milovidov and others added 4 commits November 24, 2026 10:56
…aster

`chmod` and `supportsChmod` were removed from the disk and metadata storage
interfaces on master ("Remove unused `chmod` and `supportsChmod` from disks"),
so the overrides in `MetadataStorageInMemory` and its transaction no longer
override anything and the merged tree did not compile.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…mmitted transaction

`MetadataStorageFromCacheObjectStorageTransaction` queues the blobs removed by the
underlying transaction after the commit, so that the blob killer drops their cache
entries. If that bookkeeping failed, the failure was logged and the blobs were
forgotten. On a cached `plain_rewritable` disk a later file can reuse the path of a
removed blob, and the stale cache entry would then be served for it.

Retain the committed underlying transaction, which knows the removed blobs, in the
metadata storage, and queue its blobs on the next round of the blob killer. The list
node that holds it is allocated when the transaction is created, so retaining it
after the commit does not allocate and cannot fail. Until the blobs are queued,
`hasPendingRemovalBlobs` reports them as pending, as it does for queued blobs, and
`hasDeadBlobsQueue` keeps the blob killer polling. The commit still never fails
after the metadata is committed, so committed blobs are not rolled back.

Also keep the two containers of `InMemoryRemovalQueue` in sync if the second
insertion throws: a retried `submitForRemoval` would otherwise leave a blob in the
queue that is never forgotten.

#100371 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ts own backup

`StorageSet::publishBackup` built a new `Set` from all committed backups on every
persistent `INSERT` and swapped it in. With `persistent = 1` (the default) that made
every insert cost as much as the whole table: repeated small inserts were quadratic,
and two full copies of the table were kept in memory during each of them.

Replay only the promoted backup of the `INSERT` into the live `Set`, as it was done
before this pull request. If the replay fails, the state is rebuilt from the other
committed backups and swapped in, so the queries started afterwards see exactly the
committed rows, and the backup of the failed insert is discarded as before. If the
rebuild fails as well, the state is marked as lost: `getSet` throws `NOT_INITIALIZED`
instead of handing out a `Set` with rows of the failed insert, and the next `INSERT`
rebuilds it.

This intentionally gives up one property of the previous approach: a query that is
already running can observe the rows of an `INSERT` while it is being published,
and keeps the rows of a failed one until it finishes. That is how `Set` behaves on
master. The test that pinned the opposite,
`05150_storage_set_persistent_insert_not_visible_mid_replay`, and its failpoint are
removed. `05872_storage_set_failed_insert_rollback_failure_is_not_visible` covers the
failed rollback.

300 single-row inserts into a persistent `Set` of 3 million rows now take about a
second in total in `clickhouse local`.

#100371 (comment)

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

This branch was successfully deployed

1 active deployment
staging - docs — af620e09 Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Disk that borrows space from the cache.

5 participants