Skip to content

UNIQUE KEY: index cache (7/N) - #104282

Merged
murphy-4o merged 18 commits into
ClickHouse:masterfrom
murphy-4o:uk-pr-7-dense-index-cache
Jun 4, 2026
Merged

murphy-4o merged 18 commits into
ClickHouse:masterfrom
murphy-4o:uk-pr-7-dense-index-cache

Conversation

@murphy-4o

@murphy-4o murphy-4o commented May 7, 2026 •

Copy link
Copy Markdown
Member

Part of #103486

Introduces a ClickHouse CacheBase adapter for the RocksDB block cache, including Context and Server registration along with corresponding metrics. The adapter implements the minimal rocksdb::Cache interface required for BlockBasedTableOptions::block_cache, delegating storage to CacheBase. This ensures that memory accounting is correctly integrated into system.caches via UniqueKeyIndexCacheBytes and UniqueKeyIndexCacheEntries.

The adapter narrows several rocksdb::Cache surfaces to eliminate redundant shadow bookkeeping on top of CacheBase. An audit of the RocksDB source code (specifically contrib/rocksdb/table/ and contrib/rocksdb/db/) confirms that BlockBasedTable does not rely on these narrowed paths for correctness when using a user-provided block_cache. ClickHouse maintains full ownership of the cache configuration and never enables strict mode.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry: N/A (incremental slice; user-facing changelog ships with the last PR in the stack once the full feature is reviewable).

Documentation entry for user-facing changes

  • Documentation will land with the user-facing slice.

Version info

  • Merged into: 26.6.1.388

ClickHouse-side `CacheBase` adapter that implements RocksDB's `Cache`
API for the UNIQUE KEY index SST block cache. Includes Context
registration, server-side wiring, server settings, ProfileEvents, and
CurrentMetrics.

Settings (read by Server.cpp at startup + reload):
- `unique_key_index_cache_policy` (default `SLRU`)
- `unique_key_index_cache_size_bytes` (default `1 GiB`)
- `unique_key_index_cache_size_ratio` (default `0.5`)

Setting size to 0 disables the cache; `getUniqueKeyIndexCache` returns
nullptr. On `USE_ROCKSDB=0` builds the registration is a graceful no-op.

ProfileEvents:
- `UniqueKeyIndexCacheLookupMicroseconds` — combined Lookup + Insert
  wall-clock inside the adapter.
- `UniqueKeyIndexCacheHits` / `UniqueKeyIndexCacheMisses` — per-lookup
  hit/miss counters.

CurrentMetrics:
- `UniqueKeyIndexCacheBytes`, `UniqueKeyIndexCacheEntries`.

`updateUniqueKeyIndexCacheConfiguration` logs an INFO line when the
configured cache size changes.

Tests (`gtest_unique_key_index_cache.cpp`): 5 cases pinning wrapper-only
behaviour — insert/lookup with hit/miss counter assertion, slice-key
erase, release-erase semantics, identity-aware replacement protection,
concurrency smoke. Tests that re-verify the dependency contracts
(CacheBase eviction, atomic ref counting) are intentionally not included.

Reviewer: PR 10 is the first production reader consumer of this cache;
the SST-reader-cache invalidation race helpers (removeWithToken*,
replaceIfPresent) and their gtest coverage are out of scope here and
travel with PR 10.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [36ad740]

Summary: ✅


AI Review

Summary

This PR adds a CacheBase-backed rocksdb::Cache adapter for UNIQUE KEY SST blocks, wires it into server configuration, metrics, and reload handling, and adds focused gtests around the adapter contract. I found no new blocker or major issue in the current code; the earlier strict-capacity and pinned-usage concerns are now deliberately outside this adapter's supported rocksdb::Cache surface, and the inspected BlockBasedTable hot path uses the implemented Lookup, Insert, GetUsage, and Release surfaces for correctness.

Missing context / blind spots
  • ⚠️ Full CI was still running when checked. The Praktika report showed no failed tests, but some GitHub checks such as Fast test and Build (arm_tidy) had not completed yet.
Final Verdict

Status: ✅ Approve

No code-review changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label May 7, 2026
murphy-4o added 2 commits May 7, 2026 18:05
- SetStrictCapacityLimit: rename parameter from `v` (cpp) and
  `strict_capacity_limit` (header) to `value` in both, satisfying
  readability-inconsistent-declaration-parameter-name and avoiding
  shadow with the same-name member.
- Release(): capture the erased outcome inside the predicate (which
  runs under the cache lock) instead of comparing two count() snapshots.
  Closes a race where unrelated concurrent insert/erase between the two
  count() calls could flip the return value.
Unit tests (amd_llvm_coverage) saw both Hits/Misses deltas as 0 even
though the asan/tsan/msan variants (with and without function_prop_fuzzer)
all see the expected 1/1. The Lookup is happening (the ASSERT_NE / EXPECT_EQ
on returned handles all pass on coverage too) — only the global_counters
read returns 0. Coverage seems to leave the increments in a thread-local
counters subtree that doesn't propagate to global. Gate the delta
assertions behind !WITH_COVERAGE; six other Unit-test configs validate
the wiring.
Mirror rocksdb::Cache's strict-capacity contract: refuse the standalone
when strict_capacity_limit is set, the requested charge exceeds the cap,
and the caller did not opt into an uncharged handle. With
allow_uncharged=true (the typical RocksDB caller) the standalone handle
is returned uncharged — consistent with the spec; CacheBase has no
native standalone-tracked path for proper charging.
GetPinnedUsage now reports the sum of charges of currently-pinned
entries (per-entry pin_count gates 0->1 add and 1->0 remove on the
shared total), matching rocksdb::Cache spec. Closes the strict-cap
bypass where pinned-but-evicted entries escaped both GetUsage and
GetPinnedUsage.

CreateStandalone in the strict + over-cap + allow_uncharged=true path
now sets effective_charge=0 so GetCharge / GetUsage(handle) /
GetPinnedUsage all consistently report 0.

Release(erase=true) predicate also requires pin_count==0 under the
backing lock — narrows the Lookup-vs-erase race to a small residual
window where T2's get and pin_count.fetch_add are not jointly under
the backing lock; closing that fully needs a CacheBase API extension
and is out of scope here.
murphy-4o and others added 4 commits May 10, 2026 11:08
Lands the squash of the iterative best-effort-cap exploration on top of
ecea231. Net design vs the post-Murphy clean head 707f0ed:

- Declare cache as best-effort capacity, matching MarkCache /
  UncompressedCache. SetStrictCapacityLimit(true) is reported by
  HasStrictCapacityLimit() but admission is not gated on the flag.
  Strict admission introduces concurrent-admission edge cases that
  aren't worth the cost for this cache; callers needing a hard cap
  enforce it externally.

- Honor the rocksdb::Cache::Release(h, erase_if_last_ref=true)
  "last reference" contract using the shared_ptr lifetime we already
  maintain: the predicate runs under CacheBase's bucket mutex (the
  same mutex Lookup's backing->get and Insert's backing->set take), so
  pinned.use_count() is stable wrt concurrent HandlePin construction.
  use_count == 2 (backing's strong ref + our HandlePin's) means we are
  the last external pin and the entry can be erased; > 2 means another
  live HandlePin exists and the entry stays resident so a fresh Lookup
  still hits. Mirrors rocksdb's own LRUCacheShard pattern (single mutex
  covers Unref + erase decision), with no separate pin counter and no
  CacheBase API extension.

- HandlePin gains an explicit is_standalone bool. The prior
  pin->key == UInt128{} discriminator misclassified any real key whose
  SipHash128 hashed to all zeros.

- GetPinnedUsage() returns 0 with a one-line comment. RocksDB's
  BlockBasedTable hot paths read this only as a metric, and our
  consumers don't read it for correctness.

Tests at this head: 7 cases, all PASS twice on debug arm.
- ReleaseEraseLastRefRespectsOtherLiveHandle covers the rocksdb
  "last ref" contract that any pin_count-style or use_count-style
  implementation must preserve.
- ReleaseEraseIdentityAwareDoesNotEvictReplacement covers the
  same-key replacement race.
- The two GetPinnedUsage* tests added during the strict-cap
  exploration are dropped (no consumer).

Local cursor-agent ask-mode at the pre-squash head: Clean-with-note.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
HasStrictCapacityLimit() is hardcoded to false; SetStrictCapacityLimit is
a no-op. Per rocksdb::Cache::CreateStandalone spec, non-strict mode means
the operation always succeeds and allow_uncharged is unused, so the
parameter is documented as such. GetPinnedUsage remains 0; only rocksdb
internal_stats reads it, and it degrades gracefully.

Honoring strict-cap on top of CacheBase would require shadow pin
bookkeeping plus a joint get-and-mutate primitive CacheBase does not
expose. This cache is ClickHouse-configured end-to-end and strict mode
is never enabled on it; rocksdb's BlockBasedTable does not exercise the
strict path against a user-provided block_cache either.

Tests: replaced CreateStandaloneAlwaysReturnsHandle with
StrictCapacityLimitIsUnsupported and
CreateStandaloneAlwaysSucceedsWhenNonStrict.
The flag protected two code paths that never fire in this deployment:
Release skipped backing->remove for standalone handles, and GetUsage
skipped OVERHEAD. CreateStandalone has no caller in contrib/rocksdb/
(table/, db/) on a user-provided block_cache and no ClickHouse caller
reaches it either, so neither path is observable.

Without the flag, Release's predicate is a guaranteed no-match for a
standalone handle: backing never holds the entry's shared_ptr (v ==
pinned fails) and use_count is 1 not 2 — either condition alone defeats
the match. GetUsage(handle) over-reports by 64B per standalone, again
unobservable.

Also disambiguate CacheBase::remove's two overloads via a local
'using RemovePred = std::function<...>' alias.
Three narrowings on the rocksdb::Cache adapter surface, all leaning on the
fact that the narrowed paths are either unused or consumed only by callers
that don't read the relaxed return value:

1. Ref(handle) returns false unconditionally. The spec permits this via
   "returns false if the entry could not be refed." No production rocksdb
   path calls Ref on a user-provided block_cache (grep contrib/rocksdb/).
   HandlePin::refs is removed; Release is unconditionally final, no atomic
   fetch_sub.

2. UniqueKeyIndexCacheEntry, UniqueKeyIndexCacheEntryWeight,
   UniqueKeyIndexCacheBacking, the SipHash free function, and getBacking()
   move out of the header. The header forward-declares
   UniqueKeyIndexCacheBacking and exposes only UniqueKeyIndexCache plus
   UniqueKeyIndexCachePtr. Entry/Weight/HandlePin/hash helpers live in an
   anonymous namespace in the .cpp; Backing lives in namespace DB to match
   the forward decl. Zero external uses of the moved internals (audited).

3. Release(handle, erase_if_last_ref=true) drops the table slot
   unconditionally — no use_count or identity predicate guard. Live
   HandlePins keep the entry alive via shared_ptr, so correctness is
   preserved; the cost is one extra cache miss + re-read for bursty
   multi-Lookup workloads. The relaxed `erased = true` return is consumed
   only by UncacheAggressivenessAdvisor (rocksdb's uncache_aggressiveness
   feature), which our SST probe doesn't enable.

Tests: dropped ThreadSafetySmoke (CacheBase locking, not ours);
ReleaseEraseLastRefRespectsOtherLiveHandle and
ReleaseEraseIdentityAwareDoesNotEvictReplacement (no longer guaranteed
under Trim 1). Added RefReturnsFalse and
ReleaseEraseIfLastRefYanksSlotUnconditionally. 9 -> 7 tests, all PASS.
@murphy-4o
murphy-4o marked this pull request as ready for review May 11, 2026 13:47
@Michicosun Michicosun self-assigned this May 11, 2026
Comment thread src/Interpreters/Context.cpp Resolved
murphy-4o added 2 commits May 13, 2026 11:12
If the server starts with unique_key_index_cache_size_bytes=0,
shared->unique_key_index_cache stays nullptr. The previous
updateUniqueKeyIndexCacheConfiguration also returned early when the cache
was null, making 0 a one-way disable for the process lifetime.

Construct the cache on the first reload that requests a non-zero size,
using unique_key_index_cache_policy and unique_key_index_cache_size_ratio
from the same config block. The startup path is unchanged — explicit
opt-out at startup still means no overhead from a 0-capacity adapter
until a reload re-enables it.
Walk back the unconditional backing->remove(pin->key) from d75499b.
The simplification broke two parts of the rocksdb::Cache::Release contract
that the bot review flagged: an old handle could evict a freshly-inserted
replacement under the same key, and the return value reported success even
when no shared-table entry was actually erased.

Restore the predicate
  k == pin->key && v == pinned && pinned.use_count() == 2
which runs under CacheBase's bucket lock, so the contributors to
use_count are stable: table strong ref + this HandlePin = 2; another
live HandlePin pushes it past 2 and the erase is refused; replacement
under the same key sets v != pinned and the erase is refused.

Tests: drop ReleaseEraseIfLastRefYanksSlotUnconditionally (the
unconditional-yank assertion); restore ReleaseEraseLastRefRespectsOther-
LiveHandle and ReleaseEraseIdentityAwareDoesNotEvictReplacement.
Comment thread src/Interpreters/Context.cpp Resolved
murphy-4o added 2 commits May 21, 2026 13:57
`setUniqueKeyIndexCache` and `updateUniqueKeyIndexCacheConfiguration`
have params that go unused when USE_ROCKSDB is off. The `(void)param;`
casts at the end of the function body did the job but the modern
attribute is tidier.
Address Michicosun's PR review:

1. `Release(handle, erase_if_last_ref=true)` previously called
   `backing->remove(predicate)` which iterates the entire SLRU list to
   find a single matching key. Replaced with a new O(1)
   `CacheBase::removeIfMatches(key, predicate)` primitive that does
   point lookup + conditional remove under a single mutex acquisition.
   The Release predicate becomes `v == pin->entry &&
   pin->entry.use_count() == 3` (table + caller's HandlePin +
   `removeIfMatches`'s local shared_ptr copy).

2. `ApplyToAllEntries` was a documented silent no-op (CacheBase has no
   public iteration API and the BlockBasedTable hot paths don't read
   this surface). Added `chassert(false, ...)` so debug builds catch a
   surprise caller; release builds keep the silent no-op for graceful
   degradation.

3. Added an ASCII layering diagram to the class doc comment showing the
   four pieces: UniqueKeyIndexCache (public adapter) -> Backing
   (CacheBase) -> Entry (per cached block) and HandlePin (per
   outstanding Handle*).

Tests unchanged: 8/8 still pass. The new `removeIfMatches` keeps the
identity + use_count refusal paths covered by
`ReleaseEraseLastRefRespectsOtherLiveHandle` and
`ReleaseEraseIdentityAwareDoesNotEvictReplacement`.
The previous "chassert(false) catches surprise callers" hardening was
based on the assumption that no production rocksdb path reaches this
method on a user-provided block_cache. Actually it does, via:

  DBImpl::DumpStats
    -> InternalStats::CollectCacheEntryStats
       -> CacheEntryStatsCollector::CollectStats
          -> cache->ApplyToAllEntries(...)

Periodic stats collection would hit `chassert(false)` in debug builds.
Revert to a silent no-op; document the reachable consumer in the
comment. The stats walker degrades to empty per-role buckets, which is
the right behavior since CacheBase has no public iteration API for us
to honor the spec.
murphy-4o added 2 commits June 3, 2026 15:33
The field was declared `void * allocator = nullptr` and never written
by Insert / CreateStandalone, so the destructor was
`reinterpret_cast<MemoryAllocator *>(nullptr)`-ing it through to
`helper->del_cb` every time. Per the rocksdb::Cache contract, the
allocator passed to del_cb must equal `cache->memory_allocator()` at
allocation time. This adapter does not override `memory_allocator()`,
so the base-class default is nullptr for the cache's lifetime — every
caller allocates with default new, and the deleter must be passed
nullptr to match.

The per-entry field carried zero information. Drop it and pass nullptr
literally at the del_cb call site with a comment naming the contract
and pointing at the small change (override memory_allocator() + thread
the pointer at Insert) needed if a custom allocator is ever wanted.

Also drop the now-stale "allocator" mention from the ASCII diagram in
the header.
`rocksdb::Cache::memory_allocator()` is non-virtual (advanced_cache.h:437),
so a derived "override" would only hide it. The future-fix path is to
pass `std::shared_ptr<MemoryAllocator>` to the base `Cache` constructor,
which sets `Cache::memory_allocator_`, and thread that pointer onto the
entry at Insert time. Reword the comment to match.
@murphy-4o
murphy-4o requested a review from Michicosun June 3, 2026 14:41
@clickhouse-gh

clickhouse-gh Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 245/284 (86.27%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 3 line(s) · Uncovered code

Full report · Diff report

@murphy-4o
murphy-4o enabled auto-merge June 4, 2026 13:57
@murphy-4o
murphy-4o added this pull request to the merge queue Jun 4, 2026
Merged via the queue into ClickHouse:master with commit 953f1c5 Jun 4, 2026
166 checks passed
@murphy-4o
murphy-4o deleted the uk-pr-7-dense-index-cache branch June 4, 2026 14:22
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 4, 2026
@azat

azat commented Jun 9, 2026 •

Copy link
Copy Markdown
Member

@murphy-4o looks like new test is flaky, can you PTAL? https://pastila.nl/?04c5ec7b/5e60f8fc69db94e39a6a40d51e4ccc08#s0xPJMEORBfPW8tHzNd1XA==GCM

@murphy-4o

Copy link
Copy Markdown
Member Author

The gtest added here, UniqueKeyIndexCache.InsertLookupAndHitMissCounters, turned out to be flaky:

src/Storages/MergeTree/tests/gtest_unique_key_index_cache.cpp:80: Failure
Expected equality of these values:
  ProfileEvents::global_counters[ProfileEvents::UniqueKeyIndexCacheHits].load() - hits_before
    Which is: 0
  1u

Root cause: the test reads deltas from ProfileEvents::global_counters, but ProfileEvents::increment (inside UniqueKeyIndexCache::Lookup) routes through CurrentThread::getProfileEvents, which only returns global_counters when no ThreadStatus is attached to the current thread. All gtests in unit_tests_dbms run on one main thread, and some tests (e.g. gtest_filecache) attach a ThreadStatus to it that persists for the rest of the binary. After that, the increments land in a thread-local subtree that does not propagate to global_counters, so the deltas read 0. CI shuffles gtests (--gtest_shuffle), so the failure is order-dependent.

Fix in #106839 - read the deltas from CurrentThread::getProfileEvents (the exact Counters object the increment targets) instead of global_counters, which also removes the now-unnecessary WITH_COVERAGE special case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants