Repository navigation
Recalculate TTL infos on merges that apply patch parts - #116175
valerypetrov wants to merge 92 commits into
Conversation
The zero-read shortcut for fully expired parts was gated on the assigned merge type. When TTL merge admission is unavailable, selection falls through to a Regular merge that drops exactly the same rows, so it still opened and read every source part. The shortcut now also applies when the source parts' own TTL metadata proves that every row is expired at time_of_merge, independently of the assigned type. It stays conservative for partial expiry, incomplete TTL metadata and every TTL family other than an unconditional rows TTL. Closes ClickHouse#116172
|
Workflow [PR], commit [3dbbd5a] Summary: ❌
AI ReviewSummaryThis PR recalculates TTL metadata when merges apply lightweight patches, adds metadata recalculation while TTL merges are stopped, and repairs The extended Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Make zero-TTL preservation durable across subsequent TTL passes and add the focused regressions above. |
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Extends the existing TTLDrop “no-read” merge shortcut to also apply to non-TTLDrop merges when all source parts are provably fully expired, preventing unnecessary reads during regular-merge fallbacks.
Changes:
- Broadened merge short-circuit logic to detect fully expired source parts via per-part TTL metadata even when merge type is
Regular. - Updated logging/comments to reflect the broader short-circuit condition.
- Added a new stateless test case covering the regular-merge fallback scenario and updated expected output.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
src/Storages/MergeTree/MergeTask.cpp |
Adds metadata-based detection for “all parts fully expired” and uses it to skip building the read pipeline even for non-TTLDrop merges. |
src/Storages/MergeTree/MergeTask.h |
Clarifies the meaning of the short-circuit flag now that it applies beyond MergeType::TTLDrop. |
tests/queries/0_stateless/04267_ttl_drop_merge_no_data_read.sh |
Adds Case 8 to validate that a Regular merge over fully expired parts reads 0 rows when TTL admission is unavailable. |
tests/queries/0_stateless/04267_ttl_drop_merge_no_data_read.reference |
Adds expected output for the new test Case 8. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| SYSTEM STOP MERGES t_ttl_regular_fallback; | ||
|
|
||
| INSERT INTO t_ttl_regular_fallback (id, value) SELECT number, randomString(100) FROM numbers(100); | ||
| INSERT INTO t_ttl_regular_fallback (id, value) SELECT number, randomString(100) FROM numbers(100); | ||
|
|
||
| SYSTEM START MERGES t_ttl_regular_fallback; | ||
|
|
||
| OPTIMIZE TABLE t_ttl_regular_fallback FINAL; |
There was a problem hiding this comment.
Case 8 was reworked since: merges are never stopped at all (no START MERGES / OPTIMIZE window), max_number_of_merges_with_ttl_in_pool = 0 is the deterministic saturated state, and the part_log check filters length(merged_from) > 1 with DISTINCT so a racing background Regular merge produces the same (rows, read_rows) pair. The head comment spells this out.
| const bool can_short_circuit_ttl_drop = | ||
| global_ctx->future_part->merge_type == MergeType::TTLDrop | ||
| && global_ctx->metadata_snapshot->hasOnlyRowsTTL(); | ||
| global_ctx->metadata_snapshot->hasOnlyRowsTTL() | ||
| && (global_ctx->future_part->merge_type == MergeType::TTLDrop || all_source_parts_fully_expired()); |
There was a problem hiding this comment.
The predicate went away entirely: at the current head the shortcut is again gated on merge_type == MergeType::TTLDrop only (the per-part expiry proof was withdrawn because ALTER MODIFY TTL ... materialize_ttl_after_modify = 0 makes part-local infos unprovable — Case 11 pins that), so can_short_circuit_ttl_drop is a literal description again.
…se 8 Two review points: - The short-circuit no longer applies only to TTLDrop merges: a regular merge whose source parts prove full expiry takes it too. Renamed the flag to can_short_circuit_fully_expired_merge. - Case 8 restarts background merges before OPTIMIZE, so a background merge can run alongside it and which entry is newest is a race. The check now asserts every qualifying merge short-circuited rather than picking the most recent, which removes the race and is a stronger claim: one non-short-circuiting merge would add a second row. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes15 object files changed (+72.15 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units288 translation units recompiled, 3080 s compile time in total, 288 of them have a recent master baseline. |
|
📊 Cloud Performance Report 🟢 AI verdict: This PR only changes how TTL info is recalculated during merges that apply patch parts, plus disk-space estimates and tests. None of that runs when ClickBench or TPC-H read from their tables, which have no TTL. I downgraded the Q33 (-9.1%) and Q34 (-7.9%) improvements to not sure, because both medians sit inside master's normal range and both queries have noisy history. Q20 (-45.0%, with CPU time also lower) is large enough to hit the hard trust lock, so it stays an improvement, but it is very unlikely to come from this diff: a baseline or build mismatch is the more likely cause, and the source runs for both benchmarks shared one machine. clickbench🟢 1 improved · Flagged queries (4 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
table_ttl.finished() is only set true by TTLDeleteAlgorithm when the part's cached max TTL has already expired, which means every row is dropped and the part ends up empty. The isEmpty() check right above already catches every such part, so this branch can never be taken. Co-Authored-By: Claude Opus 5 <[email protected]>
The proof that every row is expired comes from each source part's own ttl_infos, which were written before any lightweight update. Patches are applied by the merge itself, and a patch may move the rows-TTL column into the future, so those rows are still alive even though the base parts look fully expired. Skipping the read pipeline then finalizes an empty part and loses them. The guard covers the pre-existing TTLDrop arm as well, not only the one this PR adds: MergeSelectorApplier::pack() attaches patches for every merge type it produces, TTLDrop included, so that arm could reach the same state. Case 9 covers it: a hundred expired rows, ten of them un-expired by a lightweight update, must all survive the merge. Co-Authored-By: Claude Opus 5 <[email protected]>
| /// No rows at all, so nothing can be unexpired. | ||
| if (part->isEmpty()) | ||
| continue; | ||
| const time_t part_max_ttl = part->ttl_infos.part_max_ttl; | ||
| if (!part_max_ttl || part_max_ttl > global_ctx->time_of_merge) | ||
| return false; |
There was a problem hiding this comment.
This resolved itself when the per-part predicate was withdrawn (see the sibling thread): there is no part_max_ttl == 0 check at head any more — only assigned TTLDrop merges take the shortcut, and the finished()/empty-part special cases went with it.
| LOG_DEBUG(ctx->log, "Skipping data pipeline: all {} source parts are fully expired", | ||
| global_ctx->future_part->parts.size()); | ||
|
|
There was a problem hiding this comment.
At the current head the log line's condition is unambiguous again — the shortcut fires only for merge_type == MergeType::TTLDrop, and merges carrying patches never reach it (guard + the new f362599 handling), so the message names the only possible reason ("TTLDrop merge: skipping data pipeline...").
Case 9 expected the patched rows to survive the merge. They do not, and not because of the shortcut: TTL filtering runs before patches are applied, so moving the rows-TTL column into the future does not rescue a row. A build without the shortcut drops them too, which makes the row count useless for telling the two apart. What the guard does change is whether the source parts are read at all. The merge has to open them to apply the patch, so it reports read_rows = 100 where a short-circuited merge reports 0 -- the same signal Case 8 already uses. SELECT DISTINCT for the reason Case 8 has it: more than one merge may be logged. Co-Authored-By: Claude Opus 5 <[email protected]>
The shortcut proved expiry from each part's own ttl_infos and never asked whether TTL removal was allowed for this merge. OPTIMIZE TABLE ... FINAL always assigns MergeType::Regular, so after the previous commit it reached the proven-expiry arm and finalized an empty part even with TTL merges stopped -- deleting rows the operator had explicitly protected. Before this PR that same statement fell through to the pipeline, which skips its TTL step under the same condition and kept them. Gating on need_remove_expired_values reuses the flag the pipeline already consults, so both paths stay in agreement instead of drifting apart. The TTLDrop arm is unaffected: prepare() throws ABORTED for a TTL merge type while the blocker is cancelled, well before this point. Case 10 covers it: two fully expired parts, TTL merges stopped, OPTIMIZE FINAL, all 200 rows still there. Co-Authored-By: Claude Opus 5 <[email protected]>
createMergedStream() is the only place a replica re-checks allow_experimental_replacing_merge_with_cleanup against its own settings, and the shortcut is the one path that never reaches it. MergeFromLogEntryTask forwards entry.cleanup to every replica unchanged, so a replica with the setting disabled could execute a cleanup merge instead of refusing it. That is reachable without anyone typing CLEANUP: the background selector derives the flag from whichever replica proposes the merge and bakes it into the log entry. Where the shortcut does fire the output is empty either way, so this is an opt-in being bypassed rather than data being altered. Not covered by a test here: it needs two replicas whose local setting differs, which a stateless test can only simulate, and the faithful form is an integration test with divergent server configs. Co-Authored-By: Claude Opus 5 <[email protected]>
The line reported how many parts were expired but not which arm took the shortcut, so a zero-read merge in production could not be traced back to either the selector assigning TTLDrop or the new proof from part metadata. Patch presence is not worth logging: the shortcut requires patch_parts to be empty, so it is always the same. Co-Authored-By: Claude Opus 5 <[email protected]>
Review feedback on PR 116175: a part whose table_ttl is already finished carries no usable part_max_ttl -- updatePartMinMaxTTL skips finished infos, leaving it at 0 -- so the expiry predicate could never accept such a part on its own metadata, and checkAllTTLCalculated turns it away even earlier because a finished info also has table_ttl.min == 0. The flag itself is the proof: TTLDeleteAlgorithm sets it only when the part's cached max TTL has already expired, i.e. every row was droppable at computation time, and rows expired then stay expired at time_of_merge. Accept it ahead of checkAllTTLCalculated, matching how the flag is treated elsewhere (hasAnyNonFinishedTTLs excludes such parts from further TTL work).
The per-part expiry proof is unsound: checkAllTTLCalculated only checks that rows-TTL metadata exists (table_ttl.min != 0), not that it was computed under the current TTL expression, and ALTER MODIFY TTL with materialize_ttl_after_modify = 0 intentionally leaves old parts in place with infos computed under the previous expression. A regular merge over a part fully expired under a since-relaxed TTL would then short-circuit to an empty part and drop live rows, where the pipeline it skips is exactly what re-evaluates the current expression. No persisted per-part proof exists that MODIFY TTL would invalidate: ttl.txt carries only min/max/finished values with no expression digest, and metadata_version.txt is only versioned for ReplicatedMergeTree (a plain MergeTree never bumps it, so equality proves nothing there). Restrict the shortcut to the assigned MergeType::TTLDrop, which the drop selector itself derives from the parts' ttl_infos, keeping the safety conjuncts added earlier: SYSTEM STOP TTL MERGES, patch parts and cleanup merges still go through the pipeline. Case 8 now pins the conservative behavior - a Regular merge over fully expired parts reads them and drops the rows in the TTL step - without the stop/start dance, which raced the background merge it let in; a racing background Regular merge produces the same (rows, read_rows) pair and OPTIMIZE FINAL waits for it, so the part_log comparison is order-independent. Case 11 is the reviewer's regression: a short rows TTL already expired, relaxed with materialize_ttl_after_modify = 0, must survive OPTIMIZE FINAL with the rows intact and read_rows > 0. Co-Authored-By: Claude Opus 5 <[email protected]>
…ale-info row drop
|
Update on the review threads:
Separately — should the stale-info row drop inside |
Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
Master's ClickHouse#121236 removed the try block around the merge entry construction in StorageMergeTree, which conflicted with the branch's patch-aware estimateNeededDiskSpace call. The call is kept at the new indentation. Co-Authored-By: Claude Opus 5.5 <[email protected]>
When every source row is expired, the rule rolls all of them up, and a SET clause can move the rolled-up rows' TTL into the future. The entry stayed finished, so the TTL selectors skipped the part and the roll-up never ran again at that deadline. A merge that applies a patch reaches this when the patch expires every row. Clear the finished bit for a rolled-up row whose TTL is still live, the same rule as for the rows the merge leaves in place. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ead-regular-116172 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ead-regular-116172 Master's ClickHouse#123068 added a per-part rows TTL expiry check to the TTLDrop short-circuit; it is kept next to this branch's patch and cleanup checks. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A patch written before `ADD COLUMN m2 MATERIALIZED m1, m3 MATERIALIZED m2` stores only src and m1. The merge that applies it must still evaluate a DELETE WHERE rule on m3 against the patched values: the recalculated rows-WHERE bound covers the patched row, and an expired rule drops it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ead-regular-116172 Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
# Conflicts: # src/Processors/TTL/TTLAggregationAlgorithm.cpp # src/Processors/Transforms/TTLCalcTransform.h # src/Storages/MergeTree/MergeTask.cpp
…es TTL infos TTLCalcTransform now keeps its state in memory-tracking containers (style check). TTLUpdateInfoAlgorithm evaluates the WHERE expression of a ROWS WHERE rule, but the mutation planner added for recalculate-only mutations read only the TTL expression inputs, so 05496_mutation_recalculate_ttl_reads_all_ttl_inputs failed with NOT_FOUND_COLUMN_IN_BLOCK for the WHERE column. Read those inputs too. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…culates TTL infos The recalculate-only mutation planner matched TTL input names with hasPhysical, which accepts top-level columns only, so a ROWS WHERE predicate on `j.flag` left `j` unread and the mutation failed with NOT_FOUND_COLUMN_IN_BLOCK. Resolve subcolumns to their owning physical column, and add a regression test. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
has_due_ttl is taken before a patch forces TTL processing, so a part whose TTL looked not due kept no protection for SET targets that no part stores. Such a column was marked expired and the rolled-up values were dropped: 100 rows rolled up to 10 rows with sum(v) = 0 instead of 100. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A group aggregated at the end of one block is emitted when the next block starts with an unexpired row. That block aggregated no rows itself, so its output was not scanned and the emitted row's TTL never reached the bounds: rows at 2040 and 2090 left both persisted bounds at 2090. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ead-regular-116172
`modernize-use-nodiscard` is an error on master, and the other steps in this file already carry the attribute. Co-Authored-By: Claude Fable 5.2 <[email protected]>
| /// so an already-expired GROUP BY entry would come back unfinished and the part would be | ||
| /// reselected for TTL forever - the shape 04501 pins. `preserved_group_by_ttl` is snapshotted | ||
| /// before the merge and put back in `finalizeProjectionsAndWholeMerge`. | ||
| auto ttl_calc_step = std::make_unique<TTLCalcStep>( |
There was a problem hiding this comment.
[Blocker] The blocked-patch fix still loses data when a patch sets a TTL to zero.
TTLCalcStep rebuilds bounds through TTLUpdateInfoAlgorithm, but MergeTreeDataPartTTLInfo::update omits zero timestamps. Zero means no expiry to ITTLAlgorithm::isTTLExpired. With one zero-TTL row and one expired row, the recalculated maximum therefore says the entire part expired. Once TTL resumes, TTLTransform takes its drop-all shortcut and deletes the zero-TTL row too.
Reproduced with this head's Fast test binary:
SET allow_experimental_lightweight_update = 1;
SET mutations_sync = 2;
CREATE TABLE t (id UInt64, ts DateTime)
ENGINE = MergeTree ORDER BY id TTL ts
SETTINGS max_number_of_merges_with_ttl_in_pool = 0,
enable_block_number_column = 1, enable_block_offset_column = 1,
min_bytes_for_wide_part = 0;
SYSTEM STOP MERGES t;
INSERT INTO t VALUES (1, '2000-01-01 00:00:00'), (2, '2000-01-01 00:00:00');
UPDATE t SET ts = toDateTime(0) WHERE id = 1;
SYSTEM STOP TTL MERGES t;
SYSTEM START MERGES t;
OPTIMIZE TABLE t FINAL;
SYSTEM START TTL MERGES t;
OPTIMIZE TABLE t FINAL;
SELECT id, toUnixTimestamp(ts) FROM t;The result is empty; (1, 0) must survive. Using TTL ts DELETE WHERE id >= 0 as a per-row control preserves it. The same sequence with x UInt64 TTL ts silently clears x = 42 on the zero-TTL row; a control that prevents the whole-column shortcut preserves 42.
The bound representation's zero handling predates this PR, but it leaves the patched-row safety contract incomplete on the new recalculation path. Preserve the presence of non-expiring rows in the recomputed metadata, or prevent whole-part/whole-column expiry decisions when those bounds cannot prove their absence. Please cover both cases with a stateless regression that resumes TTL after the blocked merge.
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…-read-regular-116172
A zero TTL means the row never expires, but MergeTreeDataPartTTLInfo::update skips zero timestamps. When a TTL-blocked merge applies a patch that sets a row's TTL to zero, the recalculation step therefore bounded only the other rows: with one zero row and one expired row the recomputed table or column TTL max said everything had expired, and once TTL merges resumed the TTLTransform drop-all path (or TTLColumnAlgorithm's whole-column reset) deleted the zero-TTL row or cleared its column value too. TTLUpdateInfoAlgorithm now pushes the max of a table or column TTL to the last DateTime when it sees a zero timestamp, so no whole-part or whole-column expiry decision is taken from that bound while rows are still deleted one by one once the min is due. Case 23 of 04268 covers both the table TTL and the column TTL with the resumed TTL merge. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #116172
Related: #105859
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed TTL after lightweight updates: a merge that applies patch parts now recalculates the part's TTL information from the patched rows, so rows are deleted or kept according to their updated values.
Documentation entry for user-facing changes
#105859 lets a
TTLDropmerge produce its empty result without opening the source parts. This PR was originally opened to extend that shortcut to regular merges over fully expired parts (issue #116172). During review the extension was dropped: the zero-read shortcut stays TTLDrop-merge-only — the regular-merge arm is disabled entirely — and the PR instead tightens the existingTTLDroparm and pins its behavior with deterministic tests.Tightened safety conditions. A fully-expired proof now requires three conjuncts before the shortcut may skip reading the source parts:
need_remove_expired_values— TTL removal must actually be pending for the merge;patch_parts.empty()— the merge must not carry patch parts;!cleanup— the merge must not be a cleanup merge.The shortcut stands down when any of them does not hold.
hasOnlyRowsTTL()remains required, so the optimization stays off for partial expiry,WHERE-clause TTLs,GROUP BYTTLs, column TTLs, moves and recompression.Deterministic tests.
04267_ttl_drop_merge_no_data_read.shis reworked to be deterministic: Case 8 no longer relies on a STOP/START dance and instead asserts viaDISTINCT+length(merged_from) > 1. A new Case 11 pins the MODIFY-TTL-without-materialization behavior withmaterialize_ttl_after_modify = 0andmax_number_of_merges_with_ttl_in_pool = 0: theOPTIMIZE FINALregular merge READS all 200 rows (no zero-read shortcut — the extension is gone), while the ordinary TTL filter drops them per the stalettl_infosthe materialization opt-out leaves behind.The alternative from the issue — letting metadata-only drops bypass the TTL admission cap, or extending the shortcut to
MergeType::Regular— was deliberately not taken; issue #116172 therefore remains open.Workflow [PR]
Sync PR [sync-upstream/pr/116175]