Skip to content

Reject a TTL GROUP BY SET assignment that needs a set no TTL merge can build - #121268

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/reject-unfillable-set-in-ttl-group-by-set
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/reject-unfillable-set-in-ttl-group-by-set

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #121168

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 an IN operator that reads a subquery or a table inside a TTL GROUP BY ... SET assignment, at CREATE TABLE and at ALTER TABLE ... MODIFY TTL. Such an assignment was accepted and then failed every TTL merge of a part with expired rows with Not-ready Set is passed as the second argument for function 'in', so those rows were never aggregated and the affected parts could never merge.

Description

A MergeTree whose TTL GROUP BY ... SET assignment contains IN <table> or IN (SELECT ...) is accepted at CREATE, and then every TTL merge of a part with expired rows fails with Not-ready Set is passed as the second argument for function 'in'.

getTTLFromAST stores each assignment as prebuilt ExpressionActions and drops the analyzer's PreparedSets. Such a set is complete only once its caller builds it, and no consumer of set_parts does, so FunctionIn meets an unbuilt set on every aggregation. Filling it instead cannot be made well defined, since its contents change between merges.

I take that need from the analyzer that registered the set and reject the assignment at CREATE TABLE and at ALTER TABLE ... MODIFY TTL, as the key, skip index and TTL timestamp guards already do; allow_suspicious_ttl_expressions still allows it. Loading stored metadata stays permissive, so an older table attaches and still accepts INSERTs, and the same fact is re-checked where the assignment executes. No signal is lost: the LOGICAL_ERROR reported a state a user could create, and what remains after the DDL check comes from older metadata, better served by an error naming the MODIFY TTL repair.

Because the predicate is that register, an assignment whose actions never read the set they built is rejected too, an IN under indexHint for instance; the key guards reject that spelling already, and indexHint in a TTL assignment is a constant. A literal set, a Set-engine table, a folded scalar subquery and TTL ... DELETE WHERE ... IN keep working.


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

groeneai and others added 2 commits September 21, 2026 02:53
…n build

A MergeTree whose TTL `GROUP BY ... SET` assignment contains `IN <table>` or
`IN (SELECT ...)` was accepted at CREATE, and then every TTL merge of a part
with expired rows failed with "Not-ready Set is passed as the second argument
for function 'in'". The expired rows were never aggregated, OPTIMIZE TABLE
FINAL returned the error, and the background merge retried indefinitely, so
the affected parts could never merge. In an assertions-enabled build the merge
thread aborts instead of only failing the merge.

`getTTLFromAST` builds each assignment into prebuilt ExpressionActions and
discards the analyzer's PreparedSets. A set whose right-hand side is a
subquery or a non-Set-engine table is registered as a FutureSetFromSubquery,
which is complete only after its caller builds it, and no consumer of
`set_parts` does: TTLTransform::getExpressions collects the subqueries of the
timestamp and WHERE expressions only, and MergeTask, MutateTask and
MergeTreeDataWriter::updateTTL build exactly that collected list. So
FunctionIn met an unbuilt set every time TTLAggregationAlgorithm executed the
assignment.

Record on TTLAggregateDescription whether the assignment needs such a set,
taken from the analyzer that registered it, and reject it at DDL under the
existing !skip_validation, next to the two checks that already guard this
class in the same loop. The sibling DDL surfaces already reject both spellings
for sorting and primary keys, partition keys, skip indexes and the TTL
timestamp expression (checkExpressionDoesntContainSubqueries), so this closes
the one carrier that was left.

TTLValidationMode::Attach stays permissive on purpose: a rejection while
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. A stored definition therefore still loads and
still accepts INSERTs, which never evaluate an assignment, and the same
recorded fact is re-checked in TTLAggregationAlgorithm::finalizeAggregates,
inside the branch whose precondition is that rows were aggregated for this
rule, two lines above the execute() that raises the logical error today.

The recorded fact is the analyzer's register, which names every set the
analyzer built for the assignment, including one the built actions then drop.
So an assignment that registers a set and never reads it is rejected too,
where it used to merge: an `IN` under `indexHint`, whose argument
ActionsVisitor analyses into a separate DAG built from the same PreparedSets
while the executable node drops its arguments and returns a constant 1, and an
`IN` in a branch that constant folding removes, which addFunctionImpl turns
into a constant and removeUnusedActions then erases together with its
children. That is deliberate: checkExpressionDoesntContainSubqueries rejects
the same spellings for sorting and primary keys, partition keys, skip indexes
and the TTL timestamp expression, because it recurses over every AST child
regardless of what the enclosing function evaluates, and such an `IN` in a TTL
SET assignment is a constant, so nothing expressible is lost. Where the built
actions do read the registered set, the new BAD_ARGUMENTS fires exactly where
the old LOGICAL_ERROR did, names the ALTER TABLE ... MODIFY TTL repair, and
leaves merges that process TTL without aggregating anything for that rule
succeeding.

The predicate is the analyzer's register rather than a walk over the AST or
the DAG, because neither can answer the question: a DAG scan cannot see an IN
inside a lambda body, and an AST screen cannot see the EXISTS rewrite, which
TreeRewriter performs during normalization, while it would wrongly reject a
scalar subquery that is folded to a literal before the actions are built.

Filling the set instead was rejected: its contents can change between merges,
so the aggregated value would not be well defined.

TTLAggregateDescription's copy constructor and assignment operator are
hand-written and enumerate their fields, and every metadata copy passes
through them, including result.set_parts.emplace_back, so both carry the new
field; omitting it from either silently disables the whole check.

Closes: ClickHouse#121168

Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the Attach-mode design note above checkSetPartsAreExecutable and reflow the remaining invariant to two lines.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 21, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 4 gate findings over a full pass and two
delta re-reviews, the last returning none, plus 16 from my own five cold reviews; 4 fix rounds).

# Sev Finding Verdict Evidence / action
1 ⚠️ The TTL ... DELETE WHERE ... IN control used a literal tuple set, so it exercised none of the deferred-set construction its comment names AGREE, fixed Respelled as DELETE WHERE v IN (SELECT 100), which is the shape TTLTransform::getExpressions actually collects; measured identical on base and on the fix, same reference.
2 ⚠️ The screen also rejects an IN that sits only under indexHint, which master accepts and merges AGREE on the mechanism, rejection kept deliberately The key, partition, skip-index and TTL-timestamp guards reject that same spelling, and indexHint in a SET assignment is the constant 1; deriving the flag from the executable actions instead would stop catching arrayExists(x -> x IN <table>, [max(v)]), a confirmed instance of the bug. Both directions measured, boundary pinned as a test leg.
3 ⚠️ Having kept that rejection, the commit message described its extent as a single spelling, and indexHint is not the only construct with that shape AGREE, corrected A second one: ActionsDAG::addFunctionImpl constant-folds and/or/if, and removeUnusedActions then erases the in node while the set stays in the analyzer's register. The wording states that property once instead of enumerating a construct, and the extra spelling is measured on both binaries.
4 ⚠️ The runtime diagnostic does not fire for an IN inside an aggregate argument, SET r = max(v IN <table>), which fails NOT_FOUND_COLUMN_IN_BLOCK instead DISAGREE No set is registered for that spelling (makeAggregateDescriptions uses getRootActionsNoMakeSet), so an earlier check is a no-op, and the failure is not set-specific: any compound aggregate argument fails the same way, max(v + 1) as much as max(v IN t). Measured identical on base and on the fix (Code: 10).
5 ⚠️ The written answer on backward compatibility named only the failing TTL merge, while three further things change for a table that already stores such an assignment AGREE, fixed Self-raised. All four are now named and measured: the merge fails with BAD_ARGUMENTS rather than a logical error, MATERIALIZE TTL likewise (finding 6), a COLUMN ALTER is newly refused because AlterCommands::apply re-validates the table TTL, and the two deliberately over-rejected spellings of finding 2 stop merging.
6 ⚠️ "MATERIALIZE TTL is untouched" was asserted from TTLCalcTransform, and is false for exactly the tables this PR is about AGREE, fixed Self-raised, then measured A/B with background TTL merges stopped: a GROUP BY TTL takes the normal branch, so MutateTask builds a TTLTransform; on master the mutation raises Not-ready Set and the debug server aborts, with the fix it fails with the new BAD_ARGUMENTS in system.mutations.latest_fail_reason and the row is unchanged. Covered by the same check.
7 💡 No regression leg pins the one accepted IN <table> spelling, IN <a Set-engine table> DISAGREE Measured identical on base and on the fix, and not reachable by this diff: such a set arrives already filled through addFromStorage. Pinning it costs a shell companion, because the right operand of a TTL IN resolves against default while a stateless test's database is random, which would lose the exact serverError annotations. Say so and I will add one.
8 💡 A new comment writes a bare class name where this directory backticks them AGREE, fixed Backticked, nothing else in the comment changed. The same finding asked to respell hasSubqueries() without parentheses, which I did not apply: src/Storages/*.cpp comments already carry 23 distinct backticked name() forms.

Open choices worth naming rather than leaving for a reviewer to find:

  • A table that already stores such a TTL also stops accepting COLUMN alters, not only TTL merges, since AlterCommands::apply re-validates the table TTL. REMOVE TTL and MODIFY TTL still repair it, the message names that repair, and allow_suspicious_ttl_expressions is the escape hatch.
  • The check throws BAD_ARGUMENTS, matching the key-surface guard for this same defect class, while the other GROUP BY validations in that function throw BAD_TTL_EXPRESSION. Both are precedented; say the word and I will switch it.
  • Why this rejects rather than builds the set, where the sibling Not-ready Set defect on the DELETE WHERE path was fixed the other way: a WHERE decision is transient, while a GROUP BY ... SET assignment persists its value into the merged part, so a set whose contents move between merges would make the stored value depend on when the merge ran. If you read that asymmetry differently, I would rather hear it now than after a release.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260921-034200

@clickhouse-gh clickhouse-gh Bot closed this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand, not a rate: the reporter's CREATE + INSERT + OPTIMIZE TABLE ... FINAL on a debug build logs Logical error: 'Not-ready Set is passed as the second argument for function 'in'' and the merge thread aborts (signal 6).
b Root cause explained? getTTLFromAST stores each GROUP BY ... SET assignment as prebuilt ExpressionActions and drops the analyzer's PreparedSets, and TTLTransform collects the subqueries of the timestamp and WHERE expressions only, so FunctionIn meets an unbuilt set on every aggregation.
c Fix matches root cause? The predicate is the analyzer's own register of sets still needing a build, read where the actions are built and rejected at the DDL that stores them: no widened bound, no symptom guard, no new tag. Filling the set instead cannot be made well defined, since its contents can change between merges.
d Test intent preserved / new tests added? New test 05240_ttl_group_by_set_in_operator; no existing test weakened or retagged, and every positive control is discriminating and idempotent under repeated TTL merges.
e Both directions demonstrated? Yes: [ FAIL ] on a pristine-HEAD server (The query succeeded but the server error '36' was expected) and [ OK ] with the fix, on Build-ID-verified binaries, plus a statement-level A/B of every spelling and four mutation arms that each redden only their own leg.
f Fix is general across code paths? GROUP BY ... SET assignments were the only unguarded carrier: keys, partition keys, skip indexes and the TTL timestamp expression are already screened, and TTL DELETE WHERE is supported because its sets are built. Every path that executes an assignment runs TTLAggregationAlgorithm, including the MATERIALIZE TTL mutation, measured failing with the same BAD_ARGUMENTS; recalculate-only paths execute no assignment and are unaffected.
g Fix generalizes across inputs (params/datatypes/wrappers)? Eight IN spellings rejected (table identifier, subquery, GLOBAL IN, NOT IN, inside a lambda body, the EXISTS rewrite, under indexHint, and in a branch constant folding removes) and four ready-set forms still accepted (literal tuple, Set-engine table, folded scalar subquery, indexHint over a literal set). Set provenance decides, not column type, so type wrappers are not a dimension.
h Backward compatible? (maintainer-approved exception only) Qualified, deliberate and measured: no setting, default or serialized format changes, so no SettingsChangesHistory entry. A table stored before the check still attaches and still accepts inserts, and MODIFY TTL repairs it. Its already-failing TTL merge, and MATERIALIZE TTL, now fail with BAD_ARGUMENTS naming that repair; a COLUMN ALTER is newly refused, since AlterCommands::apply re-validates the table TTL like the sibling arrayJoin screen; and the two spellings row i over-rejects on purpose stop merging. allow_suspicious_ttl_expressions recreates any of them, REMOVE TTL keeps working.
i Invariants and contracts preserved? The check is const and throws before any state changes: at DDL it abandons the statement, at merge time it runs before convertToChunks, two lines above the execute that raises the logical error today. Its predicate is the analyzer's register, which names every set it built, so it also rejects two spellings whose built actions drop the set, an IN under indexHint and an IN in a constant-folded branch; both are measured, and master already refuses those spellings in a key, a partition key, a skip index and the TTL timestamp expression. A merge that processes TTL but aggregates nothing for the rule keeps succeeding.

Session id: cron:clickhouse-impl-slot-5:20260920-224400

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78b277c]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR records whether a TTL GROUP BY ... SET assignment saw a subquery-backed IN set during analysis and rejects that assignment both at DDL time and again when TTL aggregation executes. The main bug path is covered, but the persisted flag is broader than the contract the PR claims to enforce, so I would not approve it as-is.

Findings

⚠️ Majors

  • [src/Storages/TTLDescription.cpp:1564] [dismissed by author -- https://github.com/Reject a TTL GROUP BY SET assignment that needs a set no TTL merge can build #121268#issuecomment-5755288603] requires_sets_from_subqueries is derived from PreparedSets::hasSubqueries(), which records every subquery-backed set the analyzer registered, not the sets that survive into set_part.expression and are actually read during TTL execution. That over-approximation is observable: definitions like indexHint(v IN system.one) or an IN pruned by constant folding were executable before, but the new persisted flag makes their TTL merges fail under allow_suspicious_ttl_expressions and on attached legacy tables even though no merge ever needs to build that set. The PR title/body promise to reject assignments that need an unbuildable set; this implementation rejects some that do not.
    Suggested fix: derive the rejection predicate from the final ExpressionActions / ActionsDAG that TTLAggregationAlgorithm actually executes, or otherwise avoid turning pruned-away sets into a runtime failure for legacy and allow_suspicious_ttl_expressions tables.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Tighten requires_sets_from_subqueries so it tracks sets the stored assignment really consumes at execution time, or stop re-checking the coarse analyzer-level flag at runtime where it regresses previously executable legacy / allow_suspicious_ttl_expressions definitions.

LLVM Coverage Report

Measured on commit 78b277c.

Metric Baseline Current Δ
Lines 88.50% 88.60% +0.10%
Functions 91.80% 91.80% +0.00%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 32/32 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 21, 2026
Comment thread src/Storages/TTLDescription.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). label Sep 21, 2026
…ses it

checkSetPartsAreExecutable is reached from CREATE TABLE, from a rejected
ALTER TABLE ... MODIFY TTL, and from a TTL merge or mutation of a table
that already stores such a definition. The remediation named only the last
of the three: on either DDL path, being told to run
ALTER TABLE ... MODIFY TTL restates the statement that just failed.

The message now asks for the expression to be rewritten, and keeps
ALTER TABLE ... MODIFY TTL as what it is, the way out for a table that
already stores the definition. Wording only, so the error code and the
test's serverError expectations are unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 78b277c65 with master de0734db6 (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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 78b277c

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. CH Inc sync passed on this head, so nothing here is ownerless.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log not from this diff: the 32.8 KB scan holds one error code only, Code: 47 UNKNOWN_IDENTIFIER with the message Unknown expression identifier b. Maybe you meant: ['a'], every occurrence raised by MutatePlainMergeTreeTask on part all_1_1_1_2 and surfaced by MergeTreeBackgroundExecutor. That line carries 97 rows on 91 distinct pull requests in 30 days with 0 on true master, onset 2026-08-31, and this PR touches TTL GROUP BY validation, not mutation execution #118499 (mine, open)
Mergeable Check, PR aggregator statuses mirroring the row above #118499 (mine, open)

Gates (a) to (d): 0 of 176 check runs queued or running, Config Workflow, Style check and Finish Workflow all success, 71 min since the last job finished (anchor 2026-09-21T13:02:52Z), and every failing row above has an owner.

Session id: cron:our-pr-ci-monitor:20260921-140539

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). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

1 participant