Repository navigation
Reject TTL expressions referencing AggregateFunction columns at DDL time - #107366
alexey-milovidov merged 58 commits into
Conversation
|
Workflow [PR], commit [cf17635] Summary: ✅
AI ReviewSummaryThis PR substantially hardens DDL-time TTL validation for Findings
Final VerdictRequest changes: the validator still rejects a real class of valid higher-order TTL expressions, so the DDL-time contract is not yet precise enough. |
…ype`, rethrow non-type errors, dedupe WHERE path, add nested-state tests
…running the whole expression
…ead of only checking outer nodes
|
Pass #126: addressed the AI Review blocker (selector fast path requiring identical branch materializations) in 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 The failed check on the previous run was |
…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.
|
🕵 Pass #127: addressed the AI Review blocker (selector fast path over-rejecting a value branch that is lifted to the carrier result type) in 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 Verified: the full The failed check on the previous run was |
|
🕵 @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 |
| } | ||
| } | ||
| else | ||
| candidates = collectSuspectMaterializations(node->result_type, expression_kind); |
There was a problem hiding this comment.
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.
|
The fix is your own #111691 ("Pin Your failing build predates the pin: You are right that this is not infrastructure noise, but it is not a correctness flake either. Only the The two settings the minimizer printed are the producer and the consumer of a single guard in One follow-up from me: lines 16-21 of that file still attribute the flakiness to the optimizer swapping |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 386/456 (84.65%) · Uncovered code |
|
Hi @Ria-K912 @alexey-milovidov — a couple of suggestions to make this PR easier for reviewers and the changelog reader. Description (currently
Ignore this if the current title/body is intentional. |
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
…eFunction columns at DDL time
Backport #107366 to 26.6: Reject TTL expressions referencing AggregateFunction columns at DDL time
Backport #107366 to 26.7: Reject TTL expressions referencing AggregateFunction columns at DDL time
Backport #107366 to 26.5: Reject TTL expressions referencing AggregateFunction columns at DDL time
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]>
…g AggregateFunction columns at DDL time
…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]>
Closes: #107036
CREATE TABLEwith a TTL expression that references a column of typeAggregateFunction(e.g.TTL toDateTime(ts) + INTERVAL 1 DAYwheretsisAggregateFunction(max, DateTime64(3))) was accepted at DDL time but failed later at insert time withILLEGAL_TYPE_OF_ARGUMENT. This adds a validation incheckTTLExpressionto reject such expressions early during table creation.Local test results
**Test 1: toDateTime on AggregateFunction — rejected at DDL time (PASS)**Test 2: Column-level TTL— rejected at DDL time (PASS)

Test 3: DELETE WHERE with toDateTime on AggregateFunction — rejected (PASS)

Test 4: Direct plus() (expect ILLEGAL_TYPE_OF_ARGUMENT) — rejected (PASS)

Test 5: Nullable wrap — rejected (PASS)

Test 6 : toUInt32 intermediate — rejected (PASS)

Test 7 : Valid: finalizeAggregation— accepted (PASS)

Test 8 : Valid: bitmapCardinality — accepted (PASS)

**Test 9: Valid: intDiv with non-aggfunc— accepted (PASS) :

**Test 10: Valid: aggfunc not referenced— accepted (PASS) :

**Test 11: Valid: normal DateTime— accepted (PASS) :

Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reject unsupported uses of
AggregateFunctioncolumns in TTL expressions atCREATE TABLEtime (e.g.TTL toDateTime(state)) instead of failing later during TTL execution withILLEGAL_TYPE_OF_ARGUMENT. This also covers states carried insideVariantalternatives andDynamicvalues. Valid state-aware consumers such asfinalizeAggregationare still accepted.Version info
26.7.4.14,26.6.3.28,26.5.7.41