Skip to content

Fix wrong results and a server abort from stale caches after SYSTEM RESTORE REPLICA - #132791

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:qcc-clear-on-restore-replica
Nov 23, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:qcc-clear-on-restore-replica

Conversation

@groeneai

@groeneai groeneai commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fixed wrong results and a possible server abort after SYSTEM RESTORE REPLICA (for example after converting a table with ATTACH TABLE ... AS REPLICATED): the restore attaches the parts again under the names and paths that other parts of the table had before, and the query condition cache, the mmap cache and the uncompressed cache returned those parts' verdicts or data.

Description

On 26.10.5.57, by default this returns 0 instead of 2:

CREATE TABLE t (k UInt64, s String) ENGINE = MergeTree ORDER BY k;
SYSTEM STOP MERGES t;
INSERT INTO t VALUES (1, 'pear');
INSERT INTO t VALUES (2, 'apple');
SELECT sum(k) FROM t WHERE length(s) = 5;
DETACH TABLE t; ATTACH TABLE t AS REPLICATED;
SYSTEM STOP MERGES t; SYSTEM RESTORE REPLICA t;
SELECT sum(k) FROM t WHERE length(s) = 5;

A renamed part with more granules than the cached one aborts the server (vector<bool>::operator[] index out of bounds in filterPartsByQueryConditionCache).

The restore (SYSTEM RESTORE REPLICA, the convert_to_replicated flag, the forced restore on attach) moves all parts to detached/, re-creates the Keeper nodes (resetting the block counters) and attaches the parts again: 'apple' becomes all_1_1_0, the old name of the 'pear' part, under the same table UUID. The query condition cache keys entries by table UUID, part name and condition and can only be cleared as a whole, so the per-part eviction here misses it. The mmap and uncompressed caches are keyed by file path and are not evicted per part either: with local_filesystem_read_method = 'mmap' or use_uncompressed_cache = 1 it also returns 0.

StorageReplicatedMergeTree::restoreMetadataInZooKeeper now calls Context::clearCaches, as explicit-UUID CREATE and Replicated database recovery do, after all parts left the working set and before any is attached or fetched again. With #128677 and #132457 this covers every event restarting the block numbers of a table; the open #128715 fixes the uncompressed and text index caches on a plain MergeTree ATTACH. Not covered: a query reading the old parts during the restore can write entries after the clear.

The test fails on master (wrong result, then abort), its mmap and uncompressed cache queries also on this PR's previous head (40/40 randomized), and passes with the fix, 50/50 randomized.

Closes: #132674
Related: #132457
Related: #128677
Related: #128715

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.12.1.307-master (included in 26.12 and later)

… parts

`StorageReplicatedMergeTree::restoreMetadataInZooKeeper` moves every part to
`detached/`, re-creates the table's Keeper nodes (which resets the block number
counters) and attaches the active parts again, so they get new names numbered
from 0 under the same table UUID, possibly the old names of other parts of the
table. The query condition cache keys entries by (table UUID, part name,
condition hash), so a part could read the verdicts of another part: matching
marks were skipped (wrong results), and a part with more marks than the cached
entry was read past the cached bitmap (libc++ hardening abort in
`filterPartsByQueryConditionCache`). Reproduced on 26.10.5.57 and master.

The per-part cache eviction on this path
(`forcefullyMovePartToDetachedAndRemoveFromMemory` ->
`IMergeTreeDataPart::clearCaches`) cannot reach the query condition cache,
which can only be cleared as a whole. Clear it once, after all parts left the
working set and before any part is attached or fetched under a new name. This
covers every caller (SYSTEM RESTORE REPLICA, the `convert_to_replicated` flag,
the forced restore of the attach thread) and non-first replicas, which fetch
the parts under the first replica's new names. A table without UUID never has
entries, so it does not clear the cache of the other tables (same guard as the
`StorageMergeTree` attach clear of ClickHouse#132457).

Residual: a query that was already reading the old parts when the restore
started can still write entries for their old names after the clear. Closing
that needs per-part keys, rejected as too heavy in ClickHouse#128677.

See ClickHouse#132674.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 findings over 2 passes) plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ A query already reading the old parts during the restore can write their entries after the clear DISAGREE Mechanism holds (SYSTEM RESTORE REPLICA takes no table lock), but the fix does not claim it: it is stated in the description. Closing it needs per-part keys in the cache (too heavy on #128677) or a restore that waits for running queries (a locking change the reported bug does not need)
2 ⚠️ The test can pass when the cache does not participate DISAGREE With the 2 code lines removed the test fails (0 instead of 2, then the abort); base fails 20/20 with randomized settings, so no setting makes the cache decline. A hit-count check would need no-parallel
3 💡 Use Critical Bug Fix DISAGREE Kept Bug Fix like #132457 (same cache, same abort)
4 💡 Description said #128715 "fixed" the path-keyed caches AGREE, fixed in the description #128715 is still open

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-10:20261118-202600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test with --no-random-settings --no-random-merge-tree-settings fails on master every time: section 1 prints 0 instead of 2, section 2 aborts the server. 20/20 randomized runs of section 1 on master fail with the same -2/+0 diff.
b Root cause explained? restoreMetadataInZooKeeper re-creates the Keeper nodes (block number counters start from 0) and attaches the parts again, so a part can get the old name of another part under the same table UUID; the query condition cache, keyed by (UUID, part name, condition), then serves that part's verdicts.
c Fix matches root cause? Yes. The cache is cleared at the event that renumbers, after all parts left the working set and before any is attached or fetched under a new name. No read-side guard.
d Test intent preserved / new tests added? New SQL test: the same-size wrong result and a larger part that overruns the cached bitmap, with a _part check that the name really is reused.
e Both directions demonstrated? Fails on master and on this tree with the two lines removed; passes with the fix, 50/50 with randomized settings.
f Fix is general across code paths? One function covers SYSTEM RESTORE REPLICA, the convert_to_replicated flag and the forced restore on attach, and non-first replicas. Also measured: restore after a loss of Keeper metadata (master 0, fix 3).
g Fix generalizes across inputs (params/datatypes/wrappers)? The clear is per table event, independent of types, conditions and projections; a table without UUID has no entries and skips the clear.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; one cache flush per restore.
i Invariants and contracts preserved? Yes. No lock is held at that point and the call only drops cache entries. A query already reading the old parts when the restore starts can still write entries for their old names (needs per-part keys).

Session id: cron:clickhouse-impl-slot-40:20261118-192800

@clickhouse-gh clickhouse-gh Bot added the can be tested Allows running workflows for external contributors label Nov 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [798f98b]

Summary: ✅


AI Review

Summary

The PR clears caches in StorageReplicatedMergeTree::restoreMetadataInZooKeeper before parts are attached or fetched under reused names and paths, preventing stale query-condition verdicts, memory mappings, and uncompressed blocks from returning another part's data. The earlier mmap blocker is fixed. The documented concurrent-reader limitation is accepted as outside this fix's scope. No actionable findings remain at 798f98bd8d3aaeaee901dbaa3a774e5c3f947132; the regression test passed all 50 runs in the targeted ASan/UBSan CI job.

Final Verdict

Status: ✅ Approve

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

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 798f98bd8 with master 89b17242e (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. label Nov 18, 2026
@PedroTadim PedroTadim self-assigned this Nov 20, 2026
…LICA renumbers parts

The re-attached parts take the names, and so the file paths, of other parts. Clearing only
the query condition cache left the mmap cache and the uncompressed cache serving the old
files' data: with `local_filesystem_read_method = 'mmap'` or `use_uncompressed_cache = 1`
the reproducer returns 0 instead of 2 after the restore (reported by the review bot on
the mmap cache; the uncompressed cache behaves the same). Both are keyed by file path,
and the per-part eviction on this path does not reach them.

`Context::clearCaches` is what explicit-UUID CREATE and Replicated database recovery
already call when part names and paths can be reused, and it covers every cache keyed by
them, so use it here too. The hasUUID() guard is dropped: paths are reused in an Ordinary
database as well.

The test gets a third table for the mmap and uncompressed caches. It pins
`min_bytes_for_full_part_storage = 0`, since a packed part does not go through the
per-file mmap path and the mmap line would pass on the unfixed server, and
`use_columns_cache = 0`, since the columns cache could serve these queries without
reading the files and so hide a missing uncompressed cache clear.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix wrong results and a server abort from the query condition cache after SYSTEM RESTORE REPLICA Fix wrong results and a server abort from stale caches after SYSTEM RESTORE REPLICA Nov 20, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 23, 2026
@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

A question about the scope of the new getContext()->clearCaches() call in restoreMetadataInZooKeeper: Context::clearCaches is server-wide, not per table. It empties these caches for every table on the server:

  • page and columns caches
  • uncompressed, mark and primary index caches
  • statistics cache and the skip-index uncompressed and mark caches
  • vector similarity and text index caches
  • mmap cache and query condition cache
  • encryption header and delete bitmap caches

Only the query result cache is kept. So each SYSTEM RESTORE REPLICA makes every table on that server start cold.

I think this is acceptable:

  • It is the existing pattern. The same server-wide call already runs for CREATE with an explicit UUID (InterpreterCreateQuery.cpp), for Replicated database recovery (DatabaseReplicated.cpp), and in dropAllData and rename for tables without a UUID (MergeTreeData.cpp). The first two were added in 8bed27b as the simpler fix suggested in review.
  • There is no narrower option today:
    • The per-part IMergeTreeDataPart::clearCaches covers the mark, index, statistics, vector index and columns caches. It does not cover the query condition cache, which is this PR's main bug, or the uncompressed, page and mmap caches, which the t3 case of the test covers.
    • The query condition cache could be cleared for one table with CacheBase::remove(predicate) on table_id. The uncompressed, page and mmap caches are keyed by a path hash, so they cannot be cleared per table without a new API.
  • The cost is performance only, and SYSTEM RESTORE REPLICA is a rare recovery command.

Two cases where it hurts more:

  • A script that restores many tables after losing Keeper metadata flushes all caches once per table.
  • SYSTEM RESTORE REPLICA ... ON CLUSTER flushes every server.

Cheap follow-ups, not blockers: flush once per statement instead of once per table, and mention the cache flush in the SYSTEM RESTORE REPLICA documentation.

Merged via the queue into ClickHouse:master with commit addc006 Nov 23, 2026
383 of 384 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 Nov 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for checking the scope. On the two follow-ups:

  • Flush once per statement: SYSTEM RESTORE REPLICA already takes exactly one table (the parser requires it, ParserSystemQuery.cpp), so one statement is one flush. A script that restores N tables runs N statements, and only a batched form of the command could merge those flushes. With ON CLUSTER, each server renumbers the parts of its own replica, so each server needs its own flush.
  • Docs: I'll open a small PR that adds a sentence about the server-wide cache flush to SYSTEM RESTORE REPLICA in docs/reference/statements/system.mdx, and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The docs follow-up is #134022: the system.mdx page is generated from src/Parsers/ParserSystemQuery.cpp, so the paragraph about the server-wide cache flush (which caches it clears and which it keeps) is added there.

clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Nov 24, 2026
Since ClickHouse#132791, restoring a replica clears the server-wide data caches,
because the restored parts get new names that can be the former names and
paths of other parts. Document this in the SYSTEM RESTORE REPLICA section:
every table on the server starts with cold caches, every server with
ON CLUSTER, and the query cache and the filesystem cache are kept. The
cleared caches are listed with links to their SYSTEM CLEAR sections.

The reference page docs/reference/statements/system.mdx is generated from
the documentation in ParserSystemQuery.cpp, so the paragraph is added there.

Related: ClickHouse#132791

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Nov 24, 2026
Context::clearCaches also clears the encryption headers cache and the
UNIQUE KEY delete bitmap cache, so "other caches are kept" was wrong. List
the encryption headers cache with the other cleared caches and name only
the query cache and the filesystem cache as kept. With ON CLUSTER, the
caches are cleared only on the servers where the restore actually runs.

Related: ClickHouse#132791

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Nov 24, 2026
… RESTORE REPLICA clears

Context::clearCaches clears the UNIQUE KEY delete bitmap cache too; it has no
SYSTEM CLEAR statement, so it is listed without a link.

Related: ClickHouse#132791

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. pr-bugfix Pull request with bugfix, not backported by default 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.

Stale query condition cache after SYSTEM RESTORE REPLICA renumbers parts

3 participants