Repository navigation
Add per-user filesystem cache disk usage metrics - #107865
sacheendra wants to merge 45 commits into
Conversation
Expose opt-in Prometheus gauges for filesystem cache size and element count by user id. installs a usage-change callback when is enabled, while emits usage deltas and composite priorities forward the callback to their inner queues. Related: ClickHouse#105020
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
|
Workflow [PR], commit [2556807] Summary: ❌
AI ReviewSummaryThis PR adds opt-in Prometheus and PR Metadata
Findings
Final Verdict
LLVM Coverage ReportMeasured on commit 2556807.
Changed lines: Changed C/C++ lines covered: 529/561 (94.30%) · Uncovered code |
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
|
There are failures like |
…age-metrics # Conflicts: # tests/queries/0_stateless/02344_describe_cache.reference
… now weak Master commit c202b9c ("FileCache: stop invalidated priority entries from pinning KeyMetadata") changed `IFileCachePriority::Entry::key_metadata` from a strong `KeyMetadataPtr` to a weak `KeyMetadataWeakPtr`. This PR was written against the strong-pointer version and accessed `entry->key_metadata->origin.user_id` directly, which no longer compiles because `std::weak_ptr` has no `operator->`. Add a `notifyUsageChange` overload that takes the weak `KeyMetadataWeakPtr` and resolves the user id by locking it. The lock is taken only when the usage-change callback is installed, so the path stays zero-overhead when the feature is disabled (the default). The overload never throws, so it remains safe to call from `LRUFileCachePriority::LRUIterator::invalidateImpl`, which is `noexcept`: if the metadata has already expired the update is skipped rather than throwing. Entries with non-zero size are kept alive by the metadata bucket, so the lock is expected to succeed at every call site (all guarded by a non-zero size). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…age-metrics # Conflicts: # docs/en/operations/system-tables/dimensional_metrics.md # docs/en/operations/system-tables/filesystem_cache_settings.md # src/Interpreters/FileCache/FileCache.cpp # src/Interpreters/FileCache/FileCacheSettings.cpp # src/Interpreters/FileCache/IFileCachePriority.h # tests/queries/0_stateless/02344_describe_cache.reference
The AI review (Request changes) flagged that the filesystem_cache_size_bytes and filesystem_cache_elements usage gauges use FileCache::name, which is only the first name used to construct a shared cache instance. FileCacheFactory::getOrCreate reuses one FileCacheData for multiple cache names that share the same path and settings, so an alias name can show non-zero current_size in system.filesystem_cache_settings while system.dimensional_metrics has no matching series. This is intentional: the metric reports usage once, under the primary cache name of the shared instance, to avoid double-counting a single physical cache across its alias names. Document this contract in system-tables/dimensional_metrics.md and at the callback installation site in FileCache.cpp, and add a focused integration test with two cache disks that share the same path/settings: it asserts both alias names report the same current_size, and that the usage total across the alias names equals the single physical usage (not doubled), with exactly one alias name carrying the series. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Master's origin-sharing change (`CacheMetadata::getOrCreateSharedOrigin`) made `KeyMetadata::origin` a `std::shared_ptr<const FileCacheOriginInfo>` and changed the `KeyMetadata` constructor to take an `OriginInfoPtr`. Adapt the per-user usage callback to dereference `origin->user_id`, wrap the origins passed by the `UsageMetricsByUser` gtest in `std::make_shared<const FileCacheOriginInfo>`, and drop a duplicate `DimensionalMetrics.h` include that the merge left in the test. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Merged latest `master` and resolved the conflicts from the eviction-metrics feature (`filesystem_cache_evictions_total` etc.) that landed in the meantime — the two features now coexist (both `setOnEvictCallback` and `setOnUsageChangeCallback` are forwarded through the split/SLRU priorities). The merge also required adapting to master's `KeyMetadata` origin-sharing change (`KeyMetadata::origin` is now a `shared_ptr`, constructed via `getOrCreateSharedOrigin`). Verified locally: `unit_tests_dbms` links and all `FileCacheTest.*` (both usage and eviction metrics) pass. Regarding the AI review's "Request changes" on the `cache_name` label for shared cache aliases: this behavior is intentional and is now documented. When several cache configurations share the same `path`, `FileCacheFactory::getOrCreate` aliases a single `FileCache` instance, so usage is reported once — under the primary (first-created) cache name — to avoid double-counting one physical cache across its alias names (emitting under every alias would make `sum(filesystem_cache_size_bytes)` overcount). I documented this contract in `system-tables/dimensional_metrics.md` and at the callback installation site, and added an integration test (`test_shared_cache_alias_usage_metrics`) with two cache disks sharing the same path/settings: it asserts both alias names report the same `current_size`, and that the usage total across the alias names equals the single physical usage (not doubled), with exactly one alias name carrying the series. |
|
I discussed with @kssenii and we will try an asynchronous approach. In the asynchronous approach, the updates are just counters. I'll prototype and see how it looks. |
…age-metrics Reconcile the per-user filesystem cache usage metrics with master's FileCache refactoring: - `IFileCachePriority` was reordered and its cleanup task moved into `FileCache` (`setCleanupSettings` -> `FileCache`'s own maintenance task driven by `setInvalidateNotifier`). Re-applied the PR's `OnUsageChangeCallback` type, `setOnUsageChangeCallback`/ `getOnUsageChangeCallback`, the two `notifyUsageChange` overloads and the `on_usage_change_callback` member on top of master's structure, and dropped the now-removed `main_priority->setCleanupSettings(...)` call. - `LRUFileCachePriority::decrementSize` now decrements the element count when an entry becomes empty (`became_empty ? 1 : 0`); mirrored that in the `notifyUsageChange` elements delta (`became_empty ? -1 : 0`) so the `filesystem_cache_elements` gauge stays consistent with `state`. - `FileCacheSettings.cpp` / `FileCache.cpp`: kept both master's new `idle_client_*` settings and the PR's `expose_prometheus_cache_usage_metrics_per_user`, grouping the three `expose_prometheus_*` settings together. - `IFileCachePriority.cpp`: kept the `Metadata.h` include (needed by `notifyUsageChange(KeyMetadataWeakPtr, ...)`), dropped the removed `BackgroundSchedulePool.h` include. - `02344_describe_cache.reference`: rebuilt the row with all 40 settings plus the 3 runtime columns (44 fields).
|
Re-merged the latest `master` (the branch had gone conflicting again) and reconciled with master's
Verified locally: |
|
Dear @kssenii, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 341/380 (89.74%) · Uncovered code |
…age-metrics # Conflicts: # docs/en/operations/system-tables/dimensional_metrics.md # docs/en/operations/system-tables/filesystem_cache_settings.md # tests/queries/0_stateless/02344_describe_cache.reference
SLRU queue moves charge the moved segment's per-user usage counters for the new queue entry before discharging the old one; both steps happen under the cache state lock. `getUsageStatPerClient` sampled the atomic counters without that lock, so a concurrent sample (e.g. from `ServerAsynchronousMetrics` or `SYSTEM RELOAD ASYNCHRONOUS METRICS`) could observe the moved segment twice and report roughly 2x `filesystem_cache_size_bytes` / `filesystem_cache_elements` for the user. Take the state lock in `FileCache::getUsageStatPerClient` and require a `CacheStateGuard::Lock` witness in `IFileCachePriority::getUsageStatPerClient`. Add a regression test that samples concurrently with repeated SLRU handoffs; it fails when the sampler does not synchronize with the state lock. Co-Authored-By: Claude Fable 5 <[email protected]>
…age-metrics # Conflicts: # tests/queries/0_stateless/02344_describe_cache.reference
`expose_prometheus_cache_usage_metrics_per_user` was read only in the `FileCache` constructor, so `SYSTEM RELOAD CONFIG` was a silent no-op for it: enabling never installed a `FileCacheUsageTracker`, disabling never drained the gauges, and `system.filesystem_cache_settings` was left reporting a value the cache did not run with. The setting cannot be made truly reloadable: usage counters are attached to a priority queue entry when the entry is created, so enabling the feature on a live cache would never account for the entries which are already cached, and the gauges would under-report the real usage until every pre-existing entry happens to be evicted. A silently wrong gauge is worse than an absent one, so `applySettingsIfPossible` now refuses the change explicitly with a warning in the log and keeps `actual_settings` at the effective value, which is the same shape as the existing `allow_dynamic_cache_resize` refusal for `max_size`. Documented the restart requirement in the setting description and in `docs/reference/system-tables/dimensional_metrics.mdx`, and added the gtest `FileCacheTest.UsageMetricsSettingIsStartupOnly`, the counterpart of `FileCacheTest.EvictionMetricsRuntimeToggle`: it pins that a reload in either direction neither changes the accounting behaviour nor the reported setting value, so a future half-wiring that updates `actual_settings` without installing the tracker is caught.
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107865&sha=6244c58bc8cea1cd6a344b7155b6b19b7cc2a116&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. The only red check on this PR is This is unrelated to this PR, which only touches
There is no tracking issue for this exact signature yet. The assertion family itself has a long tail of auto-filed reports (#100574, #101323, #101329, #98700, #97335, #95839, #100446, all closed) and #107951 tracks the analyzer-bypass variants for the AST-fuzzer path, but the |
|
Investigated. The failure is not caused by this PR, and a fix is already in progress: #113534, which you opened yourself earlier today. I verified it fixes exactly this abort, so nothing further is owed here. What fails. The SELECT 'dict LEFT ANY, no settings', count(), sum(d.a)
FROM t3 LEFT ANY JOIN dict AS d ON (t3.key = d.key) AND (t3.a * 10 < d.a);
Verified, both directions. I transplanted #113534's two source hunks onto master
The Two corrections to the framing, both measured. Keying a census on the stack frame rather than the STID ( The template arguments in the stack are Also worth noting: 24 of the rows are from 2026-08-04 and 53 from 2026-08-05, against 1 to 3 per day before that. On a tracking issue. There is no GitHub issue for this signature, and searching On my #107957. It targets the same abort at the same line, but at the wrong layer: it reconciles the two nullability representations inside One thing there may be worth salvaging: your |
The `system.dimensional_metrics` page claimed the table is "always up to date", which stopped being true once `filesystem_cache_size_bytes` and `filesystem_cache_elements` were sampled by the asynchronous metrics task. Call the two sampled gauges out as the exception, in the page description and in the frontmatter. Also spell out what the `user_id` label is. It is the filesystem cache client (`Context::getFilesystemCacheUser`, falling back to the server UUID), not the SQL user which ran a query - which is intentional, but was not stated anywhere. Documented in the metric descriptions, in the `expose_prometheus_cache_usage_metrics_per_user` docstring and in a note on the page, and the integration test now pins the label to the exact expected value and to exactly one series instead of merely asserting that it is not empty, so a change of the label's meaning fails the test.
Build profile diff (arm_release)Comparing commit See the job log for details. |
|
Dear @kssenii, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
…age-metrics # Conflicts: # src/Interpreters/tests/gtest_filecache.cpp
…age-metrics Reconciled with master's `FileCache` priority refactor: - `LRUFileCachePriority::entryAdd`/`entrySub` now wrap `state->add`/`sub` and mirror the delta into `CacheUsage`. The per-user `addTrackedUsage`/ `subTrackedUsage` hooks are kept next to them at all five accounting sites. - Master's new `IFileCachePriority::getPriorityGuard` and `SLRUFileCachePriority::getPriorityGuardForTests` are kept alongside the per-user usage tracker API. - Master's new `UsageStat::last_access_time` field moved into `FileCacheUsageStat`, which this branch uses as `UsageStat`; the accessor keeps this branch's `CacheStateGuard::Lock` witness. - `LRUFileCachePriority::addForRestore` is new on master; it now creates its entry through `createEntry` with the client's usage counters, so entries restored from the filesystem on startup are accounted like `SLRU` ones. - `tryIncreasePriority` lost its `CachePriorityGuard` argument; the gtest call site was updated.
Compile fixes that only exist after the merge: - `IFileCachePriority::isOvercommitEviction` is gone. The tracker is now installed from the `cache_policy` setting, next to `client_tracking_possible`, which is how master decides whether the policy keeps per-client usage itself. - `FileCacheUsageStat` gained master's `last_access_time`, so the aggregate initializer in `FileCacheUsageTracker::snapshotAndPrune` names every field. - `LRUFileCachePriority::add` no longer takes the queue write lock from the caller, and `tryIncreasePriority` no longer takes a `CachePriorityGuard`; the gtests were updated, and the `SLRU` test now uses master's `getPriorityGuardForTests` and takes the state lock before the queue lock, per the lock order in `Guards.h`. Address review: state what a concurrent sample can and cannot show The review asks for all usage-counter mutations to be serialized with the state lock. That cannot deliver the property it is meant to deliver: per the lock order in `Guards.h`, cache decrements are lock-free by design, so even `getSize(Lock)` is exact only with respect to concurrent growth. A sampler holding the state lock therefore cannot be excluded from a removal in flight, no matter which lock the per-client counters are mutated under. What is achievable, and what the code already does, is a one-directional bound: every removal site (`remove`, `invalidateImpl`, `decrementSize`) discharges the per-client counters *before* the queue state, and every growth site holds the state lock, so a sample can lag a removal in flight but can never report more usage than the cache holds. That was implicit; it is now: - stated at `addTrackedUsage` / `subTrackedUsage` as a requirement on callers, - stated at `FileCache::getUsageStatPerClient`, in both gauge descriptions and in `docs/reference/system-tables/dimensional_metrics.mdx`, - pinned by the new `FileCacheTest.UsageSnapshotNeverExceedsCacheSize`, where a sampler runs against 500 add/shrink/remove cycles and asserts the per-client sum never exceeds `getSize` or `getElementsCount`. Reordering any removal site to discharge the queue state first fails it.
| /// Approximate wall-clock time of the client's last cache access (converted from the | ||
| /// steady-clock timestamp of the idle-client TTL). Empty if there was no access yet. | ||
| std::optional<time_t> last_access_time; | ||
| }; |
There was a problem hiding this comment.
As discussed, let's move the implementation to private repo since it only makes sense there (and can properly be tested there) and then sync to public public-facing parts.
There was a problem hiding this comment.
🕵 Noted. This pass only kept the branch mechanically current: merged master (one conflict in FileCache.cpp from the isOvercommitPolicy / write_cache_per_user_directory derivation refactor), fixed the Unit tests (tsan) red (a flaky gtest, see below), and addressed the bot thread on the table description. Whether the implementation moves to the private repository and only the public-facing parts stay here is a decision for @sacheendra and you; I have not changed the scope of the PR either way.
…age-metrics # Conflicts: # src/Interpreters/FileCache/FileCache.cpp
…with the asynchronously sampled gauges The page `dimensional_metrics.mdx` already says the table is not always up to date because `filesystem_cache_size_bytes` and `filesystem_cache_elements` are sampled by the asynchronous metrics task, but the source-registration string in `attachSystemTables.cpp` still advertised the old "always up to date" contract. Make both descriptions say the same thing. Co-Authored-By: Claude Fable 5.1 <[email protected]>
`UsageSnapshotNeverExceedsCacheSize`: the sampler compared a per-client usage snapshot against the queue size, but read them in the wrong order. Every removal path discharges the per-client counters *before* the queue state, so a sample that reads the counters first and the size second can straddle a lock-free removal and see a stale (larger) counter next to the already shrunk size, failing about one run in five. Read the queue state first and the counters second; this order is the one the writer ordering actually guarantees, and it still catches a reversed writer order. `UsageMetricsSettingIsStartupOnly`: the two caches live outside the fixture-managed `cache_base_path*` directories and load metadata synchronously, so a second run found the segments of the previous run already downloaded and `download` failed. Remove the directories before constructing each cache. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 Brought the branch up to date with
Locally: all touched objects and @kssenii's request to move the implementation to the private repository and keep only public-facing parts here is left to the author and reviewer; this pass did not change the PR's scope. |
| max_bytes += cache_data->cache->getMaxCacheSize(); | ||
| total_files += cache_data->cache->getFileSegmentsNum(); | ||
| const auto & cache = cache_data->cache; | ||
| total_bytes += cache->getUsedCacheSize(); |
There was a problem hiding this comment.
The new one-way skew guarantee still does not hold on the actual export path. Here updateImpl reads FilesystemCacheBytes / FilesystemCacheFiles via getUsedCacheSize and getFileSegmentsNum before it takes the cache state lock inside getUsageStatPerClient().
A concrete trace is:
- This loop reads
total_bytes += cache->getUsedCacheSize()while the cache is still empty. - Another thread adds one 10-byte segment; growth is serialized by
CacheStateGuard, so the new entry is fully visible once the lock is released. - This loop then calls
cache->getUsageStatPerClient(), takes the state lock, and snapshotsusage.size = 10.
That sample now publishes FilesystemCacheBytes = 0 but filesystem_cache_size_bytes{...} = 10 (and the same skew is possible for elements), which contradicts both the new documentation and the UsageSnapshotNeverExceedsCacheSize reasoning. Please either snapshot totals and per-user usage under one CacheStateGuard::Lock, or at least take the per-user snapshot first and only then read the unlocked totals so the skew stays one-directional.
Related: #105020
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added opt-in Prometheus gauges for current filesystem cache usage (
filesystem_cache_size_bytesandfilesystem_cache_elements), labeled bycache_nameanduser_id. The gauges are exposed throughsystem.dimensional_metricsand the Prometheus endpoint and controlled by theexpose_prometheus_cache_usage_metrics_per_usercache setting, which is disabled by default.Description
Adds two gauges exposed through
system.dimensional_metricsand the Prometheus endpoint:filesystem_cache_size_bytescache_name,user_idfilesystem_cache_elementscache_name,user_idMotivation. Operators can identify which users currently occupy filesystem cache space, measured both in bytes and in file segments, for each cache.
Mechanism. Each enabled cache owns a
FileCacheUsageTrackercontaining shared per-user atomic counters. Main cache-priority entries retain the corresponding counters and update them together with the existing cache size and element accounting.ServerAsynchronousMetricsperiodically obtains a per-user snapshot throughgetUsageStatPerClientand updates the dimensional gauges. This keepsDimensionalMetricsupdates out of cache mutation paths. Composite LRU, SLRU, and split-cache priorities share the same tracker, including during SLRU queue transitions.Counters use shared ownership so inactive users can be reclaimed safely. When a user no longer has cache entries and its counters are zero, the next snapshot removes it from the tracker. Stale dimensional metric label combinations are also removed.
Sampling. The metrics reflect the most recent asynchronous metrics update.
Cardinality. In-process cardinality is bounded by users currently retained by each cache, plus labels awaiting the next asynchronous metrics update. Stale
(cache_name, user_id)label combinations are removed. The feature remains disabled by default because enabling per-user metrics can still create significant Prometheus time-series cardinality.Documentation entry:
Workflow [PR]
Sync PR [sync-upstream/pr/107865]