Repository navigation
Skip data reading step entirely for TTLDrop merges to avoid excessive memory usage - #105859
Conversation
`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]>
|
Workflow [PR], commit [94f4954] Summary: ✅
AI ReviewSummaryThis PR short-circuits Findings❌ Blockers
Final Verdict❌ Changes requested. The |
…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]>
…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]>
…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]>
| global_ctx->text_indexes_to_merge.clear(); | ||
| } | ||
| else | ||
| { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
…op-merge-skip-data-pipeline
- 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]>
|
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. |
…:ClickHouse/ClickHouse into ttl-drop-merge-skip-data-pipeline
Michicosun
left a comment
There was a problem hiding this comment.
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?
…ouse/ClickHouse into ttl-drop-merge-skip-data-pipeline
| { | ||
| if (!exclude_index_names.contains(index.name)) | ||
| { | ||
| if (index.type == "text") |
There was a problem hiding this comment.
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?
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 33/37 (89.19%) · Uncovered code |
|
Hi @Avogar @Michicosun — while reviewing this PR I found the following:
Happy to discuss — close anything that's wrong or already addressed. |
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
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]>
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]>
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]>
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]>
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Skip data reading step entirely for
TTLDropmerges to avoid excessive memory usage, especially on read/prefetch buffers allocations. Closes #105639