Skip to content

Add per-user filesystem cache disk usage metrics - #107865

Closed
sacheendra wants to merge 45 commits into
ClickHouse:masterfrom
sacheendra:filesystem-cache-usage-metrics
Closed

sacheendra wants to merge 45 commits into
ClickHouse:masterfrom
sacheendra:filesystem-cache-usage-metrics

Conversation

@sacheendra

@sacheendra sacheendra commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Related: #105020

Changelog category (leave one):

  • Improvement

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_bytes and filesystem_cache_elements), labeled by cache_name and user_id. The gauges are exposed through system.dimensional_metrics and the Prometheus endpoint and controlled by the expose_prometheus_cache_usage_metrics_per_user cache setting, which is disabled by default.


Description

Adds two gauges exposed through system.dimensional_metrics and the Prometheus endpoint:

Name Labels
filesystem_cache_size_bytes cache_name, user_id
filesystem_cache_elements cache_name, user_id

Motivation. 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 FileCacheUsageTracker containing 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.

ServerAsynchronousMetrics periodically obtains a per-user snapshot through getUsageStatPerClient and updates the dimensional gauges. This keeps DimensionalMetrics updates 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:

  • Documentation is updated.

Workflow [PR]
Sync PR [sync-upstream/pr/107865]

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
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2556807]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR adds opt-in Prometheus and system.dimensional_metrics gauges for filesystem-cache usage, backed by per-entry accounting in FileCache and periodic export in ServerAsynchronousMetrics. The accounting changes are close, but the exported metrics still do not uphold the new one-way skew contract, so I cannot approve the PR in its current form.

PR Metadata
  • Improvement is the correct category, and a changelog entry is required and present.
  • The changelog entry is still misleading after the code/docs narrowed user_id to a filesystem cache client id rather than the SQL user. Suggested replacement: Added opt-in Prometheus gauges for current filesystem cache usage (\filesystem_cache_size_bytes` and `filesystem_cache_elements`), labeled by `cache_name` and filesystem cache client id (`user_id`). The gauges are exposed through `system.dimensional_metrics` and the Prometheus endpoint and controlled by the `expose_prometheus_cache_usage_metrics_per_user` cache setting, which is disabled by default.`
Findings

⚠️ Majors

  • [src/Interpreters/ServerAsynchronousMetrics.cpp:234-241] The exported per-user gauges can still exceed the corresponding total cache metrics in the same asynchronous sample. updateImpl reads getUsedCacheSize / getFileSegmentsNum before it takes the CacheStateGuard inside getUsageStatPerClient, so a concurrent cache growth can land between those two reads and make filesystem_cache_size_bytes / filesystem_cache_elements larger than FilesystemCacheBytes / FilesystemCacheFiles. The new documentation and UsageSnapshotNeverExceedsCacheSize only hold when both sides are sampled under the same lock, which this path does not do.
    Suggested fix: take a single locked snapshot for totals and per-user usage, or sample per-user usage first and then read the unlocked totals so the skew remains one-directional.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    1. Make the ServerAsynchronousMetrics sampling order uphold the documented one-way skew invariant, or relax the docs/tests to match the current two-way skew.
    2. Tighten the changelog entry wording so user_id is not presented as a SQL user identifier.

LLVM Coverage Report

Measured on commit 2556807.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 529/561 (94.30%) · Uncovered code

Full report · Diff report

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
@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 18, 2026
@sacheendra sacheendra changed the title Add per-user filesystem cache usage metrics Add per-user filesystem cache disk usage metrics Jun 18, 2026
@sacheendra sacheendra added the can be tested Allows running workflows for external contributors label Jun 18, 2026
Add system.dimensional_metrics entries for the opt-in filesystem cache usage gauges.

Related: ClickHouse#105020
@sacheendra
sacheendra marked this pull request as ready for review June 18, 2026 16:44
@sacheendra
sacheendra requested a review from kssenii June 18, 2026 16:44
@kssenii kssenii self-assigned this Jun 18, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

There are failures like 04033_tpc_ds_q04 which can't be ignored. Ask @rienath for assistance.

@rienath

rienath commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

It's caused by #107461 and fixed by #107968. We can't merge it until we close #107941. To close it we need diagnostic from #105905

alexey-milovidov and others added 2 commits June 29, 2026 14:00
…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]>
alexey-milovidov and others added 3 commits July 7, 2026 03:41
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

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.

@sacheendra

Copy link
Copy Markdown
Contributor Author

I discussed with @kssenii and we will try an asynchronous approach.
In this version, the metrics are synchronously updated in the insertion/eviction path.

In the asynchronous approach, the updates are just counters.
The prometheus metrics are periodically updated from the 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).
@alexey-milovidov

Copy link
Copy Markdown
Member

Re-merged the latest `master` (the branch had gone conflicting again) and reconciled with master's FileCache priority refactoring:

  • The invalidated-entries cleanup task moved out of IFileCachePriority into FileCache itself (setCleanupSettings → FileCache's own maintenance task driven by setInvalidateNotifier). Re-applied the usage-metrics additions (OnUsageChangeCallback, 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 filesystem_cache_elements stays consistent with the queue state.
  • Kept both master's new idle_client_* settings and this PR's expose_prometheus_cache_usage_metrics_per_user, and rebuilt the 02344_describe_cache.reference row.

Verified locally: unit_tests_dbms builds and links, and all 29 FileCacheTest.* pass (including UsageMetricsByUser and the master eviction-metrics tests). The AI review's cache_name-label point remains addressed (documented primary-name contract + test_shared_cache_alias_usage_metrics). The remaining Stress-test reds are the pre-existing infra/fuzzer failures tracked in #107941, not caused by this PR.

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 341/380 (89.74%) · Uncovered code

Full report · Diff report

@sacheendra
sacheendra marked this pull request as ready for review July 28, 2026 19:56
alexey-milovidov and others added 4 commits August 5, 2026 00:00
…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.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @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 Stress test (arm_tsan) with Logical error: '(isConst() || isSparse() || isReplicated() || rhs.isConst() || rhs.isSparse() || rhs.isReplicated()) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID: 2508-30f6), i.e. IColumn::assertTypeEquality from IColumn::insertFrom in buildAdditionalFilter (src/Interpreters/HashJoin/HashJoinMethodsImpl.h:807), on the LEFT/ALL HashJoin path with an additional filter.

This is unrelated to this PR, which only touches FileCache, its docs, and gtest_filecache.cpp — nothing on the join path. Evidence that it is pre-existing and fleet-wide, from play.clickhouse.com:

  • On master (pull_request_number = 0): 8 occurrences of the same STID since 2026-07-09, latest 2026-08-05, with an identical assertTypeEquality → insertFrom → HashJoin stack, across Stress test (azure, amd_tsan), Stress test (amd_msan) and Stress test (azure, amd_msan).
  • Roughly 20 other unrelated open PRs hit the same STID over the last 30 days.

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 HashJoin additional_filter stress-test stack above looks distinct and worth its own issue: something builds the additional-filter block with a column whose runtime type does not match the destination (most likely a const/sparse/low-cardinality mismatch that is normally normalized before joinRightColumnsWithAdditionalFilter).

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

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 Fatal line names the internal dictionary-source query, which is misleading; the real query is 04667_mixed_join_condition_algorithm_selection.sql line 184:

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);

dict is a FLAT dictionary, so the right side is a key-value storage. The stress runner adds join_use_nulls=1 as a client option on one thread in three (ci/jobs/scripts/stress/stress.py:164), which supplies the missing precondition. That is the exact shape of #113534's own reproducer.

Verified, both directions. I transplanted #113534's two source hunks onto master 2169bf5d402de64 (its HashJoin.cpp is byte-identical between that base and #113534's; JoinStepLogical.cpp drifted, so I compared the deltas instead and they are identical), built, and ran against the pristine master debug snapshot:

Arm pristine master with #113534
the failing query above abort, HashJoinMethodsImpl.h:807 3, NULL
same with LEFT JOIN (ALL) abort, same frame 3, NULL
same with join_use_nulls = 0 3, 0 3, 0
COMPLEX_KEY_HASHED dictionary abort correct
EmbeddedRocksDB right side abort correct
your 04811 regression test abort at line 4 of 35 matches its .reference, 35/35
your PR-body reproducer abort 3, 100

The join_use_nulls = 0 row is identical on both arms, so the setting is what arms it; the abort reproduces on master with no fuzzing and no patch.

Two corrections to the framing, both measured.

Keying a census on the stack frame rather than the STID (buildAdditionalFilter and assertTypeEquality both present in test_context_raw), 30 days: 89 rows, 76 distinct pull requests, 9 master rows, 11 build variants, 2026-07-09 to 2026-08-05. Over 120 days it is 100 rows / 85 pull requests / 11 master rows, first seen 2026-05-07. So this is three months old, not one.

The template arguments in the stack are (DB::JoinKind)1, (DB::JoinStrictness)2. JoinStrictness 2 is Any, not All (src/Core/Joins.h:49); 3 is All (:50). Across those 89 rows it is Any in 76 and All in 11, Left in all 89. So the dominant shape is LEFT ANY, and both are fixed.

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. 04667 landed on master on 2026-07-31 and is the first in-tree test to combine a dictionary right side with a non-equi ON conjunct, so it turned a rare fuzzer-only signature into a frequent one. It is exposing the bug correctly rather than being wrong itself, so I would not weaken or tag it.

On a tracking issue. There is no GitHub issue for this signature, and searching buildAdditionalFilter returns only the closed #64513. I did not open one, since #113534 already carries the root cause and a regression test and would close it immediately. Happy to file one if you would still like the record.

On my #107957. It targets the same abort at the same line, but at the wrong layer: it reconciles the two nullability representations inside buildAdditionalFilter instead of preventing the divergence. @vdimir said as much on 2026-06-24, and my reply asking whether he wanted the planning-stage rewrite went unanswered, so the PR stalled. #113534 is that rewrite, so I will close #107957 as superseded rather than keep it open.

One thing there may be worth salvaging: your 04811 covers a FLAT dictionary, and #107957 also carries a COMPLEX_KEY_HASHED dictionary test (04338) and an EmbeddedRocksDB case added to 03720. I verified both pass on #113534 and abort on master. I can send them as a test-only PR on top of yours if you want the extra layouts covered; otherwise I will drop them.

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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 25568079633d2f49435f644a5415232ceef404a9 with master failed: RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes W….

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

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.

@kssenii kssenii self-assigned this Aug 24, 2026
…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.
@abashkeev abashkeev added the comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. label Sep 4, 2026
/// 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;
};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 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.

alexey-milovidov and others added 3 commits September 16, 2026 18:47
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Brought the branch up to date with master (it was 8473 commits behind and conflicting) and fixed the only CI red.

  • Merge 379822e4ba4f: one conflict in FileCache.cpp. Master now derives write_cache_per_user_directory from the cache policy (isOvercommitPolicy), so client_tracking_possible = is_overcommit_policy and the idle_client_ttl_sec warning is gated on the setting being set explicitly. The PR's usage-tracker installation (setUsageTracker for non-overcommit policies when expose_prometheus_cache_usage_metrics_per_user is on) sits between those two lines unchanged. 02344_describe_cache.reference auto-merged: 46 fields = cache_name + 42 DECLAREs + 3 runtime columns, with the PR's setting in declaration order.
  • Review f479867d7c7f: the system.dimensional_metrics registration text in attachSystemTables.cpp no longer claims the table is always up to date, matching dimensional_metrics.mdx.
  • Flaky gtests 25568079633d: UsageSnapshotNeverExceedsCacheSize (the Unit tests (tsan) failure on the previous head, and ~1 in 5 locally) read the per-client counters before the queue size, so a sample straddling a lock-free removal could see a stale counter next to the already shrunk size. It now reads queue state first, which is the order the writer ordering (counters discharged before state) actually guarantees, and still catches a reversed writer. UsageMetricsSettingIsStartupOnly used fixed on-disk paths outside the fixture cleanup with synchronous metadata loading, so a second run found segments already downloaded; the directories are now wiped before each cache is constructed.

Locally: all touched objects and unit_tests_dbms build with 0 errors; the FileCacheTest.* / Prometheus / dimensional-metrics suite passes 52/52 in two consecutive runs, and the reordered test passes 60/60.

@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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. This loop reads total_bytes += cache->getUsedCacheSize() while the cache is still empty.
  2. Another thread adds one 10-byte segment; growth is serialized by CacheStateGuard, so the new entry is fully visible once the lock is released.
  3. This loop then calls cache->getUsageStatPerClient(), takes the state lock, and snapshots usage.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.

@sacheendra sacheendra closed this Sep 21, 2026
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 comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants