Repository navigation
UNIQUE KEY: index cache (7/N) - #104282
Conversation
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]>
|
Workflow [PR], commit [36ad740] Summary: ✅
AI ReviewSummaryThis PR adds a Missing context / blind spots
Final VerdictStatus: ✅ Approve No code-review changes requested. |
- 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.
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.
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.
`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.
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.
LLVM Coverage Report
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 |
|
The gtest added here, Root cause: the test reads deltas from Fix in #106839 - read the deltas from |
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 toCacheBase. This ensures that memory accounting is correctly integrated intosystem.cachesviaUniqueKeyIndexCacheBytesandUniqueKeyIndexCacheEntries.The adapter narrows several
rocksdb::Cachesurfaces to eliminate redundant shadow bookkeeping on top ofCacheBase. An audit of the RocksDB source code (specificallycontrib/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):
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
Version info
26.6.1.388