Repository navigation
Improve the performance of MODIFY TTL - #63383
zhongyuankai wants to merge 131 commits into
Conversation
d016b28 to
f8a26db
Compare
4b15f63 to
271654b
Compare
MODIFY TTL
|
Thanks for the PR! Two thoughts:
|
|
@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 |
|
@rschu1ze Hello, I wonder if you think this idea is okay, if so, I am willing to continue to complete it. |
|
@CurtizJ I guess you are more familiar with the TTL implementation than me. Would you like to check? |
271654b to
9a3e5a8
Compare
|
@rschu1ze Hello, are you interested in continuing the review? |
|
As mentioned above, @CurtizJ is much more familiar with the TTL code, if he finds time it makes sense to continue. |
|
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. |
|
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. |
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]>
|
Workflow [PR], commit [7b95eda] Summary: ❌
|
|
🕵 @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: |
|
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]>
|
🕵 Pushed |
…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]>
|
🕵 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. |
|
All three check out, and apart from
|
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]>
|
🕵 Merged |
…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]>
…ix clash with master Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @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 ( |
|
Yes, #126746 (mine, open) covers it. This red has the same signature: one |
|
🕵 Thanks @groeneai for confirming that #126746 covers the |
|
🕵 |
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]>
|
🕵 The PR had become |
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]>
|
🕵 The PR had become The only conflict was in With The 41 TTL tests of this PR, together with
|
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]>
ALTER TABLE ... MODIFY TTLcurrently 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 DAYbecomescreate_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 aMODIFY TTLcompletes almost instantly instead of taking minutes or hours:There is nothing to enable and no new syntax: the optimization is applied automatically inside the
MATERIALIZE TTLmutation thatMODIFY TTLalready produces, and a plainALTER TABLE ... MATERIALIZE TTLbenefits 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 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 thatnew_ttl(row) - old_ttl(row)is one constant for every row. CalendarMONTH/YEARintervals,DAY/WEEKintervals 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 exactly1970-01-01 00:00:00UTC (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):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
ALTER TABLE ... MODIFY TTLno 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 anALTERnearly 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 TTLbenefits from the same optimization.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):
Exclude tests:
Extra options:
Only specified batches in multi-batch jobs:
Details
Workflow [PR]
Sync PR [sync-upstream/pr/63383]