Skip to content

Skip data reading step entirely for TTLDrop merges to avoid excessive memory usage - #105859

Merged
Michicosun merged 16 commits into
masterfrom
ttl-drop-merge-skip-data-pipeline
Aug 3, 2026
Merged

Michicosun merged 16 commits into
masterfrom
ttl-drop-merge-skip-data-pipeline

Conversation

@Avogar

@Avogar Avogar commented May 26, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Skip data reading step entirely for TTLDrop merges to avoid excessive memory usage, especially on read/prefetch buffers allocations. Closes #105639

`TTLDrop` merges know that all source parts are fully expired, yet the
merge task was going through the full pipeline: opening every source
part, creating `MergeTreeSequentialSource` readers, and allocating
async prefetch buffers.  With many parts or wide tables (e.g. JSON
columns with hundreds of subcolumns) this caused tens of GiB of
`IOBufferAllocBytes` for a merge whose result is an empty part.

Short-circuit in `ExecuteAndFinalizeHorizontalPart::prepare`: when
`MergeType::TTLDrop` and the rows TTL has no WHERE clause, skip
`createMergedStream` entirely.  The `MergedBlockOutputStream` is still
created (needed for `finalizePart` metadata), and `finalizePart`
already handles 0-row parts correctly.

Safety considerations addressed:
- WHERE-clause TTLs: `TTLPartDropMergeSelector` assigns `TTLDrop`
  based solely on `part_max_ttl` without checking WHERE conditions.
  The short-circuit detects `where_expression_ast` and falls through
  to the normal pipeline in that case.
- Projections, skip indexes, text indexes: cleared since a 0-row
  part has no data to index.
- Vertical merge algorithm: forced to Horizontal to avoid
  `RowsSourcesTemporaryFile::finalizeWriting` throwing on an
  uninitialized file.
- TTL infos: reset to empty (matching `TTLTransform::finalize`
  behavior).

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

clickhouse-gh Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [94f4954]

Summary: ✅


AI Review

Summary

This PR short-circuits TTLDrop merges so fully expired parts can skip building the read pipeline and avoid the large buffer allocations that were previously happening. The optimization direction is reasonable, but the current shortcut still diverges from the normal secondary-index paths in two compatibility-sensitive ways, so I would not merge it yet.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTask.cpp:1079-1091, src/Storages/MergeTree/MergeTask.cpp:2445-2475] The shortcut still repopulates text_indexes_to_merge after skipping createMergedStream, so MergeTextIndexStage still reaches getTextIndexSegments for the new part even though build_text_index_transforms was never filled. The same reinitialization also undoes the earlier materialize_skip_indexes_on_merge = 0 clearing, so TTLDrop merges materialize secondary-index files when the normal path would suppress them. Tables with text indexes can still fail these background merges with LOGICAL_ERROR, and tables with disabled materialization can still produce different checksums than the non-short-circuit path.
  • [src/Storages/MergeTree/MergeTask.cpp:1083-1091, src/Storages/MergeTree/MergeTreeDataPartWriterOnDisk.cpp:165-223, src/Storages/MergeTree/MergeTreeIndexLegacyHypothesis.cpp:21-23] The short-circuit reinitialization no longer carries over the isInert filter from the normal Horizontal branch. Attached legacy tables can legitimately keep removed secondary indexes such as hypothesis; the ordinary merge path skips them precisely so merges stay attach-compatible. Here TTLDrop adds them back to merging_skip_indexes, and MergedBlockOutputStream immediately calls createIndexAggregator on them, which throws ILLEGAL_INDEX. That makes fully expired parts start failing background TTL merges on existing compatible tables.
Final Verdict

❌ Changes requested. The TTLDrop shortcut still breaks valid secondary-index compatibility paths and should match the normal merge/index setup before it is safe to merge.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 26, 2026
@Avogar
Avogar requested a review from Michicosun May 26, 2026 14:19
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@Michicosun Michicosun self-assigned this May 26, 2026
…izontal

The TTLDrop short-circuit forces `chosen_merge_algorithm` from Vertical
to Horizontal, but did not update the merge-list entry.  This caused
`system.merges` and `system.part_log` to report the wrong algorithm
for the affected merge.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Avogar and others added 3 commits May 26, 2026 14:44
…ling upgrades

The short-circuit was resetting `ttl_infos = {}`, which produces
`part_min_ttl == 0` and causes `ttl_infos.empty()` to return true,
so `ttl.txt` is not written.  The normal `all_data_dropped` path
keeps `part_min_ttl` / `part_max_ttl` from source parts and only
overwrites `table_ttl` to `{0, 0, ttl_finished=true}`, so
`ttl_infos.empty()` returns false and `ttl.txt` IS written.

This mismatch would cause different checksums for the same TTLDrop
merge during a rolling upgrade of `ReplicatedMergeTree`, triggering
unnecessary part re-fetches.

Fix: keep the accumulated `ttl_infos` from source parts and only set
`table_ttl` to the finished state, matching `TTLDeleteAlgorithm::finalize`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
If `chooseMergeAlgorithm` initially picked Vertical, the column
state was set up for vertical merging: `merging_columns` contained
only key columns and `gathering_columns` held the rest.  The
short-circuit then forced `chosen_merge_algorithm = Horizontal`
without resetting these fields, so `MergedBlockOutputStream` was
constructed with key-only `merging_columns` and `finalizePart` used
incomplete column metadata.

Reset `merging_columns`, `gathering_columns`, and skip index lists
to match the Horizontal branch of the algorithm switch, ensuring
consistent part metadata regardless of which algorithm was initially
chosen.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
…ath's `ttl_infos`

- Use `hasOnlyRowsTTL` instead of `hasRowsTTL` so the short-circuit
  is skipped when other TTL families are present (column, moves,
  recompression, GROUP BY, WHERE-clause). This avoids producing
  different `ttl.txt` contents during rolling upgrades.

- Reset `ttl_infos = {}` before setting `table_ttl`, matching what
  `TTLTransform::finalize` does in the normal `all_data_dropped` path.
  The previous code preserved accumulated `part_min_ttl` from source
  parts, which made `ttl_infos.empty()` return false and caused
  `ttl.txt` to be written — diverging from the normal path.

- Remove the redundant `!where_expression_ast` check since
  `hasOnlyRowsTTL` already excludes WHERE-clause TTLs (they are
  stored in the separate `rows_where_ttl` bucket).

- Add test cases 6 (rows TTL + column TTL) and 7 (rows TTL +
  GROUP BY TTL) to verify the short-circuit is correctly skipped.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
global_ctx->text_indexes_to_merge.clear();
}
else
{

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.

This drops the skip-index files from the short-circuited part. In the normal TTLDrop path, MergedBlockOutputStream is constructed with merging_skip_indexes; even if TTLTransform removes every row, MergeTreeDataPartWriterOnDisk::fillSkipIndicesChecksums finalizes the empty skip-index streams and adds the skp_idx_* files to checksums.txt.

Clearing the list here can therefore produce a different part checksum for the same replicated TTLDrop merge whenever the table has materialized secondary indexes, which is exactly the kind of rolling-upgrade divergence this shortcut needs to avoid. Can we keep ordinary skip indexes in merging_skip_indexes so the writer emits the same empty index files as the existing path, and either handle text indexes the same way or skip the shortcut when text indexes are present?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed

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.

This still is not fixed at the current head. In MergeTask.cpp:1078-1086 the shortcut repopulates text_indexes_to_merge even though createMergedStream() is skipped.

That means a TTLDrop shortcut on any table with a text index still reaches MergeTextIndexStage::prepare(), sees merge_may_reduce_rows, and calls getTextIndexSegments(new_data_part->name, index.name, 0) at MergeTask.cpp:2467-2470. But build_text_index_transforms is filled only from addBuildTextIndexesStep() inside createMergedStream() (MergeTask.cpp:3103-3104), so this path still throws LOGICAL_ERROR instead of finishing the merge.

The same reinitialization also undoes the earlier materialize_skip_indexes_on_merge = 0 clearing from MergeTask.cpp:1009-1015, so ordinary skip indexes are materialized in the shortcut path even when the normal path would suppress them.

Avogar and others added 2 commits June 24, 2026 18:30
- Reinitialize `merging_skip_indexes` from metadata instead of clearing
  them in the TTLDrop short-circuit path. `MergedBlockOutputStream`
  writes empty skip-index files with checksums even for 0-row parts, so
  clearing produces different checksums than the normal path, causing
  divergence on replicated tables during rolling upgrades.

- Fix flaky test `03737_ttl_delete_vertical_merge`: background TTLDrop
  merges can race with `OPTIMIZE TABLE FINAL`, producing Horizontal
  algorithm due to the short-circuit. Filter out `TTLDropMerge` entries
  in test1's `part_log` query and remove the non-deterministic test2
  algorithm check.

- Fix flaky test `04267_ttl_drop_merge_no_data_read`: in Case 7 (GROUP
  BY TTL), surviving rows still have expired TTL after the first merge,
  so `TTLPartDropMergeSelector` re-selects the single merged part for
  another TTLDrop. Filter by `length(merged_from) > 1` to only examine
  the merge that actually combined two source parts.

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

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Dear @Michicosun, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

Avogar added 2 commits July 8, 2026 12:34
…:ClickHouse/ClickHouse into ttl-drop-merge-skip-data-pipeline
@Michicosun Michicosun self-assigned this Jul 8, 2026

@Michicosun Michicosun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, but let's fix the test's flakiness. Maybe it is better to make it shorter; it has 6 cases. Would it be better to split into 6 tests instead?

{
if (!exclude_index_names.contains(index.name))
{
if (index.type == "text")

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.

This loop no longer applies the inert-index guard that the normal Horizontal branch has a few lines above. Attached legacy tables can still carry removed secondary index types like hypothesis; the regular merge path skips them specifically so merges stay attach-compatible.

In the TTLDrop shortcut we add that index back to merging_skip_indexes, and MergedBlockOutputStream then reaches createIndexAggregator for it from MergeTreeDataPartWriterOnDisk, which throws ILLEGAL_INDEX for MergeTreeIndexLegacyHypothesis. So a fully expired part on such a table will start failing background TTL merges even though ordinary merges still work.

Can we keep the same isInert filter in this reinitialization loop?

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 33/37 (89.19%) · Uncovered code

Full report · Diff report

@Michicosun
Michicosun added this pull request to the merge queue Aug 3, 2026
Merged via the queue into master with commit f9c80f4 Aug 3, 2026
179 checks passed
@Michicosun
Michicosun deleted the ttl-drop-merge-skip-data-pipeline branch August 3, 2026 16:19
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 3, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @Avogar @Michicosun — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Sep 20, 2026
The TTLDrop short-circuit added in ClickHouse#105859 skips createMergedStream, which is the
only caller of addBuildTextIndexesStep and so the only writer of
build_text_index_transforms. The branch still repopulated text_indexes_to_merge,
and MergeTextIndexStage::prepare escapes only on an empty container, so it looked
up a transform that was never created and threw:

    LOGICAL_ERROR: Text index transform for index <name> and part <part> not found

The expired parts were then never dropped and the merge retried forever. The
ttl_drop_short_circuit flag suppressed the producer while nothing told the
consumer.

Build the text index with an empty segment list on that path, which is what a
0-row pipeline produces. Do not clear the container: the normal 0-row path does
write text index files and does checksum them, so clearing would produce a part
that diverges from a replica's, the hazard the comment above that branch warns
about. Measured on a 0-row part, the short-circuit and the normal path agree on
all six skp_idx_* files including the 29-byte index header, and the clear-the-
container alternative drops all six while CHECK TABLE still reports success.

The same block dropped two guards when it copied the Horizontal setup:

  - The isInert filter was missing, so a legacy hypothesis index reached
    createIndexAggregator and threw ILLEGAL_INDEX, wedging an attached legacy
    table that has a rows TTL. That is the regression
    04500_hypothesis_index_no_longer_supported covers as already fixed.
  - The materialize_skip_indexes_on_merge clear runs before the short-circuit and
    the branch repopulated unconditionally, so the setting was honoured for a
    normal merge and silently ignored for a TTLDrop merge.

All three reproduce deterministically. The new test fails on a pristine master
build and passes on the fixed one, and 50/50 randomized runs pass.

Closes: ClickHouse#113223
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Sep 20, 2026
The short-circuit predicate tested only the merge type and hasOnlyRowsTTL,
so it also fired for a merge whose TTL merges were cancelled after the merge
was selected. ttl_merges_blocker is read twice in
ExecuteAndFinalizeHorizontalPart::prepare with a window between the reads:
the first read throws ABORTED, but a STOP landing after it only clears
need_remove_expired_values, which in turn clears merge_may_reduce_rows. The
short-circuit then still ran and committed a 0-row part, dropping expired
rows against an explicit SYSTEM STOP TTL MERGES, where before PR ClickHouse#105859 the
same case fell through to a merge with no TTLTransform and preserved them.
It also left merged_part_offsets null, so MergeTextIndexStage threw
"Merged part offsets are not set".

Requiring need_remove_expired_values makes such a merge take the normal
pipeline. This cannot disable the optimization for a genuine TTLDrop: the
selector only picks a part whose part_max_ttl is already in the past, and
under hasOnlyRowsTTL the table TTL is the sole contributor to part_min_ttl,
so the flag is always set. 04267_ttl_drop_merge_no_data_read still reports
read_rows = 0, and a passing run of the affected suites records 175
short-circuits taken.

The window itself has no failpoint, and the candidate test arm was measured
to be vacuous: driving it through SYSTEM STOP TTL MERGES reaches the first
blocker read instead, which yields count() = 200 and one ABORTED both with
and without this change.

Test changes in the same commit:

- Pin remove_empty_parts = 0 on all three tables. The index assertions read
  system.data_skipping_indices, which sums active parts only, so the
  background empty-part cleanup could reclaim the 0-row part first and make
  Case 1 fail spuriously and Case 2 pass vacuously.
- Give Case 3 a non-inert text index beside the inert hypothesis one, so an
  over-broad table-level inert filter is caught rather than only a filter
  that is missing entirely. A set index cannot serve here: on a 0-row part it
  writes present-but-empty files, so data_compressed_bytes is 0 either way,
  while a text index writes a 29-byte header.

Both oracles were validated by mutation: removing the
materialize_skip_indexes_on_merge gate flips Case 2's text row 0 -> 1, and
replacing the per-index isInert filter with a table-level one flips Case 3's
text row 1 -> 0, changing no other line.

Co-Authored-By: Claude Fable 5 <[email protected]>
murphy-4o added a commit that referenced this pull request Sep 24, 2026
Backport of the 03737 part of f432f74 (#105859). With #108626 a
TTLDrop merge is always Horizontal, so a background TTLDrop merge that
races OPTIMIZE FINAL flips test1_algo, and test2 (all rows expired) is a
TTLDrop merge whose algorithm is no longer Vertical.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
murphy-4o added a commit that referenced this pull request Sep 24, 2026
Backport of the 03737 part of f432f74 (#105859). With #108626 a
TTLDrop merge is always Horizontal, so a background TTLDrop merge that
races OPTIMIZE FINAL flips test1_algo, and test2 (all rows expired) is a
TTLDrop merge whose algorithm is no longer Vertical.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
qiuyanjun888 pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Sep 27, 2026
Each of the test's six facets stopped merges, inserted two parts, started
merges again, and then measured what OPTIMIZE TABLE ... FINAL did. Two
problems follow from that shape.

Re-enabling merges immediately before the OPTIMIZE FINAL whose effect is
asserted makes the background pool eligible to perform that merge instead
(merge_with_ttl_timeout = 0 makes a TTL merge immediately due), so the
ORDER BY event_time_microseconds LIMIT 1 system.part_log oracles can read a
row the OPTIMIZE did not produce. ClickHouse#105859 excluded TTLDropMerge on
test1_algo for exactly this reason and dropped test2_algo; test3_algo and
test4_algo were left on the unfiltered oracle. Measured locally with a
SELECT sleep(1) in that window: two merges per table, the first one a
background TTLDropMerge, on 3 of 3 tables.

Second, the file set optimize_throw_if_noop = 0, so every reason OPTIMIZE
can decline to merge (unreserved disk space, the background-pool memory
soft limit, the merge predicate, the 120s wait timeout) was discarded and
the test went on to assert pre-merge state. A declined OPTIMIZE is silent
by default and InterpreterOptimizeQuery ignores the return value, so the
failure surfaced as a TTL-correctness data diff instead of the reason the
server had already logged as "Cannot OPTIMIZE table: <reason>". A test
whose next statements assert post-merge state is exactly the caller that
setting exists for, so the test now opts in.

max_bytes_to_merge_at_max_space_in_pool = 0 makes background merges
impossible for these tables: getMaxSourcePartsBytesForMerge short-circuits
to 0 and select_without_hint rejects on that, while
StorageMergeTree::optimize always passes a non-empty partition_id and so
takes select_in_partition -> selectAllPartsToMergeWithinPartition, which
never reads the setting. That makes all 24 SYSTEM STOP/START (TTL) MERGES
statements unnecessary, and since SYSTEM STOP TTL MERGES is then never
issued, ttl_merges_blocker is never engaged and OPTIMIZE FINAL applies TTL
normally. Exactly one merge per table can exist, so ClickHouse#105859's merge_reason
filter is unreachable (an OPTIMIZE-driven merge is always
MergeType::Regular).

The oracles now assert that invariant instead of relying on it. The three
system.part_log queries drop LIMIT 1 and also project merge_reason and
length(merged_from), and facets 2, 5 and 6 gain the same query, so each
table must show exactly one RegularMerge over both source parts. test2_algo
is restored: ClickHouse#105859 deleted it as non-deterministic, and it is
deterministic again precisely because background merges are now impossible.
.reference is regenerated for the six testN_algo lines; every other value
is unchanged.

04029_ttl_delete_filter_vertical_merge_subquery is already in this shape,
and 02378_part_log_profile_events states the same guarantee.

Validation: 200 runner runs, 0 failures (100 with randomization disabled,
50 randomized, 50 randomized against an s3-backed server); all 1200
MergeParts rows are a single RegularMerge over both source parts, exactly
one per table, and no background merge was ever selected.

Negative control, the assertion is shown to fail: with the six guard
settings deleted and SELECT sleep(1) before each OPTIMIZE, the test reddens
3 of 3 runs. Isolated per facet so that only the oracle can differ, the old
single-column LIMIT 1 oracle printed the expected algorithm and every data
assertion still matched, i.e. the test would have passed silently, while
the new oracle reported two rows headed by Vertical/TTLDropMerge/2 (test4)
and Horizontal/TTLDropMerge/1 (test3), 3 of 3 trials each.

Forced-decline A/B, 5 of 5 in each direction: the old text prints
test4_after 2000 / test4_category 2 / test4_parts 2 silently, the new text
raises CANNOT_ASSIGN_OPTIMIZE naming the reason.

Co-Authored-By: Claude Opus 5 <[email protected]>
alexey-milovidov pushed a commit to zeev1079/ClickHouse that referenced this pull request Oct 11, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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.

TTLDrop merge opens all source parts and allocates buffers instead of just dropping them

5 participants