Repository navigation
Add filesystem cache eviction metrics - #105020
Conversation
Introduces four metric families exposed via the existing
DimensionalMetrics/HistogramMetrics infrastructure:
- filesystem_cache_evictions_total{cache_name, queue}
- filesystem_cache_evicted_bytes_total{cache_name, queue}
- filesystem_cache_evicted_segment_hits{cache_name} (histogram)
- filesystem_cache_evicted_segment_size_bytes{cache_name} (histogram)
Each has a `_by_client` variant additionally labelled by user_id.
Emission is gated per-FileCache by two new FileCacheSettings:
- expose_eviction_metrics (default off): enables the four families above
- expose_eviction_metrics_per_client (default off): also enables the
_by_client variants. Cardinality grows with distinct evicting users,
hence separately opt-in.
EvictionCandidates::evict gains an optional `const FileCache *` parameter.
When the parent FileCache has metrics enabled it records the metric inline
right next to the existing ProfileEvents increments at the successful-eviction
site. When the flag is off (every regular server today), the hot path is
a single branch on a bool - no observable overhead.
The queue label uses Iterator::getType (via getNestedOrThis to see through
SplitIterator); the dynamic-resize path consults original_queue_types saved
during removeQueueEntries.
Adds TEST_F(FileCacheTest, ExposeEvictionMetrics) in three phases:
flag off (no delta), aggregate flag on (deltas present, _by_client zero),
both flags on (per-client deltas present).
Counters were already labelled by queue; histograms (segment_hits, segment_size_bytes, and their _by_client variants) only carried cache_name. Adds queue as a label on the histograms too so operators can answer questions like "is the hit distribution different for evictions from the protected queue vs probationary?" - which is the main analytic value of having both queues in the metric in the first place. Cardinality impact: aggregate histograms grow by a small constant factor (3 known queue values); _by_client variants grow by the same factor on top of their already-opt-in client_id dimension.
The anonymous-namespace helpers in TEST_F(FileCacheTest, ExposeEvictionMetrics) referenced bare DimensionalMetrics:: / HistogramMetrics::, which the compiler resolved against DB:: (via using namespace DB; at file scope) where DB::HistogramMetricLog shadowed the global HistogramMetrics namespace, producing 'use of undeclared identifier' errors with a misleading 'did you mean HistogramMetricLog?' note. The top-level gtest_prometheus_metrics_writer.cpp doesn't hit this because its tests are at file scope, not in an anonymous namespace.
DimensionalMetrics.h / HistogramMetrics.h were accidentally added inside the existing #if CLICKHOUSE_CLOUD block, making them invisible in public builds (CLICKHOUSE_CLOUD=0) and breaking the ExposeEvictionMetrics test. The headers themselves aren't cloud-only, and the test isn't either, so the right home is outside the guard.
A regular FileCache configured with `expose_eviction_metrics=true`
must register the four `filesystem_cache_*` metric families and update
them via `system.dimensional_metrics` / `system.histogram_metrics` once
real evictions are driven by a workload.
The test configures a small SLRU cache on a local_blob_storage disk,
attaches it to a MergeTree, inserts and re-reads enough data to force
SLRU churn, and asserts:
- Aggregate evictions counter advances.
- Aggregate evicted_bytes counter advances.
- Hits and size histograms record one observation per evicted
segment (counter == histogram observation count).
- Per-client variants populate (test config sets _per_client too).
- Labels include the configured cache_name and at least the
`probationary` queue.
Complements the in-process gtest in `gtest_filecache.cpp` which covers
the flag-on/flag-off semantics directly.
|
Workflow [PR], commit [dcf78e8] Summary: ✅
AI ReviewSummaryThis PR adds opt-in filesystem-cache eviction counters and histograms, with runtime cache-setting toggles and coverage for the main eviction paths. The current diff fixes the earlier callback, SLRU promotion, label escaping, runtime-toggle, and metric-shape test issues I checked. Two user-facing contract gaps remain from prior dismissed threads: query-based export from Findings
Tests
Final VerdictStatus: Minimum required actions: fix or explicitly narrow the |
…l arg The cache that owns an EvictionCandidates instance doesn't change across the object's lifetime, so it belongs on the instance, not on each evict() call. Constructor takes an optional FileCache pointer (default nullptr) so tests and non-FileCache callers keep working unchanged - metrics are simply not emitted in those cases. Cleaner signature: evict() goes back to taking no arguments; the three call sites in FileCache.cpp construct via 'EvictionCandidates eviction_candidates(this);' instead of passing 'this' to every evict() call.
Reviewer pointed out that calling FileCacheMetrics::recordEviction
before pushing the iterator to queue_entries_to_invalidate left a
hole: a throw inside the metric path (e.g. allocation in withLabels)
would skip the invalidation. removeFileSegment has already taken the
segment off metadata + filesystem at that point, so the corresponding
queue entry would be stranded and afterEvictState would never clean
it up - desynchronizing cache accounting.
Two changes:
- Push the iterator into queue_entries_to_invalidate BEFORE the
metrics block. Cleanup is now committed regardless of what the
metrics path does.
- Wrap the metric calls in try/catch so any failure is logged and
swallowed. Metrics are observability and must never break the
invariants of the path they observe.
Two bugs in the previous integration test prevented evictions from
firing on the configured cache:
- `cache_on_write_operations` was placed in the cache disk config
block where it has no effect. The right setting is the user
profile setting `enable_filesystem_cache_on_write_operations`
(see existing test_filesystem_cache/users.d/cache_on_write_operations.xml).
Moved to a users.d/ file.
- `SELECT count()` was used to "populate the cache" but reads MergeTree
part counts without touching column data, so the cache was never
actually accessed. Replaced with `SELECT sum(length(blob))` which
forces a full column scan.
Also tightened the cache to 100 KiB / 16 elements / 10 KiB segments so
even a modest workload (~800 KiB per INSERT) overflows immediately. The
prior 1 MiB cache was large enough to absorb the test workload without
eviction churn.
- FileCacheMetrics.{h,cpp} folded into anonymous namespace at the top
of EvictionCandidates.cpp - the registrations and the queueLabel
helper live with their only consumer.
- Unit test rewritten with a single run_workload lambda + inline
sum_dim / sum_hist closures. Same three logical phases (flag off /
aggregate on / per-client on), ~50% less code.
- Integration test stripped of label-shape assertions; keeps the core
counter/histogram-delta checks.
Net diff vs origin/master drops from 632 to ~250 lines.
… count system.histogram_metrics exposes Prometheus-cumulative bucket rows keyed by labels['le']; each label-set has buckets.size()+1 rows. Summing value across all rows gives a quadratic-in-bucket result, not the observation count. The +Inf row carries the total per label-set; filtering on labels['le']='+Inf' and summing across label-sets yields the family-total observation count, which matches the eviction counter.
SLRUFileCachePriority::tryIncreasePriority constructs its own internal EvictionCandidates for promotion-induced downgrade. Before this change that EvictionCandidates had no cache pointer, so evictions caused by protected->probationary churn would not appear in filesystem_cache_* counters - hiding pressure in common SLRU workloads. Fix: IFileCachePriority gains a one-shot back-reference to the owning FileCache (setOwningCache / getOwningCache), set by FileCache at the end of its constructor body. Mirrors the existing setCacheUsageStatGuard pattern. SLRU and Split override setOwningCache to propagate the pointer to their nested priority queues; LRU stores it via the base implementation. SLRU::tryIncreasePriority then constructs its downgrade EvictionCandidates with getOwningCache(), so the same emit-when-flag-on logic in EvictionCandidates::evict applies. Adds gtest ExposeEvictionMetrics_SLRUPromotionInducedEviction that fills an SLRU cache, hits each segment to force promotions, and asserts the eviction counter advances on the downgrade-induced eviction path.
Counts probationary -> protected promotions per SLRU cache. Gated by the same FileCacheSettings::expose_eviction_metrics flag as the eviction metrics since promotion volume is part of the same observability story: - promotions/sec : hot-set churn rate - evictions/sec : capacity pressure - their ratio : eviction efficiency of the SLRU split Emitted only on the probationary -> protected transition (case where tryIncreasePriority does real queue movement). LRU caches never emit since they have no promotion concept. Extends the existing SLRU promotion-induced-eviction gtest to also assert this counter advances.
…advances The test config uses SLRU and reads the table multiple times after each INSERT, which promotes probationary segments to protected. Asserting the promotion counter advances closes the loop end-to-end for the new metric.
Mirrors the `_by_client` tier of the eviction metrics: gated by the
same `expose_eviction_metrics_per_client` flag, labelled additionally
by user id. Closes the symmetry gap between eviction and promotion
visibility - per-client attribution applies to both halves of the
SLRU observability story.
Tests:
- The SLRU promotion gtest now enables per_client and asserts the
new family advances alongside the aggregate one.
- Integration test asserts the same against system.dimensional_metrics.
Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
Add cache_name to the per-user filesystem cache usage metric labels so the gauges match the per-cache Prometheus model used by filesystem cache eviction metrics. Related: ClickHouse#105020
Verify the opt-in usage gauges through a real cached disk configuration and system.dimensional_metrics. Also update DESCRIBE FILESYSTEM CACHE reference output for the new setting. Related: ClickHouse#105020
Use prometheus_cache_usage_metrics_per_user for the opt-in setting name to make the per-user cache usage metric scope explicit. Related: ClickHouse#105020
Rename the per-user filesystem cache usage metrics setting to expose_prometheus_cache_usage_metrics_per_user for consistency with other Prometheus exposure settings. Related: ClickHouse#105020
Add system.dimensional_metrics entries for the opt-in filesystem cache usage gauges. Related: ClickHouse#105020
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds opt-in Prometheus metrics for filesystem-cache evictions (counters and histograms, plus per-user variants), all disabled by default and only updated on cache eviction. It does not touch the query-execution path. The three flagged ClickBench improvements (Q4 -10.7%, Q15 -17.1%, Q28 -6.1%) cannot plausibly come from this change, so all three are downgraded to not-sure as run-to-run variance. No regressions were observed. clickbenchFlagged queries (3 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
DatabaseCatalog::addUUIDMapping(uuid, db, table) threw a LOGICAL_ERROR when
the UUID was already mapped to a live table. During ATTACH DATABASE (and
server startup) tables are loaded via attachTable, which calls addUUIDMapping
directly with a real (database, table) pair and bypasses the empty "lock"
reservation. If two table metadata files in the loaded database declare the
same explicit UUID, the second table reaches that throw and the LOGICAL_ERROR
aborts the whole server in debug/sanitizer builds.
Two table .sql files sharing one UUID is user-controlled, external on-disk
state: it can be produced by manual edits, or by a leftover _tmp_replace_*
table from CREATE OR REPLACE TABLE ... UUID '...' that carries the same
explicit UUID as the live target table. That is a user error, not an internal
invariant violation, and the sibling branch already reports the same condition
as a non-fatal TABLE_ALREADY_EXISTS ("UUID collision, most likely because some
not random UUIDs were manually specified"). The runtime ATTACH TABLE path even
hits that friendly error today; only the load path aborts.
Report the collision as TABLE_ALREADY_EXISTS instead of LOGICAL_ERROR. The
conflicting table fails to load with a clear message, the rest of the database
attaches, and the server stays up. This covers both the ATTACH DATABASE async
load path and the server startup path.
Found by BuzzHouse (amd_tsan) on PR ClickHouse#105020 (STID 3178-4166); the family also
hit PRs ClickHouse#100047, ClickHouse#106268, ClickHouse#100703 (STID 3178-4504). New test
04340_attach_database_duplicate_uuid_no_crash reproduces the crash
deterministically and verifies the server survives.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Resolved conflicts in `FileCache` background eviction metrics. PR: ClickHouse#105020
Record `FilesystemCacheBackgroundEvicted*` profile events before optional Prometheus metric updates and assert `cache_name` / `user_id` label shape in the filesystem cache eviction metrics integration test.
…rics Pull upstream `master` through `e531152b092`, which reverts the vector-search rescoring change causing deterministic `02354_vector_search_rescoring` failures.
ef4b03b to
dcf78e8
Compare
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 393/400 (98.25%) | Lost baseline coverage: none · Uncovered code |
The eviction-metric settings are documented as runtime-reloadable via `SYSTEM RELOAD CONFIG`, but existing tests only build caches with final flag values. Add `EvictionMetricsRuntimeToggle`, which flips `expose_prometheus_eviction_metrics` through `applySettingsIfPossible` on a live cache and checks the full cycle: disabled (no delta), enabled (metric advances), disabled again (no further delta). This guards against a regression where the reload path stops propagating the flag to the atomic read on the eviction path. Related: ClickHouse#105020 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Resolved conflicts in `FileCache` background eviction metrics. PR: ClickHouse#105020
…-eviction-metrics Add filesystem cache eviction metrics
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Changelog entry
Added opt-in Prometheus metrics for filesystem cache eviction activity (
filesystem_cache_evictions_total,filesystem_cache_evicted_bytes_total,filesystem_cache_evicted_segment_hits,filesystem_cache_evicted_segment_size_bytes, and their per-user variants labeled withuser_id), exposed per cache viasystem.dimensional_metrics,system.histogram_metrics, and the Prometheus endpoint. They are controlled by the cache disk-config settingsexpose_prometheus_eviction_metricsandexpose_prometheus_eviction_metrics_per_user(both off by default), which can be toggled at runtime viaSYSTEM RELOAD CONFIG.Description
Adds metrics that describe
FileCacheeviction activity, registered via the existingDimensionalMetrics/HistogramMetricsinfrastructure and exposed through the Prometheus endpoint. All metrics are disabled by default; enable per-cache viaexpose_prometheus_eviction_metrics.filesystem_cache_evictions_totalcache_namefilesystem_cache_evicted_bytes_totalcache_namefilesystem_cache_evicted_segment_hitscache_namefilesystem_cache_evicted_segment_size_bytescache_name_by_uservariant of each family)user_id, need additional opt-inMotivation. Operators need to monitor eviction pressure beyond the existing process-wide
ProfileEventscounters. The new metrics are per-cache. Operators can answer "is the working set fitting in the cache?" directly from PromQL.Mechanism.
IFileCachePrioritygains an optionalOnEvictCallbackinstalled byFileCacheat construction when the feature is enabled. The callback is invoked byEvictionCandidates::evictfor each successfully-evicted segment. All metric family registrations live in an anonymous namespace inFileCache.cpp.Escapes the labels before writing them to prometheus.
Adds the counter type in addition to gauge for prometheus metrics.
Cardinality. Aggregate families are bounded by
cache_name(< 10 series per process)._by_usercardinality grows with the number of distinct evictinguser_ids and is therefore off by default.Testing.
FileCacheTest.ExposeEvictionMetrics— three phases: flag off → no delta; aggregate on → counters and histograms advance lockstep; per-user on →_by_uservariants populate.test_filesystem_cache_eviction_metrics/— full path through a realclickhouse-serverwith a small SLRU cache, asserting all families viasystem.dimensional_metricsandsystem.histogram_metrics.Version info
26.7.1.289(included in26.7and later)