Skip to content

Fix TTL ... GROUP BY ... SET with an expression or a subcolumn as an aggregate function argument - #128758

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-ttl-group-by-set-aggregate-arguments
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-ttl-group-by-set-aggregate-arguments

Conversation

@groeneai

@groeneai groeneai commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #128596
Closes: #63800
Closes: #53230
Related: #121268

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):

Fixed TTL ... GROUP BY ... SET rules whose aggregate function takes an expression or a subcolumn as an argument, e.g. SET value = sum(value * 2), sumIf(value, value > 15) or max(tup.ts): such a rule was accepted, but every merge and ALTER TABLE ... MODIFY TTL that applied it failed with NOT_FOUND_COLUMN_IN_BLOCK. A subquery, or an IN with a table, inside such an argument is now rejected by CREATE TABLE and ALTER TABLE ... MODIFY TTL. Closes #128596.

Description

On 26.10.2.103 and 26.3.60.2, a rule like TTL event + INTERVAL 1 SECOND GROUP BY k SET value = sum(value * 2) is accepted, but every merge and MODIFY TTL materialization that applies it fails with Not found column multiply(value, 2) in block. (NOT_FOUND_COLUMN_IN_BLOCK), so expired rows are never aggregated and those parts stop merging. Other non-column arguments fail the same way (a sorting key expression only in MODIFY TTL): sumIf(value, value > 15), sum(1), a subcolumn max(tup.ts), and the shapes of #63800 and #53230.

Root cause. TTLDescription keeps only the actions applied after the aggregation. The actions that compute the aggregate arguments are built inside ExpressionAnalyzer and dropped, while TTLAggregationAlgorithm feeds the Aggregator only the stored columns.

The change. TTLAggregateDescription keeps the assignment AST and builds the argument actions from it where they run, as TTLDescription::buildExpression does for the TTL expression: in TTLAggregationAlgorithm, only when an argument is not a column of the header (working rules are unchanged), and at CREATE / MODIFY TTL for validation, replacing the separate per-argument analysis. Nothing is built while loading metadata, so every stored table still attaches. The arguments are computed before executeOnBlock; subcolumns are extracted as for the sorting key. A subquery or an IN with a table in an argument is rejected at DDL: a TTL merge builds no set for it and re-runs a scalar subquery under a new name; #121268 covers the rest of the assignment.

Validation. The new test 05487_ttl_group_by_set_aggregate_argument_expression fails on master and passes 50/50 with randomized settings; the stateless ttl tests show no new failures; the repros of #63800 and #53230 now produce the aggregated row.

🤖 Generated with Claude Code


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

groeneai and others added 6 commits November 2, 2026 15:20
…e argument

A `TTL ... GROUP BY ... SET` assignment such as `value = sum(value * 2)`,
`sumIf(value, value > 15)`, `sum(1)` or `tup = tuple(max(tup.ts), 0)` was
accepted by CREATE TABLE and ALTER TABLE ... MODIFY TTL, but every merge and
every MODIFY TTL materialization that applied it failed with
NOT_FOUND_COLUMN_IN_BLOCK, so expired rows were never aggregated and the parts
stopped merging.

`TTLDescription::getTTLFromAST` keeps only the post-aggregation actions of an
assignment (`getActions(false)`) and the aggregate descriptions, whose
`argument_names` are the column names of the argument expressions. The actions
that compute those arguments are built only into the local `temp_actions` of
the `ExpressionAnalyzer` constructor and dropped, while `TTLAggregationAlgorithm`
builds its `Aggregator` on the stored columns. A plain column argument works,
and a sorting key expression works on the merge path only because a merge
header carries the precomputed key column.

`TTLAggregateDescription` now keeps the assignment AST before analysis and the
columns it reads, and `buildArgumentsExpression` builds the arguments of its
aggregates from them with the same `TreeRewriter` and `ExpressionAnalyzer`
(public `appendExpression`), like `TTLDescription::buildExpression` does for the
TTL expression. It is called:
- in `TTLAggregationAlgorithm`, only when some argument is not a column of the
  header, so every rule that works today takes the same path. The aggregator
  header is extended with the computed arguments (subcolumns extracted as for
  the sorting key), `calculateAggregates` computes them for each aggregated
  range with an explicit row count (an argument may have no inputs), and
  `finalizeAggregates` passes the extended header to `Params::getHeader`;
- at CREATE / MODIFY TTL (validation mode), where it replaces the separate
  per-argument analysis `checkTTLGroupBySetForAggregateFunctions`, which also
  planned an `IN` subquery of an argument before any check.
It is never called while loading metadata, so a stored rule (for example one
created with `allow_suspicious_ttl_expressions` whose literal set does not fit
the column type) still attaches and only its TTL merge fails.

An `IN` whose set comes from a subquery or a table cannot be evaluated during a
TTL merge, so such an argument is rejected with BAD_ARGUMENTS before anything is
planned. The build ends with the existing arrayJoin screen, so a rule stored
before the CREATE-time arrayJoin check fails its merge instead of handing the
aggregator columns of another length.

ClickHouse#128596
Also fixes the shapes of ClickHouse#63800
and ClickHouse#53230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ction state

Add the shape of ClickHouse#53230 (`sumForEachState(CAST(finalizeAggregation(s), ...))`) to 05487.
Update two comments in TTLDescription.cpp that still said a GROUP BY SET assignment has no AST.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The own `IN` predicate inspected the arguments only after `TreeRewriter`, which executes a scalar subquery and folds it
into a literal under a freshly numbered `_subqueryN` alias. A scalar subquery in an aggregate argument
(`sum(value * (SELECT max(factor) FROM factors))`) was therefore accepted, re-executed by every TTL merge, and its
argument name no longer matched the stored aggregate description, so the merge failed with NOT_FOUND_COLUMN_IN_BLOCK.

Use the shared `checkExpressionDoesntContainSubqueries`, which this file already applies to the TTL expression, on the
arguments before the analysis (scalar subqueries) and after it (SQL user-defined functions are expanded there).
Restore master's `collectAggregateFunctionArguments` for the pre-analysis walk and drop the now-unused includes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rejection is claimed for CREATE TABLE and ALTER TABLE ... MODIFY TTL; only CREATE had an arm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…us_ttl_expressions too

allow_suspicious_ttl_expressions skips the TTL validator, but a subquery, an IN with a table or an
arrayJoin inside an aggregate argument cannot run in any TTL merge, so it is rejected for every user DDL, like a subquery
in the TTL expression. Metadata load still builds nothing. Also correct a comment in MergeTreeData that this branch made
stale.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fold the buildArgumentsExpression doc into one line and merge the two new member comments of TTLAggregationAlgorithm.

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

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 9 findings over five rounds, none in the last) plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ A stored column literally named greater(value, 15) is used instead of computing value > 15 DISAGREE Same result on master: every argument of that rule is a header column, so none of the new code runs and the Aggregator resolves names in the header as before; precomputed sorting key columns rely on that lookup
2 ⚠️ No test arm for an argument computed from an AggregateFunction state (#53230) AGREE, fixed (r1) new arm sumForEachState(CAST(finalizeAggregation(s), 'Array(Int32)'))
3 💡 Comments in TTLDescription.cpp still say a GROUP BY ... SET assignment has no AST AGREE, fixed (r1) two comments updated
4 ❌ A scalar subquery in an argument is re-executed when the arguments are rebuilt, gets a new _subqueryN name and the merge still fails with NOT_FOUND_COLUMN_IN_BLOCK; the new IN predicate also duplicated checkExpressionDoesntContainSubqueries AGREE, fixed (r2) subqueries in an aggregate argument are rejected with the check the TTL expression already uses, before and after the rewrite; new test arm
5 💡 Every metadata ALTER re-validates the table TTL, so a stored rule with a subquery in an aggregate argument now reports BAD_ARGUMENTS there too noted such a rule never merged; REMOVE TTL / MODIFY TTL still repair it
6 ❌ A scalar subquery outside the aggregate (sum(value * 2) * (SELECT max(factor) FROM f)) runs again when the arguments are built, so dropping f fails the next merge DISAGREE that rule never merged on master (computed argument); master already runs the scalar of a SET assignment at every table load, so dropping f breaks either shape
7 ❌ sumIf(value, value IN allowed) with an Array column is rejected DISAGREE the TTL is analysed by the old analyzer, where the identifier after IN is a table (MarkTableIdentifiersVisitor); has(allowed, value) is accepted
8 ⚠️ No test arm for the rejection through ALTER TABLE ... MODIFY TTL AGREE, fixed (r3) new MODIFY TTL arm
9 ⚠️ With allow_suspicious_ttl_expressions the subquery check of an aggregate argument was skipped at DDL, so the rule failed only at the merge AGREE, fixed (r4) the arguments are now built for every user DDL (still never at metadata load); the setting keeps skipping only the AggregateFunction probe; new test arm
10 💡 A comment in MergeTreeData still said a GROUP BY ... SET assignment has no AST AGREE, fixed (r4) comment updated

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local with MODIFY TTL ... SET value = sum(value * 2), cnt = sum(1) fails with Not found column multiply(value, 2) on master and returns 60 2 with the fix; same for sumIf(value, value > 15) and max(tup.ts) on the merge path. Reproduced on official 26.3.60.2 and 26.10.2.103.
b Root cause explained? TTLDescription stores only the post-aggregation actions; the argument actions are built inside ExpressionAnalyzer and dropped, and TTLAggregationAlgorithm feeds the Aggregator only stored columns.
c Fix matches root cause? Yes. The argument actions are built from the stored assignment AST where they run and executed before executeOnBlock. No guard at the throw site, no try/catch.
d Test intent preserved / new tests added? New 05487_ttl_group_by_set_aggregate_argument_expression, nine arms (mutation path, merge path, subcolumn, an argument computed from an AggregateFunction state as in #53230, subqueries and IN with a table rejected by CREATE TABLE, also with allow_suspicious_ttl_expressions = 1, and by ALTER TABLE ... MODIFY TTL). No existing test changed; 04337 and 05077 keep their verdicts.
e Both directions demonstrated? New test: 5/5 FAIL on master, 50/50 OK with the fix (randomized settings). The repros of #63800 and #53230 fail on master and aggregate with the fix.
f Fix is general across code paths? Merge (MergeTask) and MODIFY TTL / MATERIALIZE TTL mutation (MutateTask) both go through TTLAggregationAlgorithm; DDL validation uses the same build; metadata loading never builds. Subcolumns use the extraction the sorting key already uses.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked Nullable, LowCardinality, LowCardinality(Nullable), Array with a lambda, Map, JSON and Tuple subcolumns, constant sum(1), literal-set IN, parametric quantileExact(0.5), an argument shared by two assignments, 100k rows over 100 parts, and 1-row merge blocks.
h Backward compatible? (maintainer-approved exception only) Yes. Stored tables load as before (rules master created under allow_suspicious_ttl_expressions, DETACH/ATTACH, restart; REMOVE TTL still works); rules that work on master take the same path. The only new rejection, a subquery or a table IN inside an aggregate argument, is a rule whose every merge fails on master.
i Invariants and contracts preserved? The aggregator header starts with the old header, so key positions are unchanged; computed columns are appended in the same order to the header and the chunk; the emitted block keeps the table header; every computed column has the chunk's row count; arrayJoin cannot reach the aggregator.

Session id: cron:clickhouse-impl-slot-41:20261102-133200

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @Michicosun, could you review this and add the can be tested label so CI runs? A TTL ... GROUP BY ... SET aggregate whose argument is an expression or a subcolumn (sum(value * 2), max(tup.ts)) failed every merge with NOT_FOUND_COLUMN_IN_BLOCK because only the post-aggregation actions were kept; TTLAggregationAlgorithm now builds the argument actions from the stored assignment AST and computes them before executeOnBlock.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [769417f]

Summary: ✅


AI Review

Summary

The PR computes expression and subcolumn arguments before TTL ... GROUP BY ... SET aggregation and rejects unsupported subqueries in aggregate arguments during DDL. Reviewed commit 769417f575f6, the full diff, surrounding execution paths, and all prior discussion. No actionable findings remain. The regression test passes in CI; its four result cases and nine additional focused cases also passed locally using the PR's CI binary.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). labels Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 769417f57 with master 4944813cc (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

146 object files changed (-26.92 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/TTL/TTLAggregationAlgorithm.cpp.o 275.79 KiB 292.75 KiB +16.95 KiB (+6.15%)

719 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

852 translation units recompiled, 6530 s compile time in total, 852 of them have a recent master baseline.

Job report

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). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

1 participant