Skip to content

TTL CLEAR INDEX for MergeTree parts - #108069

Open
EmeraldShift wants to merge 6 commits into
ClickHouse:masterfrom
EmeraldShift:ttl-index-drop
Open

EmeraldShift wants to merge 6 commits into
ClickHouse:masterfrom
EmeraldShift:ttl-index-drop

Conversation

@EmeraldShift

@EmeraldShift EmeraldShift commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #107804
Closes: #78714

Add a CLEAR INDEX TTL action that deletes a skip index's files from parts once all their rows are past the TTL.

The index stays in the table definition and new parts still build it. We want this for log tables, where the text index can be many times larger than the data, and almost every search is over the last few days.

CREATE TABLE logs (...)
ENGINE = MergeTree
PARTITION BY toYYYYMMDD(timestamp)
ORDER BY (service, timestamp)
TTL timestamp + INTERVAL 3 DAY CLEAR INDEX message_text;

Regular merges already rewrite parts, so they just leave out any index whose TTL has expired for all of their source rows. That covers most parts and doesn't need a setting. TTL delete merges recalculate TTL info as they go, so they only find out which indexes expired after writing the part, and delete those files then.

Parts at the merge size limit never merge again though, so they'd keep their index forever. For those we add a TTLClearIndex merge type, behind the MergeTree setting ttl_clear_index_merges (on by default). It hardlinks everything except the expired index files, rewrites skp_idx.packed if needed, writes checksums.txt, and loads the new part from disk. It never reads rows. The new part keeps the source part's data version, so pending mutations like RENAME COLUMN still apply to it.

These merges only take parts whose files we can hardlink, and we let them skip the merge size limits since hardlinking costs about the same for any size part. Some incompatible cases: packed part storage, parts with UUIDs, level-0 parts in engines that merge rows like ReplacingMergeTree, and tables with always_use_copy_instead_of_hardlinks or zero-copy replication. Those still get cleared by their next regular merge or an OPTIMIZE ... FINAL. Otherwise they're just TTL merges: they count against the TTL merge limits, SYSTEM STOP TTL MERGES stops them, and they're picked after the other TTL merges. Like TTLDrop merges, they don't wait for merge_with_ttl_timeout.

On ReplicatedMergeTree every replica runs the merge on its own copy of the part (copying instead of hardlinking if it has to), so an entry never waits on one particular replica. A replica whose part has a different format, or that can't reserve space, just fetches.

For rollout, wait until every replica is upgraded before adding a CLEAR INDEX rule. Older versions can't parse the rule, and they stop pulling the replication log when they see a TTLClearIndex merge. The usual compatibility setting during an upgrade also turns ttl_clear_index_merges off.

Mutations like MATERIALIZE INDEX and MATERIALIZE TTL don't clear indexes yet, because clearing them in mutations is tricky enough to warrant its own PR. Mutations write parts with MutateTask, so none of the merge code here applies to them. Until then, a mutation can write an expired index again, and the next TTLClearIndex merge will cheaply delete it.

system.parts gets index_clear_ttl_info.{expression,min,max} like the other TTL info columns, and system.part_log logs these merges as TTLClearIndexMerge.

Since the last review I simplified things a lot, so many of the earlier threads are about code that's gone now:

  • TTLClearIndex merges now only select parts they can hardlink. The old behavior, to select and fall back to rewriting data, is gone.
  • I dropped the copy size limit and the one-merge-per-table limit. With the previous change, TTLClearIndex merges are cheap.
  • The MergeTree setting ttl_clear_index_merges replaces the query setting enable_ttl_clear_index_merge_type_generation.

About two thirds of the diff is new since then, so I rewrote the history into commits that build on each other. They're meant to be read in order.

Changelog category (leave one):

  • New Feature

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

MergeTree tables support TTL ... CLEAR INDEX index_name, which deletes a skip index's files from parts once all their rows are past the TTL.


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

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

clickhouse-gh Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0b19b0c]

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

PR #108069 adds TTL ... CLEAR INDEX, TTL metadata, opportunistic index removal during merges, and dedicated TTLClearIndex maintenance merges. Reviewed head 0b19b0c4016e89397fe8cdf44cf62fed2cb31154. One new Major is reproduced: a column TTL can move the output deadline into the future after the merge has already omitted the index. The previously reported patch-update issue also remains, with an open follow-up tracking it.

Findings

⚠️ Majors

  • src/Storages/MergeTree/MergeTask.cpp:1167: Index omission uses bounds that a column TTL can invalidate during the same merge. For d Date DEFAULT toDate('2100-01-01') TTL expiry and TTL d + INTERVAL 1 DAY CLEAR INDEX idx, insert rows with both dates in 2000 and perform one regular merge. The column TTL resets d to 2100, and the final clear-index bound becomes 2100-01-02, but the index was excluded using the source bound. Reproduced with the PR's Fast test binary: index bytes change from 39 to 0, although every output row has a future deadline. A lone merged part can consequently lose index acceleration indefinitely. Preserve the index while TTL actions can change its deadline inputs, then prune only against the final output bounds.

  • src/Storages/MergeTree/MergeTask.cpp:1167: Applying lightweight updates can leave clear-index bounds stale. [dismissed by author -- https://github.com/TTL CLEAR INDEX for MergeTree parts #108069#discussion_r4350943392] The current merge still does not force TTL recalculation when patch parts change a TTL input. Reproduced again: two parts initially dated 2100-01-01, followed by UPDATE to 2000-01-01 and OPTIMIZE ... FINAL with apply_patches_on_merge = 1, store the updated dates but retain a 2100-01-02 TTL bound and the expired index. This still violates automatic expiry; the author chose a separate fix, tracked by PR #116175, which remains open. No duplicate inline comment or thread reply was posted.

Tests
  • ⚠️ Add a stateless regression for a column TTL moving a clear-index input from an expired value to a future default. Set max_number_of_merges_with_ttl_in_pool = 0 and ttl_clear_index_merges = 0, then use one OPTIMIZE ... FINAL and assert both the output bound and index presence. A second merge rebuilds the index and masks this defect.
  • ⚠️ The patch-update follow-up should cover both deadline directions and pending patches during dedicated cleanup. The current stateless tests update an index payload column, which does not exercise a changed TTL input.
Final Verdict

Status: ⚠️ Request changes

Defer early index omission when TTL actions can change the deadline inputs, and add the focused column-TTL regression. Keep the patch-update issue tracked in PR #116175.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 21, 2026
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@EmeraldShift
EmeraldShift force-pushed the ttl-index-drop branch 4 times, most recently from 2b12024 to 1adee2e Compare June 23, 2026 12:42
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Interpreters/PartLog.cpp Resolved
@EmeraldShift
EmeraldShift force-pushed the ttl-index-drop branch 3 times, most recently from e386731 to 1cba4cc Compare June 23, 2026 22:07
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
@EmeraldShift

Copy link
Copy Markdown
Contributor Author

Replies to the AI review of 55a3575:

  • Replicated metadata replay (StorageReplicatedMergeTree.cpp). StorageReplicatedMergeTree::alter runs under the table's alter lock, and executeMetadataAlter takes the same lock, so the replica's metadata can't change between checking an ALTER and committing it. The ALTER writes /metadata only if its ZooKeeper version still matches the replica's metadata version, so a replica that's fallen behind gets ZBADVERSION and the ALTER is rejected. So a DROP INDEX idx is always checked against metadata that already has the CLEAR INDEX idx rule, and AlterCommands::apply rejects it. Throwing during replay would also leave a lagging replica stuck on an ALTER that's already committed, which seems worse.

  • Stale ttl.txt (PartProperties.cpp). I dropped that check on purpose, so a part whose TTL info is missing an unrelated rule still gets its index cleared. With materialize_ttl_after_modify = 0, existing parts don't get the new rule until something rewrites them, and that's the same on master. A TTLClearIndex merge keeps the source part's ttl.txt, so the new part still reports that not all TTLs are calculated, and OPTIMIZE ... FINAL and MATERIALIZE TTL still pick it up. I claim there's nothing to do here.

  • Orphan skp_idx_* files (MergeTreeIndexClearTTL.cpp). Selection and execution agree. pruneExpiredIndexFilesFromPart only removes files that are in checksums.txt or skp_idx.packed, the same files partHasSkipIndexFiles looks at. Files missing from checksums.txt come from the Mutations via MutateAllPartColumnsTask write checksums.txt without hardlinked skip-index files #109595 bug, and regular merges don't clean them up either. I'd rather not add on-disk scanning to merge selection for that case.

  • where_expr for the other TTL modes (ASTTTLElement.cpp). groeneai is fixing that in a separate PR.

@Ergus

Ergus commented Oct 20, 2026

Copy link
Copy Markdown
Member

@EmeraldShift Could you solve the conflicts with master please?

@Ergus

Ergus commented Oct 20, 2026

Copy link
Copy Markdown
Member

CI says:

The settings history must record the changes made now under the current version ('26.11'): add a record {"26.11", previous_value, new_value, "reason"} as the first trailing argument of the setting's declaration. Records under older versions may be added freely (backports, corrections):
MergeTree setting 'ttl_clear_index_merges' was added or its default changed, but it has no '26.11' record

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment on lines +1181 to +1184
if (!ctx->force_ttl && !global_ctx->ttl_merges_blocker->isCancelled())
for (const auto & [index_name, _] : getIndexesWithExpiredClearTTL(
*global_ctx->metadata_snapshot, global_ctx->new_data_part->ttl_infos, global_ctx->time_of_merge))
exclude_index_names.insert(index_name);

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.

[P2] Recalculate index-clear TTL bounds when applying patches

force_ttl only detects missing TTL entries, so a lightweight update to a column used by CLEAR INDEX leaves this decision using the original parts' bounds. Index-clear TTLs do not contribute to part_min_ttl, so an index-only TTL does not cause TTLTransform to recalculate them when the merge applies patches.

Reproduced with this PR's ARM CI binary: create a table with TTL d + INTERVAL 1 DAY CLEAR INDEX idx and apply_patches_on_merge = 1, insert two parts dated 2100-01-01, run UPDATE ... SET d = '2000-01-01' WHERE 1, then OPTIMIZE ... FINAL. Reading with apply_patch_parts = 0 confirms that every stored row is now dated 2000-01-01, but the merged part still reports index_clear_ttl_info.max = ['2100-01-02 00:00:00'] and retains the index. Subsequent dedicated clears also trust this bound, so the expired index is retained until the old deadline. The inverse update removes the index despite every output row having a future deadline.

Please recalculate affected index_clear_ttl bounds from patched rows and defer index omission/pruning until those bounds are available. Cover both update directions, including dedicated cleanup while TTL-changing patches are pending.

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.

Master has the same problem. A merge that applies patches keeps the source parts' TTL bounds, so a lightweight update to d leaves stale bounds for DELETE and RECOMPRESS too. I'd rather fix that for every TTL kind in a separate PR. @groeneai could you take it? I think the fix is to set force_ttl when the patches update a column that a TTL expression reads. This PR already handles force_ttl.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is already fixed by #116175 (open, by @ valerypetrov): a merge that applies patch parts recalculates the TTL infos from the patched rows. I ran your scenario on master (1df150bae26c) and on that PR's CI build (80e591e425fb): TTL d + INTERVAL 1 DAY, two parts at 2100-01-01, UPDATE ... SET d = '2000-01-01' WHERE 1, then OPTIMIZE ... FINAL.

So I won't open a duplicate PR.

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 22, 2026
…alization

`ParserTTLElement` accepts `WHERE` only after `DELETE`, and `TTLDescription`
applies it only for `DELETE`, but `ASTTTLElement::readJSON` restored
`where_expr` for every mode. A `clickhouse_json` `CREATE TABLE ... TTL d TO DISK
'default'` carrying a `where_expr` was therefore accepted, the `WHERE` was
ignored, and `formatImpl` stored `TTL d TO DISK 'default' WHERE x`, which fails
to parse at the next start (`Code: 62`), so the database does not load. Same for
`RECOMPRESS` and `GROUP BY`; `formatQueryFromJSON` returned the same
unparsable SQL.

Reject `where_expr` unless the mode is `DELETE`, like the existing per-mode
checks for the codec, destination and `GROUP BY` fields in the same function.
The check sits at the read site so it does not textually overlap ClickHouse#108069 (which
adds the same check for its new `CLEAR INDEX` mode) or ClickHouse#121585.

Requested in ClickHouse#108069 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
A `TTL expr CLEAR INDEX idx` rule names a skip index whose files a part
doesn't need once every row in it has expired. This commit only parses
and validates the rule and records its min and max TTL in each part's
`ttl.txt`, which `system.parts` shows as `index_clear_ttl_info`. Nothing
deletes index files yet.
A merge leaves out an index whose `CLEAR INDEX` rule has expired for all
of its source rows. A merge that recalculates TTL info, like a TTL delete,
only learns which indexes expired after writing the part, so it deletes
their files then, rewriting `skp_idx.packed` if needed.
A `TTLClearIndex` merge takes one part and hardlinks every file except
the expired index files into the new part, copying where it can't
hardlink. It loads the new part from disk without reading any rows, and
the new part keeps the source part's data version. Nothing selects these
merges yet.
A part that never merges again, like one at the maximum size, keeps its
expired indexes. Merge selection now picks a `TTLClearIndex` merge for any
part with an expired index whose files it can hardlink. These merges count
as TTL merges, ignore the merge size limits, and are picked after the other
TTL merges.

The MergeTree setting `ttl_clear_index_merges` turns these merges off. It's
on by default, and setting `compatibility` to an older version turns it off
during a rolling upgrade.
A `TTLClearIndex` merge is cheaper than a fetch, so every replica of a
`ReplicatedMergeTree` runs the merge on its own copy of the part, copying
the files if the replica can't hardlink them. A replica fetches the result
only if its part has a different format or it can't reserve space. The
size limit on merges doesn't apply to these entries.
Comment on lines +1167 to +1170
if (!ctx->force_ttl && !global_ctx->ttl_merges_blocker->isCancelled())
for (const auto & [index_name, _] : getIndexesWithExpiredClearTTL(
*global_ctx->metadata_snapshot, global_ctx->new_data_part->ttl_infos, global_ctx->time_of_merge))
exclude_index_names.insert(index_name);

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.

[Major] Preserve the index when a column TTL changes its deadline

force_ttl stays false for an ordinary merge applying an already-calculated column TTL. That merge can change a CLEAR INDEX input, so the source bounds used here do not establish that the output rows have expired. The final pruning step cannot restore an index already excluded here.

Reproduced with this head's Fast test binary:

CREATE TABLE t
(
    k UInt64, expiry Date,
    d Date DEFAULT toDate('2100-01-01') TTL expiry,
    v UInt64, INDEX idx v TYPE minmax
)
ENGINE = MergeTree ORDER BY k
TTL d + INTERVAL 1 DAY CLEAR INDEX idx
SETTINGS ttl_clear_index_merges = 0,
    max_number_of_merges_with_ttl_in_pool = 0,
    min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0;
INSERT INTO t VALUES (1, '2000-01-01', '2000-01-01', 1);
OPTIMIZE TABLE t FINAL;

The output rows have d = '2100-01-01' and system.parts.index_clear_ttl_info.max = ['2100-01-02 00:00:00'], but secondary_indices_compressed_bytes = 0. A lone resulting part can keep scanning without its index indefinitely despite its future deadline. No patch parts are involved.

Please defer omission whenever the merge can change the TTL inputs, build the index in that case, and let the final bounds decide whether to prune it. Add a stateless regression for this column-TTL case.

@clickhouse-gh

clickhouse-gh Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Dear @Ergus, 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.

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 manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] TTL CLEAR INDEX for MergeTree parts Automatic skip index lifecycle management for aging partitions

8 participants