Skip to content

Drop the caches when a table is created with an explicit UUID or by replica recovery - #128677

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:qcc-key-by-table-object
Nov 15, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:qcc-key-by-table-object

Conversation

@groeneai

@groeneai groeneai commented Nov 2, 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 server abort when a table was created again with the UUID of an earlier table, by CREATE TABLE ... UUID, by ATTACH TABLE ... UUID with a full definition, or by Replicated database replica recovery: the query condition cache and the uncompressed, mmap, userspace page and columns caches served the earlier table's data. The caches are now dropped in these cases.

Description

On 26.10 (v26.10.2.103-stable), a MergeTree table created again with the UUID of a dropped one returns wrong results for a filter that already ran on the dropped table, and the server aborts (vector<bool>::operator[] index out of bounds, also in release builds) when the new part has more granules.

Found in Stress test (amd_debug): a DROP TABLE ... SYNC in a Replicated database dropped the table, then failed on a Keeper session expiry, and replica recovery created the table again with its recorded UUID.

A table created with the same UUID gets the same data path and numbers its blocks anew, so its parts get the earlier table's part names. The query condition and columns caches (keyed by UUID and part name) and the uncompressed, mmap and page caches (keyed by file path) then return the earlier table's data: dropAllData clears the caches only for tables without a UUID, and a table moved to an Ordinary database (as replica recovery does) keeps its columns cache entries.

As suggested in review, Context::clearCaches (which now also clears the page and columns caches) is called when:

  • a user's CREATE, or ATTACH with a full definition, names a UUID, right before the table is published (not on a short ATTACH TABLE t or a no-op IF NOT EXISTS);
  • replica recovery is about to create tables.

ON CLUSTER hosts and Replicated database replicas get the UUID from the initiator and cannot tell a user-written one apart, so they do not drop the caches.

The test covers these paths with the uncompressed and columns caches on. On master it prints wrong 0s and then aborts the server. With the fix it passes in 50 of 50 randomized runs. I checked the page cache, which the CI server config leaves off, by hand.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2350-master (included in 26.11 and later)

groeneai and others added 3 commits November 2, 2026 13:18
A MergeTree table created again with the UUID of a dropped one (Replicated
database replica recovery, or DROP TABLE ... SYNC + CREATE TABLE ... UUID)
starts its block numbers anew, so its parts get the dropped table's part
names. The query condition cache keyed entries by (table UUID, part name,
condition hash) and never evicts them, so the new table read the dropped
table's per-mark verdicts: wrong results when the marks count matched, and a
vector<bool> out-of-bounds abort (also in release builds, libc++ hardening)
when the new part had more marks (STID 6387-6640, Stress test (amd_debug)).

Every MergeTreeData now has a process-unique object id, and all MergeTree
readers and writers of the cache fold it into the key, so a re-created table
never sees the entries of the dropped one. Other storages pass 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tion test

The mmap cache is keyed by file path like the uncompressed cache, so when the
test runner draws local_filesystem_read_method = 'mmap' with a small
min_bytes_to_use_mmap_io it can return the dropped table's file contents to the
table created again with the same UUID (measured: 1 of 50 randomized runs with
only use_uncompressed_cache pinned). Both are server defaults; pinning them
keeps the test about the query condition cache only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the table_object_id comments on QueryConditionCache::write and MergeTreeData::getTableObjectId to one line each.

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

groeneai commented Nov 2, 2026

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

# Sev Finding Verdict Evidence
1 ⚠️ The new test would also pass if the query condition cache were never populated DISAGREE With the fix reverted the test prints 0 on lines 3-8, then the server aborts in filterPartsByQueryConditionCache; a hit/miss oracle would need no-parallel.

Also noticed, not changed here: SYSTEM RESTORE REPLICA re-attaches parts under new block numbers on the same table object; it needs lost Keeper metadata, and I did not reproduce it.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-8:20261102-135900

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @shankar-iyer, could you review this and add the can be tested label so CI runs? A MergeTree table created again with the UUID of a dropped one reuses its part names, so the query condition cache applied the dropped table's granule verdicts to the new parts (wrong results, or a vector<bool> out-of-bounds abort); the cache key now also includes a process-unique id of the table object.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d137836]

Summary: ✅


AI Review

Summary

This PR invalidates caches before local explicit-UUID table creation, full-definition ATTACH, and table recreation during Replicated database recovery, preventing stale data and query-condition verdicts from a previous table incarnation. Both earlier findings are fixed, including columns-cache invalidation. No new actionable findings. The documented exclusion of ordinary distributed DDL is accepted as the scope of this fix.

Missing context / blind spots
  • ⚠️ Latest-head stateless results are still pending, and tests were not rerun locally. The regression test passed all 50 runs in the previous revision's flaky check. Current-head stateless results would complete runtime verification after the latest master merge.
Final Verdict

Status: ✅ Approve. No additional code changes requested.

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

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d13783669 with master da9125b5e (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-keeper ×1.16 (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.1 s 16.5 s +9.7 s (+143%)
Compile time of recompiled translation units

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member

The fix is too heavy. Let's do something else.

@alexey-milovidov

Copy link
Copy Markdown
Member

by Replicated database replica recovery, or by DROP TABLE ... SYNC followed by CREATE TABLE ... UUID

@groeneai,
One idea is to drop all caches when a user does replicated database recovery or CREATE TABLE with an explicit UUID.
This will be a simple fix for all wrong cases.

@alexey-milovidov alexey-milovidov self-assigned this Nov 3, 2026
…eplica recovery

Replace the per-table-object query condition cache key with the simpler fix
suggested in review: a table created with the UUID of a dropped table gets the
same data path, and its block numbers start anew, so its parts get the dropped
table's part names. Every cache keyed by the path or by (UUID, part name) then
serves the dropped table's data: the query condition cache (wrong results, or a
`vector<bool>` out-of-bounds abort when the new part has more granules), and
the uncompressed, mmap and userspace page caches (stale data, or
`UNKNOWN_CODEC`).

`dropAllData` clears the caches only for tables without a UUID, so call
`Context::clearCaches` at the two entry points that can reuse a UUID:
- `CREATE` with a UUID written by the user, right before the table is
  published, so a no-op `IF NOT EXISTS` or a failing `CREATE` does not flush
  anything (not `ATTACH`, not an internal, `ON CLUSTER` or Replicated database
  query);
- `DatabaseReplicated::recoverLostReplica`, which creates tables with the
  UUIDs stored in Keeper, when it creates at least one table.

`Context::clearCaches` now also clears the userspace page cache, which is
keyed by the file path for local disks.

The test now also covers replica recovery (the case seen in the stress test)
and runs with the uncompressed cache on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Do not apply the query condition cache entries of a dropped table to a table created again with the same UUID Drop the caches when a table is created with an explicit UUID or by replica recovery Nov 3, 2026
@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Done in 8bed27b: I reverted the table-object key. Context::clearCaches is now called on a CREATE with a user-written UUID, right before the table is published (so a no-op IF NOT EXISTS does not flush), and in DatabaseReplicated::recoverLostReplica before it creates tables. clearCaches now also clears the page cache, so the uncompressed, mmap and page caches are covered too, not only the query condition cache. The test covers both paths, including the replica recovery that the stress test hit.

One gap remains: ON CLUSTER hosts and Replicated database replicas get the UUID from the initiator and cannot tell it from a user-written one, so they do not clear the caches. Part-path reuse without a UUID (TRUNCATE + DETACH/ATTACH) is a separate case, in #128715.

Comment thread src/Interpreters/Context.cpp Resolved
groeneai and others added 2 commits November 3, 2026 12:57
…l definition

The columns cache is keyed by the table UUID and the part name, and
`Context::clearCaches` did not clear it. A table moved to a database
without UUIDs (`RENAME TABLE` to an `Ordinary` database, or the move to
`<db>_broken_tables` done by `Replicated` database replica recovery) keeps
its parts, but its entries can no longer be removed under the old UUID.
A table created again with that UUID and the same columns then read the
moved table's data from the columns cache.

`ATTACH TABLE ... UUID ...` with a full definition creates a new table
when the data directory does not exist, so after `DROP TABLE ... SYNC`
it reuses the part names of the dropped table like `CREATE TABLE ... UUID`
does. Only the short `ATTACH TABLE t`, which attaches the same table
again, keeps the caches now.

Both cases were found by the automated review of the PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The server logs a warning about a deprecated Ordinary database once per
process, from the first query that creates one. When the test's
`CREATE DATABASE ... ENGINE = Ordinary` was that query (the first run on
a fresh server, as in the flaky check), the warning reached the client's
stderr and the test failed. Run that client call with
`--send_logs_level=error`, like the ATTACH section above.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 15, 2026
Merged via the queue into ClickHouse:master with commit f30d7ec Nov 15, 2026
187 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 15, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Nov 18, 2026
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]>
@Algunenano

Copy link
Copy Markdown
Member

@groeneai This seems like the wrong solution, and there are tons of associated issues with it (missed spots, full unnecessary flushes, etc).

I think we shouldn't flush all caches on table creation (seems quite dumb), instead we should adjust all caches so it's possible to flush them partially based on uuid during table drop/truncation. Please investigate that solution instead

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'm investigating per-UUID partial invalidation in every cache at DROP TABLE / TRUNCATE, to replace the flush on table creation that this PR added (as @ alexey-milovidov suggested above) and to cover #133219; I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I opened #133306, which replaces the flush on table creation added here. At DROP TABLE a table now removes its own entries: by UUID from the query condition and columns caches, and by its data path from the uncompressed, index uncompressed and mmap caches; text index cache ids include the index files' checksums. The clearCaches() calls on CREATE ... UUID and on Replicated replica recovery are removed, and #133219 (ON CLUSTER) is fixed.

TRUNCATE does not reuse part names by itself (the block number counter keeps going). They repeat only after the table is attached again, so that ATTACH removes the table's entries instead of the whole query condition cache. The PR depends on #121829 for projection marks.

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

5 participants