Skip to content

Add filesystem cache eviction metrics - #105020

Merged
kssenii merged 98 commits into
ClickHouse:masterfrom
sacheendra:filesystem-cache-eviction-metrics
Jun 30, 2026
Merged

kssenii merged 98 commits into
ClickHouse:masterfrom
sacheendra:filesystem-cache-eviction-metrics

Conversation

@sacheendra

@sacheendra sacheendra commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

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 with user_id), exposed per cache via system.dimensional_metrics, system.histogram_metrics, and the Prometheus endpoint. They are controlled by the cache disk-config settings expose_prometheus_eviction_metrics and expose_prometheus_eviction_metrics_per_user (both off by default), which can be toggled at runtime via SYSTEM RELOAD CONFIG.


Description

Adds metrics that describe FileCache eviction activity, registered via the existing DimensionalMetrics / HistogramMetrics infrastructure and exposed through the Prometheus endpoint. All metrics are disabled by default; enable per-cache via expose_prometheus_eviction_metrics.

Name Type Labels
filesystem_cache_evictions_total counter cache_name
filesystem_cache_evicted_bytes_total counter cache_name
filesystem_cache_evicted_segment_hits histogram cache_name
filesystem_cache_evicted_segment_size_bytes histogram cache_name
(_by_user variant of each family) + user_id, need additional opt-in

Motivation. Operators need to monitor eviction pressure beyond the existing process-wide ProfileEvents counters. The new metrics are per-cache. Operators can answer "is the working set fitting in the cache?" directly from PromQL.

Mechanism. IFileCachePriority gains an optional OnEvictCallback installed by FileCache at construction when the feature is enabled. The callback is invoked by EvictionCandidates::evict for each successfully-evicted segment. All metric family registrations live in an anonymous namespace in FileCache.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_user cardinality grows with the number of distinct evicting user_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_user variants populate.
  • Integration test test_filesystem_cache_eviction_metrics/ — full path through a real clickhouse-server with a small SLRU cache, asserting all families via system.dimensional_metrics and system.histogram_metrics.

Version info

  • Merged into: 26.7.1.289 (included in 26.7 and later)

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.
@CLAassistant

CLAassistant commented May 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dcf78e8]

Summary: ✅


AI Review

Summary

This 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 system.dimensional_metrics still cannot preserve counter type, and the _by_user label is still the cache-origin user in the public read/write paths rather than the SQL user.

Findings

⚠️ Majors

  • [src/Storages/System/StorageSystemDimensionalMetrics.cpp:14] [dismissed by author -- https://github.com/Add filesystem cache eviction metrics #105020#discussion_r3428035895] The PR registers filesystem_cache_*_total as counters for the direct Prometheus endpoint, but system.dimensional_metrics still exposes no type column and the documented FORMAT Prometheus query hardcodes 'gauge' AS type. Users following the documented system-table export path will publish these _total counters as gauges. Suggested fix: either carry MetricType through system.dimensional_metrics and update the docs/test, or scope the PR docs/changelog to say counter type is preserved only by the direct Prometheus endpoint.
  • [src/Interpreters/FileCache/FileCache.cpp:2395] [dismissed by author -- https://github.com/Add filesystem cache eviction metrics #105020#discussion_r3380961783] The advertised _by_user families are populated from FileCacheOriginInfo::user_id, but public cache read/write paths still create that origin from FileCache::getCommonOrigin, i.e. the configured filesystem-cache user or server UUID, not the SQL/session user that caused the eviction. Normal public cache disks therefore collapse activity into one user_id series while the PR presents it as per-user attribution. Suggested fix: thread the actual query user into the cache origin for public paths, or rename/scope the setting/docs to cache-origin attribution.
Tests
  • ⚠️ Add a server-level test for the chosen system.dimensional_metrics contract: either FORMAT Prometheus emits counter for the new _total families, or the docs explicitly exclude query-based export from counter-type preservation.
  • ⚠️ Add an integration test with two SQL users if _by_user is intended to mean ClickHouse users; otherwise update docs and tests to assert the label is the cache-origin user.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fix or explicitly narrow the system.dimensional_metrics counter-type contract, and fix or explicitly rename/scope the _by_user attribution contract.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 15, 2026
…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.
@sacheendra sacheendra self-assigned this May 15, 2026
…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.
@sacheendra
sacheendra requested review from kssenii and primeroz May 15, 2026 12:26
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.
Comment thread src/Interpreters/FileCache/FileCache.h Resolved
sacheendra added a commit to sacheendra/ClickHouse that referenced this pull request Jun 18, 2026
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
sacheendra added a commit to sacheendra/ClickHouse that referenced this pull request Jun 18, 2026
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
sacheendra added a commit to sacheendra/ClickHouse that referenced this pull request Jun 18, 2026
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
sacheendra added a commit to sacheendra/ClickHouse that referenced this pull request Jun 18, 2026
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
sacheendra added a commit to sacheendra/ClickHouse that referenced this pull request Jun 18, 2026
Add system.dimensional_metrics entries for the opt-in filesystem cache usage gauges.

Related: ClickHouse#105020
@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

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.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 262 234 -10.7% <0.0001 cache: PR only adds filesystem-cache eviction metrics (off by default); Q4 execution path untouched — variance
⚠️ 15 not_sure 245 203 -17.1% <0.0001 cache: Eviction-metric plumbing can't speed a SELECT; -17% improvement is off-path run-to-run variance
⚠️ 28 not_sure 6671 6264 -6.1% <0.0001 cache: Metrics-only change off the query hot path; -6% on a 6s query is variance, not a real PR effect

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
  • StressHouse run: 8f2059b3-df05-4b5b-afca-8038eb0768e6
  • MIRAI run: 36839461-fc6f-4caa-8875-3fe5954eae80
  • PR check IDs:
    • clickbench_487001_1782820259
    • clickbench_487007_1782820259
    • clickbench_487018_1782820259
    • tpch_adapted_1_official_487025_1782820259
    • tpch_adapted_1_official_487039_1782820259
    • tpch_adapted_1_official_487050_1782820259

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 19, 2026
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.
@sacheendra
sacheendra force-pushed the filesystem-cache-eviction-metrics branch from ef4b03b to dcf78e8 Compare June 29, 2026 16:46
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.70% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 393/400 (98.25%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@kssenii
kssenii added this pull request to the merge queue Jun 30, 2026
Merged via the queue into ClickHouse:master with commit 75154b3 Jun 30, 2026
174 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 30, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Resolved conflicts in `FileCache` background eviction metrics.

PR: ClickHouse#105020
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-eviction-metrics

Add filesystem cache eviction metrics
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 pr-improvement Pull request with some product improvements 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.

5 participants