Skip to content

Reject a TTL expression containing arrayJoin - #117266

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix-ttl-array-join
Sep 6, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix-ttl-array-join

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #117014
Related: #117022

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Reject a TTL expression that contains arrayJoin. Such a TTL was accepted and then silently deleted
rows whose own TTL was far in the future, and read past the end of the expression column when an array
was empty.

Description

arrayJoin is the one action that changes the number of rows in a block, while every consumer of a
TTL expression indexes its result column positionally by block row: TTLDeleteAlgorithm::execute
sizes its loop by block.rows() and reads timestamps[i], where timestamps has one entry per
flattened array element.

  • With a multi-element array, row i is judged by an earlier row's timestamp, so a row whose TTL is
    hours in the future is deleted.
  • With empty arrays the expression column is shorter than the block and timestamps[i] reads past the
    end of a PaddedPODArray; in practice whole blocks with nothing expired were dropped.

The loss happens both in the insert-time TTL filter — the rows never land in a part — and during a
background TTL merge or OPTIMIZE ... FINAL, with exit code 0 and nothing logged.
ReplicatedMergeTree shares the code.

checkTTLExpression only inspected FUNCTION nodes (for determinism) plus the result type, so an
ARRAY_JOIN node passed. The new check is not lifted by allow_suspicious_ttl_expressions — this is
a row-count contract violation with an out-of-bounds read, not a matter of taste. The WHERE
expression and the GROUP BY set expressions are checked the same way.

The check is alias-insensitive. ActionsVisitor builds an ARRAY_JOIN node only for the literal
name arrayJoin, so with normalize_function_names = 0 the unnest alias was left uncanonicalized
and built as an ordinary call of a special function instead - the table was accepted and every later
TTL evaluation threw FUNCTION_IS_SPECIAL. The AST is therefore checked as well, by canonical
function name. checkRowPolicyFilterExpression needs exactly the same predicate, so its private
helper is now shared as expressionContainsArrayJoin in
src/Interpreters/ExpressionContainsArrayJoin.h, including its descent into a SQL UDF body and its
skipping of nested subqueries, which have their own scope.

TTLValidationMode::Attach is the one mode that still has to accept such a TTL: a rejection while
stored metadata is being read fails the whole load rather than the one table, so the server would not
start after an upgrade and a replica could not read the metadata another replica wrote. That leaves a
TTL stored before this check existed loadable — and it used to still execute. On a table loaded from
such metadata, OPTIMIZE TABLE ... FINAL deleted a row whose own TTL was a day in the future along
with an earlier expired one; an INSERT and a background TTL merge do the same. So the check runs
again in TTLDescription::buildExpression and buildWhereExpression, which are the only way a
consumer turns a stored description back into a runnable expression (TTLTransform,
TTLCalcTransform, TTLDeleteFilterTransform and MergeTreeDataWriter::updateTTL all go through
them). The silent row loss becomes a failed INSERT or TTL merge; the table still attaches, so
ALTER TABLE ... REMOVE TTL or a MODIFY TTL to a sane expression repairs it. A GROUP BY ... SET
assignment is stored as prebuilt ExpressionActions rather than as an AST, so it is screened through
the built expression, in buildExpression, which setting up the TTLAggregationAlgorithm that
executes it also goes through.

Test 05073_ttl_array_join_rejected covers CREATE, ALTER MODIFY TTL, a column TTL, the WHERE
form, the unnest/UNNEST alias with and without normalize_function_names, the
allow_suspicious_ttl_expressions escape hatch, and that an ordinary TTL still expires exactly what
it should. Test 05099_ttl_array_join_stored_metadata covers the stored form: clickhouse-local over
a data directory creates the table with an ordinary TTL, its stored definition is then edited into the
form an older server would have written, and the next start loads it — the table attaches, the
INSERT and the TTL merge fail with BAD_TTL_EXPRESSION instead of dropping the row that is not
expired, and ALTER TABLE ... REMOVE TTL repairs the table.


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

`arrayJoin` is the one action that changes the number of rows in a block, while every consumer
of a TTL expression indexes its result column positionally against the block's rows:
`TTLDeleteAlgorithm::execute` sizes its loop by `block.rows()` and reads `timestamps[i]`. With a
multi-element array a row was judged by an earlier row's timestamp, so rows whose own TTL was
far in the future were deleted; with an empty array the read went past the end of the column and
garbage decided deletion. The loss happened both in the insert-time TTL filter and during TTL
merges, silently and with exit code 0.

Validation only inspected `FUNCTION` nodes plus the result type, so an `ARRAY_JOIN` node passed.
`allow_suspicious_ttl_expressions` does not lift this one - it is not a matter of taste - but
loading already stored metadata still does, because a rejection there fails the whole load
rather than the one table. The `WHERE` and `GROUP BY` set expressions are checked too.

Closes: #117014
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1efa7a3]

Summary: ✅


AI Review

Summary

This PR closes the real arrayJoin TTL bug in the main expression, WHERE, alias, and legacy stored-metadata paths, and the current code matches the two earlier review-thread fixes. I do not see a remaining correctness hole in those paths, but the PR now also claims GROUP BY ... SET coverage and that part still lacks focused regression evidence, so I would not approve it yet.

Tests
  • ⚠️ GROUP BY ... SET is now screened both when parsing a fresh TTL and when rebuilding a legacy attached TTL, but neither 05073_ttl_array_join_rejected nor 05099_ttl_array_join_stored_metadata exercises that carrier. Please add the smallest focused regression for TTL ... GROUP BY key SET ... arrayJoin(...) (fresh rejection, and ideally the stored-metadata/runtime path too), because this part of the contract currently depends only on reasoning about set_parts and TTLAggregationAlgorithm.
Final Verdict

Status: ⚠️ Request changes

  • Add a focused GROUP BY ... SET regression for the new arrayJoin rejection path.

LLVM Coverage Report

Measured on commit 1efa7a3.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 53/54 (98.15%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
Comment thread src/Storages/TTLDescription.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1efa7a354 with master 7ff5dfc82 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

4 object files changed (+15.72 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/ExpressionContainsArrayJoin.cpp.o new 22.90 KiB +22.90 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

9 translation units recompiled, 15 s compile time in total, 8 of them have a recent master baseline.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too.

The check only looked for an `ARRAY_JOIN` node in the built DAG, which `ActionsVisitor` creates
only for the literal name `arrayJoin`. With `normalize_function_names = 0` the `unnest` alias is
left uncanonicalized in the AST, so the expression is built as an ordinary call of a special
function instead: the table was accepted under `allow_suspicious_ttl_expressions = 1` and every
later TTL evaluation - the insert-time filter and every background TTL merge - threw
`FUNCTION_IS_SPECIAL`.

The AST is now checked too, by canonical function name, so the verdict does not depend on that
setting or on the spelling of the alias. `checkRowPolicyFilterExpression` needs exactly the same
predicate for the same reason, so its private helper is moved to `expressionContainsArrayJoin` in
`src/Interpreters/ExpressionContainsArrayJoin.h` and shared - including its descent into a SQL UDF
body and its skipping of nested subqueries, which have their own scope.

Test `05073_ttl_array_join_rejected` covers `unnest` and `UNNEST`, both with and without
`normalize_function_names`, in the TTL expression, the `WHERE` form and a column TTL.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: Stress test (arm_msan) — Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-3e49). It is unrelated to this pull request (a TTL validation check) and matches the open issues #107619 and #117806. If a fix is already in progress, link it here.

The two Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6 and 6/6) jobs failed with Container memory budget exceeded (/docker), which is a job-level infrastructure error with no test results, also unrelated.

Comment thread src/Storages/TTLDescription.cpp Resolved
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

The Stress test (arm_msan) abort is the object-storage _path pruning route, and the fix is in flight in your own #112968.

Its stack ends in StorageObjectStorageSource::createFileIterator (StorageObjectStorageSource.cpp:581) -> filterByPathOrFile -> getFilterByPathAndFileIndexes -> filterBlockWithExpression -> FunctionIn::executeImpl: the explicit-key branch runs the _path filter while the pipeline is still being built, right after the unchecked buildSetsForDAG at :579, and the globalIn set is deliberately left unbuilt there. #112968 removes exactly those two lines, gates the filter on buildSetsForDAG reporting every set ready, and otherwise defers it to KeysIterator::next (test 04669_object_storage_path_filter_global_in).

Of the two issues, #117806 is this same site: identical frames down to StorageObjectStorageSource.cpp:581, differing only in globalNotIn vs globalIn, which is why its STID hash differs. #107619 is a different arm, aborting in FilterTransform::doTransform during execution rather than in the iterator during pipeline build.

The two integration rows built on master ac95bf3cf, a strict ancestor of both /docker budget fixes (#117202, #117412), so neither was present there; the residual that survives #117412 is concentrated on 6/6 and is the session-scoped fixture container leak in #117564.

@clickhouse-gh clickhouse-gh Bot added the comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). label Sep 4, 2026
`TTLValidationMode::Attach` cannot reject an `arrayJoin` in a TTL while the metadata is being read: a
rejection there fails the whole load rather than the one table, so the server would not start after an
upgrade and a replica could not read the metadata another replica wrote. A TTL stored before the
check existed therefore still loads - and then still executed, which is the whole bug. On a table
loaded from such metadata, `OPTIMIZE TABLE ... FINAL` deleted a row whose own TTL was a day in the
future along with an earlier expired one, silently and with exit code 0. A background TTL merge and an
`INSERT` do the same.

`TTLDescription::buildExpression` and `buildWhereExpression` are the only way a consumer turns a stored
description back into a runnable expression - `TTLTransform`, `TTLCalcTransform`,
`TTLDeleteFilterTransform` and `MergeTreeDataWriter::updateTTL` all go through them - so the same check
runs there now. The silent row loss becomes a failed `INSERT` or TTL merge, the table still attaches,
and `ALTER TABLE ... REMOVE TTL` or a `MODIFY TTL` to a sane expression repairs it.

A `GROUP BY ... SET` assignment is stored as prebuilt `ExpressionActions` and not as an AST, so it is
screened through the built expression, in `buildExpression`, which setting up the
`TTLAggregationAlgorithm` that executes it also goes through.

Test `05099_ttl_array_join_stored_metadata` prepares such metadata with `clickhouse-local` over a data
directory - the table is created with an ordinary TTL and its stored definition is then edited into the
form an older server would have written - and covers the load, the `INSERT`, the TTL merge, and the
`ALTER` that repairs the table.
}

if (where_expression && !skip_validation)
checkTTLExpressionForAggregateFunctions(where_expression, /*expression_kind=*/ "WHERE ");

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.

The new tests only cover the main TTL expression and the stored main-TTL carrier, but this GROUP BY ... SET carrier is now part of the fix too and it still has no focused regression. That is the trickiest path in the patch: on ATTACH the assignment survives only as prebuilt ExpressionActions, and the safety guarantee relies on TTLDescription::buildExpression noticing it before TTLAggregationAlgorithm executes the stored actions. Please add a GROUP BY TTL case here (ideally one fresh DDL rejection and one legacy stored-metadata execution failure) so removing either of these checks would actually break a test.

@alexey-milovidov alexey-milovidov left a comment

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.

Perfect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants