Skip to content

Do not drop rows of a part without rows TTL info in a TTL merge - #123068

Merged
fm4v merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-ttl-merge-rows-without-rows-ttl-info
Oct 11, 2026
Merged

fm4v merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-ttl-merge-rows-without-rows-ttl-info

Conversation

@groeneai

@groeneai groeneai commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #121124
Related: #105859
Related: #119983

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 merges deleting all rows of a part whose rows TTL was never calculated, although none of its rows had expired: a part attached with ATTACH PARTITION ... FROM from a table without that rows TTL, or written before MODIFY TTL with materialize_ttl_after_modify = 0 added it (for example after MODIFY COLUMN ... REMOVE TTL). The rows were lost in background TTL merges and in merges with fully expired parts. Closes #121124.

Description

On 26.8.2.7-lts, ALTER TABLE dst ATTACH PARTITION tuple() FROM src, where src declares a column TTL that dst does not have, followed by an ordinary background merge, deletes every row of the attached parts.

Such a part keeps an expired ttl.txt entry of a TTL the table lacks (column, DELETE WHERE or GROUP BY) and no rows TTL info. The selector tags the merge TTLDrop from the maximum over all entries, and the #105859 short-circuit took that tag plus hasOnlyRowsTTL as proof that every row expired, writing an empty part unread.

Changes (merge path only):

  • The short-circuit also requires every source part to have a calculated rows TTL expired at the merge time, exactly when the pipeline would drop all rows. Otherwise the parts are rewritten, as on 26.7; that rewrite still reserves the disk space of a drop, which Respect free disk space in TTL drop merges that keep rows #122391 fixes.
  • The ReplicatedMergeTreeQueue size check of a TTL drop (Do not postpone a fully expired TTL drop because of source parts size #119983) counts only the source parts that may keep rows.
  • A part without rows TTL info adds nothing to the aggregated bound that TTLTransform and TTLDeleteFilterTransform use to drop all rows, so a merge with a fully expired part (also OPTIMIZE FINAL) lost its rows too, already on 26.3. The merge now resets that bound so every row is evaluated.

The new stateless test covers column, DELETE WHERE and GROUP BY leftovers, ReplicatedMergeTree and both mixed-merge algorithms, each losing all rows on master and 26.8. Two new test_ttl_drop_not_postponed_by_size cases cover the size check; 04267_ttl_drop_merge_no_data_read still reads nothing.

Not changed here: stale but calculated bounds (#117990, #116678, for example a part attached from a table with a shorter rows TTL), rows whose TTL value is 0 next to expired rows (the bound ignores them), and the older column TTL twin (a column reset to its default).


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

Version info

  • Merged into: 26.10.1.2132-master (included in 26.10 and later)

groeneai and others added 2 commits September 30, 2026 11:48
A part attached from a table with a different TTL, or written before
`MODIFY COLUMN ... REMOVE TTL` + `MODIFY TTL ... SETTINGS
materialize_ttl_after_modify = 0`, keeps an expired `ttl.txt` entry of a TTL
family the table no longer has (column, DELETE WHERE, GROUP BY) and has no
rows TTL info at all (`table_ttl = {0, 0}`). `TTLPartDropMergeSelector` tags
merges from `part_max_ttl`, the max over every family, so such parts get a
`TTLDrop` merge, and the short-circuit added in ClickHouse#105859 read `TTLDrop &&
hasOnlyRowsTTL()` as proof that every row expired and wrote an empty part
without reading anything.

The short-circuit now also requires every source part to have a calculated
rows TTL (`table_ttl.min != 0`, the rule of `checkAllTTLCalculated`) that has
expired at the time of the merge, which is exactly when the pipeline itself
would drop all rows. The `ReplicatedMergeTreeQueue` exemption from the source
parts size check (ClickHouse#119983) uses the same helper at `entry.create_time`, the
time the merge runs with, so a TTLDrop entry that rewrites rows keeps the
size check.

A part without rows TTL info also added nothing to the aggregated rows TTL
bound that `TTLTransform` and `TTLDeleteFilterTransform` use to decide "all
rows expired", so merging it with a fully expired part (the same routes, or
any OPTIMIZE FINAL) dropped its rows as well. The merge already forces the
TTL calculation for such a part; the aggregated bound is now reset so that the
per-row evaluation decides.

Closes ClickHouse#121124

Co-Authored-By: Claude Opus 5.5 <[email protected]>
State the TTLDrop disk-space exemption rule in ReplicatedMergeTreeQueue exactly: exempt only the merge that drops every source part unread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings, then 1 on a stateful re-review) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ❌ Rows whose TTL value is 0 in a part whose other rows expired still pass the new check and are dropped (MergeTask::canDropTTLExpiredPartsUnread) DISAGREE Not introduced or widened here: the old condition was a superset, and without any short-circuit TTLTransform drops the same rows from the same stored table_ttl.max (OPTIMIZE FINAL: 0 0 instead of 5 5 on master, 26.8.10.6 and 25.3.14.14). The bound ignores zero values, a separate defect of how it is written. Named in the PR description.
2 ❌ A drop that now rewrites rows is still selected and reserved as an empty drop on plain MergeTree (CompactionStatistics::estimateNeededDiskSpace, tryChooseTTLMerge) DISAGREE #122391 applies the size limits and the reservation to every TTL drop that keeps rows, including parts whose rows TTL has no value. The sizing path is unchanged here and matched 26.7; this PR restores the replicated size gate for these merges (new integration case). Named in the PR description.
3 💡 The ReplicatedMergeTreeQueue comment says a TTL drop deletes every row only when it drops every part unread; a rows TTL plus a move TTL also deletes every row through the pipeline AGREE, fixed The comment now states the rule: only a drop that reads no source part skips the size check.
4 💡 The queue exemption requires every source part to be present, so a drop on a replica that is missing one keeps the size gate Noted Such an entry can only become a fetch; same as every other merge entry.
5 💡 The changelog category should be Critical Bug Fix DISAGREE I keep Bug Fix (released 26.8, documented statements, data loss); raising it is a maintainer's call.

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

Session id: cron:clickhouse-review-slot-8:20260930-122900

@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1f877e2]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_llvm_coverage, 8/8) ERROR
test_storage_nats/test_nats_jet_stream.py::test_row_based_formats FAIL cidb IGNORED
Timeout FAIL cidb IGNORED

AI Review

Summary

This PR fixes the TTLDrop short-circuit that was deleting rows from parts whose rows TTL had never been calculated, and it adds good coverage for the merge-path regressions and the replicated queue gate. I do not think the replicated low-disk fix is complete yet, because the queue now admits mixed TTLDrop ranges based on the bytes that may remain, but the execution path still reserves disk space with the old "drop every expired part by part_max_ttl" rule.

PR Metadata
  • Changelog category should be Critical Bug Fix, not Bug Fix: this fixes row loss in stable releases, which matches the template's data-loss bucket.
  • The Changelog entry is present, but it is much more implementation-heavy than the changelog guidelines ask for. Suggested replacement: Fixes a data-loss bug in TTL merges where parts attached from tables with different TTL metadata, or parts written before MODIFY TTL ... SETTINGS materialize_ttl_after_modify = 0, could lose non-expired rows during background merges or OPTIMIZE FINAL.
Findings

⚠️ Majors

  • [src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp:1881] The new queue check now counts only source parts whose rows may survive, but replicated execution still reserves space via CompactionStatistics::estimateNeededDiskSpace (src/Storages/MergeTree/MergeFromLogEntryTask.cpp:252, src/Storages/MergeTree/Compaction/CompactionStatistics.cpp:42-62), which skips any part whose part_max_ttl is expired. In the orphan/mixed cases covered by the new tests, the surviving attached part still has an expired orphaned TTL entry, so admission can now succeed while execution still reserves 0 bytes for rows it must rewrite. Under concurrent disk pressure the merge can therefore pass shouldExecuteLogEntry and then fail later for lack of reserved space.
    Suggested fix: make the reservation estimator use the same per-part isRowsTTLExpired rule as the queue gate (or share a common "bytes that may remain after TTLDrop" helper) and add a regression that reaches the execution/reservation path, not only the queue postponement logic.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Make replicated execution-time space reservation consistent with the new queue-time TTLDrop sizing for mixed ranges that still rewrite rows.

LLVM Coverage Report

⚠️ No coverage measurement for commit 1f877e2: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_8.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 30, 2026
@groeneai
groeneai requested review from Avogar and CurtizJ September 30, 2026 13:32
@clickhouse-gh clickhouse-gh Bot added the comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). label Sep 30, 2026
… drop

The TTL drop selector takes every adjacent part whose TTL info has expired,
so fully expired parts and a part without rows TTL info (for example one
attached from a table with a column TTL) land in the same merge. The size
check exemption was all or nothing, so on a full disk such a range was
refused as a whole, and the refused entry kept the only
max_replicated_merges_with_ttl_in_queue slot (the stall of ClickHouse#119775), although
the fully expired parts write nothing back.

Count only the parts whose rows TTL has not expired, whose rows are the only
ones the merge can write back. A range of fully expired parts still counts
0 bytes, and a range of parts without rows TTL info still needs room for all
of them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1f877e260 with master 120be6b5f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8dc18243e; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

if (metadata_snapshot->hasOnlyRowsTTL())
ignore_max_size = true;
{
sum_parts_size_in_bytes = 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The queue gate is now using the right notion of "bytes that may remain", but the replicated execution path still sizes the same mixed TTLDrop range as if it wrote nothing.

MergeFromLogEntryTask::prepare reserves space through CompactionStatistics::estimateNeededDiskSpace(parts, true, entry.create_time), and that helper still drops any part whose part_max_ttl <= current_time (CompactionStatistics.cpp:42-62). In the new orphan/mixed cases from this PR, the attached part still has an expired orphaned column/group-by/DELETE WHERE TTL entry, so part_max_ttl is expired even though the merge keeps and rewrites its rows. That means shouldExecuteLogEntry can now admit the merge based on the surviving rows here, but the executor still reserves 0 bytes for those same rows.

Under concurrent disk pressure this is still not "admission and execution agree": the merge can pass the queue check and then fail later for lack of reserved space. I think the reservation path needs to share the same per-part isRowsTTLExpired test (or a common "bytes that may remain after TTLDrop" estimator), plus a regression that exercises the mixed replicated case through execution rather than only the queue postponement check.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1f877e2

Every failure below has an owner: a fixing PR (mine 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
Integration tests (amd_llvm_coverage, 8/8) / test_storage_nats/test_nats_jet_stream.py::test_row_based_formats, Timeout the whole job stalled: test_storage_nats, test_backup_restore_s3 and test_throttling ran 5.6x to 9x slower than their usual time, the NATS INSERT at test_nats_jet_stream.py:1723 hit the 900 s pytest timeout (this test usually takes about 100 s and passed about 1500 times in the last 48 hours), and the shard was cut at the session timeout after reporting 320 of its usual ~870 results. No assertion failed, the 7 sibling shards passed, and this PR only changes TTL merge code a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR rollups, red only because of the row above a fix task is created (same as above)

149 of 149 check runs completed (110 passed, 36 not selected, 3 red: the job above and the two rollups), Finish Workflow is green and CH Inc sync passed. The FAIL rows CIDB lists under both Bugfix validation (integration tests) jobs are the new test_ttl_drop_not_postponed_by_size cases failing on master as expected; both jobs passed.

Session id: cron:our-pr-ci-monitor:20260930-230153

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up on the Integration tests (amd_llvm_coverage, 8/8) row of the ledger above: I investigated it and no fixing PR will follow, because the runner itself slowed down, not a test.

  • From about 18:25 UTC every process on that machine ran 16-65x slower than usual (median per test, against the same test's usual duration on this shard) until about 19:40, and it was still 3-4x slower when the session timeout cut the job at 20:14.
  • It was not limited to ClickHouse: the NATS broker (a Go binary, not built with coverage) took 125 ms to start at 19:42 against 1.4-7 ms for the same start before and after. On the ClickHouse side, CREATE DATABASE test and DROP DATABASE test used 0.5 and 1.2 ms of CPU before and 59 and 63 ms during (medians).
  • There was no memory or I/O pressure (/docker peak 11.46 of 48.78 GiB, no kernel memory kill, iowait under 1%), and no TTL merge ran on any server whose data the job kept, so the code this PR changes was not exercised there.
  • No other master-based integration job had this shape in the last 14 days, and test_row_based_formats passed 4674 of its 4675 runs on this shard in that period.

@fm4v

fm4v commented Oct 11, 2026

Copy link
Copy Markdown
Member

@groeneai is it valid review point? Open fix if yes

[clickhouse-gh](https://github.com/apps/clickhouse-gh) Bot reviewed [2 weeks ago](https://github.com/ClickHouse/ClickHouse/pull/123068#pullrequestreview-5368887655)
[src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp](https://github.com/ClickHouse/ClickHouse/pull/123068/files/1f877e260a38cc500d012ead91215db010226f53#diff-60ac1b8c4ea5fc12319121f5bc970ed065b4cffd2ffd16e81f815ae80a75386e)
                    if (metadata_snapshot->hasOnlyRowsTTL())
                        ignore_max_size = true;
                    {
                        sum_parts_size_in_bytes = 0;
@[clickhouse-gh](https://github.com/apps/clickhouse-gh)
clickhouse-gh Bot
[2 weeks ago](https://github.com/ClickHouse/ClickHouse/pull/123068#discussion_r4146736917)
Contributor
The queue gate is now using the right notion of "bytes that may remain", but the replicated execution path still sizes the same mixed TTLDrop range as if it wrote nothing.

MergeFromLogEntryTask::prepare reserves space through CompactionStatistics::estimateNeededDiskSpace(parts, true, entry.create_time), and that helper still drops any part whose part_max_ttl <= current_time (CompactionStatistics.cpp:42-62). In the new orphan/mixed cases from this PR, the attached part still has an expired orphaned column/group-by/DELETE WHERE TTL entry, so part_max_ttl is expired even though the merge keeps and rewrites its rows. That means shouldExecuteLogEntry can now admit the merge based on the surviving rows here, but the executor still reserves 0 bytes for those same rows.

Under concurrent disk pressure this is still not "admission and execution agree": the merge can pass the queue check and then fail later for lack of reserved space. I think the reservation path needs to share the same per-part isRowsTTLExpired test (or a common "bytes that may remain after TTLDrop" estimator), plus a regression that exercises the mixed replicated case through execution rather than only the queue postponement check.

Merged via the queue into ClickHouse:master with commit 687f384 Oct 11, 2026
291 of 295 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 Oct 11, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, the code fact is right, but it is older than this PR and not specific to it. estimateNeededDiskSpace skips every part whose part_max_ttl has expired (the same check is in 26.3 and 26.7), so every TTL drop merge that writes rows back (GROUP BY, WHERE or column TTL, and these attached parts) reserves only the 1 MiB minimum. Measured with that estimator on the same data: a TTL drop merge that rewrote and kept 10000 rows reserved 1.00 MiB on this PR's build and on 26.7.6.57, a regular OPTIMIZE reserved 10.59 MiB. The outcome is a merge that can fail with No space left on device and be retried, not lost rows.

The fix is already open: #122391. There estimateNeededDiskSpace skips a part only when the table has a rows TTL and the part's own rows TTL bound is set and expired, so the attached parts here (table_ttl.max = 0) are counted by the reservation, as they are by the queue check in this PR, for every caller including MergeFromLogEntryTask. It conflicts with master now; I'll merge master into it, resolve the conflict and add the replicated mixed case from this PR to its reservation test.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master into #122391 and added a reservation check to the replicated mixed case of this PR's test: cbf951d. On master the merge that writes back the attached part reserves 1.00 MiB for its 2.08 MB; with #122391 it reserves 2.29 MB.

valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 12, 2026
…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]>
alexey-milovidov added a commit to zhongyuankai/ClickHouse that referenced this pull request Oct 15, 2026
ClickHouse#123068 clears the merged
part's `table_ttl` when any non-empty source part has `table_ttl.min == 0`,
treating it as a part without a calculated rows TTL. An epoch-only part
also has zero bounds, but its rows TTL is calculated and recorded with
`has_epoch_timestamps`, which propagates to the merged part and already
disables the whole-part shortcuts. Exclude such parts, so the merged part
keeps the propagated bounds.

Fixes `04904_materialize_ttl_merged_epoch_timestamps` and
`05048_materialize_ttl_epoch_reload` in the Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=63383&sha=c4a681b8754c3152fd4661c537356f6ca542bf77&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kute1654 pushed a commit to kute1654/ClickHouse that referenced this pull request Oct 16, 2026
…t in a merge

A merge folds the column TTL info of its source parts with
`MergeTreeDataPartTTLInfos::update`, which only iterates the entries a
source part has. A part that stores a column but has no `columns_ttl`
entry for it (attached with `ATTACH PARTITION ... FROM` from a table
without the column TTL, or written before `MODIFY COLUMN ... TTL` with
`materialize_ttl_after_modify = 0`) adds nothing, so the merged bound is
exactly the other part's. When that part's column TTL has fully expired,
`TTLColumnAlgorithm` takes its whole-block branch
(`isMaxTTLExpired() && !is_compact_part`) and replaces the column of every
merged row with the default, including rows whose TTL has not expired.
`force_ttl` is set for such merges, but it only affects `isMinTTLExpired()`.
Without a TTL step (TTL merges stopped) the wrong bound is persisted on
the merged part and the next TTL merge of that part resets it.

Collect the columns that a non-empty source part stores without TTL info
and aggregate each source part's TTL infos from a copy without those
entries. The merged part is then in the same "not calculated" state as
the source part: a TTL step evaluates the column TTL per row, and without
one the next merge sees the gap and forces it. Removing the entries
before `update` (rather than erasing the aggregated entry afterwards)
keeps `part_min_ttl`/`part_max_ttl`, which `update` derives from the
folded entries, free of the expired bound. Merges whose parts all carry
a calculated bound keep the whole-block fast path.

Column-TTL counterpart of the rows-TTL fix in ClickHouse#123068 (issue ClickHouse#121124).
Reproduces on 26.8.2.7 and 24.8.14.39.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 27, 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 comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Silent data loss: TTLDrop merge empties parts with stale TTL info after ATTACH

5 participants