Skip to content

Fix stale text index and uncompressed cache results after a part directory is reused - #128715

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:part-file-caches-keyed-by-checksum
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:part-file-caches-keyed-by-checksum

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 after TRUNCATE or ALTER TABLE ... DROP PARTITION followed by DETACH TABLE / ATTACH TABLE and a new INSERT: the new part reused the directory of a removed part, and the text index caches (on by default), the uncompressed cache and the index uncompressed cache returned the removed part's data, so hasToken and similar filters, sum and skip indexes could see the old rows or fail with UNKNOWN_CODEC or CORRUPTED_DATA. These caches are now keyed by the checksum of the part file as well as its path.

Description

Related: #116853 (the trigger without a UUID clause is in #116853 (comment)).

On 26.10.2.103, at default settings:

CREATE TABLE t (k UInt64, s String, INDEX idx s TYPE text(tokenizer = splitByNonAlpha)) ENGINE = MergeTree ORDER BY k SETTINGS old_parts_lifetime = 0;
INSERT INTO t SELECT number, if(number < 10, 'apple', 'pear') FROM numbers(100000);
SELECT count() FROM t WHERE hasToken(s, 'apple');   -- 10
TRUNCATE TABLE t; DETACH TABLE t; ATTACH TABLE t;
INSERT INTO t SELECT number, if(number = 99999, 'apple', 'pear') FROM numbers(100000);
SELECT count() FROM t WHERE hasToken(s, 'apple');   -- 10, expected 1

After DETACH/ATTACH the block numbers restart from the parts on disk, so the new part is all_1_1_0 again, in the removed part's directory. The mark, primary index and similar caches are evicted per part, but the uncompressed caches (one entry per compressed block) and the text index caches (one entry per token or posting block) are keyed by the file path only and cannot be evicted per part.

The fix adds the file's checksum from the part's checksums.txt to these keys (for a member of skp_idx.packed, the archive's checksum). A file written again at the same path misses; identical files still share entries. A stream without a checksum is read without the uncompressed cache.

The new test covers wide and compact parts, both skip index layouts, and a larger new part. It fails on master and passes 50/50 with the fix.

Not changed here: the mmap cache is keyed by the local path in the disk layer (#128738 fixed the userspace page cache of local disks), and the mark cache entries of projection parts are loaded and evicted under different keys, which #121829 fixes. #128677 clears the caches when a table is created with an explicit UUID, which does not cover this trigger.


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

groeneai and others added 2 commits November 2, 2026 16:44
…e checksum

A MergeTree part directory can hold different files over the life of a server
process: after `TRUNCATE` (or `DROP PARTITION` of the newest partition) and
`DETACH`/`ATTACH`, the block numbers restart from the parts on disk, so the
next `INSERT` writes `all_1_1_0` again into the directory of the removed part.
The same happens when a table is created again with the UUID of a dropped one.

The mark, primary index, statistics and vector index caches are evicted per
part when the part is removed. The uncompressed cache, the index uncompressed
cache (`UncompressedCache::hash(path, offset)`, one entry per compressed block)
and the text index tokens, header and postings caches
(`makeIndexIdForCaches` = disk:path:index) cannot be evicted that way, because
their keys are not enumerable from the part, and `dropAllData` clears the
server-wide caches only for tables without a UUID. Their entries outlive the
part and are returned for the new part at the same path: `sum` over the old
rows, `Code: 432 UNKNOWN_CODEC` (or a `LOGICAL_ERROR` in
`MergeTreeRangeReader`) when the new file is larger, a skip index that drops
matching granules, and a text index that returns the old part's row numbers or
`Code: 246 CORRUPTED_DATA`. The text index caches are on by default.

Add the content token that the part already has in memory to the keys: the
`file_hash` of the file from the part's checksums. A file written again at a
reused path has another checksum, so the lookup misses; identical files still
share entries, also across `DETACH`/`ATTACH`. A member of `skp_idx.packed` has
no checksums entry of its own and uses the archive's checksum, resolved by the
same lookup as `indexFileExistsInChecksums`. A stream without a checksum is
read without the uncompressed cache, and a text index without a checksum for
its header file gets an identifier that no other reader can find.

The mmap cache and the userspace page cache for local disks are keyed in the
disk layer by the local path and are not changed here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the design note above makeIndexIdForCaches and shorten the getFileHashForCaches doc to one line.

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) plus my own review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test asserts results only, so it could pass if the caches declined; header and postings cache keys are not tested one by one DISAGREE The test fails on master every run (no random settings, and 19 of 19 randomized runs); reverting each half of the fix reddens only its own cases. Cache hits on the fixed build were checked in system.query_log locally; hit counters are not asserted in the test because the caches are server-wide and shared with the parallel suite. All text index cache keys come from one identifier (makeIndexIdForCaches), so they cannot diverge.
2 💡 makeIndexIdForCaches has a fallback for a header file without a checksum that a granule read cannot reach noted not blocking
3 💡 makeIndexReaderStream resolves the file name twice (size, checksum) noted not blocking, two map lookups per stream
4 💡 The test relies on TRUNCATE deleting the old part directory immediately, which a concurrent holder of the part could delay noted not blocking, the window is the TRUNCATE call

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

Session id: cron:clickhouse-review-self-slot-58:20261102-165000

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. TRUNCATE + DETACH/ATTACH + INSERT, then the same query: text index count() 10 instead of 1 at default settings, use_uncompressed_cache = 1 gives the old sum (4950 instead of 9900) or Code: 432, a minmax index read through the index uncompressed cache drops the matching granule (0 instead of 1). Same on master and on 26.10.2.103, every run.
b Root cause explained? The block counter restarts from the parts on disk, so the new part reuses a removed part's directory. The uncompressed caches and the text index caches are keyed by the file path only and are not evicted per part (their keys are not enumerable from the part), so the new part reads the removed part's blocks, tokens and postings.
c Fix matches root cause? Yes. The keys get the content token of the file (its checksum from checksums.txt; the archive's checksum for a member of skp_idx.packed). No eviction hook, no cache scan, no change to part naming or to when caches are cleared.
d Test intent preserved / new tests added? New stateless test: text index, uncompressed cache and minmax index, wide and compact parts, both skip index layouts, same-size and larger new part. It asserts that system.parts is empty after TRUNCATE and that the new part is all_1_1_0, so the path is really reused.
e Both directions demonstrated? Master: the test fails without random settings and in 19/19 randomized runs; one run hit a LOGICAL_ERROR in MergeTreeRangeReader on a debug build. Fix: 50/50 randomized runs pass. Reverting only the text index part fails only the text cases; reverting only the uncompressed cache part fails only the uncompressed and minmax cases.
f Fix is general across code paths? UncompressedCache::hash has one caller (CachedCompressedReadBuffer), created only in MergeTreeReaderStream::init; every stream construction site passes a checksum. Every text index cache key derives from makeIndexIdForCaches. Projection parts are covered too (measured). The mmap cache and the local-disk page cache are keyed in the disk layer and are not changed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Wide and compact parts, skp_idx.packed members and own files, packed part storage, projection parts, hashed long file names, a larger new file, and the DROP PARTITION path. Nothing in the change depends on the column type.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; the keys exist only in memory. A stream that has no checksums entry (only parts whose checksums.txt is in the oldest format) is read without the uncompressed cache.
i Invariants and contracts preserved? A key now identifies the decompressed block at an offset of one particular file content. Files with the same checksum still share entries, which is correct because their bytes are identical. The lazy seek and read_until_position logic of CachedCompressedReadBuffer is unchanged, and indexFileExistsInChecksums keeps its resolution order through the shared lookup.

Session id: cron:clickhouse-impl-self-slot-57:20261102-152400

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1e9778d]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
Build ClickHouse FAIL
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED
Integration tests (amd_asan_ubsan, db disk, targeted) DROPPED
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) DROPPED

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

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @ahmadov @CheSema, could you review this and add the can be tested label so CI runs? After TRUNCATE or DROP PARTITION plus DETACH/ATTACH a new part reuses a removed part's directory, and the text index caches and the uncompressed caches, keyed by the file path only, served the removed part's data; their keys now also include the file checksum from checksums.txt.

@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 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1e9778d37 with master 8a35900e2 (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

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

Job report

groeneai and others added 2 commits November 17, 2026 13:31
…yed-by-checksum

# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexReader.cpp
Master now answers an unfiltered `sum` from the per-part `basic` statistics
(`use_statistics_for_sum_avg_aggregation`, enabled by default, with the
statistics materialized on insert), so the uncompressed cache cases of the
test never read the column files and passed without the fix. Disable it for
the test, as `05483_local_disk_page_cache_file_rewritten_at_same_path` does.

Measured on master 9b10750 (debug): with the setting at its default the test
passes the uncompressed cache lines; with it disabled it fails with
`Code: 432 UNKNOWN_CODEC` on `uc_wide_larger`, also in 10 of 10 randomized
runs. With the fix the test passes once without random settings and in 50 of
50 randomized runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
-- directory of the removed part. The caches keyed by a file path must not return the data of the removed part.

-- Only the caches under test are used.
SET use_query_condition_cache = 0, use_skip_indexes = 1, min_bytes_to_use_mmap_io = 0, use_page_cache_for_local_disks = 0, use_uncompressed_cache = 0;

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] The same part-name reuse still returns wrong results through QueryConditionCache, which is disabled here. I reproduced this on the PR-head Fast test binary (1e9778d37d0214d73f1384903559522988ab1fbc), with use_query_condition_cache at its default 1. In an Atomic database:

CREATE TABLE t (k UInt64, s String,
    INDEX idx s TYPE text(tokenizer = splitByNonAlpha))
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; -- 0; warms the cache
TRUNCATE TABLE t;
DETACH TABLE t;
ATTACH TABLE t;
INSERT INTO t VALUES (2, 'apple'); -- all_1_1_0 again
SELECT sum(k) FROM t WHERE length(s) = 5; -- 0, expected 2
SELECT sum(k) FROM t WHERE length(s) = 5
SETTINGS use_query_condition_cache = 0; -- 2

MergeTreeDataSelectExecutor.cpp:2318 still looks up the old (table UUID, part name, condition hash) entry; neither part cleanup nor short ATTACH TABLE invalidates it. The new file checksums therefore never protect this lookup. This is a pre-existing sibling defect, but it is reached by the exact lifecycle sequence this fix handles, without an explicit UUID or table recreation.

Please cover this cache too with a focused regression, or explicitly link a dedicated follow-up issue for this no-explicit-UUID trigger. The explicit-UUID creation fix does not cover short ATTACH TABLE.

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.

Confirmed on master (which has #128677): the query condition cache keys entries by table UUID and part name, so the re-attached table's new all_1_1_0 reuses the old entry, and a new part with more marks aborts the server in filterPartsByQueryConditionCache. This PR does not touch that cache, so I am fixing it in a separate PR that will reference this one.

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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 20, 2026
… new parts

The refresh of a read-only table forgot the unlisted parts only after it had
committed the newly listed ones. When the writer reuses the name of a removed
part (its block numbers restart from the parts on disk after TRUNCATE + DETACH /
ATTACH, or when the table is created again on the same path), the reader's
vanished covering part made `Transaction::commit` mark the new part Outdated,
and the reader returned 0 rows permanently.

Such parts (not covered by any listed part) are now forgotten before the new
parts are loaded. The unlisted parts a listed part covers are still forgotten
after the commit, so a merged part that replaces its sources stays atomic for
concurrent queries.

A forgotten name can then be given to a new part, so the query condition cache,
keyed by table UUID, part name and condition, would keep the old verdicts for it.
It is cleared when such a part is forgotten, as `StorageMergeTree` does on ATTACH.

The test case also pins `use_uncompressed_cache = 0`: that cache is keyed by the
file path only and returns the removed part's blocks for a reused path, on the
writer as well (fixed separately in ClickHouse#128715).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexbakharew alexbakharew reopened this Nov 24, 2026
@alexbakharew

Copy link
Copy Markdown
Contributor

Closed by accident, sorry

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.

2 participants