Skip to content

Reject TTL expressions referencing AggregateFunction columns at DDL time - #107366

Merged
alexey-milovidov merged 58 commits into
ClickHouse:masterfrom
Ria-K912:fix-ttl-aggregate-function-validation
Aug 1, 2026
Merged

alexey-milovidov merged 58 commits into
ClickHouse:masterfrom
Ria-K912:fix-ttl-aggregate-function-validation

Conversation

@Ria-K912

@Ria-K912 Ria-K912 commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #107036

CREATE TABLE with a TTL expression that references a column of type AggregateFunction (e.g. TTL toDateTime(ts) + INTERVAL 1 DAY where ts is AggregateFunction(max, DateTime64(3))) was accepted at DDL time but failed later at insert time with ILLEGAL_TYPE_OF_ARGUMENT. This adds a validation in checkTTLExpression to reject such expressions early during table creation.

Local test results **Test 1: toDateTime on AggregateFunction — rejected at DDL time (PASS)** Screenshot 2026-06-16 at 2 42 07 PM

Test 2: Column-level TTL— rejected at DDL time (PASS)
Screenshot 2026-06-16 at 2 39 26 PM

Test 3: DELETE WHERE with toDateTime on AggregateFunction — rejected (PASS)
Screenshot 2026-06-16 at 2 43 14 PM

Test 4: Direct plus() (expect ILLEGAL_TYPE_OF_ARGUMENT) — rejected (PASS)
Screenshot 2026-06-16 at 2 43 47 PM

Test 5: Nullable wrap — rejected (PASS)
Screenshot 2026-06-16 at 2 44 56 PM

Test 6 : toUInt32 intermediate — rejected (PASS)
Screenshot 2026-06-16 at 3 13 51 PM

Test 7 : Valid: finalizeAggregation— accepted (PASS)
Screenshot 2026-06-16 at 3 15 56 PM

Test 8 : Valid: bitmapCardinality — accepted (PASS)
Screenshot 2026-06-16 at 3 16 29 PM

**Test 9: Valid: intDiv with non-aggfunc— accepted (PASS) :
Screenshot 2026-06-16 at 3 17 10 PM

**Test 10: Valid: aggfunc not referenced— accepted (PASS) :
Screenshot 2026-06-16 at 3 20 03 PM

**Test 11: Valid: normal DateTime— accepted (PASS) :
Screenshot 2026-06-16 at 3 23 16 PM

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 unsupported uses of AggregateFunction columns in TTL expressions at CREATE TABLE time (e.g. TTL toDateTime(state)) instead of failing later during TTL execution with ILLEGAL_TYPE_OF_ARGUMENT. This also covers states carried inside Variant alternatives and Dynamic values. Valid state-aware consumers such as finalizeAggregation are still accepted.

Version info

  • Backported to: 26.7.4.14, 26.6.3.28, 26.5.7.41

@CLAassistant

CLAassistant commented Jun 12, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@Ria-K912
Ria-K912 marked this pull request as ready for review June 12, 2026 20:21
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jun 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cf17635]

Summary: ✅


AI Review

Summary

This PR substantially hardens DDL-time TTL validation for AggregateFunction / Variant / Dynamic carriers and closes many of the earlier late-exception paths, but the higher-order-function path still falls back to static carrier enumeration when the carrier domain comes from a typed source array rather than from the lambda body. That makes some valid TTLs fail at CREATE TABLE time.

Findings

⚠️ Majors

  • [src/Storages/TTLDescription.cpp:730] Higher-order functions with lambdas still ignore the narrowed domain of their non-lambda array arguments. For example, TTL toDateTime(arrayFirst(x -> 1, CAST(arrayResize(arr, 1, toUInt32(0)), 'Array(Dynamic)'))) + INTERVAL 1 DAY over arr Array(UInt32) is runtime-valid because arrayFirst can only return Dynamic(UInt32), but this branch falls back to collectSuspectMaterializations(Array(Dynamic)) / collectSuspectMaterializations(Dynamic) and rejects it against fabricated payloads. The same blind spot affects arrayFilter / arrayLast and arrayMap(x -> x, CAST(...)). The higher-order result needs to inherit the proven carrier domain of its source arrays instead of dropping to the static enumeration.
Final Verdict

Request changes: the validator still rejects a real class of valid higher-order TTL expressions, so the DDL-time contract is not yet precise enough.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 12, 2026
Comment thread src/Storages/TTLDescription.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
…ype`, rethrow non-type errors, dedupe WHERE path, add nested-state tests
Comment thread src/Storages/TTLDescription.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Pass #126: addressed the AI Review blocker (selector fast path requiring identical branch materializations) in 28fca5a9913, and merged master (a917f9538e6).

The selector domain propagation now uses the deduplicated union of the value arguments' candidate sets (keeping the branch-type-equals-result-type guard against supertype conversion), so TTL toDateTime(if(cond, CAST(1, 'Dynamic'), CAST(2, 'Dynamic'))) and its multiIf analogue are accepted, as well as a union of different consumable domains (if(cond, CAST(n, 'Dynamic'), CAST(1, 'Dynamic'))). Mixed unions containing a state (CAST(state, 'Dynamic') branch) and string-cast branches stay rejected - re-verified along with the full 04337_ttl_aggregate_function_column_reject test (passes against the branch build), and three new accept tests were added.

The failed check on the previous run was 01666_merge_tree_max_query_limit (TOO_MANY_SIMULTANEOUS_QUERIES in the coverage runner) - unrelated, known flaky test #112426.

Comment thread src/Storages/TTLDescription.cpp Resolved
…omain

The selector fast path in `checkActionsDAGForAggregateFunctions` required every
value argument of `if`/`multiIf`/`coalesce`/`ifNull` to already carry candidate
materializations of exactly the result type. A branch that is not a carrier
itself - `m` in `TTL toDateTime(if(cond, CAST(n, 'Dynamic'), m))` over
`n`, `m UInt32` - has no candidates, so the domain was considered unproven and
the node fell back to the static enumeration of `Dynamic` payloads, rejecting a
valid TTL at `CREATE TABLE`.

A selector converts every value argument to its result type, so such a branch
contributes exactly the payloads that conversion produces from its values: the
branch domain (its candidates, or the representative values of its static type)
is now converted with `castColumn` and the outputs join the union. A conversion
that infers the payload out of a string stays value-dependent, so it leaves the
domain unproven and keeps the fail-closed static enumeration.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass #127: addressed the AI Review blocker (selector fast path over-rejecting a value branch that is lifted to the carrier result type) in c8714e68873, with tests in cf17635def7.

A selector converts every value argument to its result type, so the domain of a branch that is no carrier itself is exactly what that conversion produces from its values. Each value branch is now converted with castColumn (from its candidates, or from the representative values of its static type) and the union of the converted domains is propagated, which makes TTL toDateTime(if(cond, CAST(n, 'Dynamic'), m)) over n, m UInt32 and TTL toDateTime(if(cond, CAST(1, 'Dynamic'), 2)) accepted. Branches whose conversion infers the payload out of a string stay value-dependent and keep the fail-closed static enumeration, and a branch domain containing an aggregate state still rejects an unsupported consumer.

Verified: the full 04337_ttl_aggregate_function_column_reject test passes (empty output), and an end-to-end run shows OPTIMIZE FINAL on the accepted table deleting exactly the rows whose selected branch holds an expired timestamp, from both branches.

The failed check on the previous run was 04493_correlated_subquery_join_runtime_filter_dup_column - unrelated to this PR: it also fails on master (2026-07-30) and on many unrelated pull requests over the last two weeks.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107366&sha=28fca5a991395a3c4719f8c9512a39070b432ae4&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The test is 04493_correlated_subquery_join_runtime_filter_dup_column (result differs with reference, one row 1 vs 0). It is unrelated to this pull request (a TTL DDL-time validation change): it fails on master (pull_request_number = 0, 2026-07-30) and on a dozen unrelated pull requests over the last two weeks, and I found no open issue tracking it. The CI minimizer points at --query_plan_optimize_join_order_randomize 130079 --join_runtime_filter_min_probe_rows 6081, so it looks like a genuine join-runtime-filter correctness flake rather than infrastructure noise.

}
}
else
candidates = collectSuspectMaterializations(node->result_type, expression_kind);

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.

This has_lambda_argument fallback still over-rejects carrier values that come from a typed source array rather than from the lambda body itself. The loop above breaks as soon as it sees the FunctionCapture, so candidates_of never looks at the non-lambda array arguments here; unless the function is exactly arrayMap and the carrier is rebuilt inside the lambda body, line 730 falls back to collectSuspectMaterializations(node->result_type).

A concrete false positive is:

CREATE TABLE t
(
    arr Array(UInt32)
)
ENGINE = MergeTree
ORDER BY tuple()
TTL toDateTime(arrayFirst(x -> 1, CAST(arrayResize(arr, 1, toUInt32(0)), 'Array(Dynamic)'))) + INTERVAL 1 DAY;

arrayFirst can only return an element of the source array, and that CAST(..., 'Array(Dynamic)') can only produce Dynamic(UInt32) elements, so the TTL is valid at runtime. Here we still validate the parent toDateTime against fabricated Array(Dynamic) / Dynamic payloads and reject the DDL. The same blind spot also hits arrayFilter / arrayLast and arrayMap(x -> x, CAST(...)). We need to carry the narrowed domain of the non-lambda array arguments into these higher-order results instead of falling back to the static enumeration.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

The fix is your own #111691 ("Pin join_runtime_filter_min_probe_rows in tests that assert runtime filter effects"), merged 2026-07-31T20:56:13Z in b52d957c5c08. It adds SET join_runtime_filter_min_probe_rows = 0 to 04493_correlated_subquery_join_runtime_filter_dup_column.sql, which is line 10 on master now. That is why no open issue tracked it.

Your failing build predates the pin: 28fca5a9 is 2026-07-30T20:44:28Z, 24 hours before the merge, and fetching the test at that ref shows no min_probe_rows line. Your current head cf17635def7 does not carry the pin either (671 commits behind the merge), so a fresh draw can still hit it until you merge master.

You are right that this is not infrastructure noise, but it is not a correctness flake either. Only the countIf(explain LIKE '%BuildRuntimeFilter%') > 0 assertions move in your diff: three flip to 0 and the fourth holds, while every correlated-subquery data row is unchanged context. Under the same settings both data queries match an enable_join_runtime_filters = 0 oracle byte for byte, so the filter is deliberately not built and nothing computes a wrong answer.

The two settings the minimizer printed are the producer and the consumer of a single guard in joinRuntimeFilter.cpp (test at :251, estimate comparison at :254): query_plan_optimize_join_order_randomize replaces real statistics with random cardinalities, and the resulting probe-side estimate falls at or below join_runtime_filter_min_probe_rows, so the filter is skipped. Pinning either setting alone is sufficient, which is why your pin closes it. Your 6081 joins 3144, 4286, 4883, 7855 and 9466 measured on earlier hits. CIDB shows no hit for this test since the merge.

One follow-up from me: lines 16-21 of that file still attribute the flakiness to the optimizer swapping ANY RIGHT JOIN into ANY LEFT JOIN and claim query_plan_join_swap_table = 'false' prevents it. That is wrong, no side swap is involved, which is why the swap pin never helped, and it now sits directly above your correct pin. I will send a comment-only correction.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 386/456 (84.65%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 1, 2026
Merged via the queue into ClickHouse:master with commit 4f8da77 Aug 1, 2026
179 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @Ria-K912 @alexey-milovidov — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: Body describes only the direct AggregateFunction column case. It does not mention the substantial Dynamic/Variant/container-carrier handling, the selector/arrayMap/CAST narrowing logic, the max_probe_combinations guard, the MismatchSettingsGuard thread-context setting behavior, or that WHERE and GROUP BY SET are also validated.

  • Suggested addition:

    Also note that states nested inside Variant/Dynamic/Array/Map/Tuple/Nullable carriers are validated by synthetically probing the directly-consuming function; selector functions (if/multiIf/coalesce/ifNull), arrayMap lambda bodies and typed CASTs get domain-narrowing so genuinely valid expressions are still accepted; probe combinations are bounded by max_probe_combinations (256, fail-closed); the check also runs for TTL WHERE and GROUP BY SET clauses; ATTACH and allow_suspicious_ttl_expressions remain escape hatches.

Ignore this if the current title/body is intentional.

alexey-milovidov added a commit to UberDever/ClickHouse that referenced this pull request Aug 9, 2026
A stored TTL is an AST plus the list of columns it needs, rebuilt from the two
on every INSERT, every merge and every time the table is loaded. Two things
could make that rebuild impossible, and the second one stopped the server from
starting.

The column list was taken from the *built* expression, so constant folding
dropped columns the AST still refers to. `TTL d + INTERVAL 1 DAY DELETE WHERE
isNull(x)` over a non-`Nullable` `x` folds to `0` and stores an empty column
list, after which every rebuild fails with `Missing columns: 'x' ... no source
columns` - the first INSERT into the table already does. It is now taken from
the syntax analysis instead, which sees the AST before folding.

The `Variant`/`Dynamic` function adaptors consult
`variant_throw_on_type_mismatch` / `dynamic_throw_on_type_mismatch` while
building an expression: with no compatible alternative at all, a strict build
throws and a lenient one resolves the result to NULL. They read it from the
query context of the current thread, and table loading has no query context, so
loading always saw the strict default and refused to attach a table that a
lenient session had created. Restarting was then impossible:

    Load job 'load table test_2.test_ttl_agg_variant_lenient_build_suspicious__fuzz_3' failed:
    Code: 43. None of the Variant alternatives (AggregateFunction(max, UInt64)) are compatible
    with function 'length': While processing isNull(length(v))
    ...
    Application: Caught exception while loading metadata

The strictness a TTL build uses is therefore pinned rather than taken from the
ambient context, through a thread-local override the adaptors consult first: a
validated build runs strict (unchanged), and a build that skips validation - on
ATTACH, or with `allow_suspicious_ttl_expressions` - runs lenient, which is the
superset. Whatever a session managed to create loads again.

Neither bug needs an escape hatch to reach. The stress test found the second one
through the AST fuzzer, which left a fuzzed copy of the table that
`04337_ttl_aggregate_function_column_reject` creates behind for the restart:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c2c9039413b2e96f64fdbbdecaa23381fb9924df&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_msan%29

Related: ClickHouse#107366
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 10, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 10, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 10, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 10, 2026
Backport #107366 to 26.6: Reject TTL expressions referencing AggregateFunction columns at DDL time
clickhouse-gh Bot added a commit that referenced this pull request Aug 10, 2026
Backport #107366 to 26.7: Reject TTL expressions referencing AggregateFunction columns at DDL time
alexey-milovidov added a commit that referenced this pull request Aug 12, 2026
Backport #107366 to 26.5: Reject TTL expressions referencing AggregateFunction columns at DDL time
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Aug 17, 2026
tryOptimizeAndCompareNotEqualsChain asserted that a comparison operand's
constant side is non-NULL. That is wrong: a constant can be NULL-valued while
its type is non-Nullable (e.g. a NULL-valued Variant). The pass only
early-returns for a Nullable AND, so with
use_variant_default_implementation_for_comparisons = 0 (comparison against a
NULL-valued Variant is non-nullable) the AND is non-nullable and the NULL
constant reached chassert(!literal->getValue().isNull()), aborting the server
in debug and sanitizer builds. In release the constant is already kept as-is.

Treat a NULL-valued constant as a non-constant side and keep the operand as-is,
matching the sibling tryOptimizeOrEqualsChain. Release behavior is unchanged.

Found by the AST fuzzer (STID 2508-5318). Reproduces on master; reported on
ClickHouse#107366 but unrelated to that PR.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
pull Bot pushed a commit to Dream-hu/ClickHouse that referenced this pull request Aug 31, 2026
…zation

The AND-compare chain passes (optimize_and_compare_chain,
optimize_redundant_comparisons) skip a Nullable-typed AND because a comparison
over a Nullable operand cannot participate in range pruning. That guard checks
only the AND's own result type. FunctionAnd uses the default implementation for
Nothing, so when one AND operand is Nothing-typed the overload resolver
short-circuits the whole AND's result type to bare Nothing. Nothing is not
Nullable, so the guard passes, yet another operand can be a comparison over a
directly-Nullable expression, which then reaches addComparisonFilter and fails
chassert(!raw_type->isNullable()).

Keep a Nullable expression operand as an opaque filter (no pruning) instead of
asserting, matching the existing non-convertible-constant fallback. This covers
all three call sites and both entry functions.

Found by the AST fuzzer: Stress test (amd_tsan), STID 2508-4871, on
ClickHouse#107366 (unrelated) at commit
d6b407c. Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107366&sha=d6b407cffd20698269f3ad97cc7d52c606586ef3&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CREATE TABLE accepts TTL on AggregateFunction column but fails at insert time with ILLEGAL_TYPE_OF_ARGUMENT

9 participants