Skip to content

Fix wrong results and a server abort from the query condition cache after a MergeTree table is attached again - #132457

Merged
hanfei1991 merged 1 commit into
ClickHouse:masterfrom
groeneai:qcc-clear-on-attach-part-name-reuse
Nov 18, 2026
Merged

hanfei1991 merged 1 commit into
ClickHouse:masterfrom
groeneai:qcc-clear-on-attach-part-name-reuse

Conversation

@groeneai

@groeneai groeneai commented Nov 17, 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 of queries using the query condition cache when a MergeTree table was attached again (DETACH/ATTACH TABLE or ATTACH DATABASE) after TRUNCATE or ALTER TABLE ... DROP PARTITION, so that a new part got the name of a removed one.

Description

On 26.10.5.57, with default settings, this returns 0 instead of 2:

CREATE TABLE t (k UInt64, s String) ENGINE = MergeTree ORDER BY k SETTINGS old_parts_lifetime = 0;
INSERT INTO t VALUES (1, 'pear');
SELECT sum(k) FROM t WHERE length(s) = 5;
TRUNCATE TABLE t; DETACH TABLE t; ATTACH TABLE t;
INSERT INTO t VALUES (2, 'apple');
SELECT sum(k) FROM t WHERE length(s) = 5;

If the new part has more granules, the read indexes past the cached bitmap and the server aborts (vector<bool>::operator[] index out of bounds in filterPartsByQueryConditionCache). The same happens after DROP PARTITION.

StorageMergeTree takes its block numbers from the parts on disk when the table is loaded, so a table attached again gives its next part the name of a removed one (all_1_1_0). The query condition cache keys entries by table UUID, part name and condition, and keeps them across the attach. #128677 clears the caches on CREATE with an explicit UUID, which a short ATTACH TABLE and ATTACH DATABASE do not reach.

The StorageMergeTree constructor now clears the query condition cache when a table with a UUID is attached at runtime. Server startup is unaffected; ReplicatedMergeTree takes block numbers from Keeper. The call is in the constructor because ATTACH DATABASE creates its tables without InterpreterCreateQuery::doCreateTable. This is not the same-UUID case of #116202: it is the same table and the user writes no UUID.

The uncompressed and text index caches, keyed by file path, have the same problem on this trigger and are fixed in #128715, so the test pins use_uncompressed_cache = 0. Calling clearCaches() here instead would cover both.

The new test fails on master (wrong result, then the abort) and passes with the fix, 50/50 with randomized settings.

Related: #128715
Related: #128677


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

Version info

  • Merged into: 26.11.1.2707-master (included in 26.11 and later)
  • Backported to: 26.10.8.8

StorageMergeTree sets its block number counter from the parts on disk
when the table is loaded. After TRUNCATE or ALTER TABLE ... DROP
PARTITION, once the removed parts are cleaned up, a table attached again
(ATTACH TABLE, ATTACH DATABASE) gives its next part the name of a
removed one, for example all_1_1_0. The query condition cache keys its
entries by table UUID, part name and condition hash, never evicts the
entries of a removed part, and the attach keeps the UUID. So the new
part gets the verdicts of the removed one: granules with matching rows
are skipped, and when the new part has more marks,
filterPartsByQueryConditionCache reads past the cached bitmap and the
server aborts on the libc++ hardening check (also on 26.10.5.57).

ClickHouse#128677 clears the caches when a table is created with an explicit UUID,
but a short ATTACH TABLE does not reach that code, and ATTACH DATABASE
loads its tables through DatabaseOrdinary without InterpreterCreateQuery
at all. Clear the query condition cache in the StorageMergeTree
constructor for a runtime attach (LoadingStrictnessLevel::ATTACH), the
only place where block numbers restart. Server startup loads tables with
FORCE_ATTACH, when the cache has no entries for them yet. A table without
a UUID never has entries, so its attach leaves the cache alone.
StorageReplicatedMergeTree takes block numbers from Keeper, which never
restart.

Only the query condition cache is cleared: the mark, primary index,
statistics and columns caches are evicted per part, and the caches keyed
by file path (uncompressed, index uncompressed, text index) are handled
by ClickHouse#128715, which is why the test pins use_uncompressed_cache = 0.

Related: ClickHouse#128715
Related: ClickHouse#128677

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; 1 finding; 1 full pass).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test asserts results only, not a cache hit before the attach and a miss after it, and has no DROP PARTITION case DISAGREE On master the test fails every run (0 instead of 2, then the abort; 20/20 randomized), so the cache is used by these queries and the test flips with the fix. A hit assertion would be broken by any concurrent ATTACH in a parallel run, which now empties the cache. The fix has no code specific to TRUNCATE; DROP PARTITION was checked by hand: master 0, fix 2.

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

Session id: cron:clickhouse-review-slot-9:20261117-185600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991, could you review this? Clear the query condition cache when a MergeTree table is attached at runtime, because its next part can reuse the name of a removed part.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test fails every time on master (wrong result, then the abort); section 1 alone failed 20/20 with randomized settings. 26.10.5.57 reproduces both by hand.
b Root cause explained? StorageMergeTree takes block numbers from the parts on disk at attach, so after TRUNCATE/DROP PARTITION the next part reuses a removed part's name. The query condition cache keys by (table UUID, part name, condition), keeps entries across the attach, and the read never checks the bitmap size.
c Fix matches root cause? Yes. The cache is cleared where numbering restarts (runtime attach of a non-replicated MergeTree table). No read-side size guard, which would hide only the abort.
d Test intent preserved / new tests added? New SQL test, two cases: ATTACH TABLE (same size, wrong result) and ATTACH DATABASE (larger part, abort). The part-name lines assert the name is really reused.
e Both directions demonstrated? Master: FAIL + abort. Fix: OK, 50/50 randomized. Moving the call into InterpreterCreateQuery makes the ATTACH DATABASE case abort again.
f Fix is general across code paths? ATTACH TABLE, ATTACH DATABASE, ON CLUSTER and lazy loading all construct the table; DROP PARTITION measured fixed. Startup has no stale entries, ReplicatedMergeTree block numbers come from Keeper, explicit UUIDs are #128677, path-keyed caches are #128715.
g Fix generalizes across inputs (params/datatypes/wrappers)? The defect depends on part names, not types. Covered: same-size and larger parts, TRUNCATE and DROP PARTITION, table and database attach, randomized settings.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; the cache is emptied on a runtime attach (performance only).
i Invariants and contracts preserved? A (UUID, part name) entry again denotes the part that wrote it: the flush runs before the table is visible, and a name is reused only after the old part's files are gone. Same lock path as SYSTEM DROP QUERY CONDITION CACHE.

Session id: cron:clickhouse-impl-slot-6:20261117-170700

@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [19ce319]

Summary: ✅


AI Review

Summary

Clears the query condition cache before a UUID-bearing, non-replicated MergeTree table is reattached, preventing stale granule verdicts when part names are reused. The new SQL regression covers ATTACH TABLE and ATTACH DATABASE, including a replacement part with more granules. No actionable findings in the current diff.

Missing context / blind spots
  • ⚠️ Automated bugfix validation was dropped after Config Workflow, causing the final new tests check to fail (CI report). No local build was available to rerun the SQL. Regression evidence includes the author's reported failures on unpatched master and 50/50 randomized passes with the fix; a successful CI rerun would independently confirm it.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Nov 17, 2026
@hanfei1991 hanfei1991 self-assigned this Nov 17, 2026
@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 19ce31905 with master 23fdd5672 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.78 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.6 s 17.6 s +11.7 s (+198%)
Compile time of recompiled translation units

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

Job report

@hanfei1991
hanfei1991 added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit c25f02d Nov 18, 2026
569 of 573 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 19, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 19, 2026
Backport #132457 to 26.10: Fix wrong results and a server abort from the query condition cache after a MergeTree table is attached again
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants