Skip to content

Fix primary indexes of newly written parts staying in memory forever when PK cache is enabled - #115314

Open
azat wants to merge 3 commits into
ClickHouse:masterfrom
azat:pk-cache-fixes
Open

azat wants to merge 3 commits into
ClickHouse:masterfrom
azat:pk-cache-fixes

Conversation

@azat

@azat azat commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix primary indexes of newly written parts staying in memory forever (unevictable, visible as primary_key_bytes_in_memory in system.parts) when the primary index cache is enabled (use_primary_key_cache). This affected parts produced by mutations, projections rebuilt by mutations, and parts that shrank below min_bytes_to_prewarm_caches during a merge or mutation. Additionally, enabling use_primary_key_cache via ALTER TABLE ... MODIFY SETTING now unloads primary indexes (including projections) that were loaded while the cache was disabled, without requiring SYSTEM UNLOAD PRIMARY KEY or a server restart.


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

azat and others added 3 commits August 18, 2026 17:27
With `use_primary_key_cache = 1` and `prewarm_primary_key_cache = 1` a
full-rewrite mutation built the new part's index in memory but, unlike
merges and inserts, never moved it into the cache: it stayed pinned in
the part (`primary_key_bytes_in_memory` in `system.parts`), unevictable
until the part became outdated.

Co-Authored-By: Claude Fable 5 <[email protected]>
Whether to save the index and marks in memory during write and whether
to move them into the caches after commit were decided independently,
with different sizes at different times: on mismatch the index stayed
in the part, unevictable, and the saved marks were dropped. One
decision per operation, carried in the writer settings, shared with the
projection writers, reused for the move into the cache after commit.

- v2: CachesToPrewarm in the writer settings instead of the save_* flags
- v3: projection writers reuse the operation's decision (a projection index could stay in the part when the parent's index is absent)
- v4: assert in moveIndexToCache

Co-Authored-By: Claude Fable 5 <[email protected]>
Indexes loaded while the cache was disabled stayed pinned in parts and
their projections, unevictable, until SYSTEM UNLOAD PRIMARY KEY or a
restart; unloadIndex now also recurses into projections.

Co-Authored-By: Claude Fable 5 <[email protected]>
@azat azat changed the title Minor fixes for primary key cache (use_primary_key_cache=1) Fix primary indexes of newly written parts staying in memory forever when PK cache is enabled Aug 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [01309dd]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
04891_distributed_plan_limit_early_stop FAIL cidb

AI Review

Summary

This PR makes the primary-index prewarm decision consistent across inserts, merges, mutations, and projections, and it unloads currently loaded primary indexes when use_primary_key_cache is enabled. The direction is correct, but two lifecycle gaps remain: enabling the cache still misses in-flight writers, and projection primary-index cache entries are not cleaned up symmetrically once parts become outdated.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeData.cpp:6267] ALTER TABLE ... MODIFY SETTING use_primary_key_cache = 1 only unloads parts that are already active. A long-running insert, merge, or mutation that snapshotted CachesToPrewarm while the cache was disabled will still publish a new active part with its primary index pinned in memory after the ALTER, so the advertised “no SYSTEM UNLOAD PRIMARY KEY or restart required” contract is still false for in-flight writes.
  • [src/Storages/MergeTree/IMergeTreeDataPart.cpp:735] Projection parts now move their primary indexes into PrimaryIndexCache, but the cleanup path is not symmetric: MergeTreeData::unloadPrimaryKeysAndClearCachesOfOutdatedParts() only calls clearCaches() on the parent part, and IMergeTreeDataPart::clearCaches() does not recurse into projection_parts. Outdated projection cache entries can therefore sit in the cache for the whole old-part lifetime and evict active entries.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Handle writes that started before use_primary_key_cache was enabled so the just-committed part does not keep its index pinned in memory.
    • Make cache cleanup recurse through projection parts, matching the new projection-side moveIndexToCache() behavior.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.80% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 264/270 (97.78%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 18, 2026

/// Indexes loaded in parts while the cache was disabled would stay there, unevictable.
if (has_primary_index_cache_been_enabled)
unloadPrimaryKeys();

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.

This only fixes parts that are already visible when the ALTER runs. Inserts, merges, and mutations snapshot CachesToPrewarm before commit, so a long-running write that started with use_primary_key_cache = 0 will still publish a new active part with its primary index kept in-memory after this ALTER, and this unloadPrimaryKeys() call will never touch it.

That means the new contract from the PR body is still false for in-flight writes: enabling use_primary_key_cache can still require a later SYSTEM UNLOAD PRIMARY KEY or restart to get rid of unevictable indexes. Can we either re-check the cache-enabled bit at finalize time, or explicitly unload the just-committed part when the setting flipped meanwhile?

/// this part's own index is absent (e.g. a mutation that rebuilds only a projection).
for (const auto & [_, projection] : projection_parts)
projection->moveIndexToCache(index_cache);
projection->moveIndexToCache(prewarm_caches);

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.

Now that projection parts also move their primary indexes into PrimaryIndexCache, the cleanup path needs the symmetric recursion too. MergeTreeData::unloadPrimaryKeysAndClearCachesOfOutdatedParts() still calls clearCaches() only on the parent part, and IMergeTreeDataPart::clearCaches() only removes this part's own cache key.

So when a part becomes outdated, its projection PK entries can stay in the cache for the whole old-part lifetime and evict active entries in the meantime. Please recurse through projection_parts from cache cleanup as well, not just from moveIndexToCache().

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 01309ddd0 with master 79d8c6689 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.06 MiB 699.03 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

31 object files changed (+6.43 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergePlainMergeTreeTask.cpp.o 132.63 KiB 114.61 KiB -18.02 KiB (-13.59%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

286 translation units recompiled, 2892 s compile time in total, 286 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +203.9 s (+8%) in total before that adjustment.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant