Skip to content

Fix flaky FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly - #104418

Merged
kssenii merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-flaky-slru-free-space-test
May 12, 2026
Merged

kssenii merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-flaky-slru-free-space-test

Conversation

@groeneai

@groeneai groeneai commented May 8, 2026 •

Copy link
Copy Markdown
Collaborator

The regression test introduced in #104313 (covering issue #104307) is flaky on
Unit tests (amd_llvm_coverage). It exercises the bug condition through
FileCache::freeSpaceRatioKeepingThreadFunc with keep_free_space_elements_ratio = 1.0,
which causes cache->initialize() to schedule the asynchronous background eviction
task. That task races with the test's read_and_check and intermediate
assertProbationary / assertProtected calls, especially on slow builds (notably
coverage), evicting entries between the populate and assert steps and producing
spurious failures.

Failures observed

All failures are exclusive to the amd_llvm_coverage shard. tsan, asan_ubsan, and
msan runs on the same commits all pass, confirming this is a timing race on slow
builds rather than a real regression of the underlying fix.

CI reports:

Approach

Replace the high-level integration test with a focused unit-level test that exercises
SLRUFileCachePriority::collectEvictionInfo directly. The new test constructs the
priority queue, adds three protected-only entries via
addForRestore(... QueueEntryType::SLRU_Protected ...), and calls collectEvictionInfo
with the bug-triggering parameters (is_total_space_cleanup=true, probationary empty,
protected populated). This reproduces the exact precondition that used to fire the
removed chassert(evict_size_from_probationary || evict_elements_from_probationary),
without involving the file cache's asynchronous machinery, making the test
deterministic on every build flavor.

Verification

  • With the fix in SLRUFileCachePriority::collectEvictionInfo, the test passes 10/10
    runs in 0 ms.
  • Reintroducing the original chassert aborts the unit test process with
    Logical error: 'evict_size_from_probationary || evict_elements_from_probationary'
    and exit code 134 (SIGABRT), confirming the test still catches the regression.
  • All 11 FileCacheTest.* tests still pass.

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

N/A -- CI fix only.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.571

@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

(session: cron:clickhouse-ci-task-worker:20260508-184500)

a) Deterministic repro? Yes. build/src/unit_tests_dbms --gtest_filter=FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly passes 10/10 runs in 0 ms with the fix; aborts with exit code 134 (SIGABRT) when the original chassert is reintroduced.

b) Root cause explained? Yes. With keep_free_space_elements_ratio = 1.0, cache->initialize() schedules the asynchronous background eviction task at FileCache.cpp:444. That task races with read_and_check and the intermediate assertProbationary / assertProtected calls. On slow shards (notably amd_llvm_coverage), the background thread evicts entries between the populate step and the asserts, causing spurious failures even though the fix in SLRUFileCachePriority::collectEvictionInfo is correct.

c) Fix matches root cause? Yes. The new test exercises SLRUFileCachePriority::collectEvictionInfo directly with the bug-triggering precondition (is_total_space_cleanup=true, probationary empty, protected populated), bypassing the file cache's asynchronous machinery entirely. The race goes away because there is no longer a background thread.

d) Test intent preserved? Yes. The new test still exercises the exact code path that the removed chassert was guarding. Without the fix it aborts with Logical error: 'evict_size_from_probationary || evict_elements_from_probationary' -- the original failure mode from issue #104307. The test is now narrower (no I/O, no schedule pool, no CachedOnDiskReadBufferFromFile), which is appropriate for a unit-level regression check.

e) Demonstrated in both directions? Yes -- see (a). The reintroduced chassert produced a fully matching stack trace with SLRUFileCachePriority::collectEvictionInfo at the top frame.

f) Fix is general, not a narrow patch? N/A -- this is a CI fix for a flaky test, not a code change.

@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @kssenii — could you review this? It's a test-only follow-up to #104313 that replaces the racy integration test (which fails on amd_llvm_coverage because the background freeSpaceRatioKeepingThreadFunc task evicts entries between the populate and assert steps) with a focused unit test on SLRUFileCachePriority::collectEvictionInfo. The new test deterministically reproduces the original chassert from #104307 (verified locally: SIGABRT with the chassert restored, 10/10 passes with the fix).

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [381f35e]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL IGNORED

AI Review

Summary

This PR replaces the flaky integration-style FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly scenario with a deterministic unit-level regression around SLRUFileCachePriority::collectEvictionInfo, and adds small per-queue accessors used to assert the exact protected/probationary precondition. I did not find unresolved correctness, safety, performance, or metadata issues in the current diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label May 8, 2026
@kssenii kssenii self-assigned this May 9, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 9, 2026
…ilecache

`FileCache::getCommonOrigin` returns `const FileCacheOriginInfo &`, so binding
the result to `const auto` made an unnecessary copy. Bind to `const auto &`
to silence the `performance-unnecessary-copy-initialization` clang-tidy
diagnostic that broke the `Build (arm_tidy)` job for PR ClickHouse#104418.

Build (arm_tidy) log:
https://github.com/ClickHouse/ClickHouse/actions/runs/25574233246/job/75093398873

Session: cron:clickhouse-ci-task-worker:20260509-224500
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushing an empty commit (5f68575f57a) to trigger a fresh CI run.

The previous PR run was blocked by a Fast test failure on 02932_refreshable_materialized_views_2 — this test is a known chronic flaky and is completely unrelated to this PR.

CIDB evidence for 02932_refreshable_materialized_views_2:

day master_failures pr_failures distinct_prs
2026-05-11 1 0 1
2026-05-10 0 1 1
2026-05-09 0 3 2
2026-05-08 1 1 2
2026-05-07 0 3 3
2026-04-28 0 1 1

(5 failures over 14 days across multiple unrelated PRs and master itself.)

Why this PR cannot have caused it: #104418 touches a single file — src/Interpreters/tests/gtest_filecache.cpp — replacing the racy integration-style regression test with a focused unit-level test on SLRUFileCachePriority::collectEvictionInfo. No production code, no refreshable-materialized-view code, and not even any other test file is modified.

Meanwhile, the bug this PR fixes keeps hitting master and many unrelated PRs:

day master_failures pr_failures
2026-05-11 0 3
2026-05-10 1 12
2026-05-09 0 14
2026-05-08 2 6

cc @kssenii @alexey-milovidov — could one of you take a look so we can get this merged? The new unit test deterministically reproduces the original chassert from #104307 (verified locally: SIGABRT with the chassert restored, 10/10 passes with the fix). It removes the timing race with the asynchronous background eviction task that FileCache::initialize schedules when keep_free_space_*_ratio is set.

(session: cron:clickhouse-ci-task-worker:20260511-034500)

Comment on lines +1608 to +1610
/// Verify the precondition: 3 entries / 15 bytes in protected, probationary empty.
ASSERT_EQ(priority.getElementsCount(state_guard.lock()), 3);
ASSERT_EQ(priority.getSize(state_guard.lock()), 15);

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.

This check does not verify that probationary is empty like the comment states

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.

@groeneai please check above comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

@kssenii Thanks for the review — addressed in 8ff6220 (just pushed).

The previous comment claimed "probationary empty" but the assertions only checked the SLRU totals (getElementsCount / getSize). I considered using assertProbationary(priority.dump(...), Ranges{}) to make the empty-probationary claim explicit, but LRUFileCachePriority::iterate (which dump goes through) chasserts on entries whose KeyMetadata has no FileSegmentMetadata attached — the unit test uses addForRestore precisely to skip that setup and avoid the FileCache::initialize race that made the original test flaky.

Instead, I added small inline per-sub-queue accessors to SLRUFileCachePriority:

size_t getProtectedSize(...) const { return protected_queue.getSize(...); }
size_t getProtectedElementsCount(...) const { return protected_queue.getElementsCount(...); }
size_t getProbationarySize(...) const { return probationary_queue.getSize(...); }
size_t getProbationaryElementsCount(...) const { return probationary_queue.getElementsCount(...); }

They use the exact same access pattern already in getStateInfoForLog (which reads protected_queue.getSize/... directly), so the new surface area is minimal.

The precondition block now reads:

ASSERT_EQ(priority.getElementsCount(state_guard.lock()), 3);
ASSERT_EQ(priority.getSize(state_guard.lock()), 15);
ASSERT_EQ(priority.getProtectedElementsCount(state_guard.lock()), 3);
ASSERT_EQ(priority.getProtectedSize(state_guard.lock()), 15);
ASSERT_EQ(priority.getProbationaryElementsCount(state_guard.lock()), 0);
ASSERT_EQ(priority.getProbationarySize(state_guard.lock()), 0);

The empty-probationary ASSERT_EQ is what you specifically asked for; the populated-protected pair is its mirror.

Verified locally: unit_tests_dbms --gtest_filter=FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly 30/30 passes on debug build.

Diff: +17/-1 across two files.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, why did the FunctionsStress fail? Provide a fix.

groeneai added 4 commits May 11, 2026 16:17
The original test (added in ClickHouse#104313 to cover ClickHouse#104307) drove the bug condition through
`FileCache::freeSpaceRatioKeepingThreadFunc` with `keep_free_space_elements_ratio = 1.0`.
That setting causes `cache->initialize()` to schedule the asynchronous background
eviction task at `FileCache.cpp:444`, which then races with the test's `read_and_check`
and intermediate `assertProbationary` / `assertProtected` calls. On slow builds (notably
`Unit tests (amd_llvm_coverage)`) the background thread evicts entries between the
populate and assert steps, causing the test to fail spuriously even though the underlying
fix is correct.

Confirmed master-branch failures on commits `74e1c5ed` (16:03:32 UTC, line 1626 mismatch)
and `407d6cca` (16:24:46 UTC, `assertProtected` mismatch at line 214 from line 1616).
The same failure pattern reproduces in PR run for ClickHouse#89334 (b5c32ee, line 214 mismatches).
All failures are exclusive to the coverage shard; tsan / asan_ubsan / msan all pass.

The replacement test exercises `SLRUFileCachePriority::collectEvictionInfo` directly,
constructing the priority queue and adding three protected-only entries via
`addForRestore(... QueueEntryType::SLRU_Protected ...)`. This reproduces the exact bug
condition (probationary empty, protected populated, `is_total_space_cleanup=true`) without
involving the file cache's asynchronous machinery, making it deterministic across all
build flavors.

Verified locally:
- With the fix in `SLRUFileCachePriority::collectEvictionInfo`, the test passes 10/10
  in 0 ms.
- Reintroducing the original `chassert` aborts the unit test process with `Logical
  error: 'evict_size_from_probationary || evict_elements_from_probationary'` and exit
  code 134 (SIGABRT), confirming the test still catches the regression.
- All 11 `FileCacheTest.*` tests still pass.

CI failures observed in
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=74e1c5ed2c4437352b486d59b16ee8bd98a8b688&name_0=MasterCI&name_1=Unit%20tests%20%28amd_llvm_coverage%29
and
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=407d6ccaeb432fbd86b15dc6d341651a64f447dc&name_0=MasterCI&name_1=Unit%20tests%20%28amd_llvm_coverage%29
…ilecache

`FileCache::getCommonOrigin` returns `const FileCacheOriginInfo &`, so binding
the result to `const auto` made an unnecessary copy. Bind to `const auto &`
to silence the `performance-unnecessary-copy-initialization` clang-tidy
diagnostic that broke the `Build (arm_tidy)` job for PR ClickHouse#104418.

Build (arm_tidy) log:
https://github.com/ClickHouse/ClickHouse/actions/runs/25574233246/job/75093398873

Session: cron:clickhouse-ci-task-worker:20260509-224500
The previous Fast test failure on 02932_refreshable_materialized_views_2 is
a known chronic flaky test (5 failures over 14 days across multiple PRs
including master). This PR only modifies src/Interpreters/tests/gtest_filecache.cpp
and cannot affect refreshable materialized view behavior.
Reviewer @kssenii noted that the precondition comment said "probationary
empty" but the assertions only checked the SLRU totals (`getSize` /
`getElementsCount`). With three `addForRestore` calls all targeting
`SLRU_Protected`, the structural invariant guarantees probationary is
empty, but a future regression that misroutes the entry type or hashes
the `KeyMetadata` differently would still satisfy the total counters.

This change makes the precondition explicit:

- Add per-sub-queue accessors `getProtectedSize`,
  `getProtectedElementsCount`, `getProbationarySize`,
  `getProbationaryElementsCount` to `SLRUFileCachePriority`. They are
  small inline wrappers over `protected_queue.*` / `probationary_queue.*`
  (the same access pattern already used by `getStateInfoForLog`), so the
  new surface area is minimal and the implementation is trivially
  correct.

- Replace the precondition block in the regression test with four
  per-queue `ASSERT_EQ` calls. The empty-probationary assertion is the
  one the reviewer specifically asked for; the populated-protected
  assertion is its mirror.

Note: the original draft used `assertProtected` / `assertProbationary`
against `priority.dump(...)`. That path goes through
`LRUFileCachePriority::iterate`, which `chassert`s on entries whose
`KeyMetadata` has no `FileSegmentMetadata` attached (the unit test uses
`addForRestore` precisely to skip that setup and avoid the
`FileCache::initialize` race that made the previous test flaky). Direct
per-queue counters via the new accessors give the same coverage without
requiring `dump` to iterate.

Verified locally: `unit_tests_dbms
--gtest_filter=FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly` 30/30
passes.
@groeneai
groeneai force-pushed the groeneai/fix-flaky-slru-free-space-test branch from 8ff6220 to b004a52 Compare May 11, 2026 16:18
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov — the FunctionsStress.stress failure on commit 8ff62204adb was the chronic prev.thread_id == curr.thread_id chassert in ~FunctionsStressTestThread teardown, fixed by PR #103982 (merged at 14:55 UTC today, ~28 min before your directive). The PR #104418 branch base predated the fix.

Rebased onto current master (c492bdd0f51, which now includes PR #103982 merge commit 3bed49b) and force-pushed — new head is b004a5251e3. CI is re-running; FunctionsStress should be clean on this run.

Session: cron:clickhouse-ci-task-worker:20260511-161500

Comment on lines +1552 to +1568
/// `SLRUFileCachePriority::collectEvictionInfo` is invoked from
/// `FileCache::freeSpaceRatioKeepingThreadFunc` (driven by the
/// `keep_free_space_size(elements)_ratio` features) with `is_total_space_cleanup=true`.
/// With a high enough free-space target the function used to `chassert` that we
/// evict at least one element/byte from the probationary queue. This is wrong when
/// entries have all been promoted to the protected queue and the probationary queue
/// is empty: the function must still be able to evict from the protected queue.
/// Without the fix, the assertion aborts the server in debug/sanitizer builds and
/// throws a `LOGICAL_ERROR` in release.
///
/// We exercise `SLRUFileCachePriority::collectEvictionInfo` directly rather than
/// going through `FileCache::freeSpaceRatioKeepingThreadFunc` to avoid the timing
/// race with the asynchronous background eviction task that `FileCache` schedules
/// when `keep_free_space_*_ratio` is set: that task evicts entries between the
/// populate and assert steps, especially on slow builds (e.g. coverage), which
/// makes the higher-level test inherently flaky. The unit-level test below
/// reproduces the exact bug condition deterministically and on every build flavor.

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.

@groeneai this comment is too huge, please make it consize

Comment on lines +35 to +38
/// Per-sub-queue accessors. Used by `getStateInfoForLog` and by unit tests that
/// need to verify that an entry landed in the expected SLRU sub-queue without
/// going through `dump`/`iterate` (which require full `KeyMetadata` setup that
/// the `addForRestore` test path does not perform).

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.

Remove this comment, the methods are self explanatory

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 381f35e — removed the comment block, methods left self-explanatory.

Removes the comment block above the per-sub-queue accessors in
`SLRUFileCachePriority.h`. Per @kssenii's inline review on PR ClickHouse#104418,
the method names are self-explanatory.

ClickHouse#104418 (comment)
@clickhouse-gh

clickhouse-gh Bot commented May 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 100.00% (49/49) · Uncovered code

Full report · Diff report

@kssenii
kssenii added this pull request to the merge queue May 12, 2026
Merged via the queue into ClickHouse:master with commit 55a1c75 May 12, 2026
322 of 326 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 12, 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 pr-ci 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.

4 participants