Skip to content

Fix rows never deleted when two TTL DELETE WHERE rules share a time expression - #113384

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-113116-ttl-delete-where-shared-time-expression
Aug 5, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-113116-ttl-delete-where-shared-time-expression

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Closes: #113116

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 rows never being deleted when a MergeTree table has two or more TTL ... DELETE WHERE rules whose time expression is identical and which differ only in the WHERE condition. After a TTL delete merge the part's rows_where_ttl_info was reset to zero, so no further TTL merge was ever scheduled for it and the expired rows were retained indefinitely with no error or log message. Closes #113116.

Description

Per-part rows-where TTL infos live in a map keyed by the TTL time expression's result_column, not by the rule, so two DELETE WHERE rules sharing a time expression share one slot. TTLDeleteAlgorithm::finalize wrote that slot with an unconditional assignment, so the last rule finalized won. If that rule's WHERE matched no surviving row its info is empty and the earlier rule's valid min/max was discarded.

A zero min is durable: part_min_ttl is not stored in ttl.txt and is recomputed from the map on load, updatePartMinMaxTTL ignores a zero min, and ITTLMergeSelector::findCenters skips any part whose TTL is 0, so the part is never selected for a TTL merge again.

The change makes finalize merge into the shared slot with MergeTreeDataPartTTLInfo::update instead of overwriting it, so the slot holds the earliest and latest still-live matching row across all rules on that time expression. This is the same aggregation MergeTreeDataPartTTLInfos::update already applies to this map when parts combine. With one rule per time expression the merged value equals the old assignment, so nothing else changes.

The key collision itself is left alone: the key is serialized verbatim into ttl.txt and hashed for checksums, so re-keying per rule would be an on-disk format change needing upgrade and downgrade paths. Merging already restores correct scheduling, which is the user-visible defect.

The behaviour regressed in 25.9 with 67a3166, which correctly stopped rows failing the WHERE from updating the TTL info; before that the shared slot held a WHERE-ignoring but nonzero range, so scheduling survived by accident. That commit's test 03622_ttl_infos_where still passes, so this is not a revert.

Validated with a new stateless test that fails on unpatched master and passes with the fix, 50/50 under CI randomization, and covering restart, MATERIALIZE TTL and reversed rule order.

…xpression

Per-part rows-where TTL infos are stored in a map keyed by the TTL time
expression's result_column (MergeTreeDataPartTTLInfo.h:36,49). That key comes
from the time expression alone (TTLDescription.cpp:1285) while the WHERE clause
has a separate where_result_column (:1310), so two or more DELETE WHERE rules
sharing a time expression share one map slot.

TTLTransform::finalize resets data_part->ttl_infos and then calls finalize on
each algorithm in declaration order. TTLDeleteAlgorithm::finalize wrote the
shared slot with an unconditional assignment, so the last rule won: if that
rule's WHERE matched no surviving row its new_ttl_info is empty and the earlier
rule's valid min/max was discarded.

The loss is durable and silent. part_min_ttl is not stored in ttl.txt and is
recomputed from the map on load, updatePartMinMaxTTL ignores a zero min, and
ITTLMergeSelector::findCenters skips any part whose TTL is 0, so no further TTL
merge is ever selected for that part and the expired rows are retained
indefinitely with no error and no log line.

Merge into the shared slot with MergeTreeDataPartTTLInfo::update instead of
overwriting it. That takes the smaller nonzero min, the larger max and ANDs
ttl_finished, so the slot means "the earliest and latest still-live matching row
across all rules on this time expression", which is what the merge selector
needs. It is the same aggregation MergeTreeDataPartTTLInfos::update already
applies to this map when parts combine. Because finalize starts from a
default-constructed slot, a table with one rule per time expression gets a value
identical to the old assignment.

The per-time-expression key collision is deliberately left alone: the key is
serialized verbatim into ttl.txt and the map is hashed for checksums
(MergeTreeDataPartTTLInfo.h:35), so re-keying per rule would be an on-disk
format change requiring upgrade and downgrade paths. Merging restores correct
scheduling, which is the user-visible defect.

The behaviour regressed in 25.9 with 67a3166 ("fix infinite recalculation
of TTL with WHERE"), which added an if (where_filter_passed) guard around
new_ttl_info.update(cur_ttl). Before that, rows failing the WHERE still updated
the shared slot, so it always held a WHERE-ignoring but nonzero range and
scheduling survived by accident. That commit is correct for its own purpose and
its test 03622_ttl_infos_where stays green, so this is not a revert.

Verified against a pristine-master build that the new test fails without the fix
and passes with it, that ttl.txt keeps the same layout (only the value differs),
that the result no longer depends on the order the rules are declared in, and
that the infinite TTL recalculation 67a3166 fixed is not reintroduced.

Closes: ClickHouse#113116
Two arms of the test did not pin what the change claims.

The reordered arm declared the live rule last, so the pre-fix unconditional
assignment also wrote that rule's valid range: the arm produced identical
output with and without the fix. It now declares the live rule in the middle,
so an empty info is finalized after it and the old assignment clobbers again.

No arm distinguished merging from a weaker alternative that assigns only when
the incoming info is initialized, because every arm had exactly one rule
contributing a nonzero range. The new t_two_live arm gives two rules a live row
each at different timestamps, so the slot's min must come from one rule and its
max from the other, which only a merge produces.

Measured against two mutants, both 5/5 deterministic. Restoring the assignment
reddens merged, reloaded, materialized, reordered and two live. The
assign-if-initialized variant reddens two live, and also control, because it
never creates the uninitialized second slot.

Test-only change; TTLDeleteAlgorithm is untouched.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, clean)

Two independent review rounds against a second model, plus my own cold review of the resulting
code each round. Round 1 bounced the PR back for test-liveness work; round 2 is clean.

Round 1 (sha 7823eb77) - test did not pin the contract

⚠️ reordered arm was vacuous. It declared the live rule LAST, so the pre-fix unconditional
assignment also wrote that rule's valid range: the arm produced identical output with and without
the fix. Its comment claimed order-independence it did not demonstrate. AGREED and fixed - the
live rule now sits in the middle (b, a, c), so an empty info is finalized after it.

⚠️ No arm distinguished the fix from a weaker alternative. Every arm had exactly one rule
contributing a nonzero range, so "merge across rules" and "assign only when initialized" were
indistinguishable. That is the changelog's actual claim, and nothing tested it. AGREED and fixed -
the new t_two_live arm gives two rules a live row each at different timestamps, so the slot's
min must come from one rule and its max from the other.

Both verified with an executed 3-binary mutant matrix (5/5 deterministic each, Build ID asserted
against the running server before every verdict):

arm fix restore assignment assign-if-initialized
merged / reloaded / materialized 2099 / 2099 1970 / 1970 2099 / 2099
reordered (repaired) 2099 / 2099 1970 / 1970 2099 / 2099
two live (new) 2099 / 2100 2100 / 2100 2100 / 2100
control (distinct expressions) 2 slots 2 slots 1 slot

Before the repair, reordered reddened neither mutant. two live is the only arm that reddens
both. The control arm also turned out to redden the second mutant, because that variant never
creates the legitimately-empty second slot.

Round 2 (sha 6924e21a) - 0 findings

Second-model re-review of the full change: 0 findings. My own cold review: 0 blockers,
0 majors, 0 nits
.

💡 During independent carrier enumeration I raised, then refuted, one candidate gap: MergeTask
has a second TTL-delete path (TTLDeleteFilterStep, the vertical-merge optimization) which
pre-filters rows and writes no TTL info. It is not a missed carrier - MergeTask.cpp:3320-3326
adds the TTLStep in both merge algorithms, so the fixed finalize runs either way. CI
randomizes vertical_merge_algorithm_min_rows_to_activate / min_columns_to_activate and
min_bytes_for_wide_part, so the 50/50 run crossed both algorithms.

💡 One nit declined: the validation sentence in this description names restart, MATERIALIZE TTL
and reversed rule order but not the new two-live-rules arm. The sentence is accurate as written,
and the contract that arm pins is already stated in the changelog entry and above.

Also verified

Serialization is unchanged in both directions - write() emits finished() as
value_or(false), so the std::optional merge inside update is not observable in ttl.txt,
and the map key is untouched, so no format versioning applies. 03622_ttl_infos_where, the test
added by the commit that changed this behaviour in 25.9, still passes, including its
CANNOT_ASSIGN_OPTIMIZE assertion - so this is not a revert of it.

Test is parallel-safe (no no-parallel, scoped to currentDatabase()), does not touch part
directories, and is a single file.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Gate Result
a Deterministic repro Yes. One clickhouse local run reproduces on demand; the new test fails 5/5 on unpatched master and passes 5/5 with the fix. Not a rate.
b Root cause explained Yes. rows_where_ttl is keyed by the time expression's result_column only, so N DELETE WHERE rules share one slot; TTLDeleteAlgorithm::finalize assigned into it, so the last rule won and an empty info erased the earlier rule's range. A zero min is not persisted and is recomputed on load, updatePartMinMaxTTL ignores it, and ITTLMergeSelector::findCenters skips a part whose TTL is 0, so the part is never scheduled again.
c Fix matches root cause Yes. It changes the write that loses the data (assignment to .update), not a downstream guard. Re-keying the map, reverting 67a3166, and patching the scheduling predicate were all considered and rejected as format-breaking or symptom-level.
d Test intent preserved, new test added Yes. Nothing weakened or skipped; new stateless test 04735_ttl_delete_where_shared_time_expression with a mandatory fails-without-fix arm. Arm liveness proven against two mutants rather than asserted: restoring the assignment reddens 5 of its 6 assertions, and a weaker "assign only when initialized" variant reddens the two-live-rules arm, which is the arm that pins the merge contract. 03622_ttl_infos_where (added by 67a3166, including its CANNOT_ASSIGN_OPTIMIZE assertion) is 50/50 green.
e Demonstrated both directions Yes. Pre-fix binary: slot reads 1970-01-01 after the merge and after DETACH/ATTACH. Fixed binary: 2099-02-01. Build ID asserted to move between arms, and the running server's buildId() asserted equal to the binary's before every verdict.
f General across code paths Yes, by measurement. MergeTreeDataWriter (insert) is already correct: updateTTL takes the info by reference, so rules accumulate, which is why the bug needs a merge. TTLUpdateInfoAlgorithm also assigns but is WHERE-agnostic (no where occurrence in the file), so all sharing rules compute an identical value and changing it would be a no-op. group_by / moves / recompression siblings are structurally immune because WHERE is parsed only for TTLMode::DELETE. Readers consume the merged slot unchanged. Replicated and Shared MergeTree share this code path. MATERIALIZE TTL is pinned by an arm that fails on master.
g Generalizes across inputs Yes. Verified with LowCardinality(Nullable(String)) WHERE columns including a NULL row; two and three rules sharing one expression; both declaration orders; the single-rule path (byte-identical to master); and the case where every rule's WHERE matches nothing surviving, where an empty slot is still correctly produced.
h Backward compatible Nothing engaged. No key change, no ttl.txt schema change (compared on disk between arms: identical layout, only the value differs), no checksum change, no new or changed setting, so no SettingsChangesHistory.cpp entry. Old parts load unchanged and new parts stay readable by old code.
i Invariants and contracts finalize has no early return; the table_ttl branch is untouched. The real risk was reintroducing the infinite TTL recalculation 67a3166 fixed, since a non-zero slot makes the part schedulable again: measured, the merge count stabilised and did not move over a further 20 seconds, and 03622_ttl_infos_where stays green. ttl_finished ANDing is the conservative direction, so the slot is finished only when every sharing rule is.

Regression runs: the rows_where_ttl and MATERIALIZE TTL consumers all pass
(03622_ttl_infos_where, 01070_modify_ttl, 01070_modify_ttl_recalc_only,
04159_unique_key_ttl_rejected, 02158_explain_ast_alter_commands, 01070_materialize_ttl,
03285_materialize_ttl_only_drop_parts). The new test is 50/50 under CI randomization.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun, could you review this? Two TTL DELETE WHERE rules sharing a time expression share one rows_where_ttl slot, and finalize assigned into it rather than merging, so an empty info from the last rule erased the earlier rule's range and the part was never selected for a TTL merge again.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6924e21]

Summary: ❌

job_name test_name status info comment
Stress test (amd_msan) FAIL
Logical error: '(isConst() || isSparse() || isReplicated() || rhs.isConst() || rhs.isSparse() || rhs.isReplicated()) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID: 2508-30f6) FAIL cidb IGNORED

AI Review

Summary

This PR fixes the rows_where_ttl rebuild for MergeTree parts when multiple TTL ... DELETE WHERE rules share the same time expression. I did not find any new blockers or majors in the current code: TTLTransform::finalize clears data_part->ttl_infos before rebuilding it, so switching TTLDeleteAlgorithm::finalize from assignment to update correctly merges the shared slot instead of preserving stale pre-merge state, and the new stateless test exercises the important surfaces (OPTIMIZE, DETACH/ATTACH, MATERIALIZE TTL, reordered rules, and the two-live-rules merge case).

Final Verdict

✅ No blocking issues found.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 3/3 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6924e21a6 with master d0758c6f8 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e75fe0854; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 688.57 MiB 685.93 MiB -2.64 MiB (-0.38%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

1383 object files changed (+1.51 MiB total), 3 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Parquet/GeoFilter.cpp.o new 860.64 KiB +860.64 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/SharedPartColumns.cpp.o new 294.32 KiB +294.32 KiB
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Parquet/Reader.cpp.o 558.56 KiB 634.53 KiB +75.97 KiB (+13.60%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/IMergeTreeDataPart.cpp.o 1.38 MiB 1.33 MiB -46.27 KiB (-3.28%)
src/CMakeFiles/dbms.dir/Interpreters/InterserverIOHandler.cpp.o new 29.52 KiB +29.52 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/ColumnsSubstreams.cpp.o 132.58 KiB 154.18 KiB +21.60 KiB (+16.29%)

737 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

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

Job report

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6924e21

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / assertTypeEquality LOGICAL_ERROR, STID 2508-30f6 flaky, pre-existing trunk bug in HashJoin::buildAdditionalFilter (plain column receiving a sparse/const/replicated source) #107957 (ours, open)

Session id: cron:our-pr-ci-monitor:20260805-033000

@PedroTadim PedroTadim self-assigned this Aug 5, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 5, 2026
Merged via the queue into ClickHouse:master with commit 458264b Aug 5, 2026
178 of 180 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 5, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.3, 26.5, 26.6, 26.7. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks - I checked this myself rather than relying on the runs above, and the branch list is right, with one correction to how it is best requested.

I ran this PR's own merged regression test against the official per-release binaries and scored only the fix-dependent lines (merged, reloaded, materialized, reordered, two live):

branch binary fix-dependent oracles differing verdict
26.7 26.7.3.19 5 of 5 (2099-02-01 -> 1970-01-01) reproduces
26.6 26.6.3.7 5 of 5 reproduces
26.5 26.5.7.11 5 of 5 reproduces
26.3 26.3.18.4 5 of 5 reproduces
25.8 25.8.30.3 0 of 5 does not reproduce

So your four branches are correct. Worth spelling out why 25.8 is excluded, because a whole-file diff would wrongly flag it: 25.8 does differ from the master reference, but only on the control line, and that line is not fix-dependent. It predates the regressing commit 67a31666c8141554e513a677ee3e5cf9d64b9ba3, so it still prints the old WHERE-ignoring 2099-03-01 there instead of 1970-01-01. Scoring the whole file rather than the fix-dependent lines is the one way to get this branch wrong.

One correction on the request itself. A v<X.Y>-must-backport label is a floor, not a per-branch selector: select_backport_branches takes the minimum version-specific label and expands it to that release plus every newer active branch. Running that function against the active set (26.7, 26.6, 26.5, 26.3, 25.8, from the open release-labelled PRs) gives:

  • v26.3-must-backport -> 26.7, 26.6, 26.5, 26.3
  • v26.5-must-backport -> 26.7, 26.6, 26.5
  • pr-must-backport -> all five, including 25.8

So a single v26.3-must-backport covers exactly the four affected branches, and pr-must-backport would be wrong here because it also targets 25.8, where the test's control reference does not match.

I also checked the port is mechanical rather than assuming it. Simulating the automation's cherry-pick against each of the four branches gives rc=0 with no conflicts and exactly 3 files (+2/-1 in TTLDeleteAlgorithm.cpp, plus the new test and reference); the pre-image line is present verbatim on all four and test number 04735 is free on each. The fix's precondition also holds everywhere: .update() is only correct because both finalize callers zero ttl_infos first, and data_part->ttl_infos = {}; is present in both TTLTransform.cpp and TTLCalcTransform.cpp on all four branches, so this cannot land as a half no-op.

@PedroTadim, since you merged this one - could you apply v26.3-must-backport? That single label gives the four branches above. I am not labelling it myself or hand-authoring release-branch PRs, per the standing instruction to go through the label route.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TTL DELETE WHERE: rows_where_ttl_info zeroed when two rules share a time expression, silently retaining rows forever

5 participants