Skip to content

Improve the performance of MODIFY TTL - #63383

Open
zhongyuankai wants to merge 131 commits into
ClickHouse:masterfrom
zhongyuankai:fast_materialize_ttl
Open

zhongyuankai wants to merge 131 commits into
ClickHouse:masterfrom
zhongyuankai:fast_materialize_ttl

Conversation

@zhongyuankai

@zhongyuankai zhongyuankai commented May 5, 2024 •

Copy link
Copy Markdown
Contributor

ALTER TABLE ... MODIFY TTL currently rewrites every part of the table, which on a large table means reading and writing all of its data just to change when rows expire.

Very often the new TTL is the old one shifted in time - the retention period is extended or shortened, e.g. create_time + INTERVAL 300 DAY becomes create_time + INTERVAL 10 DAY. In that case every row's expiry time moves by the same constant number of seconds, so the parts do not have to be rewritten at all: it is enough to shift the expiry timestamps ClickHouse already stores per part. This pull request adds that fast path, and the result for the user is that such a MODIFY TTL completes almost instantly instead of taking minutes or hours:

CREATE TABLE test_fast_ttl (`id` UInt32, `name` String, `create_time` DateTime)
ENGINE = MergeTree
ORDER BY id
TTL create_time + toIntervalDay(300);

INSERT INTO test_fast_ttl SELECT number, 'AAA', date_sub(day, 100, now()) from numbers(100000000);

-- Before
ALTER TABLE test_fast_ttl MODIFY TTL create_time + INTERVAL 10 DAY;
--  0 rows in set. Elapsed: 25.564 sec.

-- After
ALTER TABLE test_fast_ttl MODIFY TTL create_time + INTERVAL 10 DAY;
-- 0 rows in set. Elapsed: 0.046 sec.

There is nothing to enable and no new syntax: the optimization is applied automatically inside the MATERIALIZE TTL mutation that MODIFY TTL already produces, and a plain ALTER TABLE ... MATERIALIZE TTL benefits from it as well. The observable result is exactly the same as before - the same rows expire and the parts end up with the same TTL bounds - only the work is avoided.

Per part, the mutation now does one of the following:

  • the part is fully expired under the new TTL - it is replaced with an empty part;
  • no row of the part is expired yet - the part is cloned (its data files hardlinked) and only its stored TTL bounds are shifted;
  • otherwise - the part is rewritten exactly as before.

The fast path is only taken when it is provably equivalent to the rewrite. It requires that the unconditional rows TTL (TTL <expr>) is the only TTL of the table, and that the old and the new TTL are the same date/time column shifted by constant fixed-length intervals, so that new_ttl(row) - old_ttl(row) is one constant for every row. Calendar MONTH/YEAR intervals, DAY/WEEK intervals in a time zone with daylight saving time, and row-dependent expressions are all rejected. The proof is redone for each part against the TTL expression (and time zone) that the part's stored timestamps were actually computed under, so a part that lags the table metadata, or was written by an older server, falls back to the regular rewrite rather than being shifted unsoundly. The same applies to the boundary cases of the stored timestamps themselves: a part containing a row whose TTL timestamp is exactly 1970-01-01 00:00:00 UTC (which ClickHouse treats as "no TTL"), a shift that would move some timestamp onto that value, and a part whose stored TTL is already fully expired (which the regular rewrite drops wholesale, even when the new TTL is longer) all take the regular rewrite.

Changelog category (leave one):

  • Performance Improvement

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

ALTER TABLE ... MODIFY TTL no longer rewrites the table's data when the new TTL is the old one shifted by a constant amount of time (the same date/time column plus fixed-length intervals), which is the common case of extending or shortening the retention period. Fully expired parts are replaced with empty ones and the rest are cloned with only their stored TTL metadata shifted, which makes such an ALTER nearly instant. Cases where the shift is not provably constant - calendar month/year intervals, day/week intervals in a time zone with daylight saving time, or row-dependent TTL expressions - fall back to the regular rewrite. ALTER TABLE ... MATERIALIZE TTL benefits from the same optimization.

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

Modify your CI run

NOTE: If your merge the PR with modified CI you MUST KNOW what you are doing
NOTE: Checked options will be applied if set before CI RunConfig/PrepareRunConfig step

Include tests (required builds will be added automatically):

  • Fast test
  • Integration Tests
  • Stateless tests
  • Stateful tests
  • Unit tests
  • Performance tests
  • All with ASAN
  • All with TSAN
  • All with Analyzer
  • All with Azure
  • Add your option here

Exclude tests:

  • Fast test
  • Integration Tests
  • Stateless tests
  • Stateful tests
  • Performance tests
  • All with ASAN
  • All with TSAN
  • All with MSAN
  • All with UBSAN
  • All with Coverage
  • All with Aarch64
  • Add your option here

Extra options:

  • do not test (only style check)
  • disable merge-commit (no merge from master before tests)
  • disable CI cache (job reuse)

Only specified batches in multi-batch jobs:

  • 1
  • 2
  • 3
  • 4
Details

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

@CLAassistant

CLAassistant commented May 5, 2024 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@zhongyuankai
zhongyuankai force-pushed the fast_materialize_ttl branch from d016b28 to f8a26db Compare May 5, 2024 15:45
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 5, 2024
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-performance Pull request with some performance improvements label May 5, 2024
@zhongyuankai
zhongyuankai force-pushed the fast_materialize_ttl branch from 4b15f63 to 271654b Compare May 6, 2024 05:06
@rschu1ze rschu1ze self-assigned this May 8, 2024
@rschu1ze rschu1ze changed the title Improve the performance of MODIFY TTL Improve the performance of MODIFY TTL May 14, 2024
@rschu1ze

rschu1ze commented May 14, 2024 •

Copy link
Copy Markdown
Member

Thanks for the PR! Two thoughts:

  • to the reviewer / reader, it is not clear how the optimization actually works and why it is faster than the old path. Neither the PR message, nor commit message(s), nor code comments actually explain how MODIFY TTL previously worked and how it works now. Are there caveats of the new path, i.e. situations where it doesn't work or is slower than the old path? I'd basically need to debug the old and new paths to find it out manually. It would be great if you could provide more information.
  • for simplicity, we should not have two paths (and likewise, no setting to enable the new path). This PR should also remove the old path. (in case something breaks, we can go back to the previous state by reverting this PR).

@zhongyuankai

Copy link
Copy Markdown
Contributor Author

@rschu1ze Thank you for your reply. What this PR optimizes is when we modify the life cycle of table data. This is a very frequent operation. However, under the current implementation, modifying a table with a large amount of data requires a lot of time and resources. The reason is MODIFY TTL is a general implementation that requires rewriting all data, resulting in very slow speed.
According to my understanding, when the life cycle of the table is adjusted from 100 days to 10 days, only the data of the last 10 days need to be rewritten, and other data will be deleted directly. When adjusting the table life cycle from 10 days to 100 days, you only need to modify the ttl.txt and checksums.txt files. There is no need to rewrite the data, which will significantly increase the modification speed.
Do you think this idea can be implemented?

@zhongyuankai

Copy link
Copy Markdown
Contributor Author

@rschu1ze Hello, I wonder if you think this idea is okay, if so, I am willing to continue to complete it.

@rschu1ze

Copy link
Copy Markdown
Member

@CurtizJ I guess you are more familiar with the TTL implementation than me. Would you like to check?

Comment thread src/Core/Settings.h Resolved
@zhongyuankai
zhongyuankai force-pushed the fast_materialize_ttl branch from 271654b to 9a3e5a8 Compare June 22, 2024 07:44
@zhongyuankai

Copy link
Copy Markdown
Contributor Author

@rschu1ze Hello, are you interested in continuing the review?

@rschu1ze

rschu1ze commented Jul 1, 2024

Copy link
Copy Markdown
Member

As mentioned above, @CurtizJ is much more familiar with the TTL code, if he finds time it makes sense to continue.

@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2024

Copy link
Copy Markdown
Contributor

Dear @rschu1ze, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@CurtizJ CurtizJ self-assigned this Nov 4, 2024
@clickhouse-gh

clickhouse-gh Bot commented Dec 10, 2024

Copy link
Copy Markdown
Contributor

Dear @CurtizJ, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

alexey-milovidov and others added 3 commits June 17, 2026 20:38
Bring the `MODIFY TTL` performance optimization up to date with master after
a long gap. The branch was ~96k commits behind, so all of the touched files
had to be re-adapted to current APIs:

- `MutationCommand` now persists a serialized `ast_text` and reparses it on
  demand (`ast()` / `mutateAst()`) instead of holding a live AST. The
  `ttl_delta` round-trips through `ast_text` via the `MATERIALIZE TTL <delta>`
  format/parse changes, and `FAST_MATERIALIZE_TTL` is reconstructed in
  `MutationCommand::parse`.
- `MutationCommand::parse` takes `const ASTAlterCommand &` and extra parser
  limit arguments; `createFastMaterializeTTLCommand` now sets `ast_text`.
- `Field::get` was renamed to `Field::safeGet`.
- `ASTAlterCommand::formatImpl` writes to a `WriteBuffer &` directly.
- `MutateTask::prepare` was restructured around `isStorageTouchedByMutations`;
  the part-clone code is factored into a `clone_part` lambda shared by the
  untouched-part path and the fast `MODIFY TTL` path. `createEmptyPart` gained
  `partition` and `metadata_snapshot` arguments.
- `getMutationCommands` applies commands to a metadata copy before the TTL
  loop, so `tryOptimizeModifyTLL` is now fed `original_metadata` to read the
  old TTL and compute a non-zero delta.
- The guard against a user issuing the internal `MATERIALIZE TTL <delta>`
  syntax directly moved to `InterpreterAlterQuery::executeToTable`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adapt `AlterCommands.cpp` to current APIs surfaced by the build:

- ASTs are `boost::intrusive_ptr` now, so the literal-normalizing visitor uses
  `make_intrusive<ASTLiteral>(Field(0))` instead of `std::make_shared`.
- `allow_suspicious_ttl_expressions` is read via `settings[Setting::...]`.
- Include `Columns/ColumnConst.h` and `Columns/ColumnsNumber.h` so the result
  TTL column type checks in `tryOptimizeModifyTLL` see complete column types.

Verified locally: `03148_fast_materialize_ttl` passes (0.9s) and a batch of TTL
regression tests (`01070_modify_ttl`, `01070_modify_ttl_recalc_only`,
`01070_materialize_ttl`, `00933_*_ttl`, `00976_ttl_with_old_parts`, ...) pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The optimized mutation is persisted to the replicated log as
`MATERIALIZE TTL <delta>`, which older servers cannot parse. Per maintainer
decision the optimization stays unconditional (no gating setting); record the
trade-off next to where the command is created so it is a known, intentional
choice rather than a hidden landmine.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7b95eda]

Summary: ❌

job_name test_name status info comment
Style check FAIL
failpoint_tests_are_isolated FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate these failures and provide fixes in separate PRs. If a fix is already in progress, link it here. Both are unrelated to this PR (neither touches TTL code):

The other red checks already have fixes in progress: 05055_format_schema_source_query_background_access in #127797, and the stress-test Cannot write to canceled buffer in client progress in #127834. Build profile diff failed on CI infrastructure (LogClusterNotReady).

@groeneai

Copy link
Copy Markdown
Collaborator

Both already have fixes in progress, both mine:

…ion when a column is reset

`TTLDeleteAlgorithm::finalize` keeps the incoming rows-TTL bounds together with the fingerprint of the
expression they were computed under when it does not rescan the part. That expression may differ from
the current rows TTL, while `TTLTransform` checked reset columns (column TTLs, whole-part expired
columns and recomputed `MATERIALIZED` dependents) only against the sources of the current rows TTL.
After a `MODIFY TTL` back to the older expression, the fast `MATERIALIZE TTL` path shifted bounds that
described values a column TTL had already replaced, deleting live rows.

When the kept bounds carry a fingerprint different from the current rows TTL and any column may be
reset, drop their provenance so the next materialization rescans the part.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed 723d119ca34d, which addresses the latest review: rows-TTL bounds kept under an older TTL expression are now invalidated when a column TTL resets a column. It adds the test 05453_materialize_ttl_column_ttl_old_expression. Thanks @groeneai for linking the fixes for the two unrelated failures. On 3aada75914d0 the only red checks were Build profile diff, which failed on CI infrastructure (LogClusterNotReady: the endpoint never became ready), and CH Inc sync.

…ttl_only_drop_parts`

`TTLPartDropMergeSelector` excluded every part carrying `has_epoch_timestamps`. With
`ttl_only_drop_parts = 1` the row-delete TTL selector is disabled, so such a part was never cleaned up
automatically, even when the marker was stale: an ordinary `DELETE` mutation copies the TTL infos
without recalculating them, so the marker can outlive the epoch row that set it.

Let the selector consider such parts again, and instead make `MergeTask::isRowsTTLExpired` refuse the
part, so the `TTLDrop` merge does not drop it without reading. The merge then scans the part, removes
the expired rows described by the bounds and keeps the epoch rows, which also refreshes the marker.
The same predicate decides the space reservation of a replicated `TTLDrop` merge, which now reserves
room for such a part.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The CI failures on 723d119 are not caused by this PR, and fixes are already in progress:

@groeneai, please check these and link any other fix here if one exists.

@groeneai

Copy link
Copy Markdown
Collaborator

All three check out, and apart from CH Inc sync they are the only red checks on 723d119, so there is no other fix to link.

alexey-milovidov and others added 2 commits October 30, 2026 10:42
A part whose rows were all removed by a merge (e.g. a lightweight delete of
the whole part followed by `OPTIMIZE`) keeps the rows-TTL bounds of the
removed rows. `MergeTreeDataPartTTLInfos::update` already ignored the
provenance of a source with no rows, but still merged its `table_ttl`
bounds, so merging the empty part with a live sibling attached the deleted
row's maximum to the sibling's valid fingerprint. A later metadata-only
`MATERIALIZE TTL` then shifted that stale maximum, and with
`ttl_only_drop_parts` an entirely expired part was kept until it.

Skip the `table_ttl` bounds of a source with no rows as well. Adds the test
`05459_materialize_ttl_empty_source_bounds`.

ClickHouse#63383

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and pushed 6e8e49adf27a, which addresses the latest review: an empty source part no longer adds its stale rows-TTL bounds to the merged part. New test: 05459_materialize_ttl_empty_source_bounds. The only failure on 1c4f3a825c29 was 05397_clickhouse_local_locked_path_untouched in Fast test (arm_darwin). That failure is unrelated to this PR, and master already skips the test on macOS (59f220cb8187), so the merge picks up the fix. The two older open threads (CompactionStatistics and the whole-part shortcut for pre-upgrade parts) concern behaviour master already has. They still need a maintainer decision.

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
alexey-milovidov and others added 3 commits October 31, 2026 05:29
…fore the epoch

A full recalculation stores `max = 0` for a TTL range before the epoch, while
the shift with `materialize_ttl_recalculate_only = 1` persisted a negative
`max`. A later `MODIFY TTL` then took the part as fully expired
(`all_data_dropped` in `TTLTransform`) and dropped rows that the new TTL keeps.
Reject the shift whenever the shifted minimum is not positive.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=63383&sha=6e8e49adf27a00ca015b1003c7ef3daba800a2ce&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%202%2F4%29 (test_storage_rabbitmq/test.py::test_rabbitmq_reconnect_drops_stale_deliveries, a rabbitmqctl list_queues call hung for 300 s) and provide a fix in a separate PR. If the fix is already in progress, link it here. It looks like #126746 covers it.

@groeneai

Copy link
Copy Markdown
Collaborator

Yes, #126746 (mine, open) covers it. This red has the same signature: one rabbitmqctl -q list_queues call in queue_drained (test.py:4041) never returned, and the harness waited its 300 s default. #126746 bounds that call at 30 s and asks again within the test's existing deadline, and it only asks once the row count has been stable for 3 s, so it is about one call per run. It also closes the connections through the management API instead of rabbitmqctl close_all_connections, which hung the same way on #126642. Its CI is green and it is waiting for review.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai for confirming that #126746 covers the test_storage_rabbitmq red. On b94f023b094c every check is green except CH Inc sync, which failed because the private sync PR had conflicts. I resolved them and pushed a merge to the sync branch. The PR no longer changes PartProperties, so that file now takes private master. In MutateTask.cpp I kept the Cloud-specific clone path from the previous sync. The sync PR is now mergeable. No change to this PR was needed. The two open review threads (CompactionStatistics, and the whole-part shortcut for pre-upgrade parts) are about behaviour master already has, and they still need a maintainer decision.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 CH Inc sync failed with build failed: my previous conflict resolution on the private sync branch left a stray fragment of the public clone_part lambda in MutateTask.cpp. I rebuilt that file from the last sync resolution that compiled plus the new public PR delta, merged the latest private master, and pushed e0f217bffbf5 to the sync branch. Only that one file changed, and only in the Cloud-specific clone code. This PR itself needs no change: every other check on b94f023b094c is green. The two open review threads (CompactionStatistics, and the whole-part shortcut for pre-upgrade parts) are about behaviour master already has, and they still need a maintainer decision.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
Resolve the conflict in `TTLTransform.cpp`: keep this PR's `GROUP BY` TTL
loop (which records `rows_ttl_provenance_invalidated`) and take master's
switch of `TTLAggregationAlgorithm` to `getOutputPort().getHeader()`
from d6c7f4c.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The PR had become CONFLICTING, so I merged master and pushed f3dd39608bc4. The only conflict was in TTLTransform.cpp: this PR's GROUP BY TTL loop (the one that sets rows_ttl_provenance_invalidated) against d6c7f4c, which builds TTLAggregationAlgorithm with getOutputPort().getHeader(). I kept both changes. TTLTransform.cpp, MergeTask.cpp and MutateTask.cpp compile, and the set of files this PR changes is the same as before the merge. The two open review threads (CompactionStatistics, and the whole-part shortcut for pre-upgrade parts) still need a maintainer decision, as explained in the replies there.

alexey-milovidov and others added 3 commits November 10, 2026 17:09
Resolve the conflict in `MutateTask.cpp` by keeping both the PR's
`rewrite_ttl_infos` and master's `recalculate_ttl_only` flags, and adapt
the fast `MATERIALIZE TTL` path to `setResultPart`, which replaced
`promise.set_value` on master.
Conflict in `TTLTransform.cpp`: a788c82 moved the setup of the expired columns'
default expressions to the top of the `TTLTransform` constructor, before the new
`apply_ttl` early return. Took that placement and kept this PR's check that invalidates
the rows-TTL provenance when an expired column is a source column of the rows TTL.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The PR had become CONFLICTING again, so I merged master and pushed a5c1338a47b7.

The only conflict was in TTLTransform.cpp. a788c82 ("Apply TTL in a merge only when the merge may apply it") moved the setup of the expired columns' default expressions to the top of the TTLTransform constructor, before its new apply_ttl early return. I took that placement and kept this PR's check that invalidates the rows-TTL provenance when an expired column is a source column of the rows TTL.

With apply_ttl = false that check no longer runs, and finalize keeps the TTL infos of the part. This does not open a gap: such a column is absent from the source parts, so the provenance check in MergeTask.cpp already drops the fingerprint for it.

The 41 TTL tests of this PR, together with 05257_ttl_merge_with_unmaterialized_column from that master commit, pass locally on the merged tree. The set of files this PR changes is the same as before the merge.

CH Inc sync was red on the previous head and will re-run on this one. The two open review threads (CompactionStatistics.cpp and TTLDeleteFilterTransform.cpp) are unchanged: both describe behaviour that master already has, both have a reply, and they are left for a maintainer to decide.

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
alexey-milovidov and others added 2 commits November 24, 2026 05:15
Conflict in `TTLTransform.cpp`: keep the rows-TTL provenance tracking of this
branch in `add_column_ttl_algorithm` and pass the new `shares_nested_offsets`
argument that `TTLColumnAlgorithm` takes on master.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…pending `DROP COLUMN`

`AlterConversions::hasMutations` covers only the data mutations applied on the fly and
`getRenameMap` the renames, while a pending `DROP COLUMN` is tracked separately. The merge
reader ignores the values a source part stores under the dropped name and fills a column
added again under that name from its DEFAULT, but the presence and type check in
`MergeTask` still saw the old physical column, so the merged part kept the fingerprint of
rows-TTL bounds computed from other values. A later `MODIFY TTL` to a shift of the old
expression then shifted the stale bounds and removed live rows.

Check `getValueUpdatedColumns`, which includes the names touched by pending drops.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

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-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants