Skip to content

Recalculate TTL infos on merges that apply patch parts - #116175

Open
valerypetrov wants to merge 92 commits into
ClickHouse:masterfrom
valerypetrov:fix/ttl-drop-zero-read-regular-116172
Open

valerypetrov wants to merge 92 commits into
ClickHouse:masterfrom
valerypetrov:fix/ttl-drop-zero-read-regular-116172

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Related: #116172
Related: #105859

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 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 TTLDrop merge 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 existing TTLDrop arm 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 BY TTLs, column TTLs, moves and recompression.

Deterministic tests. 04267_ttl_drop_merge_no_data_read.sh is reworked to be deterministic: Case 8 no longer relies on a STOP/START dance and instead asserts via DISTINCT + length(merged_from) > 1. A new Case 11 pins the MODIFY-TTL-without-materialization behavior with materialize_ttl_after_modify = 0 and max_number_of_merges_with_ttl_in_pool = 0: the OPTIMIZE FINAL regular merge READS all 200 rows (no zero-read shortcut — the extension is gone), while the ordinary TTL filter drops them per the stale ttl_infos the 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]

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
@scanhex12 scanhex12 self-assigned this Aug 25, 2026
@scanhex12 scanhex12 added the can be tested Allows running workflows for external contributors label Aug 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3dbbd5a]

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

Summary

This PR recalculates TTL metadata when merges apply lightweight patches, adds metadata recalculation while TTL merges are stopped, and repairs GROUP BY TTL bounds and scheduling. The latest zero-TTL fix protects the first resumed merge, but subsequent merges still delete non-expiring rows or clear their column values. The existing blocker remains unresolved at head 3dbbd5a76507344705f81f4e9e42ba0f8501efa9.

The extended TTLCalcTransform output feeds skip-index expressions, text-index and statistics builders, part writing, and projection rebuilding; expired columns are reintroduced before those consumers. Its mutation callers pass an empty expired-column list and retain their original output header.

Findings

❌ Blockers

  • Zero-TTL protection must survive every subsequent TTL pass. src/Processors/TTL/TTLUpdateInfoAlgorithm.cpp:47–48 preserves a non-expiring row by raising the recalculated maximum. However, the next ordinary TTL pass rebuilds that metadata through TTLDeleteAlgorithm or TTLColumnAlgorithm, whose surviving-row updates still omit zero (TTLDeleteAlgorithm.cpp:51, TTLColumnAlgorithm.cpp:115). If another surviving row expires later, its timestamp becomes the new maximum. Once that deadline passes, whole-part deletion or whole-column expiry incorrectly includes the zero-TTL row. This is the remaining instance of the existing zero-TTL finding; no duplicate thread was posted.

    Reproduced using this head's native Fast test binary, version 26.12.1.1, with clickhouse local: use Case 23's table/settings, add a third row expiring ten seconds in the future, and patch row 1 to toDateTime(0). Merge while TTL is stopped, resume TTL and merge immediately, then merge again after row 3 expires. For the column variant, every row initially has x = 42.

    Stage Rows retained by TTL ts Column variant: (id, x)
    Blocked patch merge [1,2,3] [(1,42),(2,42),(3,42)]
    First resumed merge [1,3] [(1,42),(2,0),(3,42)]
    Merge after row 3 expires [] [(1,0),(2,0),(3,0)]

    Row 1 must remain, with x = 42. The unblocked patch-merge variant also eventually deletes row 1. Preserve the non-expiring-row invariant across the ordinary TTL algorithms and other metadata producers, or prevent whole-part/whole-column expiry when the bounds cannot establish that every row expires.

Tests
  • ⚠️ Case 23 in 04268_ttl_blocked_patch_merge_infos.sh:374–383 covers only a zero-TTL row plus an already-expired row and stops after the first resumed merge. Add a surviving row with a later deadline and assert preservation after an intermediate TTL pass and a further merge past that deadline, for both table and column TTLs. Include the unblocked patch path. All three focused reproductions above completed without exceptions and demonstrated the data loss.
Final Verdict

Status: ❌ Block

Make zero-TTL preservation durable across subsequent TTL passes and add the focused regressions above.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 25, 2026
@scanhex12
scanhex12 requested a lite review from Copilot August 25, 2026 16:51

Copilot AI left a comment

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.

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.

Comment on lines +432 to +439
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;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/Storages/MergeTree/MergeTask.cpp Outdated
Comment on lines +1073 to +1075
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());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2594e8c87 with master 0ba40ae08 (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.

Object file sizes

15 object files changed (+72.15 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Transforms/TTLCalcTransform.cpp.o 99.65 KiB 136.17 KiB +36.52 KiB (+36.65%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTask.cpp.o 1.88 MiB 1.90 MiB +26.05 KiB (+1.36%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

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 · ⚠️ 3 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 222 122 -45.0% <0.0001 The -45.0% delta falls under the hard trust lock, so the verdict stays. The diff only changes TTL handling during merges, which this read-only SELECT never runs, so this PR is not a credible cause.
⚠️ 28 not_sure 1001 1067 +6.6% 0.0005 The +6.6% delta is borderline, the two tests disagree and both sides were noisy. CPU time is flat and the diff does not touch this query's path.
⚠️ 33 not_sure 1127 1025 -9.1% <0.0001 The -9.1% source median sits inside master's current range and this query's history is noisy. The PR only changes merge-time TTL code, which this SELECT does not run.
⚠️ 34 not_sure 1123 1034 -7.9% <0.0001 The -7.9% source median sits inside master's current range and this query's history is noisy. The PR only changes merge-time TTL code, which this SELECT does not run.

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
  • StressHouse run: ba045c27-1a0e-4a0d-a415-bf39a1fc1499
  • MIRAI run: 61445c17-0867-4e96-a9cd-e662834d3ba5
  • PR check IDs:
    • clickbench_44174_1791927905
    • clickbench_44342_1791927922
    • clickbench_44549_1791927937
    • tpch_adapted_1_official_44570_1791927937
    • tpch_adapted_1_official_44767_1791927948
    • tpch_adapted_1_official_44952_1791928041

valerypetrov and others added 2 commits August 25, 2026 21:13
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]>
@valerypetrov
valerypetrov requested a lite review from Copilot August 26, 2026 05:29

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

Comment thread src/Storages/MergeTree/MergeTask.cpp Outdated
Comment on lines +1059 to +1064
/// 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;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/Storages/MergeTree/MergeTask.cpp Outdated
Comment on lines 1078 to 1080
LOG_DEBUG(ctx->log, "Skipping data pipeline: all {} source parts are fully expired",
global_ctx->future_part->parts.size());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
valerypetrov and others added 5 commits August 26, 2026 08:25
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).
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
valerypetrov and others added 2 commits August 27, 2026 12:39
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]>
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Update on the review threads:

  • The shortcut is NOT extended to regular merges — that arm is disabled entirely. The TTLDrop-only shortcut keeps the three safety conjuncts: need_remove_expired_values, patch_parts.empty(), and !cleanup (2e64f74).
  • Case 8 is now deterministic (no STOP/START dance; DISTINCT + length(merged_from) > 1). New Case 11 pins materialize_ttl_after_modify = 0 + max_number_of_merges_with_ttl_in_pool = 0: the OPTIMIZE FINAL regular merge READS all 200 rows (no zero-read shortcut), while the ordinary TTL filter drops them per the stale infos the materialization opt-out leaves behind (0833c4b).

Separately — should the stale-info row drop inside TTLDeleteFilterTransform::build (all_data_dropped from pre-MODIFY ttl_infos) be tracked separately upstream?

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 28, 2026
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
valerypetrov and others added 4 commits October 3, 2026 22:07
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

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]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
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]>
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). labels Oct 13, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
valerypetrov and others added 2 commits November 4, 2026 21:35
# 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]>
@clickhouse-gh clickhouse-gh Bot added comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 5, 2026
…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]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
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]>
valerypetrov and others added 2 commits November 22, 2026 17:32
`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>(

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

@stresshouse

stresshouse Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

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
  • StressHouse run: e429019b-476e-46e9-82f9-1253c0313371
  • MIRAI run: 182d996b-e821-44ea-bae8-4ec3ec98946c
  • PR check IDs:
    • clickbench_904973_1795402670
    • clickbench_904979_1795402671
    • tpch_adapted_1_official_905005_1795402670
    • tpch_adapted_1_official_905017_1795402670

valerypetrov and others added 2 commits November 23, 2026 10:20
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]>

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-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants