Skip to content

Remove the cache entries of a dropped table instead of dropping all caches when a table is created with a UUID - #133306

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:per-uuid-cache-invalidation
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:per-uuid-cache-invalidation

Conversation

@groeneai

@groeneai groeneai commented Nov 20, 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, Cannot read all data errors and a possible server abort when a table was created again with the UUID of a dropped table (for example through ON CLUSTER): the uncompressed, mmap, text index and query condition caches served the dropped table's data. A dropped table now removes its own entries from these caches, and CREATE TABLE with an explicit UUID no longer drops all caches.

Description

On 26.10.8.35 (also 26.8, 26.9: #133219), CREATE TABLE ... UUID ... ON CLUSTER or a full-definition ATTACH after DROP TABLE ... SYNC returns the dropped table's rows from the uncompressed cache.

A table re-created with a dropped table's UUID gets its data path and part names. The query condition cache (keyed by UUID and part name), the uncompressed and mmap caches (keyed by file path) and the text index caches do not evict them per part. #128677 dropped all caches on CREATE ... UUID and on Replicated recovery, which misses ON CLUSTER and Replicated DDL. As @ Algunenano asked in #128677 (comment), this replaces that flush (@ alexey-milovidov's suggestion):

  • DROP TABLE of any engine removes its query condition cache entries (File, S3 and URL tables have them too) and its store/ path from the mmap cache (Log tables use it with use_reader_executor). Nothing uses the table or its UUID then, so every creation path is covered.
  • dropAllData of a MergeTree table with UUID removes its columns cache entries and its data path from the uncompressed, index uncompressed and mmap caches.
  • The text index cache id includes the index files' checksums.
  • A runtime ATTACH (part names can repeat after TRUNCATE) removes the table's entries, not the whole query condition cache (Fix wrong results and a server abort from the query condition cache after a MergeTree table is attached again #132457). TRUNCATE takes only a shared lock and reuses no name.
  • A move into a database without UUIDs (also Replicated recovery's _broken_tables) drops the caches.

Projection marks are evicted per part only with #121829 (else reading a re-created table with a projection fails): merge after it. Removal scans the whole query condition cache under its lock (~9 ms per 100k entries, debug build).

The tests fail on master, pass 50/50 randomized.

Closes: #133219
Depends on: #121829
Related: #128677
Related: #132457
Related: #128715
Related: #132791

🤖 Generated with Claude Code


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

groeneai and others added 5 commits November 20, 2026 14:46
…hing them at creation

A MergeTree table created again with the UUID of a dropped table gets the
same data path and restarts its block numbers, so its parts get the names
and file paths of the dropped table's parts. The query condition cache
(keyed by UUID and part name), the uncompressed caches and the mmap cache
(keyed by file path) and the text index caches (keyed by the index file
path) are not evicted per part, so they served the dropped table's entries
to the new one: wrong results, `Cannot read all data`, or the libc++
hardening abort in `filterPartsByQueryConditionCache` (STID 6387-6640).

ClickHouse#128677 compensated by calling `Context::clearCaches()` on `CREATE TABLE`
with an explicit UUID and on Replicated database replica recovery. That
misses every creation the initiator does not run itself (`ON CLUSTER`, the
DDL of a Replicated database: ClickHouse#133219) and flushes every cache of every
table on each such CREATE.

Now the old incarnation removes its own entries when it ends:
`MergeTreeData::clearCachesOfTable` removes the table's query condition
and columns cache entries by UUID (`QueryConditionCache::Entry` keeps the
table UUID in all builds) and the uncompressed, index uncompressed and
mmap cache entries under the table's data paths (the uncompressed cache
cell keeps the path of its file). It is called from `dropAllData` for
tables with UUID, after the parts are removed, where no query can hold the
table any more and the UUID cannot be reused yet, so every creation path
is covered without knowing it. The text index caches cannot be selected
per table (the tokens cache shares entries between tables), so the index
id they are keyed by also includes the checksums of the index files: a new
part at the same path does not find the old entries.

A runtime `ATTACH` numbers new parts from the parts on disk, so after
`TRUNCATE` or `DROP PARTITION` new parts can take the names and paths of
removed ones: the `StorageMergeTree` constructor calls
`clearCachesOfTable` there instead of clearing the whole query condition
cache (ClickHouse#132457). `TRUNCATE` itself is not a call site: it takes only a
shared lock, so a running SELECT can write entries after it, and it never
reuses a part name. A table renamed into a database without UUIDs gives
its UUID up while its parts stay, so it flushes the caches like a table
without UUID does.

The two flushes added by ClickHouse#128677 are removed.

Closes ClickHouse#133219

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`MergeTreeData::dropAllData` returns early when every disk of the table is
read-only or write-once, before `clearCachesOfTable`, so the query
condition cache kept the entries of such a table after `DROP TABLE`,
keyed by its UUID and part names, for a table attached again with that
UUID to find. Remove them before that return as well.

A table moved from an Atomic to an Ordinary database (also by Replicated
recovery into `<db>_broken_tables`) gives its UUID up while its files
stay. The caches are now dropped there in `DatabaseOnDisk::renameTable`,
for every engine, and `MergeTreeData::rename` is as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `use_reader_executor = 1`, `LocalSourceReader` passes the file size to
`createReadBufferFromFileBase`, so `Log`, `TinyLog` and `StripeLog` reads
map their files through the global mmap cache, keyed by file path, offset
and size. Their `drop` only removes the files, so a table created again
with the dropped table's UUID, so under the same `store/` path, read the
old mapping when its file had the same size (`Log` with `CODEC(NONE)`:
count 0 instead of 50).

`DatabaseCatalog::dropTableFinally` now removes the mappings under the
table's `store/` path on every disk before the UUID can be reused. It
derives the path from the UUID instead of calling `getDataPaths`, which
would load the nested table of a `StorageTableProxy` again after its drop.
`TRUNCATE` of these engines already clears the mmap cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `Log` section relies on the reader executor, which can fall back to the
legacy read path (async prefetch, the distributed cache, unsupported
sources). That path does not map these files, so the counts would be the
same with and without the `dropTableFinally` removal. Both reads now run
with a query id, and the test checks in `query_log` that each of them hit
or missed the mmap cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove two comments that restate the field and function names (UncompressedCacheCell::path, QueryConditionCache::removeTable).

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). Reviewed head ff2ee71.

# Sev Finding Verdict Evidence
1 ⚠️ dropAllData returned before removing the cache entries of a table on read-only disks AGREE, fixed Entries of the dropped UUID after DROP TABLE: 1 before, 0 after.
2 ⚠️ Log tables read through the mmap cache with use_reader_executor, and nothing removed their mappings at drop AGREE, fixed dropTableFinally removes the store/ path; the re-created Log table read 0 instead of 50 before (1 mmap cache hit), 50 after.
3 ⚠️ The tests could pass with the caches never consulted DISAGREE Each cache removal has a mutation that turns its section red, and every section fails on master; a hit oracle would need no-parallel.
4 ⚠️ The Log section stays green if the experimental reader executor falls back AGREE, fixed The legacy path does not map these files, so the section now also checks that both reads went through the mmap cache (0 instead of 2 with use_reader_executor = 0).
5 ⚠️ Temporary Log tables with an explicit UUID keep their mappings after drop DISAGREE Not covered on master either (the temporary table branch returns before the removed flush); needs the experimental use_reader_executor.

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

Session id: cron:clickhouse-review-slot-48:20261120-195600

@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c89c1d4]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

⚠️ Review sessions stopped as a cybersecurity risk

The model provider stopped these review sessions as a possible cybersecurity risk:

  • attempt 1: gpt-6.1-sol

This summary comes from a session with gpt-5.4. A session is typically stopped when it reaches a memory-safety finding, and the finding is lost with it, so this review can miss a real defect. Please review the change in detail, and run the review internally with a model that has cyber access.

Summary

This PR replaces the broad CREATE ... UUID cache flush with targeted invalidation on drop / attach / rename, which is the right direction, but one UUID-keyed content cache is still left behind for external Parquet tables. As written, a dropped File / S3 / URL table recreated with the same UUID can still reuse stale decoded columns from the ColumnsCache and return wrong results, so I cannot approve it yet.

Findings
  • ❌ Blockers
    • [src/Interpreters/DatabaseCatalog.cpp:1955] The common final-drop path still leaves external-file Parquet ColumnsCache entries keyed by the table UUID. StorageFile / object-storage readers write those entries under the table UUID (src/Storages/StorageFile.cpp:2259, src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:2083), but DatabaseCatalog::dropTableFinally now removes only query-condition and mmap entries. After this PR removes the CREATE ... UUID global clearCaches(), recreating a File / S3 / URL table with the same UUID can therefore reuse stale decoded columns and return wrong results. A concrete repro is a Parquet file with column K: first read it with input_format_parquet_case_insensitive_column_matching = 0 and use_columns_cache = 1, then recreate the same UUID with matching enabled. The Parquet columns-cache identity does not hash that setting (src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp:141, src/Processors/Formats/Impl/Parquet/Reader.cpp:5127), so the second incarnation can still see the old all-default k column.
    • Suggested fix: invalidate ColumnsCache entries for table.table_id.uuid in DatabaseCatalog::dropTableFinally (or keep the create-time flush until that invalidation exists), and add a focused regression that recreates a Parquet external-file table with the same UUID and different stored reader settings.
Final Verdict

Status: ❌ Block

  • Invalidate external-file ColumnsCache entries on final drop, or keep the create-time cache flush until that invalidation exists.
  • Add a regression covering use_columns_cache = 1 for a Parquet File / object-storage table recreated with the same UUID and different reader settings.

@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 20, 2026
Comment thread src/Interpreters/DatabaseCatalog.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e0f0750ff with master 57aa10da3 (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

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

Job report

…gine

`File`, `S3` and `URL` tables write query condition cache entries under
their UUID too, but only `MergeTreeData::dropAllData` removed entries by
UUID. Without the flush on `CREATE ... UUID` that this PR removes, a table
created again with the UUID of a dropped `File` table over the same file
reused its verdicts: with other reader settings (e.g.
`input_format_parquet_case_insensitive_column_matching`) a query returned
0 instead of 1000 rows. Found by the clickhouse-gh review.

The removal moves to `DatabaseCatalog::dropTableFinally`, next to the mmap
cache one, so a `MergeTree` DROP still scans the cache once. The runtime
`ATTACH` of a `MergeTree` table, where part names can repeat, removes them
itself. The read-only-disk call in `dropAllData` is gone: the drop path
covers the query condition cache there, and the other caches serve the
same unchanged files.

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

/// The UUID, so the data path, can be reused after this, and these caches are keyed by them.
if (auto query_condition_cache = getContext()->getQueryConditionCache())
query_condition_cache->removeTable(table.table_id.uuid);

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.

[Blocker] This common final-drop path still leaves the external-file ColumnsCache behind. StorageFile and object-storage Parquet readers populate columns-cache entries under the table UUID (src/Storages/StorageFile.cpp:2259, src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:2083), but here we remove only the query-condition and mmap entries. After this PR removes the CREATE ... UUID global clearCaches(), a dropped File / S3 / URL table recreated with the same UUID can therefore reuse stale decoded columns from the old incarnation and return wrong results.

A concrete repro is a Parquet file with column K: read it once through a table with use_columns_cache = 1 and input_format_parquet_case_insensitive_column_matching = 0, then recreate the table with the same UUID and matching enabled. The Parquet columns-cache identity does not hash that setting (src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp:141, src/Processors/Formats/Impl/Parquet/Reader.cpp:5127), so the second incarnation can still see the cached all-default k column.

Please invalidate ColumnsCache entries for table.table_id.uuid in DatabaseCatalog::dropTableFinally (or keep the create-time flush until that invalidation exists) and add a focused regression for a Parquet external-file table recreated with the same UUID under different stored reader settings.

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.

Measured on c89c1d4: the second table returns sum(k) = 1000, the same as with use_columns_cache = 0, because a column missing from the file is never written to the columns cache, and a cached column's identity already includes the file version, the file column it is read from and its types (Reader::initColumnsCache). So a table created again with the same UUID can only hit entries that decode to the same values, as file() already does when this setting changes between queries that all share the nil UUID.

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Table recreated with a dropped table's UUID through ON CLUSTER reads the dropped table's data from the uncompressed cache

1 participant