Repository navigation
Fix mark cache keys and eviction of projection parts - #121829
Conversation
A mark-cache key must identify the part that owns the marks. Two sites disagreed about that, and for a projection part they compose into a cache that is written and read under keys nothing else uses. MergeTreeMarksLoader's read path built the key from data_part_storage->getFullPath() = <disk>/<root_path>/<part_dir>/, while addMarksToCache and all three eviction sites (MergeTreeDataPartCompact::removeMarksFromCache, MergeTreeDataPartWide::removeMarksFromCache, IMergeTreeDataPart::removeIndexMarksFromCache) build it from getRelativePathOfActivePart() = <disk>/<root_path>/<name>/. The only difference is part_dir vs name, and for a projection part they differ permanently: DataPartStorageOnDiskFull::getProjection gives the projection storage part_dir = "<proj>.proj" while writeProjectionPart names the part "<proj>". An Active top-level part always has part_dir == name, which is why this stayed invisible. MergeTreeTemporaryPart::prewarmCaches() called addMarksToCache(*part, ...) for every entry of streams, but on the INSERT path streams also holds the projections' output streams: writeTempPartImpl moves them into the parent's list whenever finalize_projection_parts_synchronously is false, which is the default. A compact writer keys its cached marks by the literal "data", and addMarksToCache resolves both the filename and the key from the part it is handed, so a compact projection's marks were written under the parent's data.<ext> key with the projection's num_columns_in_mark. Composed, the two mean prewarm_mark_cache never warmed a projection's marks at all: the writer-side insert went to the parent's key, and even a correctly attributed insert at <parent>/<proj>/ would not have been found by a read that looks up <parent>/<proj>.proj/. The entries the read path did cache for a projection were keyed on a string no eviction site ever computes, so nothing could remove them. Both read sites now share one private getCacheKey() helper built from getFullRootPath() / getPartName() / mrk_path, so the expression exists once instead of twice and cannot drift apart again; getPartName() returns data_part->name, the same member getRelativePathOfActivePart() reads, so the keys are byte-identical. prewarmCaches() resolves the owning part per stream via getProjectionParts(). The index mark cache benefits from the same edit: its loaders also go through loadMarksSync, so its read key moves into agreement with its own eviction site at IMergeTreeDataPart.cpp:1060. This convention is already written down in tree, at IMergeTreeDataPart.cpp:742 and MergeTreeIndexReader.cpp:179, and both the primary index cache and the vector similarity index cache already use the name form on both sides. The data mark cache was the only part-level cache that did not. Alternatives considered and rejected: adding num_columns_in_mark to the key converts the MergeTreeMarksGetter assertion into a silent cache miss and leaves both the wrong-part write and the never-evicted entry in place; downgrading that assertion to CORRUPTED_DATA is the same objection, and the assertion is correct - after this change it is unreachable by construction; changing the eviction sites to getFullPath() instead contradicts the two in-tree comments, diverges from the other part-level caches, and would make an entry inserted while a part sat in a tmp_* directory unevictable after the rename, which is the same defect with the arrow reversed; gating the insert on getState() == Active, as MergeTreeIndexReader::read does for vector granules, is a perf change with a different justification, because marks are the hot path and a query under a transaction legitimately reads Outdated parts. Neither getFullRootPath() nor getPartName() costs more than getFullPath(), and getCacheKey() runs once per loader, not per mark. There is no compatibility surface: the change is confined to in-memory cache keys, with no on-disk format, no marks format, no setting and no versioning involved. The first read after an upgrade simply repopulates the cache. The new test 05243_mark_cache_projection_key asserts, from the per-query ProfileEvents in system.query_log, that a projection-served query records MarkCacheMisses = 0 and MarkCacheHits > 0 when prewarm_mark_cache = 1, and that the projection really served it so the oracle cannot pass vacuously. It is a per-query oracle on purpose: the mark cache is shared with every other test in a parallel run, which would make a global cache-size assertion both flaky and vacuous. The three settings that could silently disable the measured path are pinned in the table's own SETTINGS and the query's own SETTINGS rather than with a no-random-settings tag, and each of them was confirmed to turn the oracle red rather than vacuous when perturbed. The test fails with either edit applied alone and passes only with both, which is the reason one change touches two sites. Even so it carries no-parallel and no-parallel-replicas. The oracle is a cache-hit oracle, so another test's SYSTEM CLEAR MARK CACHE landing between the INSERT that warms the marks and the SELECT that reads them empties the cache it measures, and a projection cannot serve the query at all when parallel replicas run without a local plan or with aggregation in order. Re-warming instead of tagging is not available: SYSTEM PREWARM MARK CACHE does not recurse into projections, and its insert route is the read key, which would make the test pass with only one of the two edits.
Cut the two comment lines that narrated the fix's design; kept the pre-existing-property lines.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 gate findings plus 4 from my own
The one quantitative claim in the description was re-measured against the public CI database before Round 2 was a delta re-review of the single fix round (the tags line; Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260923-174200 |
|
Workflow [PR], commit [b77b018] Summary: ✅
AI ReviewSummaryThe PR aligns projection mark-cache keys across reads, insert prewarming, and eviction; preserves projection marks during synchronous finalization; and clears projection caches before detach. Review of Missing context / blind spots
Final VerdictStatus: ✅ Approve |
`prewarm_mark_cache` warmed the marks of the projection parts an INSERT writes only when `finalize_projection_parts_synchronously` is 0. With the setting on, each projection stream's finalizer is finished in place and the projection's temporary part is destroyed at the end of the loop iteration, so the stream never reaches `temp_part->streams` and `prewarmCaches()` never sees its cached marks: the projection's marks were dropped instead of inserted. Measured on the previous head of this PR (build id d17331439dca), with `prewarm_mark_cache = 1` and a projection-served aggregation: finalize_projection_parts_synchronously = 0 -> MarkCacheHits 1, Misses 0 finalize_projection_parts_synchronously = 1 -> MarkCacheHits 0, Misses 1 and on this head (build id c6321883f121) both modes report 1 hit / 0 misses. Pristine master (95a6488) fails both arms of the test, 1 0 0. The finished stream's marks are taken where the stream is released and warmed after the part is renamed, which is the only point where the cache key names the final path. Only the mark maps are kept (60 bytes for the test's projection part; marks x columns x 16 bytes in general), not the writer buffers that branch exists to free, so the setting's memory reduction is preserved. Nothing is kept when prewarming is off, because the writer then caches no marks and both maps come back empty.
…t-evict-key Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 0527953Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261017-143010 |
|
The key mismatch this PR fixes is also reachable as a failing query. On 26.10.2.103: CREATE TABLE pd (a UInt64, b UInt64, PROJECTION p (SELECT a, b ORDER BY b))
ENGINE = MergeTree ORDER BY a SETTINGS old_parts_lifetime = 0;
INSERT INTO pd SELECT number, number FROM numbers(100000);
SELECT sum(b) FROM pd WHERE b < 300000 SETTINGS force_optimize_projection = 1;
TRUNCATE TABLE pd; DETACH TABLE pd; ATTACH TABLE pd;
INSERT INTO pd SELECT number, number * 3 FROM numbers(300000); -- all_1_1_0/p.proj again
SELECT sum(b) FROM pd WHERE b < 300000 SETTINGS force_optimize_projection = 1; -- expected 14999850000The last query fails with #125404 fixes the same mismatch from the other side: it makes |
|
The key alignment looks correct, but the detach path still leaves projection marks in the cache. |
`forcefullyMovePartToDetachedAndRemoveFromMemory` clears the caches of the part before `renameToDetached`, because the rename changes the root path that the cache keys are built from. It cleared only the parent part: its projection parts cleared their own entries later, when they were destroyed, by which time `changeRootPath` had moved their keys under `detached/`, so the entries of the active path stayed in the mark cache. A part attached back under the same name (`SYSTEM RESTORE REPLICA`, or a part fetched again after being detached as broken or not byte-identical) then read the marks of the detached one. `clearCaches` now calls `clearCaches` of each projection part, which also covers the index mark cache, the primary index cache and the statistics cache of projections, and replaces the loop that did this for the columns cache only. `removeIndexMarksFromCache` enumerated the indices of the table for a projection part too, while a projection part holds the indices of its projection (the implicit minmax indices enabled by `add_minmax_index_for_*` in the projection's `WITH SETTINGS`), so their index marks were never evicted, not even by `DROP TABLE ... SYNC`. It now uses the projection's metadata. `ALTER TABLE ... DETACH PART` is not affected: it clones the part into `detached` and removes the original under its own path. Co-Authored-By: Claude Opus 5.5 <[email protected]>
prewarm_mark_cache warms projections|
Thanks, confirmed and fixed in d28a021.
I also changed the category to Bug Fix: the repro now in the description fails with |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units310 translation units recompiled, 3439 s compile time in total, 310 of them have a recent master baseline. |
…cleared `forcefullyMovePartToDetachedAndRemoveFromMemory` clears the caches of a part before renaming it to `detached`, and that part may still be held by a running read, which can write columns cache entries again afterwards. The comments in `clearCaches` and `ColumnsCache::removePart` described only the destructor and the uniquely owned outdated parts, where no reader is left. Comments only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
54bae75
Related: #107302
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
Mark index N is out of range(LOGICAL_ERROR) and similar errors in queries served by a projection after a part with the same name was created again, for example afterTRUNCATEorSYSTEM RESTORE REPLICA: the mark cache entries of projection parts were not evicted.prewarm_mark_cachenow also warms the marks of the projection parts anINSERTwrites.Description
On 26.10.2.103 and 26.8.34.13 the queries below fail with
Code: 49 ... Mark index 26 is out of range [0, 26)(26.3.60.2:Unknown codec family code): the projection read finds the marks of the projection part thatTRUNCATEremoved.A mark cache key must identify the part that owns the marks. Fixed sites:
getFullPath(), which is<part>/<name>.proj/for a projection, while the insert and every eviction site key ongetRelativePathOfActivePart()=<part>/<name>/. Both read sites now share onegetCacheKey();prewarmCaches()added the marks of projection streams under the parent part, and dropped them withfinalize_projection_parts_synchronously = 1; each stream is now attributed to its own part;clearCaches()cleared only the part itself. A projection cleared its entries when destroyed, but onforcefullyMovePartToDetachedAndRemoveFromMemory(SYSTEM RESTORE REPLICA, broken or not byte-identical parts) that is afterrenameToDetachedmoved its keys underdetached/. It now clears the projection parts too, replacing the loop that did this for the columns cache only;removeIndexMarksFromCache()used the table's indices for a projection part, so the marks of a projection's own implicit minmax indices were never evicted.ALTER TABLE ... DETACH PARTclones the part and was not affected.Tests:
05243_mark_cache_projection_key(a prewarmed projection read has no misses, both finalization modes) and05243_mark_cache_projection_key_detached(afterSYSTEM RESTORE REPLICAa projection read loads its data and index marks again). Both fail on master, the second also with only theclearCaches()change; 30 randomized runs each are green.The mismatch is also the only way to reach
LOGICAL_ERROR: Number of marks N is not divisible by number of columns in mark M(7Stress testaborts in 150 days, latest 2026-08-28arm_msan); I could not reproduce that abort locally.Repro
Workflow [PR]
Sync PR [sync-upstream/pr/121829]
Version info
26.12.1.243-master(included in26.12and later)